Coder Social home page Coder Social logo

jsonld-java's Introduction

JSONLD-Java is looking for a maintainer

JSONLD-JAVA

This is a Java implementation of the JSON-LD 1.0 specification and the JSON-LD-API 1.0 specification.

Build Status Coverage Status

USAGE

From Maven

<dependency>
    <groupId>com.github.jsonld-java</groupId>
    <artifactId>jsonld-java</artifactId>
    <version>0.13.5</version>
</dependency>

Code example

// Open a valid json(-ld) input file
InputStream inputStream = new FileInputStream("input.json");
// Read the file into an Object (The type of this object will be a List, Map, String, Boolean,
// Number or null depending on the root object in the file).
Object jsonObject = JsonUtils.fromInputStream(inputStream);
// Create a context JSON map containing prefixes and definitions
Map context = new HashMap();
// Customise context...
// Create an instance of JsonLdOptions with the standard JSON-LD options
JsonLdOptions options = new JsonLdOptions();
// Customise options...
// Call whichever JSONLD function you want! (e.g. compact)
Object compact = JsonLdProcessor.compact(jsonObject, context, options);
// Print out the result (or don't, it's your call!)
System.out.println(JsonUtils.toPrettyString(compact));

Processor options

The Options specified by the JSON-LD API Specification are accessible via the com.github.jsonldjava.core.JsonLdOptions class, and each JsonLdProcessor.* function has an optional input to take an instance of this class.

Controlling network traffic

Parsing JSON-LD will normally follow any external @context declarations. Loading these contexts from the network may in some cases not be desirable, or might require additional proxy configuration or authentication.

JSONLD-Java uses the Apache HTTPComponents Client for these network connections, based on the SystemDefaultHttpClient which reads standard Java properties like http.proxyHost.

The default HTTP Client is wrapped with a CachingHttpClient to provide a small memory-based cache (1000 objects, max 128 kB each) of regularly accessed contexts.

Loading contexts from classpath

Your application might be parsing JSONLD documents which always use the same external @context IRIs. Although the default HTTP cache (see above) will avoid repeated downloading of the same contexts, your application would still initially be vulnerable to network connectivity.

To bypass this issue, and even facilitate parsing of such documents in an offline state, it is possible to provide a 'warmed' cache populated from the classpath, e.g. loaded from a JAR.

In your application, simply add a resource jarcache.json to the root of your classpath together with the JSON-LD contexts to embed. (Note that you might have to recursively embed any nested contexts).

The syntax of jarcache.json is best explained by example:

[
  {
    "Content-Location": "http://www.example.com/context",
    "X-Classpath": "contexts/example.jsonld",
    "Content-Type": "application/ld+json"
  },
  {
    "Content-Location": "http://data.example.net/other",
    "X-Classpath": "contexts/other.jsonld",
    "Content-Type": "application/ld+json"
  }
]

(See also core/src/test/resources/jarcache.json).

This will mean that any JSON-LD document trying to import the @context http://www.example.com/context will instead be given contexts/example.jsonld loaded as a classpath resource.

The X-Classpath location is an IRI reference resolved relative to the location of the jarcache.json - so if you have multiple JARs with a jarcache.json each, then the X-Classpath will be resolved within the corresponding JAR (minimizing any conflicts).

Additional HTTP headers (such as Content-Type above) can be included, although these are generally ignored by JSONLD-Java.

Unless overridden in jarcache.json, this Cache-Control header is automatically injected together with the current Date, meaning that the resource loaded from the JAR will effectively never expire (the real HTTP server will never be consulted by the Apache HTTP client):

Date: Wed, 19 Mar 2014 13:25:08 GMT
Cache-Control: max-age=2147483647

The mechanism for loading jarcache.json relies on Thread.currentThread().getContextClassLoader() to locate resources from the classpath - if you are running on a command line, within a framework (e.g. OSGi) or Servlet container (e.g. Tomcat) this should normally be set correctly. If not, try:

ClassLoader oldContextCL = Thread.currentThread().getContextClassLoader();
try { 
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    JsonLdProcessor.expand(input);   // or any other JsonLd operation
} finally { 
    // Restore, in case the current thread was doing something else
    // with the context classloader before calling our method
    Thread.currentThread().setContextClassLoader(oldContextCL);
}

To disable all remote document fetching, when using the default DocumentLoader, set the following Java System Property to "true" using:

System.setProperty("com.github.jsonldjava.disallowRemoteContextLoading", "true");

You can also use the constant provided in DocumentLoader for the same purpose:

System.setProperty(DocumentLoader.DISALLOW_REMOTE_CONTEXT_LOADING, "true");

Note that if you override DocumentLoader you should also support this setting for consistency and security.

Loading contexts from a string

Your application might be parsing JSONLD documents which reference external @context IRIs that are not available as file URIs on the classpath. In this case, the jarcache.json approach will not work. Instead you can inject the literal context file strings through the JsonLdOptions object, as follows:

// Inject a context document into the options as a literal string
DocumentLoader dl = new DocumentLoader();
JsonLdOptions options = new JsonLdOptions();
// ... the contents of "contexts/example.jsonld"
String jsonContext = "{ \"@context\": { ... } }";
dl.addInjectedDoc("http://www.example.com/context",  jsonContext);
options.setDocumentLoader(dl);

InputStream inputStream = new FileInputStream("input.json");
Object jsonObject = JsonUtils.fromInputStream(inputStream);
Map context = new HashMap();
Object compact = JsonLdProcessor.compact(jsonObject, context, options);
System.out.println(JsonUtils.toPrettyString(compact));

Customizing the Apache HttpClient

To customize the HTTP behaviour (e.g. to disable the cache or provide authentication credentials), you may want to create and configure your own CloseableHttpClient instance, which can be passed to a DocumentLoader instance using setHttpClient(). This document loader can then be inserted into JsonLdOptions using setDocumentLoader() and passed as an argument to JsonLdProcessor arguments.

Example of inserting a credential provider (e.g. to load a @context protected by HTTP Basic Auth):

Object input = JsonUtils.fromInputStream(..);
DocumentLoader documentLoader = new DocumentLoader();
        
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope("localhost", 443),
        new UsernamePasswordCredentials("username", "password"));
       
CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(1000)
        .setMaxObjectSize(1024 * 128).build();

CloseableHttpClient httpClient = CachingHttpClientBuilder
        .create()
        // allow caching
        .setCacheConfig(cacheConfig)
        // Wrap the local JarCacheStorage around a BasicHttpCacheStorage
        .setHttpCacheStorage(
                new JarCacheStorage(null, cacheConfig, new BasicHttpCacheStorage(
                        cacheConfig)))....
		
        // Add in the credentials provider
        .setDefaultCredentialsProvider(credsProvider);
        // When you are finished setting the properties, call build
        .build();

