[Mulgara-svn] r1505 - trunk/src/jar/content-n3/java/org/mulgara/content/n3

ronald at mulgara.org ronald at mulgara.org
Tue Feb 17 10:38:00 UTC 2009


Author: ronald
Date: 2009-02-17 02:37:59 -0800 (Tue, 17 Feb 2009)
New Revision: 1505

Added:
   trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3Writer.java
   trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3WriterUnitTest.java
Modified:
   trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3ContentHandler.java
Log:
Added ability to write out statements/content as NTriples.

Modified: trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3ContentHandler.java
===================================================================
--- trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3ContentHandler.java	2009-02-17 10:37:54 UTC (rev 1504)
+++ trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3ContentHandler.java	2009-02-17 10:37:59 UTC (rev 1505)
@@ -27,6 +27,12 @@
 
 package org.mulgara.content.n3;
 
+// Java packages
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
 // Java 2 enterprise packages
 import javax.activation.MimeType;
 import javax.activation.MimeTypeParseException;
@@ -38,6 +44,7 @@
 import org.mulgara.content.Content;
 import org.mulgara.content.ContentHandler;
 import org.mulgara.content.ContentHandlerException;
+import org.mulgara.content.ModifiedException;
 import org.mulgara.content.NotModifiedException;
 import org.mulgara.resolver.spi.ResolverSession;
 import org.mulgara.resolver.spi.Statements;
@@ -115,13 +122,18 @@
   }
 
   /**
-   * @throws ContentHandlerException  {@inheritDoc}; this particular
-   *   implementation doesn't implement this method and will always throw the
-   *   exception
+   * Writes out the statements in basic NTriples format.
    */
   public void serialize(Statements      statements,
                         Content         content,
-                        ResolverSession resolverSession) throws ContentHandlerException {
-    throw new ContentHandlerException("N3 output not implemented");
+                        ResolverSession resolverSession)
+      throws ContentHandlerException, ModifiedException {
+    try {
+      Writer out = new BufferedWriter(new OutputStreamWriter(content.newOutputStream(), "utf-8"));
+      new N3Writer().write(statements, resolverSession, out);
+      out.close();
+    } catch (IOException e) {
+      throw new ContentHandlerException("Failed to serialize N3 to " + content.getURIString(), e);
+    }
   }
 }

Added: trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3Writer.java
===================================================================
--- trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3Writer.java	                        (rev 0)
+++ trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3Writer.java	2009-02-17 10:37:59 UTC (rev 1505)
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2008 The Topaz Foundation
+ *
+ * Licensed 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.
+ *
+ * Contributions:
+ */
+
+package org.mulgara.content.n3;
+
+import java.io.IOException;
+import java.io.Writer;
+
+import org.jrdf.graph.BlankNode;
+import org.jrdf.graph.Literal;
+import org.jrdf.graph.Node;
+import org.jrdf.graph.URIReference;
+
+import org.mulgara.resolver.spi.GlobalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.resolver.spi.Statements;
+import org.mulgara.query.TuplesException;
+
+/**
+ * A helper that generates N3 from Statements and writes to a {@link Writer}. Currently only
+ * generates NTriples.
+ *
+ * @created 2009-02-15
+ * @author Ronald Tschalär
+ * @licence Apache License v2.0
+ */
+public class N3Writer {
+  /**
+   * Write out the given statements to the given writer in NTriples format.
+   *
+   * @param statements the statements to write out
+   * @param session    the session to use for globalizing
+   * @param writer     where to write the results
+   */
+  public void write(Statements statements, ResolverSession session, Writer writer)
+      throws IOException {
+    //validate
+    if (statements == null) throw new IllegalArgumentException("Statements cannot be null.");
+    if (session == null) throw new IllegalArgumentException("ResolverSession cannot be null.");
+    if (writer == null) throw new IllegalArgumentException("Writer cannot be null.");
+
+    // write
+    try {
+      statements.beforeFirst();
+      while (statements.next()) {
+        writer.write(toN3String(session.globalize(statements.getSubject())));
+        writer.write(" ");
+        writer.write(toN3String(session.globalize(statements.getPredicate())));
+        writer.write(" ");
+        writer.write(toN3String(session.globalize(statements.getObject())));
+        writer.write(" .\n");
+      }
+    } catch (TuplesException te) {
+      throw (IOException) new IOException("Error reading statements").initCause(te);
+    } catch (GlobalizeException ge) {
+      throw (IOException) new IOException("Error globalizing node").initCause(ge);
+    }
+  }
+
+  private String toN3String(Node node) {
+    if (node instanceof URIReference) {
+      return "<" + ((URIReference)node).getURI().toASCIIString() + ">";
+    } else if (node instanceof Literal) {
+      return ((Literal)node).getEscapedForm();
+    } else if (node instanceof BlankNode) {
+      return "_:" + ((BlankNode)node).getID();
+    } else {
+      throw new RuntimeException("Unknown node type found: " + node.getClass() + ": " + node);
+    }
+  }
+}


