Search in sources :

Example 1 with GeoJSONStreamWriter

use of org.geotoolkit.storage.geojson.GeoJSONStreamWriter in project geotoolkit by Geomatys.

the class GeoJSONStreamWritingDemo method main.

public static void main(String[] args) throws DataStoreException {
    Demos.init();
    final GeometryFactory gf = org.geotoolkit.geometry.jts.JTS.getFactory();
    // start by creating a memory featurestore for this test -----------------------------
    final FeatureTypeBuilder ftb = new FeatureTypeBuilder();
    ftb.setName("Fish");
    ftb.addAttribute(String.class).setName("name");
    ftb.addAttribute(Integer.class).setName("length");
    ftb.addAttribute(Point.class).setName("position").setCRS(CommonCRS.WGS84.normalizedGeographic()).addRole(AttributeRole.DEFAULT_GEOMETRY);
    final FeatureType type = ftb.build();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final GeoJSONStreamWriter writer = new GeoJSONStreamWriter(baos, type, 7);
    Feature feature = writer.next();
    feature.setPropertyValue("name", "sam");
    feature.setPropertyValue("length", 30);
    feature.setPropertyValue("position", gf.createPoint(new Coordinate(20, 30)));
    writer.write();
    feature = writer.next();
    feature.setPropertyValue("name", "tomy");
    feature.setPropertyValue("length", 5);
    feature.setPropertyValue("position", gf.createPoint(new Coordinate(41, 56)));
    writer.write();
    // and so on write features ...
    writer.close();
    try {
        // print output JSON
        System.out.println(baos.toString("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Also used : FeatureTypeBuilder(org.apache.sis.feature.builder.FeatureTypeBuilder) FeatureType(org.opengis.feature.FeatureType) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) Coordinate(org.locationtech.jts.geom.Coordinate) GeoJSONStreamWriter(org.geotoolkit.storage.geojson.GeoJSONStreamWriter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Point(org.locationtech.jts.geom.Point) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Feature(org.opengis.feature.Feature)

Example 2 with GeoJSONStreamWriter

use of org.geotoolkit.storage.geojson.GeoJSONStreamWriter in project geotoolkit by Geomatys.

the class FeatureCollectionToReferenceConverter method convert.

/**
 * {@inheritDoc}
 */
@Override
public Reference convert(final FeatureCollection source, final Map<String, Object> params) throws UnconvertibleObjectException {
    if (params.get(TMP_DIR_PATH) == null) {
        throw new UnconvertibleObjectException("The output directory should be defined.");
    }
    if (params.get(TMP_DIR_URL) == null) {
        throw new UnconvertibleObjectException("The output directory URL should be defined.");
    }
    if (source == null) {
        throw new UnconvertibleObjectException("The output data should be defined.");
    }
    // TODO : useless test, null test above is all we need, fix this and other converters
    if (!(source instanceof FeatureCollection)) {
        throw new UnconvertibleObjectException("The requested output data is not an instance of FeatureCollection.");
    }
    Reference reference = new Reference();
    reference.setMimeType((String) params.get(MIME));
    reference.setEncoding((String) params.get(ENCODING));
    final FeatureType ft = source.getType();
    final String namespace = NamesExt.getNamespace(ft.getName());
    final Map<String, String> schemaLocation = new HashMap<>();
    final String randomFileName = UUID.randomUUID().toString();
    if (WPSMimeType.APP_GEOJSON.val().equalsIgnoreCase(reference.getMimeType())) {
        // create file
        final Path dataFile = buildPath(params, randomFileName + ".json");
        try (OutputStream fos = Files.newOutputStream(dataFile, CREATE, TRUNCATE_EXISTING, WRITE);
            GeoJSONStreamWriter writer = new GeoJSONStreamWriter(fos, ft, WPSConvertersUtils.FRACTION_DIGITS);
            Stream<Feature> st = source.features(false)) {
            Iterator<Feature> iterator = st.iterator();
            while (iterator.hasNext()) {
                Feature next = iterator.next();
                Feature neww = writer.next();
                FeatureExt.copy(next, neww, false);
                writer.write();
            }
        } catch (DataStoreException e) {
            throw new UnconvertibleObjectException("Can't write Feature into GeoJSON output stream.", e);
        } catch (IOException e) {
            throw new UnconvertibleObjectException(e);
        }
        final String relLoc = getRelativeLocation(dataFile, params);
        reference.setHref(params.get(TMP_DIR_URL) + "/" + relLoc);
        reference.setSchema(null);
    } else if (WPSMimeType.APP_GML.val().equalsIgnoreCase(reference.getMimeType()) || WPSMimeType.TEXT_XML.val().equalsIgnoreCase(reference.getMimeType()) || WPSMimeType.TEXT_GML.val().equalsIgnoreCase(reference.getMimeType())) {
        try {
            reference.setSchema(WPSConvertersUtils.writeSchema(ft, params));
            schemaLocation.put(namespace, reference.getSchema());
        } catch (JAXBException ex) {
            throw new UnconvertibleObjectException("Can't write FeatureType into xsd schema.", ex);
        } catch (IOException ex) {
            throw new UnconvertibleObjectException("Can't create xsd schema file.", ex);
        }
        // Write Feature
        final JAXPStreamFeatureWriter featureWriter = new JAXPStreamFeatureWriter(schemaLocation);
        // create file
        final Path dataFile = buildPath(params, randomFileName + ".xml");
        try (final OutputStream dataStream = Files.newOutputStream(dataFile);
            final AutoCloseable xmlCloser = () -> featureWriter.dispose()) {
            // Write feature in file
            featureWriter.write(source, dataStream);
            final String relLoc = getRelativeLocation(dataFile, params);
            reference.setHref(params.get(TMP_DIR_URL) + "/" + relLoc);
        } catch (XMLStreamException ex) {
            throw new UnconvertibleObjectException("Stax exception while writing the feature collection", ex);
        } catch (DataStoreException ex) {
            throw new UnconvertibleObjectException("FeatureStore exception while writing the feature collection", ex);
        } catch (FeatureStoreRuntimeException ex) {
            throw new UnconvertibleObjectException("FeatureStoreRuntimeException exception while writing the feature collection", ex);
        } catch (Exception ex) {
            throw new UnconvertibleObjectException(ex);
        }
    } else {
        throw new UnconvertibleObjectException("Unsupported mime-type for " + this.getClass().getName() + " : " + reference.getMimeType());
    }
    return reference;
}
Also used : Path(java.nio.file.Path) FeatureType(org.opengis.feature.FeatureType) DataStoreException(org.apache.sis.storage.DataStoreException) HashMap(java.util.HashMap) Reference(org.geotoolkit.wps.xml.v200.Reference) JAXBException(javax.xml.bind.JAXBException) JAXPStreamFeatureWriter(org.geotoolkit.feature.xml.jaxp.JAXPStreamFeatureWriter) Feature(org.opengis.feature.Feature) XMLStreamException(javax.xml.stream.XMLStreamException) DataStoreException(org.apache.sis.storage.DataStoreException) FeatureStoreRuntimeException(org.geotoolkit.storage.feature.FeatureStoreRuntimeException) JAXBException(javax.xml.bind.JAXBException) UnconvertibleObjectException(org.apache.sis.util.UnconvertibleObjectException) UnconvertibleObjectException(org.apache.sis.util.UnconvertibleObjectException) XMLStreamException(javax.xml.stream.XMLStreamException) FeatureCollection(org.geotoolkit.storage.feature.FeatureCollection) GeoJSONStreamWriter(org.geotoolkit.storage.geojson.GeoJSONStreamWriter) FeatureStoreRuntimeException(org.geotoolkit.storage.feature.FeatureStoreRuntimeException)

Example 3 with GeoJSONStreamWriter

use of org.geotoolkit.storage.geojson.GeoJSONStreamWriter in project geotoolkit by Geomatys.

the class FeatureToReferenceConverter method convert.

/**
 * {@inheritDoc}
 */
@Override
public Reference convert(final Feature source, final Map<String, Object> params) throws UnconvertibleObjectException {
    if (params.get(TMP_DIR_PATH) == null) {
        throw new UnconvertibleObjectException("The output directory should be defined.");
    }
    if (source == null) {
        throw new UnconvertibleObjectException("The output directory should be defined.");
    }
    FeatureType ft = null;
    if (source instanceof Feature) {
        ft = source.getType();
    } else {
        throw new UnconvertibleObjectException("The requested output reference data is not an instance of Feature.");
    }
    Reference reference = new Reference();
    reference.setMimeType((String) params.get(MIME));
    reference.setEncoding((String) params.get(ENCODING));
    final String namespace = NamesExt.getNamespace(ft.getName());
    final Map<String, String> schemaLocation = new HashMap<>();
    final String randomFileName = UUID.randomUUID().toString();
    final String tmpDirUrl = (String) params.get(TMP_DIR_URL);
    if (WPSMimeType.APP_GEOJSON.val().equalsIgnoreCase(reference.getMimeType())) {
        // create file
        final Path dataFile = buildPath(params, randomFileName + ".json");
        try {
            try (OutputStream fos = Files.newOutputStream(dataFile);
                GeoJSONStreamWriter writer = new GeoJSONStreamWriter(fos, ft, WPSConvertersUtils.FRACTION_DIGITS)) {
                Feature next = writer.next();
                FeatureExt.copy(source, next, true);
                writer.write();
            }
        } catch (DataStoreException e) {
            throw new UnconvertibleObjectException("Can't write Feature into GeoJSON output stream.", e);
        } catch (IOException e) {
            throw new UnconvertibleObjectException(e);
        }
        final String relLoc = getRelativeLocation(dataFile, params);
        reference.setHref(tmpDirUrl + "/" + relLoc);
        reference.setSchema(null);
    } else if (WPSMimeType.APP_GML.val().equalsIgnoreCase(reference.getMimeType()) || WPSMimeType.TEXT_XML.val().equalsIgnoreCase(reference.getMimeType()) || WPSMimeType.TEXT_GML.val().equalsIgnoreCase(reference.getMimeType())) {
        // Write FeatureType
        try {
            reference.setSchema(WPSConvertersUtils.writeSchema(ft, params));
            schemaLocation.put(namespace, reference.getSchema());
        } catch (JAXBException ex) {
            throw new UnconvertibleObjectException("Can't write FeatureType into xsd schema.", ex);
        } catch (IOException ex) {
            throw new UnconvertibleObjectException("Can't create xsd schema file.", ex);
        }
        // Write Feature
        final XmlFeatureWriter featureWriter = new JAXPStreamFeatureWriter(schemaLocation);
        // create file
        final Path dataFile = buildPath(params, randomFileName + ".xml");
        try (final OutputStream dataStream = Files.newOutputStream(dataFile);
            final AutoCloseable xmlCloser = () -> featureWriter.dispose()) {
            // Write feature in file
            featureWriter.write(source, dataStream);
            final String relLoc = getRelativeLocation(dataFile, params);
            reference.setHref(tmpDirUrl + "/" + relLoc);
        } catch (XMLStreamException ex) {
            throw new UnconvertibleObjectException("Stax exception while writing the feature collection", ex);
        } catch (DataStoreException ex) {
            throw new UnconvertibleObjectException("FeatureStore exception while writing the feature collection", ex);
        } catch (FeatureStoreRuntimeException ex) {
            throw new UnconvertibleObjectException("FeatureStoreRuntimeException exception while writing the feature collection", ex);
        } catch (Exception ex) {
            throw new UnconvertibleObjectException(ex);
        }
    } else
        throw new UnconvertibleObjectException("Unsupported mime-type for " + this.getClass().getName() + " : " + reference.getMimeType());
    return reference;
}
Also used : Path(java.nio.file.Path) FeatureType(org.opengis.feature.FeatureType) DataStoreException(org.apache.sis.storage.DataStoreException) HashMap(java.util.HashMap) Reference(org.geotoolkit.wps.xml.v200.Reference) OutputStream(java.io.OutputStream) JAXBException(javax.xml.bind.JAXBException) IOException(java.io.IOException) JAXPStreamFeatureWriter(org.geotoolkit.feature.xml.jaxp.JAXPStreamFeatureWriter) Feature(org.opengis.feature.Feature) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) XMLStreamException(javax.xml.stream.XMLStreamException) UnconvertibleObjectException(org.apache.sis.util.UnconvertibleObjectException) DataStoreException(org.apache.sis.storage.DataStoreException) FeatureStoreRuntimeException(org.geotoolkit.storage.feature.FeatureStoreRuntimeException) UnconvertibleObjectException(org.apache.sis.util.UnconvertibleObjectException) XMLStreamException(javax.xml.stream.XMLStreamException) XmlFeatureWriter(org.geotoolkit.feature.xml.XmlFeatureWriter) GeoJSONStreamWriter(org.geotoolkit.storage.geojson.GeoJSONStreamWriter) FeatureStoreRuntimeException(org.geotoolkit.storage.feature.FeatureStoreRuntimeException)

Example 4 with GeoJSONStreamWriter

use of org.geotoolkit.storage.geojson.GeoJSONStreamWriter in project geotoolkit by Geomatys.

the class GeoJSONWriteTest method writePropertyArrayTest.

@Test
public void writePropertyArrayTest() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FeatureType validFeatureType = buildPropertyArrayFeatureType("arrayFT", Point.class);
    Point pt = (Point) WKT_READER.read(PROPERTIES.getProperty("point"));
    double[][] array1 = new double[5][5];
    double[][] array2 = new double[5][5];
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            array1[i][j] = i + j;
            array2[i][j] = i - j;
        }
    }
    try (GeoJSONStreamWriter fw = new GeoJSONStreamWriter(baos, validFeatureType, 4)) {
        Feature feature = fw.next();
        feature.setPropertyValue("array", array1);
        feature.setPropertyValue(AttributeConvention.GEOMETRY, pt);
        fw.write();
        feature = fw.next();
        feature.setPropertyValue("array", array2);
        feature.setPropertyValue(AttributeConvention.GEOMETRY, pt);
        fw.write();
    }
    String outputJSON = baos.toString("UTF-8");
    assertNotNull(outputJSON);
    assertFalse(outputJSON.isEmpty());
    String expected = "{\n" + "\"type\":\"FeatureCollection\"\n" + ",\"features\":[\n" + "{\"type\":\"Feature\",\"id\":\"0\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[-105.0162,39.5742]},\"properties\":{\"array\":[[0.0,1.0,2.0,3.0,4.0],[1.0,2.0,3.0,4.0,5.0],[2.0,3.0,4.0,5.0,6.0],[3.0,4.0,5.0,6.0,7.0],[4.0,5.0,6.0,7.0,8.0]]}}\n" + ",{\"type\":\"Feature\",\"id\":\"1\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[-105.0162,39.5742]},\"properties\":{\"array\":[[0.0,-1.0,-2.0,-3.0,-4.0],[1.0,0.0,-1.0,-2.0,-3.0],[2.0,1.0,0.0,-1.0,-2.0],[3.0,2.0,1.0,0.0,-1.0],[4.0,3.0,2.0,1.0,0.0]]}}\n" + "]}";
    compareJSON(expected, outputJSON);
}
Also used : FeatureType(org.opengis.feature.FeatureType) GeoJSONStreamWriter(org.geotoolkit.storage.geojson.GeoJSONStreamWriter) SimpleInternationalString(org.apache.sis.util.SimpleInternationalString) Feature(org.opengis.feature.Feature) Test(org.junit.Test)