documentLoader.setHttpClient(httpClient);
        
JsonLdOptions options = new JsonLdOptions();
options.setDocumentLoader(documentLoader);
// .. and any other options        
Object rdf = JsonLdProcessor.toRDF(input, options);

PLAYGROUND

The jsonld-java-tools repository contains a simple application which provides command line access to JSON-LD functions

Initial clone and setup

git clone [email protected]:jsonld-java/jsonld-java-tools.git
chmod +x ./jsonldplayground

Usage

run the following to get usage details:

./jsonldplayground --help

For Developers

Compiling & Packaging

jsonld-java uses maven to compile. From the base jsonld-java module run mvn clean install to install the jar into your local maven repository.

Running tests

mvn test

or

mvn test -pl core

to run only core package tests

Code style

The JSONLD-Java project uses custom Eclipse formatting and cleanup style guides to ensure that Pull Requests are fairly simple to merge.

These guides can be found in the /conf directory and can be installed in Eclipse using "Properties>Java Code Style>Formatter", followed by "Properties>Java Code Style>Clean Up" for each of the modules making up the JSONLD-Java project.

If you don't use Eclipse, then don't worry, your pull requests can be cleaned up by a repository maintainer prior to merging, but it makes the initial check easier if the modified code uses the conventions.

Submitting Pull Requests

Once you have made a change to fix a bug or add a new feature, you should commit and push the change to your fork.

Then, you can open a pull request to merge your change into the master branch of the main repository.

Implementation Reports for JSONLD-Java conformance with JSONLD-1.0

The Implementation Reports documenting the conformance of JSONLD-Java with JSONLD-1.0 are available at:

https://github.com/jsonld-java/jsonld-java/tree/master/core/reports

Regenerating Implementation Report

Implementation Reports conforming to the JSON-LD Implementation Report document can be regenerated using the following command:

mvn test -pl core -Dtest=JsonLdProcessorTest -Dreport.format=<format>

Current possible values for <format> include JSON-LD (application/ld+json or jsonld), NQuads (text/plain, nquads, ntriples, nq or nt) and Turtle (text/turtle, turtle or ttl). * can be used to generate reports in all available formats.

Integration of JSONLD-Java with other Java packages

This is the base package for JSONLD-Java. Integration with other Java packages are done in separate repositories.

Existing integrations

Creating an integration module

Create a repository for your module

Create a GitHub repository for your module under your user account, or have a JSONLD-Java maintainer create one in the jsonld-java organisation.

Create maven module

Create pom.xml for your module

Here is the basic outline for what your module's pom.xml should look like

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <parent>
    <groupId>com.github.jsonld-java</groupId>
    <artifactId>jsonld-java-parent</artifactId>
    <version>0.13.5</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>jsonld-java-{your module}</artifactId>
  <version>0.13.5-SNAPSHOT</version>
  <name>JSONLD Java :: {your module name}</name>
  <description>JSON-LD Java integration module for {RDF Library your module integrates}</description>
  <packaging>jar</packaging>

  <developers>
    <developer>
      <name>{YOU}</name>
      <email>{YOUR EMAIL ADDRESS}</email>
    </developer>
  </developers>

  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>jsonld-java</artifactId>
      <version>${project.version}</version>
      <type>jar</type> 
      <scope>compile</scope> 
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>jsonld-java</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-jdk14</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Make sure you edit the following:

  • project/artifactId : set this to jsonld-java-{module id}, where {module id} usually represents the RDF library you're integrating (e.g. jsonld-java-jena)
  • project/name : set this to JSONLD Java :: {Module Name}, wher {module name} is usually the name of the RDF library you're integrating.
  • project/description
  • project/developers/developer/... : Give youself credit by filling in the developer field. At least put your <name> in (see here for all available options).
  • project/dependencies/... : remember to add any dependencies your project needs

Import into your favorite editor

For Example: Follow the first few steps in the section above to import the whole jsonld-java project or only your new module into eclipse.

Create RDFParser Implementation

The interface com.github.jsonldjava.core.RDFParser is used to parse RDF from the library into the JSONLD-Java internal RDF format. See the documentation in RDFParser.java for details on how to implement this interface.

Create TripleCallback Implementation

The interface com.github.jsonldjava.core.JSONLDTripleCallback is used to generate a representation of the JSON-LD input in the RDF library. See the documentation in JSONLDTripleCallback.java for details on how to implement this interface.

Using your Implementations

RDFParser

A JSONLD RDF parser is a class that can parse your frameworks' RDF model and generate JSON-LD.

There are two ways to use your RDFParser implementation.

Register your parser with the JSONLD class and set options.format when you call fromRDF

JSONLD.registerRDFParser("format/identifier", new YourRDFParser());
Object jsonld = JSONLD.fromRDF(yourInput, new Options("") {{ format = "format/identifier" }});

or pass an instance of your RDFParser into the fromRDF function

Object jsonld = JSONLD.fromRDF(yourInput, new YourRDFParser());

JSONLDTripleCallback

A JSONLD triple callback is a class that can populate your framework's RDF model from JSON-LD - being called for each triple (technically quad).

Pass an instance of your TripleCallback to JSONLD.toRDF

Object yourOutput = JSONLD.toRDF(jsonld, new YourTripleCallback());

Integrate with your framework

Your framework might have its own system of readers and writers, where you should register JSON-LD as a supported format. Remember that here the "parse" direction is opposite of above, a 'reader' may be a class that can parse JSON-LD and populate an RDF Graph.

Write Tests

It's helpful to have a test or two for your implementations to make sure they work and continue to work with future versions.

Write README.md

Write a README.md file with instrutions on how to use your module.

Submit your module

Once you've committed your code, and pushed it into your github fork you can issue a Pull Request so that we can add a reference to your module in this README file.

Alternatively, we can also host your repository in the jsonld-java organisation to give it more visibility.

CHANGELOG

2023-11-06

  • Release 0.13.6
  • Bump Jackson-databind version to latest for security update

2023-11-03

  • Release 0.13.5
  • Bump Jackson and Guava versions to latest for security updates

2021-12-13

  • Release 0.13.4
  • Switch test logging from log4j to logback (Patch by @ansell)
  • Improve Travis CI build Performance (Patch by @YunLemon)

2021-03-06

  • Release 0.13.3
  • Fix @type when subject and object are the same (Reported by @barthanssens, Patch by @umbreak)
  • Ignore @base if remote context is not relative (Reported by @whikloj, Patch by @dr0i)
  • Fix throwing recursive context inclusion (Patch by @umbreak)

2020-09-24

  • Release 0.13.2
  • Fix Guava dependency shading (Reported by @ggrasso)
  • Fix @context issues when using a remote context (Patch by @umbreak)
  • Deprecate Context.serialize (Patch by @umbreak)