Property changes on: trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3Writer.java
___________________________________________________________________
Name: svn:keywords
   + Id HeadURL Revision
Name: svn:eol-style
   + native

Added: trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3WriterUnitTest.java
===================================================================
--- trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3WriterUnitTest.java	                        (rev 0)
+++ trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3WriterUnitTest.java	2009-02-17 10:37:59 UTC (rev 1505)
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2008 The Topaz Foundation
+ *
+ * Licensed 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.
+ *
+ * Contributions:
+ */
+
+package org.mulgara.content.n3;
+
+// Java 2 standard packages
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.StringWriter;
+import java.net.URI;
+import java.util.Map;
+
+// Java 2 enterprise packages
+import javax.activation.MimeType;
+
+// Third party packages
+import junit.framework.TestCase;
+import org.jrdf.graph.BlankNode;
+
+// Locally written packages
+import org.mulgara.content.Content;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.resolver.spi.Statements;
+import org.mulgara.resolver.spi.TestResolverSession;
+
+/**
+ * Test suite for {@link N3Writer}.
+ *
+ * @created 2009-02-15
+ * @author Ronald Tschalär
+ * @licence Apache License v2.0
+ */
+public class N3WriterUnitTest extends TestCase {
+  /**
+   * Test {@link N3Wrtier} writing.
+   *
+   * @throws Exception if there's an error running the test (note that if the test
+   *                   merely fails, this should <em>not</em> throw any exception
+   */
+  public void test1() throws Exception {
+    // basic statement with plain literal
+    runTest("<foo:bar> <foo:baz> \"42\" .\n", null);
+    // basic statement with blank-node and datatyped literal
+    runTest("_:node1000001 <foo:baz> \"42\"^^<xsd:int> .\n", null);
+    // literal and uri with non-ascii characters
+    runTest("<foo:i18n:øé> <foo:baz> \"Some text with \\\" in it, and 日本 chars, and \\u00E0 \" .",
+            "<foo:i18n:%C3%B8%C3%A9> <foo:baz> \"Some text with \\\" in it, and \\u65E5\\u672C chars, and \\u00E0 \" .\n");
+    // literal with newlines, ff, etc
+    runTest("<foo:bar> <foo:baz> \"Some text with \n, \r, \f, \u0000 in it\" .",
+            "<foo:bar> <foo:baz> \"Some text with \\n, \\r, \\u000C, \\u0000 in it\" .\n");
+    runTest("<foo:bar> <foo:baz> \"Some text with \\n, \\r, \\f, \\u0000 in it\" .",
+            "<foo:bar> <foo:baz> \"Some text with \\n, \\r, \\u000C, \\u0000 in it\" .\n");
+    // multiple blank-nodes, and language-tag
+    runTest("_:bn1 <baz:baz> _:bn2 .\n" +
+            "_:bn2 <bar:bar> <foo:foo> .\n" +
+            "<foo:foo> <dc:title> \"hello\"@en .",
+            "_:node1000002 <baz:baz> _:node1000001 .\n" +
+            "_:node1000001 <bar:bar> <foo:foo> .\n" +
+            "<foo:foo> <dc:title> \"hello\"@en .\n");
+    // multiple blank-nodes using internal-ids (numbers)
+    runTest("_:42 <baz:baz> _:987 .\n" +
+            "_:987 <bar:bar> <foo:foo> .\n",
+            "_:node1000002 <baz:baz> _:node1000001 .\n" +
+            "_:node1000001 <bar:bar> <foo:foo> .\n");
+  }
+
+  private void runTest(String n3, String exp) throws Exception {
+    // Obtain a resolver session
+    ResolverSession resolverSession = new TestResolverSession();
+
+    // create the statements
+    Statements statements = new N3Statements(new StringContent(n3), resolverSession);
+
+    // test
+    StringWriter out = new StringWriter();
+    new N3Writer().write(statements, resolverSession, out);
+
+    assertEquals(exp != null ? exp : n3, out.toString());
+  }
+
+  private static class StringContent implements Content {
+    private final String content;
+
+    public StringContent(String content) {
+      this.content = content;
+    }
+
+    public Map<Object,BlankNode> getBlankNodeMap()         { return null; }
+    public MimeType getContentType()                       { return null; }
+    public URI getURI()                                    { return null; }
+    public String getURIString()                           { return null; }
+    public OutputStream newOutputStream()                  { return null; }
+
+    public InputStream newInputStream() throws IOException {
+      return new ByteArrayInputStream(content.getBytes("UTF-8"));
+    }
+  }
+}


Property changes on: trunk/src/jar/content-n3/java/org/mulgara/content/n3/N3WriterUnitTest.java
___________________________________________________________________
Name: svn:keywords
   + Id HeadURL Revision
Name: svn:eol-style
   + native




More information about the Mulgara-svn mailing list