Example 5 with GeoJSONStreamWriter

use of org.geotoolkit.storage.geojson.GeoJSONStreamWriter in project geotoolkit by Geomatys.

the class GeoJSONWriteTest method testWriteEmptyStream.

/**
 * Verify writer can be safely closed without being used.
 * It can happen when a component receive an empty dataset, and therefore does not write anything in output.
 */
@Test
public void testWriteEmptyStream() throws Exception {
    final GeoJSONStreamWriter writer = new GeoJSONStreamWriter(new ByteArrayOutputStream(0), buildGeometryFeatureType("test", Point.class), 7);
    writer.close();
}
Also used : GeoJSONStreamWriter(org.geotoolkit.storage.geojson.GeoJSONStreamWriter) Test(org.junit.Test)

Aggregations

GeoJSONStreamWriter (org.geotoolkit.storage.geojson.GeoJSONStreamWriter)12 Feature (org.opengis.feature.Feature)11 FeatureType (org.opengis.feature.FeatureType)11 HashMap (java.util.HashMap)6 JAXBException (javax.xml.bind.JAXBException)6 DataStoreException (org.apache.sis.storage.DataStoreException)6 UnconvertibleObjectException (org.apache.sis.util.UnconvertibleObjectException)6 Test (org.junit.Test)5 SimpleInternationalString (org.apache.sis.util.SimpleInternationalString)4 Path (java.nio.file.Path)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 ElementFeatureWriter (org.geotoolkit.feature.xml.jaxp.ElementFeatureWriter)3 JAXPStreamFeatureWriter (org.geotoolkit.feature.xml.jaxp.JAXPStreamFeatureWriter)3 FeatureStoreRuntimeException (org.geotoolkit.storage.feature.FeatureStoreRuntimeException)3 Data (org.geotoolkit.wps.xml.v200.Data)3 Reference (org.geotoolkit.wps.xml.v200.Reference)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1