2020-09-09

  • Release 0.13.1
  • Fix java.net.URI resolution (Reported by @ebremer and @afs, Patch by @dr0i)
  • Shade Guava failureaccess module (Patch by @peacekeeper)
  • Don't minimize Guava class shading (Patch by @elahrvivaz)
  • Follow link headers to @context files (Patch by @dr0i and @fsteeg)

2019-11-28

  • Release 0.13.0
  • Bump Jackson versions to latest for security updates (Patch by @afs)
  • Do not canonicalise XSD Decimal typed values (Patch by @jhg023)
  • Bump dependency and plugin versions

2019-08-03

  • Release 0.12.5
  • Bump Jackson versions to latest for security updates (Patches by @afs)
  • IRI resolution fixes (Patch by @fsteeg)

2019-04-20

  • Release 0.12.4
  • Bump Jackson version to 2.9.8
  • Add a regression test for a past framing bug
  • Throw error on empty key
  • Add regression tests for workarounds to Text/URL dual definitions
  • Persist JsonLdOptions through normalize/toRDF

2018-11-24

  • Release 0.12.3
  • Fix NaN/Inf/-Inf raw value types on conversion to RDF
  • Added fix for wrong rdf:type to @type conversion (Path by @umbreak)
  • Open up Context.getTypeMapping and Context.getLanguageMapping for reuse

2018-11-03

  • W3c json ld syntax 34 allow container set on aliased type (Patch by @dr0i)
  • Release 0.12.2

2018-09-05

  • handle omit graph flag (Patch by @eroux)
  • Release 0.12.1
  • Make pruneBlankNodeIdentifiers false by default in 1.0 mode and always true in 1.1 mode (Patch by @eroux)
  • Fix issue with blank node identifier pruning when @id is aliased (Patch by @eroux)
  • Allow wildcard {} for @id in framing (Patch by @eroux)

2018-07-07

  • Fix tests setup for schema.org with HttpURLConnection that break because of the inability of HttpURLConnection to redirect from HTTP to HTTPS

2018-04-08

  • Release 0.12.0
  • Encapsulate RemoteDocument and make it immutable

2018-04-03

  • Fix performance issue caused by not caching schema.org and others that use Cache-Control: private (Patch by @HansBrende)
  • Cache classpath scans for jarcache.json to fix a similar performance issue
  • Add internal shaded dependency on Google Guava to use maintained soft and weak reference maps rather than adhoc versions
  • Make JsonLdError a RuntimeException to improve its use in closures
  • Bump minor version to 0.12 to reflect the API incompatibility caused by JsonLdError and protected field change and hiding in JarCacheStorage

2018-01-25

  • Fix resource leak in JsonUtils.fromURL on unsuccessful requests (Patch by @plaplaige)

2017-11-15

  • Ignore UTF BOM (Patch by @christopher-johnson)

2017-08-26

  • Release 0.11.1
  • Fix @embed:@always support (Patch by @dr0i)

2017-08-24

  • Release 0.11.0

2017-08-22

  • Add implicit "flag only" subframe to fix incomplete list recursion (Patch by @christopher-johnson)
  • Support pruneBlankNodeIdentifiers framing option in 1.1 mode (Patch by @fsteeg and @eroux)
  • Support new @embed values (Patch by @eroux)

2017-07-11

  • Add injection of contexts directly into DocumentLoader (Patch by @ryankenney)
  • Fix N-Quads content type (Patch by @NicolasRouquette)
  • Add JsonUtils.fromJsonParser (Patch by @dschulten)

2017-02-16

  • Make literals compare consistently (Patch by @stain)
  • Release 0.10.0

2017-01-09

  • Propagate causes for JsonLdError instances where they were caused by other Exceptions
  • Remove schema.org hack as it appears to work again now...
  • Remove deprecated and unused APIs
  • Bump version to 0.10.0-SNAPSHOT per the removed/changed APIs

2016-12-23

  • Release 0.9.0
  • Fixes schema.org support that is broken with Apache HTTP Client but works with java.net.URL

2016-05-20

  • Fix reported NPE in JsonLdApi.removeDependents

2016-05-18

  • Release 0.8.3
  • Fix @base in remote contexts corrupting the local context

2016-04-23

  • Support @default inside of sets for framing

2016-02-29

  • Fix ConcurrentModificationException in the implementation of the Framing API

2016-02-17

  • Re-release version 0.8.2 with the refactoring work actually in it. 0.8.1 is identical in functionality to 0.8.0
  • Release version 0.8.1
  • Refactor JSONUtils and DocumentLoader to move most of the static logic into JSONUtils, and deprecate the DocumentLoader versions

2016-02-10

  • Release version 0.8.0

2015-11-19

  • Replace deprecated HTTPClient code with the new builder pattern
  • Chain JarCacheStorage to any other HttpCacheStorage to simplify the way local caching is performed
  • Bump version to 0.8.0-SNAPSHOT as some interface method parameters changed, particularly, DocumentLoader.setHttpClient changed to require CloseableHttpClient that was introduced in HttpClient-4.3

2015-11-16

  • Bump dependencies to latest versions, particularly HTTPClient that is seeing more use on 4.5/4.4 than the 4.2 series that we have used so far
  • Performance improvements for serialisation to N-Quads by replacing string append and replace with StringBuilder
  • Support setting a system property, com.github.jsonldjava.disallowRemoteContextLoading, to "true" to disable remote context loading.

2015-09-30

  • Release 0.7.0

2015-09-27

  • Move Tools, Clerezza and RDF2GO modules out to separate repositories. The Tools repository had a circular build dependency with Sesame, while the other modules are best located and managed in separate repositories

2015-08-25

  • Remove Sesame-2.7 module in favour of sesame-rio-jsonld for Sesame-2.8 and 4.0
  • Fix bug where parsing did not fail if content was present after the end of a full JSON top level element

2015-03-12

  • Compact context arrays if they contain a single element during compaction
  • Bump to Sesame-2.7.15

2015-03-01

  • Use jopt-simple for the playground cli to simplify the coding and improve error messages
  • Allow RDF parsing and writing using all of the available Sesame Rio parsers through the playground cli
  • Make the httpclient dependency OSGi compliant

2014-12-31

  • Fix locale sensitive serialisation of XSD double/decimal typed literals to always be Locale.US
  • Bump to Sesame-2.7.14
  • Bump to Clerezza-0.14

2014-11-14

  • Fix identification of integer, boolean, and decimal in RDF-JSONLD with useNativeTypes
  • Release 0.5.1

2014-10-29

  • Add OSGi metadata to Jar files
  • Bump to Sesame-2.7.13

2014-07-14

  • Release version 0.5.0
  • Fix Jackson parse exceptions being propagated through Sesame without wrapping as RDFParseExceptions

