diff --git a/.travis.yml b/.travis.yml index 2ee0939..6c8bfa2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,11 +1,15 @@ language: java +sudo: false +cache: + directories: + - $HOME/.m2 jdk: - - openjdk7 - - oraclejdk7 - oraclejdk8 -notifications: - email: - - ansell.peter@gmail.com - - tristan.king@gmail.com +matrix: + include: + - jdk: openjdk11 + before_install: + - rm "${JAVA_HOME}/lib/security/cacerts" + - ln -s /etc/ssl/certs/java/cacerts "${JAVA_HOME}/lib/security/cacerts" after_success: - mvn clean test jacoco:report coveralls:report diff --git a/README.md b/README.md index 93ba528..4f6972d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Tools for using JSONLD-Java ### Dependencies -* Java-1.6+ +* Java-1.8+ * Maven-3 Playground @@ -27,3 +27,16 @@ run the following to get usage details: ./jsonldplayground --help +### Support for basic authentication + +Authentication involves 5 options: + +| Option | Description | +|-----------------------|-----------------------------------| +| `--username ` | username for basic authentication | +| `[--password ]` | password for basic authentication, defaults to the value of the `PASSWORD` environment variable, if any, or the empty string. | +| `[--authHost ]` | host scope of the authentication, defaults to 'localhost' | +| `[--authPort ]` | port scope of the authentication, defaults to '443' | +| `[--insecure]` | Similar to `curl -k` or `curl --insecure`: if unspecified, all SSL connections are secure by default; if specified, trust everything (do not use for production!) | + + diff --git a/jsonldplayground b/jsonldplayground index a838ff3..280b0e1 100755 --- a/jsonldplayground +++ b/jsonldplayground @@ -6,9 +6,12 @@ # # run ./jsonldplayground for the usage -if [ ! -d "tools/target/appassembler/bin" ]; then - mvn -quiet clean install -DskipTests +TOP=$(dirname $0) + +if [ ! -d "${TOP}/target/appassembler/bin" ]; then + echo -e "Building with maven... (This could fail if you haven't previously run 'mvn install' on jsonld-java)\n">&2 + (cd "${TOP}"; mvn -quiet clean install -DskipTests) fi -chmod u+x tools/target/appassembler/bin/* -tools/target/appassembler/bin/jsonldplayground "$@" +chmod u+x "${TOP}/target/appassembler/bin"/* +"${TOP}/target/appassembler/bin/jsonldplayground" "$@" diff --git a/pom.xml b/pom.xml index 559c944..64a90ca 100644 --- a/pom.xml +++ b/pom.xml @@ -4,23 +4,24 @@ jsonld-java-parent com.github.jsonld-java - 0.7.0-SNAPSHOT + 0.13.0 4.0.0 jsonld-java-tools + 0.13.0-SNAPSHOT JSONLD Java :: Tools JSON-LD Java tools jar - 2.8.5 + 3.0.4 ${project.groupId} jsonld-java - ${project.version} + 0.13.0 junit @@ -35,70 +36,71 @@ net.sf.jopt-simple jopt-simple - 4.8 + 5.0.4 - org.openrdf.sesame - sesame-model - ${sesame.version} + org.eclipse.rdf4j + rdf4j-model + ${rdf4j.version} - org.openrdf.sesame - sesame-rio-api - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-api + ${rdf4j.version} - org.openrdf.sesame - sesame-rio-jsonld - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-jsonld + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-nquads - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-nquads + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-turtle - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-turtle + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-rdfxml - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-rdfxml + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-rdfjson - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-rdfjson + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-ntriples - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-ntriples + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-trig - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-trig + ${rdf4j.version} runtime - org.openrdf.sesame - sesame-rio-trix - ${sesame.version} + org.eclipse.rdf4j + rdf4j-rio-trix + ${rdf4j.version} runtime + org.codehaus.mojo appassembler-maven-plugin @@ -114,7 +116,7 @@ com.github.jsonldjava.tools.Playground - jsonldplayground + jsonldplayground @@ -122,6 +124,13 @@ org.codehaus.mojo animal-sniffer-maven-plugin + + + org.codehaus.mojo.signature + java18 + 1.0 + + diff --git a/src/main/java/com/github/jsonldjava/tools/Playground.java b/src/main/java/com/github/jsonldjava/tools/Playground.java index ae2b8a0..59316d0 100644 --- a/src/main/java/com/github/jsonldjava/tools/Playground.java +++ b/src/main/java/com/github/jsonldjava/tools/Playground.java @@ -4,14 +4,49 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.io.StringReader; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.cache.BasicHttpCacheStorage; +import org.apache.http.impl.client.cache.CacheConfig; +import org.apache.http.impl.client.cache.CachingHttpClientBuilder; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.rio.RDFFormat; +import org.eclipse.rdf4j.rio.RDFParserRegistry; +import org.eclipse.rdf4j.rio.Rio; + +import com.github.jsonldjava.core.DocumentLoader; +import com.github.jsonldjava.core.JsonLdApi; +import com.github.jsonldjava.core.JsonLdConsts; +import com.github.jsonldjava.core.JsonLdOptions; +import com.github.jsonldjava.core.JsonLdProcessor; +import com.github.jsonldjava.core.RDFDataset; +import com.github.jsonldjava.utils.JarCacheStorage; +import com.github.jsonldjava.utils.JsonUtils; + import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; @@ -19,42 +54,16 @@ import joptsimple.ValueConversionException; import joptsimple.ValueConverter; -import org.openrdf.model.Model; -import org.openrdf.rio.RDFFormat; -import org.openrdf.rio.RDFParserRegistry; -import org.openrdf.rio.Rio; - -import com.github.jsonldjava.core.JsonLdOptions; -import com.github.jsonldjava.core.JsonLdProcessor; -import com.github.jsonldjava.utils.JsonUtils; - +/** + * A command-line-interface used to load and process JSON-LD and RDF files. + */ public class Playground { - private static Set getProcessingOptions() { - return new LinkedHashSet(Arrays.asList("expand", "compact", "frame", "normalize", - "flatten", "fromrdf", "tordf")); - } - - private static boolean hasContext(String opt) { - return "compact".equals(opt) || "frame".equals(opt) || "flatten".equals(opt); - } - - private static Map getOutputFormats() { - final Map outputFormats = new HashMap(); - - for (final RDFFormat format : RDFParserRegistry.getInstance().getKeys()) { - outputFormats.put(format.getName().replaceAll("-", "").replaceAll("/", "") - .toLowerCase(), format); - } - - return outputFormats; - } - public static void main(String[] args) throws Exception { final Map formats = getOutputFormats(); - final Set outputForms = new LinkedHashSet(Arrays.asList("compacted", - "expanded", "flattened")); + final Set outputForms = new LinkedHashSet( + Arrays.asList("compacted", "expanded", "flattened")); final OptionParser parser = new OptionParser(); @@ -69,20 +78,17 @@ public static void main(String[] args) throws Exception { final OptionSpec context = parser.accepts("context").withRequiredArg() .ofType(File.class).describedAs("The context"); - final OptionSpec outputFormat = parser - .accepts("format") - .withOptionalArg() - .ofType(String.class) - .withValuesConvertedBy(new ValueConverter() { + final OptionSpec outputFormat = parser.accepts("format").withOptionalArg() + .ofType(String.class).withValuesConvertedBy(new ValueConverter() { @Override - public RDFFormat convert(String arg0) { + public RDFFormat convert(String inputFormat) { // Normalise the name to provide alternatives - final String formatName = arg0.replaceAll("-", "").replaceAll("/", "") - .toLowerCase(); + final String formatName = inputFormat.replaceAll("-", "") + .replaceAll("/", "").toLowerCase(); if (formats.containsKey(formatName)) { return formats.get(formatName); } - throw new ValueConversionException("Format was not known: " + arg0 + throw new ValueConversionException("Format was not known: " + inputFormat + " (Valid values are: " + formats.keySet() + ")"); } @@ -95,17 +101,12 @@ public String valuePattern() { public Class valueType() { return RDFFormat.class; } - }) - .defaultsTo(RDFFormat.NQUADS) - .describedAs( - "The output file format to use. Defaults to nquads. Valid values are: " - + formats.keySet()); - - final OptionSpec processingOption = parser - .accepts("process") - .withRequiredArg() - .ofType(String.class) - .required() + }).defaultsTo(RDFFormat.NQUADS) + .describedAs("The output file format to use. Defaults to nquads. Valid values are: " + + formats.keySet()); + + final OptionSpec processingOption = parser.accepts("process").withRequiredArg() + .ofType(String.class).required() .withValuesConvertedBy(new ValueConverter() { @Override public String convert(String value) { @@ -125,16 +126,11 @@ public Class valueType() { public String valuePattern() { return null; } - }) - .describedAs( - "The processing to perform. Valid values are: " - + getProcessingOptions().toString()); - - final OptionSpec outputForm = parser - .accepts("outputForm") - .withOptionalArg() - .ofType(String.class) - .defaultsTo("expanded") + }).describedAs("The processing to perform. Valid values are: " + + getProcessingOptions().toString()); + + final OptionSpec outputForm = parser.accepts("outputForm").withOptionalArg() + .ofType(String.class).defaultsTo("expanded") .withValuesConvertedBy(new ValueConverter() { @Override public String convert(String value) { @@ -154,11 +150,28 @@ public String valuePattern() { public Class valueType() { return String.class; } - }) - .describedAs( + }).describedAs( "The way to output the results from fromRDF. Defaults to expanded. Valid values are: " + outputForms); + final OptionSpec usernameOption = parser.accepts("username").withOptionalArg() + .ofType(String.class).describedAs("username for basic authentication credentials"); + + final OptionSpec passwordOption = parser.accepts("password").withOptionalArg() + .ofType(String.class).describedAs( + "password for basic authentication credentials (defaults to value of 'PASSWORD' environment property, if set, or empty string otherwise)"); + + final OptionSpec authHostOption = parser.accepts("authHost").withOptionalArg() + .ofType(String.class).defaultsTo("localhost") + .describedAs("host authentication scope"); + + final OptionSpec authPortOption = parser.accepts("authPort").withOptionalArg() + .ofType(Integer.class).defaultsTo(443) + .describedAs("host port authentication scope"); + + final OptionSpec authInsecureOption = parser.accepts("insecure", + "Similar to `curl -k` or `curl --insecure`: if unspecified, all SSL connections are secure by default; if specified, trust everything (do not use for production!)"); + OptionSet options = null; try { @@ -180,17 +193,18 @@ public Class valueType() { opts.setBase(options.valueOf(base)); opts.outputForm = options.valueOf(outputForm); - opts.format = options.has(outputFormat) ? options.valueOf(outputFormat) - .getDefaultMIMEType() : "application/nquads"; + opts.format = options.has(outputFormat) ? options.valueOf(outputFormat).getDefaultMIMEType() + : JsonLdConsts.APPLICATION_NQUADS; final RDFFormat sesameOutputFormat = options.valueOf(outputFormat); - final RDFFormat sesameInputFormat = Rio.getParserFormatForFileName( - options.valueOf(inputFile).getName(), RDFFormat.JSONLD); + final RDFFormat sesameInputFormat = Rio + .getParserFormatForFileName(options.valueOf(inputFile).getName()) + .orElse(RDFFormat.JSONLD); final String processingOptionValue = options.valueOf(processingOption); if (!options.valueOf(inputFile).exists()) { - System.out.println("Error: input file \"" + options.valueOf(inputFile) - + "\" doesn't exist"); + System.out.println( + "Error: input file \"" + options.valueOf(inputFile) + "\" doesn't exist"); parser.printHelpOn(System.out); return; } @@ -199,6 +213,52 @@ public Class valueType() { opts.setBase(options.valueOf(inputFile).toURI().toASCIIString()); } + if (options.hasArgument(usernameOption)) { + final String username = options.valueOf(usernameOption); + final String envPassword = System.getenv("PASSWORD"); + final String password = options.hasArgument(passwordOption) + ? options.valueOf(passwordOption) + : (null != envPassword) ? envPassword : ""; + final String authHost = options.valueOf(authHostOption); + final Integer authPort = options.valueOf(authPortOption); + + final DocumentLoader documentLoader = new DocumentLoader(); + + final CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(authHost, authPort), + new UsernamePasswordCredentials(username, password)); + + final CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(1000) + .setMaxObjectSize(1024 * 128).build(); + + HttpClientBuilder builder = CachingHttpClientBuilder.create() + // allow caching + .setCacheConfig(cacheConfig) + // Wrap the local JarCacheStorage around a + // BasicHttpCacheStorage + .setHttpCacheStorage(new JarCacheStorage(null, cacheConfig, + new BasicHttpCacheStorage(cacheConfig))) + .setDefaultCredentialsProvider(credsProvider); + + if (options.has(authInsecureOption)) { + final SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(null, new TrustManager[] { new InsecureX509TrustManager() }, null); + final HostnameVerifier v = new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }; + + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, v); + // insecure ssl connections + builder = builder.setSSLSocketFactory(sslsf); + } + + documentLoader.setHttpClient(builder.build()); + opts.setDocumentLoader(documentLoader); + } + if ("fromrdf".equals(processingOptionValue)) { inobj = readFile(options.valueOf(inputFile)); } else { @@ -207,8 +267,8 @@ public Class valueType() { if (hasContext(processingOptionValue) && options.has(context)) { if (!options.valueOf(context).exists()) { - System.out.println("Error: context file \"" + options.valueOf(context) - + "\" doesn't exist"); + System.out.println( + "Error: context file \"" + options.valueOf(context) + "\" doesn't exist"); parser.printHelpOn(System.out); return; } @@ -220,13 +280,12 @@ public Class valueType() { final Model inModel = Rio.parse(new StringReader((String) inobj), opts.getBase(), sesameInputFormat); - outobj = JsonLdProcessor.fromRDF(inModel, opts, new SesameJSONLDRDFParser()); + outobj = JsonLdProcessor.fromRDF(inModel, opts, new RDF4JJSONLDRDFParser()); } else if ("tordf".equals(processingOptionValue)) { opts.useNamespaces = true; - outobj = JsonLdProcessor - .toRDF(inobj, - new SesameJSONLDTripleCallback(Rio.createWriter(sesameOutputFormat, - System.out)), opts); + outobj = JsonLdProcessor.toRDF(inobj, + new RDF4JJSONLDTripleCallback(Rio.createWriter(sesameOutputFormat, System.out)), + opts); } else if ("expand".equals(processingOptionValue)) { outobj = JsonLdProcessor.expand(inobj, opts); } else if ("compact".equals(processingOptionValue)) { @@ -237,11 +296,32 @@ public Class valueType() { } outobj = JsonLdProcessor.compact(inobj, ctxobj, opts); } else if ("normalize".equals(processingOptionValue)) { - outobj = JsonLdProcessor.normalize(inobj, opts); + // see https://github.com/jsonld-java/jsonld-java/issues/193 + // outobj = JsonLdProcessor.normalize(inobj, opts); + + // see https://github.com/jsonld-java/jsonld-java/issues/194 + // until this is fixed, it is necessary to clear the format so that + // JsonLdProcessor won't try to interpret it. + opts.format = null; + + // If an output format is specified, add a callback to show the + // result. + final Object result = JsonLdProcessor.toRDF(inobj, + options.has(outputFormat) + ? new RDF4JJSONLDTripleCallback( + Rio.createWriter(sesameOutputFormat, System.out)) + : null, + opts); + if (RDFDataset.class.isInstance(result)) { + final RDFDataset rdfds = RDFDataset.class.cast(result); + outobj = new JsonLdApi(opts).normalize(rdfds); + } else { + outobj = result; + } } else if ("frame".equals(processingOptionValue)) { if (ctxobj != null && !(ctxobj instanceof Map)) { - System.out - .println("Invalid JSON-LD syntax; a JSON-LD frame must be a single object."); + System.out.println( + "Invalid JSON-LD syntax; a JSON-LD frame must be a single object."); parser.printHelpOn(System.out); return; } @@ -258,52 +338,83 @@ public Class valueType() { if ("tordf".equals(processingOptionValue)) { // Already serialised above } else if ("normalize".equals(processingOptionValue)) { - System.out.println((String) outobj); + if (!options.has(outputFormat)) { + // if no output format was specified, then show the result. + System.out.println(JsonUtils.toPrettyString(outobj)); + } } else { System.out.println(JsonUtils.toPrettyString(outobj)); } } + private static Set getProcessingOptions() { + return new LinkedHashSet(Arrays.asList("expand", "compact", "frame", "normalize", + "flatten", "fromrdf", "tordf")); + } + + private static boolean hasContext(String opt) { + return "compact".equals(opt) || "frame".equals(opt) || "flatten".equals(opt); + } + + private static Map getOutputFormats() { + final Map outputFormats = new HashMap(); + + for (final RDFFormat format : RDFParserRegistry.getInstance().getKeys()) { + outputFormats.put( + format.getName().replaceAll("-", "").replaceAll("/", "").toLowerCase(), format); + } + + return outputFormats; + } + private static String readFile(File in) throws IOException { - final BufferedReader buf = new BufferedReader(new InputStreamReader( - new FileInputStream(in), "UTF-8")); - String inobj = ""; - try { + final StringBuilder inobj = new StringBuilder(1024); + try (BufferedReader buf = Files.newBufferedReader(in.toPath(), StandardCharsets.UTF_8)) { String line; while ((line = buf.readLine()) != null) { line = line.trim(); - inobj = (inobj) + line + "\n"; + inobj.append(line).append('\n'); } - } finally { - buf.close(); } - return inobj; + return inobj.toString(); + } + + private static class InsecureX509TrustManager extends X509ExtendedTrustManager + implements X509TrustManager { + + @Override + public void checkClientTrusted(X509Certificate[] xcs, String string) { + } + + @Override + public void checkServerTrusted(X509Certificate[] xcs, String string) + throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) + throws CertificateException { + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, + SSLEngine sslEngine) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, + SSLEngine sslEngine) throws CertificateException { + } } - // private static void usage() { - // System.out.println("Usage: jsonldplayground "); - // System.out.println("\tinput: a filename or JsonLdUrl to the rdf input (in rdfxml or n3)"); - // System.out.println("\toptions:"); - // System.out - // .println("\t\t--ignorekeys : a (space separated) list of keys to ignore (e.g. @geojson)"); - // System.out.println("\t\t--base : base URI"); - // System.out.println("\t\t--debug: Print out stack traces when errors occur"); - // System.out.println("\t\t--expand : expand the input JSON-LD"); - // System.out - // .println("\t\t--compact : compact the input JSON-LD applying the optional context file"); - // System.out - // .println("\t\t--normalize : normalize the input JSON-LD outputting as format (defaults to nquads)"); - // System.out - // .println("\t\t--frame : frame the input JSON-LD with the optional frame file"); - // System.out - // .println("\t\t--flatten : flatten the input JSON-LD applying the optional context file"); - // System.out - // .println("\t\t--fromRDF : generate JSON-LD from the input rdf (format defaults to nquads)"); - // System.out - // .println("\t\t--toRDF : generate RDF from the input JSON-LD (format defaults to nquads)"); - // System.out - // .println("\t\t--outputForm [compacted|expanded|flattened] : the way to output the results from fromRDF (defaults to expanded)"); - // System.out.println("\t\t--simplify : simplify the input JSON-LD"); - // System.exit(1); - // } } diff --git a/src/main/java/com/github/jsonldjava/tools/SesameJSONLDRDFParser.java b/src/main/java/com/github/jsonldjava/tools/RDF4JJSONLDRDFParser.java similarity index 65% rename from src/main/java/com/github/jsonldjava/tools/SesameJSONLDRDFParser.java rename to src/main/java/com/github/jsonldjava/tools/RDF4JJSONLDRDFParser.java index 1645e1a..41af3ea 100644 --- a/src/main/java/com/github/jsonldjava/tools/SesameJSONLDRDFParser.java +++ b/src/main/java/com/github/jsonldjava/tools/RDF4JJSONLDRDFParser.java @@ -1,28 +1,28 @@ package com.github.jsonldjava.tools; +import java.util.Optional; import java.util.Set; -import org.openrdf.model.BNode; -import org.openrdf.model.Graph; -import org.openrdf.model.Literal; -import org.openrdf.model.Model; -import org.openrdf.model.Namespace; -import org.openrdf.model.Resource; -import org.openrdf.model.Statement; -import org.openrdf.model.URI; -import org.openrdf.model.Value; -import org.openrdf.model.vocabulary.RDF; -import org.openrdf.model.vocabulary.XMLSchema; +import org.eclipse.rdf4j.model.BNode; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Literal; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Namespace; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.vocabulary.RDF; +import org.eclipse.rdf4j.model.vocabulary.XMLSchema; import com.github.jsonldjava.core.JsonLdError; import com.github.jsonldjava.core.RDFDataset; /** - * Implementation of RDFParser for Sesame-2.8. + * Implementation of RDFParser for RDF4J-2. * * @author Peter Ansell */ -class SesameJSONLDRDFParser implements com.github.jsonldjava.core.RDFParser { +class RDF4JJSONLDRDFParser implements com.github.jsonldjava.core.RDFParser { public void setPrefix(RDFDataset result, String fullUri, String prefix) { result.setNamespace(fullUri, prefix); @@ -41,23 +41,23 @@ public void handleStatement(RDFDataset result, Statement nextStatement) { if (object instanceof Literal) { final Literal literal = (Literal) object; final String value = literal.getLabel(); - final String language = literal.getLanguage(); + final Optional language = literal.getLanguage(); String datatype = getResourceValue(literal.getDatatype()); // In RDF-1.1, Language Literals internally have the datatype // rdf:langString - if (language != null && datatype == null) { + if (language.isPresent() && datatype == null) { datatype = RDF.LANGSTRING.stringValue(); } // In RDF-1.1, RDF-1.0 Plain Literals are now Typed Literals with // type xsd:String - if (language == null && datatype == null) { + if (!language.isPresent() && datatype == null) { datatype = XMLSchema.STRING.stringValue(); } - result.addQuad(subject, predicate, value, datatype, language, graphName); + result.addQuad(subject, predicate, value, datatype, language.orElse(null), graphName); } else { result.addQuad(subject, predicate, getResourceValue((Resource) object), graphName); @@ -67,14 +67,14 @@ public void handleStatement(RDFDataset result, Statement nextStatement) { private String getResourceValue(Resource subject) { if (subject == null) { return null; - } else if (subject instanceof URI) { + } else if (subject instanceof IRI) { return subject.stringValue(); } else if (subject instanceof BNode) { return "_:" + subject.stringValue(); } - throw new IllegalStateException("Did not recognise resource type: " - + subject.getClass().getName()); + throw new IllegalStateException( + "Did not recognise resource type: " + subject.getClass().getName()); } @Override @@ -82,15 +82,13 @@ public RDFDataset parse(Object input) throws JsonLdError { final RDFDataset result = new RDFDataset(); if (input instanceof Statement) { handleStatement(result, (Statement) input); - } else if (input instanceof Graph) { - if (input instanceof Model) { - final Set namespaces = ((Model) input).getNamespaces(); - for (final Namespace nextNs : namespaces) { - result.setNamespace(nextNs.getName(), nextNs.getPrefix()); - } + } else if (input instanceof Model) { + final Set namespaces = ((Model) input).getNamespaces(); + for (final Namespace nextNs : namespaces) { + result.setNamespace(nextNs.getName(), nextNs.getPrefix()); } - for (final Statement nextStatement : (Graph) input) { + for (final Statement nextStatement : (Model) input) { handleStatement(result, nextStatement); } } diff --git a/src/main/java/com/github/jsonldjava/tools/SesameJSONLDTripleCallback.java b/src/main/java/com/github/jsonldjava/tools/RDF4JJSONLDTripleCallback.java similarity index 75% rename from src/main/java/com/github/jsonldjava/tools/SesameJSONLDTripleCallback.java rename to src/main/java/com/github/jsonldjava/tools/RDF4JJSONLDTripleCallback.java index 0029da5..497d83c 100644 --- a/src/main/java/com/github/jsonldjava/tools/SesameJSONLDTripleCallback.java +++ b/src/main/java/com/github/jsonldjava/tools/RDF4JJSONLDTripleCallback.java @@ -3,31 +3,31 @@ import java.util.List; import java.util.Map.Entry; -import org.openrdf.model.Resource; -import org.openrdf.model.Statement; -import org.openrdf.model.URI; -import org.openrdf.model.Value; -import org.openrdf.model.ValueFactory; -import org.openrdf.model.impl.LinkedHashModel; -import org.openrdf.model.impl.ValueFactoryImpl; -import org.openrdf.rio.ParseErrorListener; -import org.openrdf.rio.ParserConfig; -import org.openrdf.rio.RDFHandler; -import org.openrdf.rio.RDFHandlerException; -import org.openrdf.rio.RDFParseException; -import org.openrdf.rio.helpers.ParseErrorLogger; -import org.openrdf.rio.helpers.RDFParserHelper; -import org.openrdf.rio.helpers.StatementCollector; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.rio.ParseErrorListener; +import org.eclipse.rdf4j.rio.ParserConfig; +import org.eclipse.rdf4j.rio.RDFHandler; +import org.eclipse.rdf4j.rio.RDFHandlerException; +import org.eclipse.rdf4j.rio.RDFParseException; +import org.eclipse.rdf4j.rio.helpers.ParseErrorLogger; +import org.eclipse.rdf4j.rio.helpers.RDFParserHelper; +import org.eclipse.rdf4j.rio.helpers.StatementCollector; import com.github.jsonldjava.core.JsonLdTripleCallback; import com.github.jsonldjava.core.RDFDataset; /** - * Implementation of JsonLdTripleCallback for Sesame-2.8. + * Implementation of JsonLdTripleCallback for RDF4J-2. * * @author Peter Ansell */ -class SesameJSONLDTripleCallback implements JsonLdTripleCallback { +class RDF4JJSONLDTripleCallback implements JsonLdTripleCallback { private ValueFactory vf; @@ -37,19 +37,19 @@ class SesameJSONLDTripleCallback implements JsonLdTripleCallback { private final ParseErrorListener parseErrorListener; - public SesameJSONLDTripleCallback() { + public RDF4JJSONLDTripleCallback() { this(new StatementCollector(new LinkedHashModel())); } - public SesameJSONLDTripleCallback(RDFHandler nextHandler) { - this(nextHandler, ValueFactoryImpl.getInstance()); + public RDF4JJSONLDTripleCallback(RDFHandler nextHandler) { + this(nextHandler, SimpleValueFactory.getInstance()); } - public SesameJSONLDTripleCallback(RDFHandler nextHandler, ValueFactory vf) { + public RDF4JJSONLDTripleCallback(RDFHandler nextHandler, ValueFactory vf) { this(nextHandler, vf, new ParserConfig(), new ParseErrorLogger()); } - public SesameJSONLDTripleCallback(RDFHandler nextHandler, ValueFactory vf, + public RDF4JJSONLDTripleCallback(RDFHandler nextHandler, ValueFactory vf, ParserConfig parserConfig, ParseErrorListener parseErrorListener) { this.handler = nextHandler; this.vf = vf; @@ -67,9 +67,9 @@ private void triple(String s, String p, String o, String graph) { // This method is always called with three Resources as subject // predicate and object if (graph == null) { - result = vf.createStatement(createResource(s), vf.createURI(p), createResource(o)); + result = vf.createStatement(createResource(s), vf.createIRI(p), createResource(o)); } else { - result = vf.createStatement(createResource(s), vf.createURI(p), createResource(o), + result = vf.createStatement(createResource(s), vf.createIRI(p), createResource(o), createResource(graph)); } @@ -89,7 +89,7 @@ private Resource createResource(String resource) { } else if (resource.startsWith("_:")) { return vf.createBNode(resource.substring(2)); } else { - return vf.createURI(resource); + return vf.createIRI(resource); } } @@ -103,8 +103,8 @@ private void triple(String s, String p, String value, String datatype, String la final Resource subject = createResource(s); - final URI predicate = vf.createURI(p); - final URI datatypeURI = datatype == null ? null : vf.createURI(datatype); + final IRI predicate = vf.createIRI(p); + final IRI datatypeURI = datatype == null ? null : vf.createIRI(datatype); Value object; try { @@ -184,7 +184,8 @@ public Object call(final RDFDataset dataset) { if (handler != null) { try { handler.startRDF(); - for (final Entry nextNamespace : dataset.getNamespaces().entrySet()) { + for (final Entry nextNamespace : dataset.getNamespaces() + .entrySet()) { handler.handleNamespace(nextNamespace.getKey(), nextNamespace.getValue()); } } catch (final RDFHandlerException e) { @@ -198,12 +199,12 @@ public Object call(final RDFDataset dataset) { } for (final RDFDataset.Quad quad : quads) { if (quad.getObject().isLiteral()) { - triple(quad.getSubject().getValue(), quad.getPredicate().getValue(), quad - .getObject().getValue(), quad.getObject().getDatatype(), quad - .getObject().getLanguage(), graphName); + triple(quad.getSubject().getValue(), quad.getPredicate().getValue(), + quad.getObject().getValue(), quad.getObject().getDatatype(), + quad.getObject().getLanguage(), graphName); } else { - triple(quad.getSubject().getValue(), quad.getPredicate().getValue(), quad - .getObject().getValue(), graphName); + triple(quad.getSubject().getValue(), quad.getPredicate().getValue(), + quad.getObject().getValue(), graphName); } } }