Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions integration/clerezza/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,46 @@ Note: this is the documentation for the current unstable development branch. [Fo
JSONLD-Java Clerezza Integration module
=======================================

This module provide a `ParsingProvider`and `SerializingProvider` for Apache Clerezza. Those Providers plug into the Clerezza `Parser` and `Serializer` service infrastructure. Meaning that adding this bundle will allow Clerezza to parse and serialize JSON-LD.

USAGE
=====

From Maven
----------
Maven Dependency
----------------

<dependency>
<groupId>com.github.jsonld-java</groupId>
<artifactId>jsonld-java-clerezza</artifactId>
<version>0.4-SNAPSHOT</version>
<version>0.6.1-SNAPSHOT</version>
</dependency>

(Adjust for most recent <version>, as found in ``pom.xml``).

From OSGI
---------

Assuming the above Bundle is active in the OSGI Environment one can simple inject the `Serializer` and/or `Parser` service.

@Reference
private Serializer serializer;

@Reference
private Parser parser;


Normal Java
-----------

Both the `Parser` and `Serializer` also support `java.util.ServiceLoader`. So when running outside an OSGI environment one can use the `getInstance()` to obtain an instance.

Serializer serializer = Serializer.getInstance();

Parser parser = Parser.getInstance();

ClerezzaTripleCallback
------------------
Supported Formats
-----------------

The ClerezzaTripleCallback returns an instance of `org.apache.clerezza.rdf.core.MGraph`
The JSON-LD parser implementation supports `application/ld+json`. The serializer supports both `application/ld+json` and `application/json`.

See [ClerezzaTripleCallbackTest.java](./src/test/java/com/github/jsonldjava/clerezza/ClerezzaTripleCallbackTest.java) for example Usage.
The rational behind this is that the parser can not parse any JSON however the Serializer does generate valid JSON.
34 changes: 27 additions & 7 deletions integration/clerezza/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
<developer>
<name>Peter Ansell</name>
</developer>
<developer>
<name>Rupert Westenthaler</name>
</developer>
</developers>

<dependencies>
Expand All @@ -32,17 +35,30 @@
<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>org.apache.clerezza</groupId>
<artifactId>rdf.core</artifactId>
</dependency>
<!-- OSGI related -->
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.annotations</artifactId>
</dependency>


<!-- Test dependencies -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jsonld-java</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.clerezza</groupId>
<artifactId>rdf.ontologies</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand All @@ -69,6 +85,10 @@
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.github.jsonldjava.clerezza;

import java.util.HashMap;
import java.util.Map;

import org.apache.clerezza.rdf.core.BNode;
import org.apache.clerezza.rdf.core.Language;
import org.apache.clerezza.rdf.core.Literal;
import org.apache.clerezza.rdf.core.NonLiteral;
import org.apache.clerezza.rdf.core.PlainLiteral;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.Triple;
import org.apache.clerezza.rdf.core.TripleCollection;
import org.apache.clerezza.rdf.core.TypedLiteral;
import org.apache.clerezza.rdf.core.UriRef;

import com.github.jsonldjava.core.JsonLdError;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.core.RDFDataset;
import com.github.jsonldjava.core.RDFParser;

/**
* Converts a Clerezza {@link TripleCollection} to the {@link RDFDataset} used
* by the {@link JsonLdProcessor}
*
* @author Rupert Westenthaler
*
*/
public class ClerezzaRDFParser implements RDFParser {

private static String RDF_LANG_STRING = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";

private long count = 0;

@Override
public RDFDataset parse(Object input) throws JsonLdError {
count = 0;
final Map<BNode, String> bNodeMap = new HashMap<BNode, String>(1024);
final RDFDataset result = new RDFDataset();
if (input instanceof TripleCollection) {
for (final Triple t : ((TripleCollection) input)) {
handleStatement(result, t, bNodeMap);
}
}
bNodeMap.clear(); // help gc
return result;
}

private void handleStatement(RDFDataset result, Triple t, Map<BNode, String> bNodeMap) {
final String subject = getResourceValue(t.getSubject(), bNodeMap);
final String predicate = getResourceValue(t.getPredicate(), bNodeMap);
final Resource object = t.getObject();

if (object instanceof Literal) {

final String value = ((Literal) object).getLexicalForm();
final String language;
final String datatype;
if (object instanceof TypedLiteral) {
language = null;
datatype = getResourceValue(((TypedLiteral) object).getDataType(), bNodeMap);
} else if (object instanceof PlainLiteral) {
// we use RDF 1.1 literals so we do set the RDF_LANG_STRING
// datatype
datatype = RDF_LANG_STRING;
final Language l = ((PlainLiteral) object).getLanguage();
if (l == null) {
language = null;
} else {
language = l.toString();
}
} else {
throw new IllegalStateException("Unknown Literal class "
+ object.getClass().getName());
}
result.addTriple(subject, predicate, value, datatype, language);
count++;
} else {
result.addTriple(subject, predicate, getResourceValue((NonLiteral) object, bNodeMap));
count++;
}

}

/**
* The count of processed triples (not thread save)
*
* @return the count of triples processed by the last {@link #parse(Object)}
* call
*/
public long getCount() {
return count;
}

private String getResourceValue(NonLiteral nl, Map<BNode, String> bNodeMap) {
if (nl == null) {
return null;
} else if (nl instanceof UriRef) {
return ((UriRef) nl).getUnicodeString();
} else if (nl instanceof BNode) {
String bNodeId = bNodeMap.get(nl);
if (bNodeId == null) {
bNodeId = Integer.toString(bNodeMap.size());
bNodeMap.put((BNode) nl, bNodeId);
}
return new StringBuilder("_:b").append(bNodeId).toString();
} else {
throw new IllegalStateException("Unknwon NonLiteral type " + nl.getClass().getName()
+ "!");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

public class ClerezzaTripleCallback implements JsonLdTripleCallback {

private static String RDF_LANG_STRING = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";

private MGraph mGraph = new SimpleMGraph();
private Map<String, BNode> bNodeMap = new HashMap<String, BNode>();

Expand Down Expand Up @@ -52,10 +54,10 @@ private void triple(String s, String p, String value, String datatype, String la
if (language != null) {
object = new PlainLiteralImpl(value, new Language(language));
} else {
if (datatype != null) {
object = new TypedLiteralImpl(value, new UriRef(datatype));
} else {
if(datatype == null || RDF_LANG_STRING.equals(datatype)){
object = new PlainLiteralImpl(value);
} else {
object = new TypedLiteralImpl(value, new UriRef(datatype));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jsonldjava.clerezza;

import java.io.IOException;
import java.io.InputStream;

import org.apache.clerezza.rdf.core.MGraph;
import org.apache.clerezza.rdf.core.UriRef;
import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.jsonldjava.core.JsonLdError;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.utils.JsonUtils;

/**
* A {@link org.apache.clerezza.rdf.core.serializedform.ParsingProvider} for
* JSON-LD (application/ld+json) based on the java-jsonld library
*
* @author Rupert Westenthaler
*
*/
@Component(immediate = true, policy = ConfigurationPolicy.OPTIONAL)
@Service
@SupportedFormat("application/ld+json")
public class JsonLdParsingProvider implements ParsingProvider {

private final Logger logger = LoggerFactory.getLogger(getClass());

@Override
public void parse(MGraph target, InputStream serializedGraph, String formatIdentifier,
UriRef baseUri) {
// The callback will add parsed triples to the target MGraph
final ClerezzaTripleCallback ctc = new ClerezzaTripleCallback();
ctc.setMGraph(target);
Object input;
int startSize = 0;
if (logger.isDebugEnabled()) {
startSize = target.size();
}
final long start = System.currentTimeMillis();
try {
input = JsonUtils.fromInputStream(serializedGraph, "UTF-8");
} catch (final IOException e) {
logger.error("Unable to read from the parsed input stream", e);
throw new RuntimeException(e.getMessage(), e);
}
try {
JsonLdProcessor.toRDF(input, ctc);
} catch (final JsonLdError e) {
logger.error("Unable to parse JSON-LD from the parsed input stream", e);
throw new RuntimeException(e.getMessage(), e);
}
if (logger.isDebugEnabled()) {
logger.debug(" - parsed {} triples in {}ms", target.size() - startSize,
System.currentTimeMillis() - start);
}
}

}
Loading