2014-07-02

  • Fix use of Java-7 API so we are still Java-6 compatible
  • Ensure that Sesame RDFHandler endRDF and startRDF are called in SesameTripleCallback

2014-06-30

  • Release version 0.4.2
  • Bump to Sesame-2.7.12
  • Remove Jena integration module, as it is now maintained by Jena team in their repository

2014-04-22

  • Release version 0.4
  • Bump to Sesame-2.7.11
  • Bump to Jackson-2.3.3
  • Bump to Jena-2.11.1

2014-03-26

  • Bump RDF2GO to version 5.0.0

2014-03-24

  • Allow loading remote @context from bundled JAR cache
  • Support JSON array in @context with toRDF
  • Avoid exception on @context with default @language and unmapped key

2014-02-24

  • Javadoc some core classes, JsonLdProcessor, JsonLdApi, and JsonUtils
  • Rename some core classes for consistency, particularly JSONUtils to JsonUtils and JsonLdTripleCallback
  • Fix for a Context constructor that wasn't taking base into account

2014-02-20

  • Fix JsonLdApi mapping options in framing algorithm (Thanks Scott Blomquist @sblom)

2014-02-06

  • Release version 0.3
  • Bump to Sesame-2.7.10
  • Fix Jena module to use new API

2014-01-29

  • Updated to final Recommendation
  • Namespaces supported by Sesame integration module
  • Initial implementation of remote document loading
  • Bump to Jackson-2.3.1

2013-11-22

  • updated jena writer

