You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2016/12/25 17:41:42 UTC
svn commit: r1776023 [2/2] - in /sis/branches/JDK8:
core/sis-utility/src/main/java/org/apache/sis/util/resources/
core/sis-utility/src/main/java/org/apache/sis/xml/
storage/sis-earth-observation/src/main/java/org/apache/sis/storage/earthobservation/
st...
Modified: sis/branches/JDK8/storage/sis-xmlstore/src/main/java/org/apache/sis/internal/xml/StaxStreamWriter.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/storage/sis-xmlstore/src/main/java/org/apache/sis/internal/xml/StaxStreamWriter.java?rev=1776023&r1=1776022&r2=1776023&view=diff
==============================================================================
--- sis/branches/JDK8/storage/sis-xmlstore/src/main/java/org/apache/sis/internal/xml/StaxStreamWriter.java [UTF-8] (original)
+++ sis/branches/JDK8/storage/sis-xmlstore/src/main/java/org/apache/sis/internal/xml/StaxStreamWriter.java [UTF-8] Sun Dec 25 17:41:42 2016
@@ -17,54 +17,39 @@
package org.apache.sis.internal.xml;
import java.util.Map;
-import java.util.HashMap;
-import java.io.BufferedOutputStream;
import java.io.IOException;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import javax.xml.stream.XMLEventWriter;
-import javax.xml.stream.XMLOutputFactory;
+import java.nio.charset.Charset;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
-import javax.xml.transform.Result;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.sax.SAXResult;
-import javax.xml.transform.stax.StAXResult;
-import org.w3c.dom.Node;
-import org.xml.sax.ContentHandler;
import org.apache.sis.storage.DataStoreException;
-import org.apache.sis.storage.UnsupportedStorageException;
-import org.apache.sis.util.ArgumentChecks;
-import org.apache.sis.util.Classes;
-import org.apache.sis.util.ObjectConverters;
-import org.apache.sis.util.UnconvertibleObjectException;
-import org.apache.sis.util.resources.Errors;
-import org.apache.sis.xml.Namespaces;
+import org.apache.sis.xml.MarshallerPool;
/**
* Base class of Apache SIS writers of XML files using STAX writer.
- * This is a helper class for {@link org.apache.sis.storage.DataStore} implementations.
- * Writers for a given specification should extend this class and provide appropriate write methods.
+ * This class is itself a consumer of {@code Feature} instances to write in the XML file.
+ *
+ * <p>This is a helper class for {@link org.apache.sis.storage.DataStore} implementations.
+ * Writers for a given specification should extend this class and implement methods as
+ * in the following example:</p>
*
* <p>Example:</p>
* {@preformat java
- * public class UserWriter extends StaxStreamWriter {
- * public void write(User user) throws XMLStreamException {
+ * public class UserObjectWriter extends StaxStreamWriter {
+ * public void accept(Feature f) throws BackingStoreException {
* // Actual STAX write operations.
* writer.writeStartElement(\u2026);
* }
* }
* }
*
- * And should be used like below:
+ * Writers can be used like below:
*
* {@preformat java
- * try (UserWriter instance = new UserWriter()) {
- * instance.setOutput(stream);
- * instance.write(aUser);
+ * try (UserObjectWriter writer = new UserObjectWriter(dataStore)) {
+ * writer.accept(feature);
* }
* }
*
@@ -82,104 +67,69 @@ public abstract class StaxStreamWriter e
/**
* The XML stream writer.
*/
- private XMLStreamWriter writer;
-
- /**
- * The namespaces for which no prefix are mapped. In such case, default prefixes will be created.
- * Keys are namespaces URL and values are prefixes.
- */
- private final Map<String,String> unknownNamespaces = new HashMap<>();
+ protected final XMLStreamWriter writer;
/**
- * Creates a new XML writer from the given file, URL, stream or writer object.
- * The {@code output} argument shall be an instance of {@link XMLStreamWriter}, {@link XMLEventWriter},
- * {@link ContentHandler}, {@link OutputStream}, {@link Writer}, {@link Result}, {@link Node} or an
- * object convertible to {@link Path}, otherwise a {@link DataStoreException} will be thrown.
+ * Creates a new XML writer for the given data store.
*
- * @param owner the data store for which this writer is created.
- * @param output where to write the XML file.
- * @param encoding the document encoding (usually {@code "UTF-8"}). May be ignored.
- * @throws DataStoreException if the output type is not recognized.
- * @throws IOException if an error occurred while creating the file.
+ * @param owner the data store for which this writer is created.
+ * @throws DataStoreException if the output type is not recognized or the data store is closed.
* @throws XMLStreamException if an error occurred while opening the XML file.
+ * @throws IOException if an error occurred while preparing the output stream.
*/
- protected StaxStreamWriter(final StaxDataStore owner, final Object output, final String encoding)
- throws DataStoreException, IOException, XMLStreamException
- {
+ @SuppressWarnings("ThisEscapedInObjectConstruction")
+ protected StaxStreamWriter(final StaxDataStore owner) throws DataStoreException, XMLStreamException, IOException {
super(owner);
- ArgumentChecks.ensureNonNull("output", output);
- if (output instanceof XMLStreamWriter) writer = (XMLStreamWriter) output;
- else if (output instanceof XMLEventWriter) writer = factory().createXMLStreamWriter(new StAXResult((XMLEventWriter) output));
- else if (output instanceof ContentHandler) writer = factory().createXMLStreamWriter(new SAXResult((ContentHandler) output));
- else if (output instanceof OutputStream) writer = factory().createXMLStreamWriter((OutputStream) output, encoding);
- else if (output instanceof Writer) writer = factory().createXMLStreamWriter((Writer) output);
- else if (output instanceof Result) writer = factory().createXMLStreamWriter((Result) output);
- else if (output instanceof Node) writer = factory().createXMLStreamWriter(new DOMResult((Node) output));
- else try {
- final Path path = ObjectConverters.convert(output, Path.class);
- final BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(path));
- writer = factory().createXMLStreamWriter(out, encoding);
- } catch (UnconvertibleObjectException e) {
- throw new UnsupportedStorageException(errors().getString(Errors.Keys.IllegalOutputTypeForWriter_2,
- owner.getFormatName(), Classes.getClass(output)), e);
+ writer = owner.createWriter(this); // Okay because will not store the 'this' reference.
+ Charset encoding = owner.encoding;
+ if (encoding == null) {
+ encoding = Charset.defaultCharset();
}
+ writer.writeStartDocument(encoding.name());
}
- /**
- * Convenience method invoking {@link StaxDataStore#outputFactory()}.
- */
- private XMLOutputFactory factory() {
- return owner.outputFactory();
- }
- /**
- * Returns the XML stream writer if it is not closed.
- *
- * @return the XML stream writer (never null).
- * @throws XMLStreamException if this XML writer has been closed.
- */
- protected final XMLStreamWriter getWriter() throws XMLStreamException {
- if (writer != null) {
- return writer;
- }
- throw new XMLStreamException(errors().getString(Errors.Keys.ClosedWriter_1, "XML"));
- }
+
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ //////// ////////
+ //////// Convenience methods for subclass implementations ////////
+ //////// ////////
+ ////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Writes a new tag with the given value and no attribute.
* If the given value is null, then this method does nothing.
*
- * @param namespace namespace (URL) of the tag to write.
* @param localName local name of the tag to write.
* @param value text to write inside the tag.
* @throws XMLStreamException if the underlying STAX writer raised an error.
*/
- protected final void writeSimpleTag(final String namespace, final String localName, final Object value) throws XMLStreamException {
+ protected final void writeSimpleTag(final String localName, final Object value) throws XMLStreamException {
if (value != null) {
- writer.writeStartElement(namespace, localName);
+ writer.writeStartElement(localName);
writer.writeCharacters(value.toString());
writer.writeEndElement();
}
}
/**
- * Returns the prefix for the given namespace. If the given namespace is one of the
- * {@linkplain Namespaces well-known namespaces}, then this method returns the prefix
- * commonly used for that namespace. Otherwise a new prefix is generated.
+ * Delegates to JAXB the marshalling of a part of XML document.
*
- * @param namespace the namespace (URL) for which to get the prefix.
- * @return prefix for the given namespace.
+ * @param object the object to marshall, or {@code null} if none.
+ * @throws XMLStreamException if the XML stream is closed.
+ * @throws JAXBException if an error occurred during marshalling.
+ *
+ * @see javax.xml.bind.Marshaller#marshal(Object, XMLStreamWriter)
*/
- protected final String getPrefix(final String namespace) {
- String prefix = Namespaces.getPreferredPrefix(namespace, null);
- if (prefix == null) {
- prefix = unknownNamespaces.get(namespace);
- if (prefix == null) {
- prefix = "ns" + (unknownNamespaces.size() + 1);
- unknownNamespaces.put(namespace, prefix);
- }
+ protected final void marshal(final Object object) throws XMLStreamException, JAXBException {
+ final MarshallerPool pool = getMarshallerPool();
+ final Marshaller marshaller = pool.acquireMarshaller();
+ for (final Map.Entry<String,?> entry : ((Map<String,?>) owner.configuration).entrySet()) {
+ marshaller.setProperty(entry.getKey(), entry.getValue());
}
- return prefix;
+ marshaller.marshal(object, writer);
+ pool.recycle(marshaller);
}
/**
@@ -191,10 +141,8 @@ public abstract class StaxStreamWriter e
*/
@Override
public void close() throws Exception {
- if (writer != null) {
- writer.close();
- writer = null;
- }
+ writer.writeEndDocument();
+ writer.close();
super.close();
}
}
Modified: sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXReaderTest.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXReaderTest.java?rev=1776023&r1=1776022&r2=1776023&view=diff
==============================================================================
--- sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXReaderTest.java [UTF-8] (original)
+++ sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXReaderTest.java [UTF-8] Sun Dec 25 17:41:42 2016
@@ -27,6 +27,8 @@ import org.apache.sis.storage.StorageCon
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.test.DependsOnMethod;
import org.apache.sis.test.TestCase;
+import org.junit.BeforeClass;
+import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -48,12 +50,33 @@ import org.opengis.feature.Feature;
*/
public final strictfp class GPXReaderTest extends TestCase {
/**
+ * The provider shared by all data stores created in this test class.
+ */
+ private static StoreProvider provider;
+
+ /**
+ * Creates the provider to be shared by all data stores created in this test class.
+ */
+ @BeforeClass
+ public static void createProvider() {
+ provider = new StoreProvider();
+ }
+
+ /**
+ * Disposes the data store provider after all tests have been completed.
+ */
+ @AfterClass
+ public static void disposeProvider() {
+ provider = null;
+ }
+
+ /**
* Creates a new GPX data store which will read the given test file.
*
* @param resource name of the test file in a directory relative to {@code "org/apache/sis/internal/gpx"}.
*/
private static GPXStore create(final String resource) throws DataStoreException {
- return new GPXStore(new StorageConnector(GPXReaderTest.class.getResourceAsStream(resource)));
+ return new GPXStore(provider, new StorageConnector(GPXReaderTest.class.getResourceAsStream(resource)));
}
/**
Modified: sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXWriterTest.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXWriterTest.java?rev=1776023&r1=1776022&r2=1776023&view=diff
==============================================================================
--- sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXWriterTest.java [UTF-8] (original)
+++ sis/branches/JDK8/storage/sis-xmlstore/src/test/java/org/apache/sis/internal/gpx/GPXWriterTest.java [UTF-8] Sun Dec 25 17:41:42 2016
@@ -31,6 +31,8 @@ import org.apache.sis.storage.DataStoreE
import org.apache.sis.storage.StorageConnector;
import org.apache.sis.test.DependsOn;
import org.apache.sis.test.TestCase;
+import org.junit.BeforeClass;
+import org.junit.AfterClass;
import org.junit.After;
import org.junit.Test;
@@ -53,11 +55,32 @@ import org.opengis.feature.Feature;
*/
@DependsOn(GPXReaderTest.class)
public final strictfp class GPXWriterTest extends TestCase {
+ /**
+ * The provider shared by all data stores created in this test class.
+ */
+ private static StoreProvider provider;
+
+ /**
+ * Creates the provider to be shared by all data stores created in this test class.
+ */
+ @BeforeClass
+ public static void createProvider() {
+ provider = new StoreProvider();
+ }
+
+ /**
+ * Disposes the data store provider after all tests have been completed.
+ */
+ @AfterClass
+ public static void disposeProvider() {
+ provider = null;
+ }
+
private GPXStore store;
private GPXReader reader(final File resource) throws Exception {
StorageConnector storage = new StorageConnector(resource);
- return new GPXReader(store = new GPXStore(storage));
+ return new GPXReader(store = new GPXStore(provider, storage));
}
@After
@@ -68,7 +91,7 @@ public final strictfp class GPXWriterTes
}
private static GPXWriter110 writer(final File f) throws DataStoreException, IOException, XMLStreamException {
- return new GPXWriter110(new GPXStore(new StorageConnector("dummy")), "Apache SIS", f, "UTF-8");
+ return new GPXWriter110(new GPXStore(provider, new StorageConnector(f)), null);
}
/**
@@ -82,7 +105,6 @@ public final strictfp class GPXWriterTes
final File f = new File("output.xml");
f.deleteOnExit();
if (f.exists()) f.delete();
- final GPXWriter110 writer = writer(f);
final Person person = new Person();
person.name = "Jean-Pierre";
@@ -110,16 +132,13 @@ public final strictfp class GPXWriterTes
metaData.keywords = Arrays.asList("test", "sample");
metaData.bounds = bounds;
- writer.writeStartDocument();
- writer.write(metaData, null, null, null);
- writer.writeEndDocument();
- writer.close();
-
+ try (GPXWriter110 writer = writer(f)) {
+ writer.write(metaData, null, null, null);
+ }
try (GPXReader reader = reader(f)) {
assertEquals(GPXStore.V1_1, reader.initialize(true));
assertEquals(metaData, reader.getMetadata());
}
-
if (f.exists()) f.delete();
}
@@ -136,7 +155,6 @@ public final strictfp class GPXWriterTes
final File f = new File("output.xml");
f.deleteOnExit();
if (f.exists()) f.delete();
- final GPXWriter110 writer = writer(f);
//way points -----------------------------------------------------------
Feature point1 = types.wayPoint.newInstance();
@@ -271,12 +289,9 @@ public final strictfp class GPXWriterTes
tracks.add(track1);
tracks.add(track2);
-
- writer.writeStartDocument();
- writer.write(null, wayPoints, routes, tracks);
- writer.writeEndDocument();
- writer.close();
-
+ try (GPXWriter110 writer = writer(f)) {
+ writer.write(null, wayPoints, routes, tracks);
+ }
try (final GPXReader reader = reader(f)) {
assertEquals(GPXStore.V1_1, reader.initialize(false));