clerezza-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From r...@apache.org
Subject [1/2] clerezza git commit: CLEREZZA-966:moved rdfjson to be a child of rdf
Date Tue, 26 May 2015 08:44:22 GMT
Repository: clerezza
Updated Branches:
  refs/heads/master 9794006d0 -> c8293374e


http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/main/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializingProvider.java
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/main/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializingProvider.java
b/rdf/rdfjson/src/main/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializingProvider.java
new file mode 100644
index 0000000..b0b8991
--- /dev/null
+++ b/rdf/rdfjson/src/main/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializingProvider.java
@@ -0,0 +1,217 @@
+/*
+ * 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 org.apache.clerezza.rdf.rdfjson.serializer;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.clerezza.commons.rdf.BlankNode;
+import org.apache.clerezza.commons.rdf.BlankNodeOrIRI;
+import org.apache.clerezza.commons.rdf.RDFTerm;
+import org.apache.clerezza.commons.rdf.Triple;
+import org.apache.clerezza.commons.rdf.Graph;
+import org.apache.clerezza.commons.rdf.IRI;
+import org.apache.clerezza.commons.rdf.Literal;
+import org.apache.clerezza.rdf.core.serializedform.SerializingProvider;
+import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Service;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+
+/**
+ * A {@link org.apache.clerezza.rdf.core.serializedform.SerializingProvider} for
+ * rdf/json.
+ * 
+ * This implementation is based on first sorting the triples within the parsed
+ * {@link Graph} based on the {@link #SUBJECT_COMPARATOR subject}.
+ * <p>
+ * The serialization is done on a subject scope. Meaning that all triples for a
+ * subject are serialized and instantly written to the provided
+ * {@link OutputStream}.
+ * <p>
+ * 'UFT-8' is used as encoding to write the data.
+ * 
+ * @author tio, hasan, rwesten
+ */
+@Component(immediate = true)
+@Service(SerializingProvider.class)
+@SupportedFormat(SupportedFormat.RDF_JSON)
+public class RdfJsonSerializingProvider implements SerializingProvider {
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void serialize(OutputStream serializedGraph, Graph tc,
+            String formatIdentifier) {
+        if (tc.isEmpty()) { // ensure writing an empty element in case of an
+                            // empty collection
+            try {
+                serializedGraph.write(new JSONObject().toJSONString().getBytes(
+                        "UTF-8"));
+            } catch (IOException e) {
+                throw new IllegalStateException(
+                        "Exception while writing to parsed OutputStream", e);
+            }
+            return;
+        }
+        BlankNodeManager bNodeMgr = new BlankNodeManager();
+        BufferedWriter out;
+        try {
+            out = new BufferedWriter(new OutputStreamWriter(serializedGraph,
+                    "UTF-8"));
+        } catch (UnsupportedEncodingException e) {
+            throw new IllegalStateException(
+                    "Encoding 'UTF-8' is not supported by this System", e);
+        }
+        Triple[] sortedTriples = tc.toArray(new Triple[tc.size()]);
+        Arrays.sort(sortedTriples, SUBJECT_COMPARATOR);
+        Triple triple;
+        BlankNodeOrIRI subject = null;
+        String subjectStr = null;
+        IRI predicate = null;
+        Map<IRI, JSONArray> predicateValues = new HashMap<IRI, JSONArray>();
+        JSONObject jSubject = new JSONObject();
+        try {
+            out.write("{"); // start the root object
+            for (int i = 0; i < sortedTriples.length; i++) {
+                triple = sortedTriples[i];
+                boolean subjectChange = !triple.getSubject().equals(subject);
+                if (subjectChange) {
+                    if (subject != null) {
+                        // write the predicate values
+                        for (Entry<IRI, JSONArray> predicates : predicateValues
+                                .entrySet()) {
+                            jSubject.put(
+                                    predicates.getKey().getUnicodeString(),
+                                    predicates.getValue());
+                        }
+                        // write subject
+                        out.write(JSONObject.toString(subjectStr, jSubject));
+                        out.write(",");
+                        jSubject.clear(); // just clear
+                        predicateValues.clear();
+                    }
+                    // init next subject
+                    subject = triple.getSubject();
+                    if (subject instanceof BlankNode) {
+                        subjectStr = bNodeMgr.getBlankNodeId((BlankNode) subject);
+                    } else { // if (subject instanceof IRI)
+                        subjectStr = ((IRI) subject).getUnicodeString();
+                    }
+                }
+                predicate = triple.getPredicate();
+                JSONArray values = predicateValues.get(predicate);
+                if (values == null) {
+                    values = new JSONArray();
+                    predicateValues.put(predicate, values);
+                }
+                values.add(writeObject(bNodeMgr, triple.getObject()));
+            }
+            if (subjectStr != null) {
+                for (Entry<IRI, JSONArray> predicates : predicateValues
+                        .entrySet()) {
+                    jSubject.put(predicates.getKey().getUnicodeString(),
+                            predicates.getValue());
+                }
+                out.write(JSONObject.toString(subjectStr, jSubject));
+            }
+            out.write("}");// end the root object
+            out.flush();
+        } catch (IOException e) {
+            throw new IllegalStateException(
+                    "Exception while writing on the parsed OutputStream", e);
+        }
+    }
+
+    private class BlankNodeManager {
+        private Map<BlankNode, String> bNodeMap = new HashMap<BlankNode, String>();
+        private int counter = 0;
+
+        public String getBlankNodeId(BlankNode node) {
+            String bNodeId = bNodeMap.get(node);
+            if (bNodeId == null) {
+                bNodeId = "_:b" + ++counter;
+                bNodeMap.put((BlankNode) node, bNodeId);
+            }
+            return bNodeId;
+        }
+    }
+
+    /**
+     * Converts the {@link RDFTerm object} of an triple to JSON
+     * 
+     * @param bNodeMgr
+     *            used to lookup {@link BlankNode} instances
+     * @param object
+     *            the object of the triple
+     * @return the JSON representation of parsed object
+     */
+    @SuppressWarnings("unchecked")
+    private JSONObject writeObject(BlankNodeManager bNodeMgr, RDFTerm object) {
+        JSONObject jObject = new JSONObject();
+        if (object instanceof Literal) {
+            Literal literal = (Literal) object;
+            jObject.put("value", literal.getLexicalForm());
+            jObject.put("type", "literal");
+            jObject.put("datatype", literal.getDataType().getUnicodeString());
+            if (literal.getLanguage() != null) {
+                jObject.put("lang", literal.getLanguage().toString());
+            }
+        } else if (object instanceof IRI) {
+            IRI uriRef = (IRI) object;
+            jObject.put("value", uriRef.getUnicodeString());
+            jObject.put("type", "uri");
+        } else if (object instanceof BlankNode) {
+            String bNodeId = bNodeMgr.getBlankNodeId((BlankNode) object);
+            jObject.put("value", bNodeId);
+            jObject.put("type", "bnode");
+        }
+        return jObject;
+    }
+
+    /**
+     * Compares only the subjects of the triples. If they are equals
+     * <code>0</code> is returned. This will ensure that all triples with the
+     * same subjects are sorted correctly. However it does not sort predicates
+     * and objects!
+     */
+    public static final Comparator<Triple> SUBJECT_COMPARATOR = new Comparator<Triple>()
{
+
+        @Override
+        public int compare(Triple a, Triple b) {
+            return compare(a.getSubject(), b.getSubject());
+        }
+
+        private int compare(BlankNodeOrIRI a, BlankNodeOrIRI b) {
+            int hashA = a.hashCode();
+            int hashB = b.hashCode();
+            if (hashA != hashB) {
+                return hashA > hashB ? 1 : -1;
+            }
+            return a.toString().compareTo(b.toString());
+        }
+
+    };
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.ParsingProvider
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.ParsingProvider
b/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.ParsingProvider
new file mode 100644
index 0000000..2599bc3
--- /dev/null
+++ b/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.ParsingProvider
@@ -0,0 +1 @@
+org.apache.clerezza.rdf.rdfjson.parser.RdfJsonParsingProvider

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.SerializingProvider
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.SerializingProvider
b/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.SerializingProvider
new file mode 100644
index 0000000..c0c6766
--- /dev/null
+++ b/rdf/rdfjson/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.serializedform.SerializingProvider
@@ -0,0 +1 @@
+org.apache.clerezza.rdf.rdfjson.serializer.RdfJsonSerializingProvider

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/parser/RdfJsonParserProviderTest.java
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/parser/RdfJsonParserProviderTest.java
b/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/parser/RdfJsonParserProviderTest.java
new file mode 100644
index 0000000..200a253
--- /dev/null
+++ b/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/parser/RdfJsonParserProviderTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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 org.apache.clerezza.rdf.rdfjson.parser;
+
+import java.io.InputStream;
+import java.util.Iterator;
+import org.apache.clerezza.commons.rdf.BlankNode;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.apache.clerezza.commons.rdf.Graph;
+import org.apache.clerezza.commons.rdf.BlankNodeOrIRI;
+import org.apache.clerezza.commons.rdf.Triple;
+import org.apache.clerezza.commons.rdf.IRI;
+import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph;
+import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
+
+/**
+ * @author tio, hasan
+ */
+public class RdfJsonParserProviderTest {
+
+    @Test
+    public void testParsingOfObjectBlankNode() {
+        ParsingProvider provider = new RdfJsonParsingProvider();
+        InputStream jsonIn = getClass().getResourceAsStream("test-object-bnode.json");
+        Graph parsedGraph = new SimpleGraph();
+        provider.parse(parsedGraph, jsonIn, "application/rdf+json", null);
+        Assert.assertEquals(parsedGraph.size(), 1);
+        Iterator<Triple> triples = parsedGraph.filter(new IRI("http://example.org/node1"),
+                new IRI("http://example.org/prop1"), null);
+        Assert.assertTrue(triples.hasNext());
+        Assert.assertTrue(triples.next().getObject() instanceof BlankNode);
+    }
+
+    @Test
+    public void testParsingOfSubjectBlankNode() {
+        ParsingProvider provider = new RdfJsonParsingProvider();
+        InputStream jsonIn = getClass().getResourceAsStream("test-subject-bnode.json");
+        Graph parsedGraph = new SimpleGraph();
+        provider.parse(parsedGraph, jsonIn, "application/rdf+json", null);
+        Assert.assertEquals(3, parsedGraph.size());
+        Iterator<Triple> triples = parsedGraph.filter(null, new IRI("http://example.org/prop1"),
+                new IRI("http://example.org/node1"));
+        Assert.assertTrue(triples.hasNext());
+        BlankNodeOrIRI subject = triples.next().getSubject();
+        Assert.assertTrue(subject instanceof BlankNode);
+
+        triples = parsedGraph.filter(null, new IRI("http://example.org/prop2"),
+                new IRI("http://example.org/node2"));
+        Assert.assertTrue(triples.hasNext());
+        Assert.assertTrue(subject.equals(triples.next().getSubject()));
+
+        triples = parsedGraph.filter(null, new IRI("http://example.org/prop3"),
+                new IRI("http://example.org/node3"));
+        Assert.assertTrue(triples.hasNext());
+        Assert.assertFalse(subject.equals(triples.next().getSubject()));
+    }
+
+    @Test
+    public void testParser() {
+        ParsingProvider provider = new RdfJsonParsingProvider();
+        InputStream jsonIn = getClass().getResourceAsStream("test.json");
+        Graph deserializedGraph = new SimpleGraph();
+        provider.parse(deserializedGraph, jsonIn, "application/rdf+json", null);
+        Assert.assertEquals(deserializedGraph.size(), 6);
+        Iterator<Triple> triples = deserializedGraph.filter(new IRI("http://base/child1"),
null, null);
+        while (triples.hasNext()) {
+            IRI uri = triples.next().getPredicate();
+            Assert.assertEquals(uri.getUnicodeString(), "http://base/propertyB");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializerProviderTest.java
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializerProviderTest.java
b/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializerProviderTest.java
new file mode 100644
index 0000000..f997e97
--- /dev/null
+++ b/rdf/rdfjson/src/test/java/org/apache/clerezza/rdf/rdfjson/serializer/RdfJsonSerializerProviderTest.java
@@ -0,0 +1,277 @@
+/*
+ * 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 org.apache.clerezza.rdf.rdfjson.serializer;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import java.util.Set;
+import org.junit.Assert;
+import org.junit.Test;
+import org.apache.clerezza.commons.rdf.BlankNode;
+import org.apache.clerezza.commons.rdf.Language;
+import org.apache.clerezza.commons.rdf.Graph;
+import org.apache.clerezza.commons.rdf.BlankNodeOrIRI;
+import org.apache.clerezza.commons.rdf.Triple;
+import org.apache.clerezza.commons.rdf.IRI;
+import org.apache.clerezza.commons.rdf.Literal;
+import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl;
+import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph;
+import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl;
+import org.apache.clerezza.rdf.core.LiteralFactory;
+import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
+import org.apache.clerezza.rdf.core.serializedform.SerializingProvider;
+import org.apache.clerezza.rdf.ontologies.FOAF;
+import org.apache.clerezza.rdf.ontologies.RDF;
+import org.apache.clerezza.rdf.ontologies.RDFS;
+import org.apache.clerezza.rdf.rdfjson.parser.RdfJsonParsingProvider;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+
+/**
+ * 
+ * @author tio, hasan
+ */
+public class RdfJsonSerializerProviderTest {
+
+    private final static LiteralFactory lf = LiteralFactory.getInstance();
+    private final static IRI RDF_NIL = new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
+    private final static IRI node1 = new IRI("http://example.org/node1");
+    private final static IRI node2 = new IRI("http://example.org/node2");
+    private final static IRI prop1 = new IRI("http://example.org/prop1");
+    private final static IRI prop2 = new IRI("http://example.org/prop2");
+    private final static IRI prop3 = new IRI("http://example.org/prop3");
+    private final static IRI prop4 = new IRI("http://example.org/prop4");
+    private final static IRI prop5 = new IRI("http://example.org/prop5");
+    private final static IRI prop6 = new IRI("http://example.org/prop6");
+    private final static BlankNode blank1 = new BlankNode();
+    private final static BlankNode blank2 = new BlankNode();
+    private final static PlainLiteralImpl plainLiteralA = new PlainLiteralImpl("A");
+    private final static PlainLiteralImpl plainLiteralB = new PlainLiteralImpl("B");
+    private final static PlainLiteralImpl plainLiteralC = new PlainLiteralImpl("C");
+    private final static Literal typedLiteralA = lf.createTypedLiteral("A");
+
+    private Graph mGraph;
+
+    @BeforeClass
+    public static void setUpClass() throws Exception {
+    }
+
+    @AfterClass
+    public static void tearDownClass() throws Exception {
+    }
+
+    @Before
+    public void setUp() {
+        mGraph = new SimpleGraph();
+    }
+
+    @After
+    public void tearDown() {
+    }
+
+    @Test
+    public void testSerializationOfBlankNode() {
+        mGraph.add(new TripleImpl(node1, prop1, blank1));
+        SerializingProvider provider = new RdfJsonSerializingProvider();
+        ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
+        provider.serialize(serializedGraph, mGraph, "application/rdf+json");
+        Assert.assertTrue(serializedGraph.toString().contains("_:"));
+    }
+
+    @Test
+    public void testSerializationOfRdfList() {
+        mGraph.add(new TripleImpl(blank1, RDF.first, blank2));
+        mGraph.add(new TripleImpl(blank1, RDF.rest, RDF_NIL));
+        mGraph.add(new TripleImpl(blank2, prop1, node1));
+
+//        System.out.println(mGraph);
+
+        SerializingProvider provider = new RdfJsonSerializingProvider();
+        ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
+        provider.serialize(serializedGraph, mGraph, "application/rdf+json");
+
+//        System.out.println(serializedGraph.toString());
+
+        ParsingProvider parsingProvider = new RdfJsonParsingProvider();
+        ByteArrayInputStream jsonIn = new ByteArrayInputStream(serializedGraph.toByteArray());
+        Graph parsedGraph = new SimpleGraph();
+        parsingProvider.parse(parsedGraph, jsonIn, "application/rdf+json", null);
+
+        Assert.assertEquals(mGraph.getImmutableGraph(), parsedGraph.getImmutableGraph());
+    }
+
+    /*
+     * serializes a graph and parse it back.
+     */
+    @Test
+    public void testSerializer() {
+        mGraph.add(new TripleImpl(node1, prop1, plainLiteralA));
+        mGraph.add(new TripleImpl(node1, prop2, node2));
+        mGraph.add(new TripleImpl(node2, prop3, plainLiteralB));
+        mGraph.add(new TripleImpl(blank1, prop4, plainLiteralC));
+        mGraph.add(new TripleImpl(blank1, prop5, typedLiteralA));
+        mGraph.add(new TripleImpl(node1, prop6, blank1));
+        serializeDeserialize(mGraph);
+    }
+    
+    @Test
+    public void literalWithLanguage() {
+        Literal l = new PlainLiteralImpl("Ein deutsches Literal.", 
+                new Language("de"));
+        mGraph.add(new TripleImpl(blank1, RDF.first, l));
+        serializeDeserialize(mGraph);
+    }
+    
+    /**
+     * For local performance testing
+     */
+    @Test
+    public void testBigGraph() throws Exception {
+        //reduced ImmutableGraph size to 5000 to allow equals test between the
+        //serialised and parsed RDF graphs. Equals tests on bigger graphs
+        //would take to much time
+        int NUM_TRIPLES = 5000;
+        //randoms are in the range [0..3]
+        double l = 1.0; //literal
+        double i = l / 3; //int
+        double d = l * 2 / 3;//double
+        double b = 2.0;//bNode
+        double nb = b - (l * 2 / 3); //create new bNode
+        double random;
+        BlankNodeOrIRI subject = null;
+        IRI predicate = null;
+        List<IRI> predicateList = new ArrayList<IRI>();
+        predicateList.add(RDF.first);
+        predicateList.add(RDF.rest);
+        predicateList.add(RDF.type);
+        predicateList.add(RDFS.label);
+        predicateList.add(RDFS.comment);
+        predicateList.add(RDFS.range);
+        predicateList.add(RDFS.domain);
+        predicateList.add(FOAF.name);
+        predicateList.add(FOAF.nick);
+        predicateList.add(FOAF.homepage);
+        predicateList.add(FOAF.age);
+        predicateList.add(FOAF.depiction);
+        String URI_PREFIX = "http://www.test.org/bigGraph/ref";
+        Language DE = new Language("de");
+        Language EN = new Language("en");
+        Iterator<IRI> predicates = predicateList.iterator();
+        List<BlankNode> bNodes = new ArrayList<BlankNode>();
+        bNodes.add(new BlankNode());
+        for (int count = 0; mGraph.size() < NUM_TRIPLES; count++) {
+            random = Math.random() * 3;
+            if (random >= 2.5 || count == 0) {
+                if (random <= 2.75) {
+                    subject = new IRI(URI_PREFIX + count);
+                } else {
+                    int rndIndex = (int) ((random - 2.75) * bNodes.size() / (3.0 - 2.75));
+                    subject = bNodes.get(rndIndex);
+                }
+            }
+            if (random > 2.0 || count == 0) {
+                if (!predicates.hasNext()) {
+                    Collections.shuffle(predicateList);
+                    predicates = predicateList.iterator();
+                }
+                predicate = predicates.next();
+            }
+            if (random <= l) { //literal
+                if (random <= i) {
+                    mGraph.add(new TripleImpl(subject, predicate, lf.createTypedLiteral(count)));
+                } else if (random <= d) {
+                    mGraph.add(new TripleImpl(subject, predicate, lf.createTypedLiteral(random)));
+                } else {
+                    Literal text;
+                    if (random <= i) {
+                        text = new PlainLiteralImpl("Literal for " + count);
+                    } else if (random <= d) {
+                        text = new PlainLiteralImpl("An English literal for " + count, EN);
+                    } else {
+                        text = new PlainLiteralImpl("Ein Dutsches Literal für " + count,
DE);
+                    }
+                    mGraph.add(new TripleImpl(subject, predicate, text));
+                }
+            } else if (random <= b) { //bnode
+                BlankNode bnode;
+                if (random <= nb) {
+                    bnode = new BlankNode();
+                    bNodes.add(bnode);
+                } else { //>nb <b
+                    int rndIndex = (int) ((random - nb) * bNodes.size() / (b - nb));
+                    bnode = bNodes.get(rndIndex);
+                }
+                mGraph.add(new TripleImpl(subject, predicate, bnode));
+            } else { //IRI
+                mGraph.add(new TripleImpl(subject, predicate,
+                        new IRI(URI_PREFIX + (int) count * random)));
+            }
+        }
+        //Asserts the correct sorting of the triples in the graph by the
+        //Comparator used by the JSON serializer
+        Set<BlankNodeOrIRI> subjects = new HashSet<BlankNodeOrIRI>();
+        Triple[] sortedTriples = mGraph.toArray(new Triple[mGraph.size()]);
+        Arrays.sort(sortedTriples, RdfJsonSerializingProvider.SUBJECT_COMPARATOR);
+        BlankNodeOrIRI current = sortedTriples[0].getSubject();
+        for(Triple triple : sortedTriples){
+            if(!triple.getSubject().equals(current)){
+                subjects.add(current);
+                current = triple.getSubject();
+                Assert.assertFalse(subjects.contains(current));
+            }
+        }
+        sortedTriples = null;
+        subjects = null;
+        
+        int originalSize = mGraph.size();
+        
+        SerializingProvider provider = new RdfJsonSerializingProvider();
+        ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
+        long start = System.currentTimeMillis();
+        provider.serialize(serializedGraph, mGraph, "application/rdf+json");
+        System.out.println("Serialized " + mGraph.size() + " Triples in " + (System.currentTimeMillis()
- start) + " ms");
+        ParsingProvider parsingProvider = new RdfJsonParsingProvider();
+        ByteArrayInputStream jsonIn = new ByteArrayInputStream(serializedGraph.toByteArray());
+        Graph parsedGraph = new SimpleGraph();
+        parsingProvider.parse(parsedGraph, jsonIn, "application/rdf+json", null);
+        Assert.assertEquals(originalSize, parsedGraph.size());
+        sortedTriples = parsedGraph.toArray(new Triple[parsedGraph.size()]);
+        Arrays.sort(sortedTriples, RdfJsonSerializingProvider.SUBJECT_COMPARATOR);
+        Assert.assertEquals(mGraph.getImmutableGraph(), parsedGraph.getImmutableGraph());
+    }
+
+    private void serializeDeserialize(Graph mGraph) {
+        SerializingProvider provider = new RdfJsonSerializingProvider();
+        ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
+        provider.serialize(serializedGraph, mGraph, "application/rdf+json");
+        ParsingProvider parsingProvider = new RdfJsonParsingProvider();
+        ByteArrayInputStream jsonIn = new ByteArrayInputStream(serializedGraph.toByteArray());
+        Graph parsedGraph = new SimpleGraph();
+        parsingProvider.parse(parsedGraph, jsonIn, "application/rdf+json", null);
+        Assert.assertEquals(mGraph.size(), parsedGraph.size());
+        Assert.assertEquals(mGraph.getImmutableGraph(), parsedGraph.getImmutableGraph());
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-object-bnode.json
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-object-bnode.json
b/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-object-bnode.json
new file mode 100644
index 0000000..40d2882
--- /dev/null
+++ b/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-object-bnode.json
@@ -0,0 +1,5 @@
+{	
+	"http://example.org/node1":	{
+		"http://example.org/prop1": [{"value":"_:bnode1","type":"bnode"}]
+	}
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-subject-bnode.json
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-subject-bnode.json
b/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-subject-bnode.json
new file mode 100644
index 0000000..bf856fe
--- /dev/null
+++ b/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test-subject-bnode.json
@@ -0,0 +1,10 @@
+{	
+	"_:bnode1":	{
+		"http://example.org/prop1": [{"value":"http://example.org/node1","type":"uri"}],
+		"http://example.org/prop2": [{"value":"http://example.org/node2","type":"uri"}]
+	},
+
+	"_:bnode2":	{
+		"http://example.org/prop3": [{"value":"http://example.org/node3","type":"uri"}]
+	}
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/c8293374/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test.json
----------------------------------------------------------------------
diff --git a/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test.json
b/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test.json
new file mode 100644
index 0000000..150ab90
--- /dev/null
+++ b/rdf/rdfjson/src/test/resources/org/apache/clerezza/rdf/rdfjson/parser/test.json
@@ -0,0 +1,16 @@
+{
+	"http://base/child1": {
+		"http://base/propertyB":[{"value":"B","type":"literal"}]
+	},
+	
+	"_:b1": {
+		"http://base/propertyC":[{"value":"C","type":"literal","lang":"en"}],
+		"http://base/propertyE":[{"value":"E","type":"literal","datatype":"http://www.w3.org/2001/XMLSchema#string"}]
+	},
+
+	"http://base/root": {
+		"http://base/propertyA":[{"value":"A","type":"literal"}],
+		"http://base/resourcePropertyB":[{"value":"http://base/child1","type":"uri"}],
+		"http://base/resourcePropertyD":[{"value":"_:b1","type":"bnode"}]
+	}
+}


Mime
View raw message