2013-11-07

  • Integration packages renamed com.github.jsonldjava.sesame, com.github.jsonldjava.jena etc. (Issue #76)

2013-10-07

  • Matched class names to Spec
  • Renamed JSONLDException to JsonLdError
  • Renamed JSONLDProcessor to JsonLdApi
  • Renamed JSONLD to JsonLdProcessor
  • Renamed ActiveContext to Context
  • Renamed Options to JsonLdOptions
  • All context related utility functions moved to be members of the Context class

2013-09-30

  • Fixed JSON-LD to Jena to handle of BNodes

2013-09-02

  • Add RDF2Go integration
  • Bump Sesame and Clerezza dependency versions

2013-06-18

  • Bump to version 0.2
  • Updated Turtle integration
  • Added Caching of contexts loaded from URI
  • Added source formatting eclipse config
  • Fixed up seasame integration package names
  • Replaced depreciated Jackson code

2013-05-19

  • Added Turtle RDFParser and TripleCallback
  • Changed Maven groupIds to com.github.jsonld-java to match github domain.
  • Released version 0.1

2013-05-16

  • Updated core code to match JSON-LD 1.0 Processing Algorithms and API / W3C Editor's Draft 14 May 2013
  • Deprecated JSONLDSerializer in favor of the RDFParser interface to better represent the purpose of the interface and better fit in with the updated core code.
  • Updated the JSONLDTripleCallback to better fit with the updated code.
  • Updated the Playground tool to support updated core code.

2013-05-07

  • Changed base package names to com.github.jsonldjava
  • Reverted version to 0.1-SNAPSHOT to allow version incrementing pre 1.0 while allowing a 1.0 release when the json-ld spec is finalised.
  • Turned JSONLDTripleCallback into an interface.

2013-04-18

  • Updated to Sesame 2.7.0, Jena 2.10.0, Jackson 2.1.4
  • Fixing a character encoding issue in the JSONLDProcessorTests
  • Bumping to 1.0.1 to reflect dependency changes

2012-10-30

  • Brought the implementation up to date with the reference implementation (minus the normalization stuff)
  • Changed entry point for the functions to the static functions in the JSONLD class
  • Changed the JSONLDSerializer to an abstract class, requiring the implementation of a "parse" function. The JSONLDSerializer is now passed to the JSONLD.fromRDF function.
  • Added JSONLDProcessingError class to handle errors more efficiently

Considerations for 1.0 release / optimisations

  • The Context class is a Map and many of the options are stored as values of the map. These could be made into variables, whice should speed things up a bit (the same with the termDefinitions variable inside the Context).
  • some sort of document loader interface (with a mockup for testing) is required

jsonld-java's People

Contributors

abrokenjester avatar afs avatar ansell avatar christopher-johnson avatar dr0i avatar elahrvivaz avatar eroux avatar florent-andre avatar fsteeg avatar hansbrende avatar hmottestad avatar ismriv avatar jhg023 avatar kaefer3000 avatar kishorkunal-raj avatar kmax avatar lroffia avatar mhgrove avatar nicolasrouquette avatar nvdk avatar peacekeeper avatar rvesse avatar sblom avatar skahmann avatar stain avatar stuehmer avatar tjb1982 avatar tristan avatar ubbo avatar umbreak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonld-java's Issues

prefixes not resolved in @context

the following json-ld:

{
"@context": {
"Person": "foaf:Person",
"foaf": "http://xmlns.com/foaf/0.1/",
"name": "foaf:name"
},
"@type": "Person",
"name": "Santa Claus"
}

should expand to (from http://json-ld.org/playground/):

_:t0 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://xmlns.com/foaf/0.1/Person .
_:t0 http://xmlns.com/foaf/0.1/name "Santa Claus" .

but I get:

_:t0 http://www.w3.org/1999/02/22-rdf-syntax-ns#type foaf:Person.
_:t0 foaf:name "Santa Claus"^^http://www.w3.org/2001/XMLSchema#string.

JenaJSONLDSerializer does not implement JSONLDSerializer

On the current code JSONLDSerializer and JenaJSONLDSerializer does not have the same methods. so instead of:

JSONLDSerializer serializer = new JenaJSONLDSerializer();

You should use:

JenaJSONLDSerializer serializer = new JenaJSONLDSerializer();

That's not a big deal, but it's a bad practice on API design according the Faรงade pattern.

Position of @id and @type

Is there a way to ensure that the @id and @type show up at the top of the JSON object? I know it doesn't matter from a JSON perspective, but it makes the JSON so much easier to read if those two key/value pairs are at the top. Other JSON-LD implementations (the JSON-LD Playground, and the Ruby library https://github.com/gkellogg/json-ld) place the @id and @type at the top.

Use different Java packages for different modules

I tried to convert jsonld-java to OSGi bundles, but I could not get it to work. One of the issues was that the package com.github.jsonldjava.impl is used across several modules - which causes some headaches with OSGi as it assumes a package only lives within a single module/JAR (multiple packages inside the same is OK, though).

It is also not good that these packages are called .impl when they are meant to be used from the outside - OSGi normally prevents access to .impl subpackages.

So the suggestion is to rename the packages to match the modules, so say com.github.jsonldjava.jena, com.github.jsonldjava.sesame, etc. This would normally mean a bump in major version as an API change - hopefully we can still get away with this as last release was version 0.2 ("Major version zero (0.y.z) is for initial development. Anything may change at any time. The public API should not be considered stable." - http://semver.org/)

Core can stay as it is although you should not need to access anything in the .impl - this should be fine as is since both NQuad/Turtle Parser/Callback are accessible through the JSONLD class.

I can prepare the patch if you agree on this.

Remove DFKI parent pom requirement

The parent pom existed for internal reasons and is not needed outside of DFKI and I feel it should be removed for this to become a true OOS project.

Add OSGi bundle metadata for jar files

@stain and @retobg have both separately implemented support for OSGi bundles at different stages in the project but their work has not yet been pulled back into the main repository.

Although I don't use OSGi personally, my impression is that it is much easier for those who do if we add that metadata to all of the artifacts we publish. The bundle metadata has no effect on plain java users.

We would of course rely on the OSGi users to tell us if the metadata is either broken or missing something due to typos or other mistakes we make!

Release 0.2

It would be useful to release 0.2 to get the context handling patches @stain has contributed out in a release.

test failure

When running mvn install I get:

Failed tests:
runTest46: Expected object was null

My mvn -version:

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /home/reto/lib/apache-maven-3.0.3
Java version: 1.7.0_09, vendor: Oracle Corporation
Java home: /usr/local/lib/jdk1.7.0_09/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.5.0-27-generic", arch: "amd64", family: "unix"

Update code to match latest draft json-ld spec

This will be a recurring ticket until the json-ld specification has been finalised.

Make sure the code in this project matches the specification http://json-ld.org/spec/latest/.

The current code is heavily based off the javascript implementation found at https://github.com/json-ld/json-ld.org/blob/master/playground/jsonld.js (however, i'm working away from this as the algorithms in the json-ld-api document are much easier to work with than they were when I started writing this library) and is made to pass all of the tests found in https://github.com/json-ld/json-ld.org/tree/master/test-suite/tests .

toRDF needs explicit expand?

This is probably down to user trouble, I'm struggling to understand the json-ld specs.

I'm trying to test how to drive json-ld in a java environment with Jena (2.7.4) and find I need an explicit call to expand a json object before converting it to RDF. Is that expected?

Test data:

{
  "@context":
    {
      "foaf": "http://xmlns.com/foaf/0.1/",
      "name": "http://xmlns.com/foaf/0.1/name",
      "depiction":
        {
          "@id": "http://xmlns.com/foaf/0.1/depiction",
          "@type": "@id"
        },
      "homepage":
        {
          "@id": "http://xmlns.com/foaf/0.1/homepage",
          "@type": "@id"
        }
    },

          "@id" : "http://example.com/test",
          "name": "Manu Sporny",
          "homepage": "http://manu.sporny.org/",
          "depiction": "http://twitter.com/account/profile_image/manusporny",
          "foaf:dummy" : "foobar"
}

There may be errors in that data but I have tried lots of variants of this with arrays, with explicit @graph etc.

Driving code:

        InputStream inputStream = new FileInputStream(SRC);
        Object jsonObject = JSONUtils.fromInputStream(inputStream);
        System.out.println("Input is:" + jsonObject);

        Object expanded = JSONLD.expand(jsonObject);
        System.out.println("Expanded is:" + expanded);

        JenaTripleCallback callback = new JenaTripleCallback();
        Model m = ModelFactory.createDefaultModel();
        callback.setJenaModel(m);
//        JSONLD.toRDF(expanded, callback);
        JSONLD.toRDF(jsonObject, callback);
        System.out.println("Model = ");
        m.write(System.out, "Turtle");

If I swap the commenting to use the pre-expanded JSON I get back the RDF I expect. If I use the code as above I get the model:

<http://example.com/test>
      <foaf:dummy> "foobar" .

So the @context isn't being processed at all and the curie is being treated as if it were a URI.

Is that expected behaviour?

Dave

Change base package names to something more generic.

If enough people adopt this library as the standard json-ld library for java it makes sense to make the package names more generic. Perhaps talking to the guys designing the json-ld specification about using org.json-ld as the base package name. I feel this should be done before pushing the package into maven central.

Anyone have any thoughts or ideas on this issue?

Compile Error

Thanks for your contributuiion. This project is very helpful to me.
But, I got an error while complie as below. Please give me some help for this

mvn package -DskipTests -U
[INFO] Scanning for projects...
[INFO] Reactor build order:
[INFO] JSONLD Java :: Parent
[INFO] JSONLD Java :: Core
[INFO] JSONLD Java :: Integration Modules Parent
[INFO] JSONLD Java :: Sesame Integration
[INFO] JSONLD Java :: Jena Integration
[INFO] JSONLD Java :: Clerezza Integration
[INFO] JSONLD Java :: Tools
[INFO] ------------------------------------------------------------------------
[INFO] Building JSONLD Java :: Parent
[INFO] task-segment: [package]
[INFO] ------------------------------------------------------------------------
[INFO] [enforcer:enforce {execution: enforce-maven}]
[INFO] [site:attach-descriptor {execution: default-attach-descriptor}]
[INFO] ------------------------------------------------------------------------
[INFO] Building JSONLD Java :: Core
[INFO] task-segment: [package]
[INFO] ------------------------------------------------------------------------
[INFO] [enforcer:enforce {execution: enforce-maven}]
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /tmp/jsonld-java/core/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources {execution: default-testResources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 454 resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire:test {execution: default-test}]
[INFO] Tests are skipped.
[INFO] [jar:jar {execution: default-jar}]
[INFO] [jar:test-jar {execution: default}]
[INFO] ------------------------------------------------------------------------
[INFO] Building JSONLD Java :: Integration Modules Parent
[INFO] task-segment: [package]
[INFO] ------------------------------------------------------------------------
[INFO] [enforcer:enforce {execution: enforce-maven}]
[INFO] [site:attach-descriptor {execution: default-attach-descriptor}]
[INFO] ------------------------------------------------------------------------
[INFO] Building JSONLD Java :: Sesame Integration
[INFO] task-segment: [package]
[INFO] ------------------------------------------------------------------------
[INFO] [enforcer:enforce {execution: enforce-maven}]
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 6 source files to /tmp/jsonld-java/integration/sesame/target/classes
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure

/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDWriter.java:[21,30] error: cannot find symbol

could not parse error message: symbol: class RDFWriterBase
location: package org.openrdf.rio.helpers
/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDWriter.java:32: error: cannot find symbol
public class SesameJSONLDWriter extends RDFWriterBase implements RDFWriter {
^

could not parse error message: symbol: class RDFWriterBase
/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDParser.java:56: error: valueFactory has private access in RDFParserBase
getRDFHandler(), valueFactory);
^

/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDParser.java:[61,11] error: no suitable constructor found for RDFParseException(String,JSONLDProcessingError)

constructor RDFParseException.RDFParseException(Throwable,int,int) is not applicable
  (actual and formal argument lists differ in length)
constructor RDFParseException.RDFParseException(Throwable) is not applicable
  (actual and formal argument lists differ in length)
constructor RDFParseException.RDFParseException(String,int,int) is not applicable
  (actual and formal argument lists differ in length)
constructor RDFParseException.RDFParseException(String) is not applicable
  (actual and formal argument lists differ in length)

/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDParser.java:[69,19] error: valueFactory has private access in RDFParserBase

/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDParser.java:[74,11] error: no suitable constructor found for RDFParseException(String,JSONLDProcessingError)

constructor RDFParseException.RDFParseException(Throwable,int,int) is not applicable
  (actual and formal argument lists differ in length)
constructor RDFParseException.RDFParseException(Throwable) is not applicable
  (actual and formal argument lists differ in length)
constructor RDFParseException.RDFParseException(String,int,int) is not applicable
  (actual and formal argument lists differ in length)
constructor RDFParseException.RDFParseException(String) is not applicable
  (actual and formal argument lists differ in length)

/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDWriterFactory.java:[28,8] error: incompatible types

could not parse error message: required: RDFWriter
found: SesameJSONLDWriter
/tmp/jsonld-java/integration/sesame/src/main/java/de/dfki/km/json/jsonld/impl/SesameJSONLDWriterFactory.java:33: error: incompatible types
return new SesameJSONLDWriter(writer);
^

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4 seconds
[INFO] Finished at: Wed Mar 20 12:52:09 GMT 2013
[INFO] Final Memory: 34M/278M
[INFO] ------------------------------------------------------------------------

Unusable current snapshot

I've using your Java implementation for Java for a couple of months, but updating to the snapshot version you're publishing via your maven repo I can't get it work again. After change some code to adapt it to the new API, I'm getting the following error:

java.lang.NullPointerException
at de.dfki.km.json.jsonld.JSONLDUtils.compactIRI(JSONLDUtils.java:143)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:389)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:265)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:282)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:206)
at de.dfki.km.json.jsonld.JSONLDSerializer.asObject(JSONLDSerializer.java:158)
at org.fundacionctic.su4j.endpoint.formatter.JSONLDFormatter.serialize(JSONLDFormatter.java:34)
at org.fundacionctic.su4j.endpoint.formatter.SparqlHttpResultFormatter.format(SparqlHttpResultFormatter.java:69)
at org.fundacionctic.su4j.endpoint.DefaultSparqlEndpoint.query(DefaultSparqlEndpoint.java:249)
at org.fundacionctic.su4j.endpoint.demo.SparqlServlet.doGet(SparqlServlet.java:31)

You can see the code throwing such error at https://bitbucket.org/fundacionctic/su4j/src/e2a7d196de2d/libs/su4j-endpoint/src/main/java/org/fundacionctic/su4j/endpoint/formatter/JSONLDFormatter.java#cl-34

Any idea what going wrong?

Using ServiceLoader to automatically load RDFParsers and TripleCallbacks

I'm interested to see if we can use the java.util.ServiceLoader concept to automatically load RDFParsers and TripleCallbacks that are on the classpath.

The key things to figure out will be:

  • Content negotiation (especially for the TripleCallback): either the basic form of having a .canHandle(Input.class) method, or perhaps we can do something with generics (e.g. jsonld = JSONLD.fromRDF<jena.Model>(model) and model = JSONLD.toRDF<jena.Model>(jsonld)).
  • how to make sure state isn't held in the callbacks, as the serviceloader only instantiates each service once. perhaps each interface needs an .initialize(Options) method to make sure they reset their state.

Look at re-designing JSONLDSerializer as an interface

The base JSONLDSerializer class currently has a lot of non-trivial code and core code requires the existance of methods that are not implementation specific (i.e. the non-abstract methods in the current incarnation).

Look into whether we can move the non-trivial code out of the class and allow it to become an interface.

Advice: v0.2 or v0.3?

I want to propose a release of Jena, and I'd like to include JSON-LD. That means Jena will depend on jsonld-java/jsonld-java/core and that in-turn needs a stable, non-snapshot version.

What is your advice - release, depending on the current v0.2 or wait a short while for v0.3, if that is imminent?

jsonld2rdf

It would help making use of JSON-LD to have another script jsonld2rdf to create NTriples from JSON-LD. One should be able to specify a JSON-LD file and an optional context file.

Requirement for ignoreKeys and simplify functionality

Since I don't have any projects requiring them, and they're not part of the JSON-LD specification I have not re-implemented either of these functionalities in the core code.

simplify still exists, but there are no tests for it anymore and I haven't updated it at all so i'm not sure of how it functions any more.

If anyone actually needs this functionality I may look at re-implementing them.

Attribution for new port

I have been working on a port of the json-ld api for objective-c, the port is loosely based on this java port.

I'd like to give the appropriate attribution, as my port is in a different language and not directly derived from the Java, should I still include your BSD license in the header along with the projects own header, or would attribution in the project README be more appropriate.

Or would there be a better form of attribution.

Andy

Jena dependency upgrade

Would be possible to update the dependency to Jena to the latest stable release (2.7.0-incubating?

The API is fully compatible with the 2.6.x branch.

It might help to avoid the usage of exclusion assert in other projects that are already using it.

Incorrect version in jena integration readme

  1. The version of Jena should be 2.11.0
  2. the should be 0.2.0 or 0.3-SNAPSHOT, I don't think that 0.3.0 has been released yet.

JSONLD-Java Jena integration module
This module integrates JSONLD-Java with Jena 0.11.0 or later.

There are several levels of integration, detailed under Usage below.

USAGE
From Maven

com.github.jsonld-java jsonld-java-jena 0.3.0

Namespaces not populated by JSON-LD parser with Sesame

Hi,

The following JUnit test fails when loading the following trivial JSON-LD file into Sesame, as the JSON-LD parser doesn't seem to be populating Sesame's namespaces Map. I would really like to preserve the namespaces defined in my JSON-LD file when working in Java (reading the equivalent Turtle file below works fine) - but is this possible with the current JSON-LD Java parser...?

"NamespaceTest.jsonld":

{
"@context": {
"ex": "http://example.org#"
},

"@id": "ex:test",
"ex:greeting": "Hello"
}

The same test works fine for this equivalent Turtle representation:

"NamespaceTest.ttl":

@Prefix ex: http://example.org# .

ex:test ex:greeting "Hello" .

package com.dnb.ontology.codegenerator;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.StatementCollector;
import org.openrdf.sail.memory.MemoryStore;

public class JsonLdNamespaceTest {
@test
public void testWithTurtle() throws RepositoryException, IOException, RDFParseException, RDFHandlerException {
namespacesLoaded("ontologies/NamespaceTest.ttl");
}

@Test
public void testWithJsonLd() throws RepositoryException, IOException, RDFParseException, RDFHandlerException {
    namespacesLoaded("ontologies/NamespaceTest.jsonld");
}


public void namespacesLoaded(final String filename) {
    try {
        final Repository repository = new SailRepository(new MemoryStore());
        repository.initialize();

        final java.net.URL documentUrl = JsonLdNamespaceTest.class.getClassLoader().getResource(filename);
        if (documentUrl == null) {
            throw new IllegalArgumentException("Could not resolve file from classpath: [" + filename + "]");
        }

        final InputStream inputStream = documentUrl.openStream();
        RDFParser rdfParser = Rio.createParser(RDFFormat.forFileName(filename));

        final org.openrdf.model.Model myGraph = new org.openrdf.model.impl.LinkedHashModel();
        final Map<String, String> namespaces = new HashMap<String, String>();

        rdfParser.setRDFHandler(new StatementCollector(myGraph, namespaces));

        rdfParser.parse(inputStream, documentUrl.toString());

        Assert.assertEquals(1, namespaces.size());
        Assert.assertEquals("http://example.org#", namespaces.get("ex"));
    } catch (RepositoryException ex) {
        Assert.fail(ex.toString());
    } catch (IOException ex) {
        Assert.fail(ex.toString());
    } catch (RDFParseException ex) {
        Assert.fail(ex.toString());
    } catch (RDFHandlerException ex) {
        Assert.fail(ex.toString());
    }
}

}

Replace current jena module with @afs's jena-jsonld project.

https://github.com/afs/jena-jsonld

My initial thoughts would be to put the RDFParser and TripleCallback into the com.github.jsonldjava.x (i use x because i'm thinking about changing it from impl, like it is at the moment, to something more module specific) and put the riot stuff in com.github.jsonldjava.x.riot. Does that makes sense?

This also seems like something that Jena may want to have integrated directly, but I suppose there's not a lot of difference between them hosting the code themselves and simply adding the module as a dependency and calling this code.

Perhaps we should at least look at the structure of Jena's Lang code and see if we can lay out the riot stuff such that it matches their code structure (if that makes sense).

Need to print JSON-LD without @graph

I want to print like:
{
"@context": {
"name": "http://xmlns.com/foaf/0.1/name",
"homepage": {
"@id": "http://xmlns.com/foaf/0.1/homepage",
"@type": "@id"
}
},
"homepage": "http://manu.sporny.org/",
"name": "Manu Sporny"
}

But when I use

Model modelResult = ModelFactory.createDefaultModel().read(is, "",
"RDF/XML");
JenaRDFParser parser = new JenaRDFParser();
Object json = JSONLD.simplify(JSONLD.fromRDF(modelResult, parser));
System.out.println("JSON: " + JSONUtils.toPrettyString(json));

It prints like:

{
"@context": {
"name": "http://xmlns.com/foaf/0.1/name",
"homepage": {
"@id": "http://xmlns.com/foaf/0.1/homepage",
"@type": "@id"
}
},
"@graph": [{
"@id": "_:b0",
"homepage": "http://manu.sporny.org/",
"name": "Manu Sporny"
}, {
"@id": "http://manu.sporny.org/"
}]
}

add LICENSE

This project does not provide any license information.

Would be great if this would be available under a permissive License such as Apache License, MIT or BSD

NullPointerException serializing to raw json

With the current verison of the code the repository, I'm getting:

  java.lang.NullPointerException
at de.dfki.km.json.jsonld.JSONLDUtils.compactIRI(JSONLDUtils.java:145)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:350)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:243)
at de.dfki.km.json.jsonld.impl.JSONLDProcessorImpl.compact(JSONLDProcessorImpl.java:168)
at de.dfki.km.json.jsonld.JSONLDSerializer.asObject(JSONLDSerializer.java:167)
at org.fundacionctic.su4j.endpoint.formatter.JSONLDFormatter.serialize(JSONLDFormatter.java:43)
at org.fundacionctic.su4j.endpoint.formatter.SparqlHttpResultFormatter.format(SparqlHttpResultFormatter.java:84)
at org.fundacionctic.su4j.endpoint.DefaultSparqlEndpoint.query(DefaultSparqlEndpoint.java:263)
at org.fundacionctic.su4j.endpoint.demo.SparqlServlet.doGet(SparqlServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:828)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:514)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:450)

Both with serializer.asString() and JSONUtils.toString(serializer.asObject())

The code is available at https://bitbucket.org/fundacionctic/su4j/src/76d923ce89e5/libs/su4j-endpoint/src/main/java/org/fundacionctic/su4j/endpoint/formatter/JSONLDFormatter.java#cl-43

Integration module for OWLAPI

@stain mentioned on twitter that it would be nice to have a tighter integration of OWLAPI and JSONLD-Java.

This will likely take two different approaches:

  • Creating JSON-LD contexts out of OWL ontologies
  • Parsing and rendering full JSON-LD documents to and from OWLAPI

The first is novel, as far as I know, while the second can be implemented by adding JSON-LD as a supported format for OWLAPI-RIO, while using the Sesame integration module as the bridge.

Single triple <urn:foo, a, urn:myType> generates 2 JSON objects

Serialising a model with the following triple:
<urn:foo, a, urn:myType>

Generates the following JSON:
[{@id=urn:foo, @type=[urn:myType]}, {@id=urn:myType}]

I would expect to obtain this instead (as in previous versions of jsonld-java):
{@id=urn:foo, @type=[urn:myType]}

I have played around with Options, but haven't managed to get to the desired result. Is there a way to tell the parser to skip those objects?

PS: I've tried with the Jena and Sesame's parsers, as well as the RDF2Go one.

Verify tests against Proposed Recommendation

The W3C published a Proposed Recommendation for JSONLD (05 November 2013)

We should verify that our implementation still matches that with any changes since the Candidate Recommendation (10 September 2013) and then release a version 0.3

I don't think it is a good time to release a 1.0 version as we still have not stabilised the public API, so I recommend going to 0.4 after that for any cleanups from the recent changes, possibly reverting them to something similar to the previous option.

(@tristan If possible, when you cleanup the API could you start off with the current master to avoid the merging hassles from last time)

Jackson call in JSONUtils closes Writer

The JSONUtils.write method calls a Jackson method that closes the writer.

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValue(w, jsonObject);

The offending location is in jackson-mapper-asl:

    if (cfg.isEnabled(SerializationConfig.Feature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
        _configAndWriteCloseable(jgen, value, cfg);

This seems to imply that we could disable the CLOSE_CLOSEABLE feature in a configuration.

inconvenient representation for data properties

If definition contains the data and object properties like

<network_layer3:controlIPAddress>122.22.33.4</network_layer3:controlIPAddress>
<vlan:otherName rdf:resource=".../instance.owl#2"/>

JSON-LD-JAVA converts that to

{@context: {
"controlIPAddress" : "http://...#controlIPAddress",
    "string" : {
      "@id" : "http://www.w3.org/2001/XMLSchema#string",
      "@type" : "@id"
    },

"otherName" : {
      "@id" : "http://..../vlan.owl#otherName",
      "@type" : "@id"
    }
},

data: {
"@id" : "Client3-sw1-eth0/1-vlan2",
    "@type" : "Thing",
    "controlIPAddress" : {
      "@type" : "string",
      "@value" : "122.22.33.4"
    },
    "otherName" : "http://url#2"
}}

Is not any way to handle controlIPAddress like you handle otherName (like: "controlIPAddress" : "122.22.33.4") without creating the inner data structure? I'm converting the resulting JSON to the class instance, which has two properties controlIPAddress and otherName.

ClassNotFoundException for apache http library

I am importing the jsonld-java-sesame-0.2 maven module, in the runtime scope, as part of a maven integration test, and I am getting the following exception:

java.lang.ClassNotFoundException: org.apache.http.impl.client.SystemDefaultHttpClient
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:413)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:366)
at com.github.jsonldjava.impl.SesameJSONLDWriter.endRDF(SesameJSONLDWriter.java:99)
at org.openrdf.repository.sail.SailRepositoryConnection.exportStatements(SailRepositoryConnection.java:262)
at org.openrdf.repository.base.RepositoryConnectionBase.export(RepositoryConnectionBase.java:173)

@list not correctly expanded

@list is not correctly expanded to rdf:first and :rest statements, instead TripleCallback#triple is invoked with @list as predicate.

So parsing a file like simplify-0001-in.jsonld in testfiles doesn't result in the correct 10 triples, but in the following 9 (of which one has the invalid predicate uri @list):

_:2 http://www.w3.org/2001/XMLSchema#maxLength "1024"^^http://www.w3.org/2001/XMLSchema#nonNegativeInteger.
http://qudt.org/schema/qudt#string1024 http://www.w3.org/2000/01/rdf-schema#label "string1024"^^http://www.w3.org/2001/XMLSchema#string.
http://qudt.org/schema/qudt#string1024 http://www.w3.org/2002/07/owl#equivalentClass _:1.
http://qudt.org/schema/qudt#string1024 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2000/01/rdf-schema#Datatype.
http://qudt.org/schema/qudt#string1024 http://www.w3.org/2000/01/rdf-schema#subClassOf http://www.w3.org/2001/XMLSchema#string.
_:3 @list _:2.
_:1 http://www.w3.org/2002/07/owl#withRestrictions _:3.
_:1 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2000/01/rdf-schema#Datatype.
_:1 http://www.w3.org/2002/07/owl#onDatatype http://www.w3.org/2001/XMLSchema#string.

The following would be correct (from the jsonld playground):
http://qudt.org/schema/qudt#string1024 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2000/01/rdf-schema#Datatype .
http://qudt.org/schema/qudt#string1024 http://www.w3.org/2000/01/rdf-schema#label "string1024" .
http://qudt.org/schema/qudt#string1024 http://www.w3.org/2000/01/rdf-schema#subClassOf http://www.w3.org/2001/XMLSchema#string .
http://qudt.org/schema/qudt#string1024 http://www.w3.org/2002/07/owl#equivalentClass _:t0 .
_:t0 http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2000/01/rdf-schema#Datatype .
_:t0 http://www.w3.org/2002/07/owl#onDatatype http://www.w3.org/2001/XMLSchema#string .
_:t0 http://www.w3.org/2002/07/owl#withRestrictions _:t1 .
_:t1 http://www.w3.org/1999/02/22-rdf-syntax-ns#first _:t2 .
_:t1 http://www.w3.org/1999/02/22-rdf-syntax-ns#rest http://www.w3.org/1999/02/22-rdf-syntax-ns#nil .
_:t2 http://www.w3.org/2001/XMLSchema#maxLength "1024"^^http://www.w3.org/2001/XMLSchema#nonNegativeInteger .

Problem with @type

I have a problem with toPrettyString outputting the correct type for a string. For some reason, the resulting JSON doesn't have any @type for the "ABC", but it does for "123". They are both using the same xsd:string type! I tested this using the 083ac36 commit.

See my test case and output below:

import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.jsonldjava.core.JSONLD;
import com.github.jsonldjava.core.JSONLDProcessingError;
import com.github.jsonldjava.impl.JenaRDFParser;
import com.github.jsonldjava.utils.JSONUtils;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;

public class JsonLDTest {

private static Logger logger = LoggerFactory
        .getLogger(ConstellationQueryUtils.class);

@Test
public void test() throws JSONLDProcessingError {

    String turtle = "prefix const: <http://foo.com/> \n"
            + "prefix xsd: <http://www.w3.org/2001/XMLSchema#>\n"
            + "<http://localhost:8080/foo1>\n"
            + "const:code \"123\"^^xsd:string  .\n"
            + "<http://localhost:8080/foo2>\n"
            + "const:code \"ABC\"^^xsd:string .\n";

    InputStream is = IOUtils.toInputStream(turtle);
    Model modelResult = ModelFactory.createDefaultModel().read(is, "",
            "TURTLE");
    JenaRDFParser parser = new JenaRDFParser();
    Object json = JSONLD.fromRDF(modelResult, parser);
    logger.info("JSON: " + JSONUtils.toPrettyString(json));

}

}

The above code produces this output:
16:52:33 INFO ConstellationQueryUtils :: JSON: [ {
"@id" : "http://localhost:8080/foo1",
"http://foo.com/code" : [ {
"@value" : "123",
"@type" : "http://www.w3.org/2001/XMLSchema#string"
} ]
}, {
"@id" : "http://localhost:8080/foo2",
"http://foo.com/code" : [ {
"@value" : "ABC"
} ]
} ]

Add code formatting style files

To make it easier to contribute to the project it would be nice to have code formatting style files to enable automatic reformatting to keep patches clean.

Javadocs..?

Is it possible to write and generate some Javadocs for the most important bits of the library? It can be a bit difficult for newcomers, specially as they might not even know Jackson from before.

fromRDF and RDFParser API

This ticket is for discussion on the current API for the fromRDF and RDFParser API methods. Any comments, constructive critisizm or change suggestions are welcome.

Sesame integration

Hi,

Would like to use jsonld-java with sesame 2.7.9 but i have the following error:
UnsupportedRDFormatException No writer factory available for RDF format JSON-LD (mimeTypes=application/ld+json; ext=jsonld) org.openrdf.rio.Rio.createWriter (Rio.java:236)

I don't know exactly how to proceed ?

Thanks,

Samuel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.