Java Code Examples for org.geotools.data.DataStore#getFeatureSource()

The following examples show how to use org.geotools.data.DataStore#getFeatureSource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiPolygons.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
private static Set<MultiPolygon> initializeFrom(File shapeFile) throws IOException {
    URL shapeFileURL = shapeFile.toURI().toURL();
    Map<String, URL> inputMap = new HashMap<>();
    inputMap.put("url", shapeFileURL);

    DataStore dataStore = DataStoreFinder.getDataStore(inputMap);
    SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
    SimpleFeatureCollection collection = DataUtilities.collection(featureSource.getFeatures());
    dataStore.dispose();

    Set<MultiPolygon> polygons = new HashSet<>();
    SimpleFeatureIterator iterator = collection.features();
    while (iterator.hasNext())
        polygons.add((MultiPolygon) iterator.next().getDefaultGeometry());
    return polygons;
}
 
Example 2
Source File: CreateExternalDataSource.java    From sldeditor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Connect to vector data source.
 *
 * @param typeName the type name
 * @param dataStore the data store
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void connectToVectorDataSource(String typeName, DataStore dataStore)
        throws IOException {
    dsInfo.setTypeName(typeName);

    SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
    SimpleFeatureType schema = source.getSchema();

    if (schema.getCoordinateReferenceSystem() == null) {
        // No crs found to set a default and reload
        if (dataStore instanceof ShapefileDataStore) {
            ShapefileDataStore shapeFileDatastore = (ShapefileDataStore) dataStore;

            CoordinateReferenceSystem crs =
                    JCRSChooser.showDialog(
                            Localisation.getString(
                                    CreateExternalDataSource.class, "CRSPanel.title"),
                            defaultCRS.getIdentifiers().iterator().next().toString());
            if (crs != null) {
                shapeFileDatastore.forceSchemaCRS(crs);
            }

            source = dataStore.getFeatureSource(typeName);
            schema = source.getSchema();
        }
    }
    dsInfo.setSchema(schema);

    determineGeometryType(schema.getGeometryDescriptor().getType());
}
 
Example 3
Source File: GeoWaveFeatureSourceTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
public void testPartial(final Populater populater, final String ext)
    throws CQLException, Exception {
  final String typeName = "GeoWaveFeatureSourceTest_p" + ext;
  final SimpleFeatureType type =
      DataUtilities.createType(
          typeName,
          "geometry:Geometry:srid=4326,pop:java.lang.Long,pid:String,when:Date");
  final DataStore dataStore = createDataStore();
  populater.populate(type, dataStore);
  final SimpleFeatureSource source = dataStore.getFeatureSource(typeName);

  final Query query =
      new Query(
          typeName,
          CQL.toFilter(
              "BBOX(geometry,42,28,44,30) and when during 2005-05-01T20:32:56Z/2005-05-29T21:32:56Z"),
          new String[] {"geometry", "when", "pid"});
  final ReferencedEnvelope env = source.getBounds(query);
  assertEquals(43.454, env.getMaxX(), 0.0001);
  assertEquals(28.232, env.getMinY(), 0.0001);
  assertEquals(28.242, env.getMaxY(), 0.0001);
  assertEquals(2, source.getCount(query));
}
 
Example 4
Source File: GeoMesaGeoIndexer.java    From rya with Apache License 2.0 6 votes vote down vote up
private void initInternal() throws IOException {
    validPredicates = ConfigUtils.getGeoPredicates(conf);

    final DataStore dataStore = createDataStore(conf);

    try {
        featureType = getStatementFeatureType(dataStore);
    } catch (final IOException | SchemaException e) {
        throw new IOException(e);
    }

    featureSource = dataStore.getFeatureSource(featureType.getName());
    if (!(featureSource instanceof FeatureStore)) {
        throw new IllegalStateException("Could not retrieve feature store");
    }
    featureStore = (FeatureStore<SimpleFeatureType, SimpleFeature>) featureSource;
}
 
Example 5
Source File: ShpConnector.java    From TripleGeo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads the shape file from the configuration path and returns the
 * feature collection associated according to the configuration.
 *
 * @param shapePath with the path to the shapefile.
 * @param featureString with the featureString to filter.
 *
 * @return FeatureCollection with the collection of features filtered.
 */
private FeatureCollection getShapeFileFeatureCollection(String shapePath, String featureString) throws IOException 
{
  File file = new File(shapePath);

  // Create the map with the file URL to be passed to DataStore.
  Map map = new HashMap();
  try {
    map.put("url", file.toURL());
  } catch (MalformedURLException ex) {
    Logger.getLogger(ShpConnector.class.getName()).log(Level.SEVERE, null, ex);
  }
  if (map.size() > 0) {
    DataStore dataStore = DataStoreFinder.getDataStore(map);
    FeatureSource featureSource = dataStore.getFeatureSource(featureString);
    return featureSource.getFeatures();
  }
  return null;
}
 
Example 6
Source File: ShapeFileParser.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public List<GeneralResultRow> getData(String tablename) throws Exception {
	if (cacheList.containsKey(tablename)) {
		return cacheList.get(tablename);
	} else if (cacheList.containsKey(tablename.replaceAll("_geometry", ""))) {
		return cacheList.get(tablename.replaceAll("_geometry", ""));
	}
	DataStore dataStore = null;
	List<GeneralResultRow> result = null;
	try {
		Map<String, URL> connect = new HashMap<String, URL>();
		connect.put("url", shapefile.toURI().toURL());
		dataStore = DataStoreFinder.getDataStore(connect);
		FeatureSource<?, ?> featureSource = dataStore.getFeatureSource(tablename
				.replaceAll("_geometry", ""));
		if (featureSource != null) {
			result = getData(featureSource);
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		dataStore.dispose();
	}
	cacheList.put(tablename.replaceAll("_geometry", ""), result);
	return result;
}
 
Example 7
Source File: DatabaseClient.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks for the presence of a geometry field.
 *
 * @param dataStore the data store
 * @param name the name
 * @return true, if geometry field present
 */
private boolean hasGeometryField(DataStore dataStore, Name name) {
    try {
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(name);
        GeometryDescriptor geometryDescriptor =
                featureSource.getSchema().getGeometryDescriptor();

        return (geometryDescriptor != null);

    } catch (IOException e) {
        ConsoleManager.getInstance().exception(this, e);
    }
    return false;
}
 
Example 8
Source File: GeoWaveFeatureSourceTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void populate(final SimpleFeatureType type, final DataStore dataStore)
    throws IOException, CQLException, ParseException {

  dataStore.createSchema(type);

  final Transaction transaction1 = new DefaultTransaction();

  final SimpleFeatureStore source =
      (SimpleFeatureStore) dataStore.getFeatureSource(type.getName());
  final FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
      dataStore.getFeatureWriter(type.getTypeName(), transaction1);
  assertFalse(writer.hasNext());
  SimpleFeature newFeature = writer.next();
  newFeature.setAttribute("pop", Long.valueOf(77));
  newFeature.setAttribute("pid", UUID.randomUUID().toString());
  newFeature.setAttribute("when", DateUtilities.parseISO("2005-05-19T20:32:56Z"));
  newFeature.setAttribute("geometry", factory.createPoint(new Coordinate(43.454, 28.232)));
  source.addFeatures(DataUtilities.collection(newFeature));

  newFeature = writer.next();
  newFeature.setAttribute("pop", Long.valueOf(66));
  newFeature.setAttribute("pid", UUID.randomUUID().toString());
  newFeature.setAttribute("when", DateUtilities.parseISO("2005-05-18T20:32:56Z"));
  newFeature.setAttribute("geometry", factory.createPoint(new Coordinate(43.454, 27.232)));
  source.addFeatures(DataUtilities.collection(newFeature));

  newFeature = writer.next();
  newFeature.setAttribute("pop", Long.valueOf(100));
  newFeature.setAttribute("pid", UUID.randomUUID().toString());
  newFeature.setAttribute("when", DateUtilities.parseISO("2005-05-17T20:32:56Z"));
  newFeature.setAttribute("geometry", factory.createPoint(new Coordinate(43.454, 28.242)));
  source.addFeatures(DataUtilities.collection(newFeature));
  transaction1.commit();
  transaction1.close();
}
 
Example 9
Source File: GeoWaveFeatureSourceTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
public void testEmpty() throws Exception {
  final SimpleFeatureType type =
      DataUtilities.createType(
          "GeoWaveFeatureSourceTest_e",
          "geometry:Geometry:srid=4326,pop:java.lang.Long,pid:String,when:Date");
  final DataStore dataStore = createDataStore();
  dataStore.createSchema(type);
  final SimpleFeatureSource source = dataStore.getFeatureSource("GeoWaveFeatureSourceTest_e");
  final ReferencedEnvelope env = source.getBounds();
  assertEquals(90.0, env.getMaxX(), 0.0001);
  assertEquals(-180.0, env.getMinY(), 0.0001);
  final Query query = new Query("GeoWaveFeatureSourceTest_e", Filter.INCLUDE);
  assertEquals(0, source.getCount(query));
}
 
Example 10
Source File: FeatureFigureEditorApp.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource(File file) throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
    map.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);
    DataStore shapefileStore = DataStoreFinder.getDataStore(map);
    String typeName = shapefileStore.getTypeNames()[0]; // Shape files do only have one type name
    FeatureSource<SimpleFeatureType, SimpleFeature> featureSource;
    featureSource = shapefileStore.getFeatureSource(typeName);
    return featureSource;
}
 
Example 11
Source File: DataSourceInfoTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method for {@link com.sldeditor.datasource.impl.DataSourceInfo#getGeometryFieldName()}.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testGetGeometryFieldName() {
    URL url =
            SLDEditorFile.class
                    .getClassLoader()
                    .getResource("point/sld/shp/sld_cookbook_point.shp");

    Map map = new HashMap();
    map.put("url", url);
    DataStore dataStore;
    try {
        dataStore = DataStoreFinder.getDataStore(map);

        DataSourceInfo dsInfo = new DataSourceInfo();

        String typeName = dataStore.getTypeNames()[0];
        dsInfo.setTypeName(typeName);
        SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
        SimpleFeatureType schema = source.getSchema();

        assertNull(dsInfo.getGeometryFieldName());
        dsInfo.setSchema(schema);

        assertEquals("the_geom", dsInfo.getGeometryFieldName());
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 12
Source File: DataSourceInfoTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method for {@link
 * com.sldeditor.datasource.impl.DataSourceInfo#getPropertyDescriptorList()}.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testGetPropertyDescriptorList() {
    URL url =
            SLDEditorFile.class
                    .getClassLoader()
                    .getResource("point/sld/shp/sld_cookbook_point.shp");

    Map map = new HashMap();
    map.put("url", url);
    DataStore dataStore;
    try {
        dataStore = DataStoreFinder.getDataStore(map);

        DataSourceInfo dsInfo = new DataSourceInfo();

        String typeName = dataStore.getTypeNames()[0];
        dsInfo.setTypeName(typeName);
        SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
        SimpleFeatureType schema = source.getSchema();

        assertNull(dsInfo.getPropertyDescriptorList());
        dsInfo.setSchema(schema);

        Collection<PropertyDescriptor> fieldList = dsInfo.getPropertyDescriptorList();

        assertTrue(fieldList.size() == 3);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 13
Source File: DataSourceInfoTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method for {@link com.sldeditor.datasource.impl.DataSourceInfo#getFeatureStore()}. Test
 * method for {@link
 * com.sldeditor.datasource.impl.DataSourceInfo#setSchema(org.opengis.feature.type.FeatureType)}.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testGetFeatureStore() {
    URL url =
            SLDEditorFile.class
                    .getClassLoader()
                    .getResource("point/sld/shp/sld_cookbook_point.shp");

    Map map = new HashMap();
    map.put("url", url);
    DataStore dataStore;
    try {
        dataStore = DataStoreFinder.getDataStore(map);

        DataSourceInfo dsInfo = new DataSourceInfo();

        String typeName = dataStore.getTypeNames()[0];
        dsInfo.setTypeName(typeName);
        SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
        SimpleFeatureType schema = source.getSchema();
        dsInfo.setSchema(schema);

        assertNull(dsInfo.getFeatureStore());
        dsInfo.setDataStore(dataStore);

        FeatureStore<SimpleFeatureType, SimpleFeature> featureStore = dsInfo.getFeatureStore();

        assertTrue(featureStore != null);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 14
Source File: DataSourceInfoTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method for {@link com.sldeditor.datasource.impl.DataSourceInfo#getFeatureCollection()}.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testGetFeatureCollection() {
    URL url =
            SLDEditorFile.class
                    .getClassLoader()
                    .getResource("point/sld/shp/sld_cookbook_point.shp");

    Map map = new HashMap();
    map.put("url", url);
    DataStore dataStore;
    try {
        dataStore = DataStoreFinder.getDataStore(map);

        DataSourceInfo dsInfo = new DataSourceInfo();

        String typeName = dataStore.getTypeNames()[0];
        dsInfo.setTypeName(typeName);
        SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
        SimpleFeatureType schema = source.getSchema();

        assertNull(dsInfo.getGeometryFieldName());
        dsInfo.setSchema(schema);

        assertEquals("the_geom", dsInfo.getGeometryFieldName());
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 15
Source File: DataSourceInfoTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/** Test method for {@link com.sldeditor.datasource.impl.DataSourceInfo#getFeatures()}. */
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testGetFeatures() {
    URL url =
            SLDEditorFile.class
                    .getClassLoader()
                    .getResource("point/sld/shp/sld_cookbook_point.shp");

    Map map = new HashMap();
    map.put("url", url);
    DataStore dataStore;
    try {
        dataStore = DataStoreFinder.getDataStore(map);

        DataSourceInfo dsInfo = new DataSourceInfo();

        String typeName = dataStore.getTypeNames()[0];
        dsInfo.setTypeName(typeName);
        SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
        SimpleFeatureType schema = source.getSchema();

        assertNull(dsInfo.getFeatures());
        dsInfo.setSchema(schema);

        assertNull(dsInfo.getFeatures());
        dsInfo.setDataStore(dataStore);

        assertTrue(dsInfo.getFeatures() != null);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 16
Source File: WRS2GeometryStore.java    From geowave with Apache License 2.0 4 votes vote down vote up
private void init() throws MalformedURLException, IOException {
  if (!wrs2Shape.exists()) {
    if (!wrs2Directory.delete()) {
      LOGGER.warn("Unable to delete '" + wrs2Directory.getAbsolutePath() + "'");
    }
    final File wsDir = wrs2Directory.getParentFile();
    if (!wsDir.exists() && !wsDir.mkdirs()) {
      LOGGER.warn("Unable to create directory '" + wsDir.getAbsolutePath() + "'");
    }

    if (!wrs2Directory.mkdirs()) {
      LOGGER.warn("Unable to create directory '" + wrs2Directory.getAbsolutePath() + "'");
    }
    // download and unzip the shapefile
    final File targetFile = new File(wrs2Directory, WRS2_SHAPE_ZIP);
    if (targetFile.exists()) {
      if (!targetFile.delete()) {
        LOGGER.warn("Unable to delete file '" + targetFile.getAbsolutePath() + "'");
      }
    }
    FileUtils.copyURLToFile(new URL(WRS2_SHAPE_URL), targetFile);
    final ZipFile zipFile = new ZipFile(targetFile);
    try {
      final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
      while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
          FileUtils.copyInputStreamToFile(
              zipFile.getInputStream(entry),
              new File(wrs2Directory, entry.getName()));
          // HP Fortify "Path Traversal" false positive
          // What Fortify considers "user input" comes only
          // from users with OS-level access anyway
        }
      }
    } finally {
      zipFile.close();
    }
  }
  // read the shapefile and cache the features for quick lookup by path
  // and row
  try {
    final Map<String, Object> map = new HashMap<>();
    map.put("url", wrs2Shape.toURI().toURL());
    final DataStore dataStore = DataStoreFinder.getDataStore(map);
    if (dataStore == null) {
      LOGGER.error("Unable to get a datastore instance, getDataStore returned null");
      return;
    }
    final SimpleFeatureSource source = dataStore.getFeatureSource(WRS2_TYPE_NAME);

    final SimpleFeatureCollection featureCollection = source.getFeatures();
    wrs2Type = featureCollection.getSchema();
    final SimpleFeatureIterator iterator = featureCollection.features();
    while (iterator.hasNext()) {
      final SimpleFeature feature = iterator.next();
      final Number path = (Number) feature.getAttribute("PATH");
      final Number row = (Number) feature.getAttribute("ROW");
      featureCache.put(
          new WRS2Key(path.intValue(), row.intValue()),
          (MultiPolygon) feature.getDefaultGeometry());
    }
  } catch (final IOException e) {
    LOGGER.error(
        "Unable to read wrs2_asc_desc shapefile '" + wrs2Shape.getAbsolutePath() + "'",
        e);
    throw (e);
  }
}
 
Example 17
Source File: ShapefileMappingGenerator.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
public void run() throws IOException {
	Map<String, URL> connect = new HashMap<String, URL>();
	connect.put("url", new File(pathToShapefile).toURI().toURL());
	DataStore dataStore = DataStoreFinder.getDataStore(connect);
	String[] typeNames = dataStore.getTypeNames();
	for (int i = 0; i < typeNames.length; ++i) {
		String typeName = typeNames[i];
		triplesMaps.put(typeName, "");
		triplesMaps.put(typeName, triplesMaps.get(typeName) + printTriplesMap(typeName));
		triplesMaps.put(typeName, triplesMaps.get(typeName) + printLogicalSource(typeName));
		triplesMaps.put(typeName, triplesMaps.get(typeName) + printSubjectMap(baseURI, typeName));
		FeatureSource<?, ?> featureSource = dataStore.getFeatureSource(typeName);

		FeatureType ft = featureSource.getSchema();
		String typeNameGeo = typeNames[i] + "_Geometry";
		for (PropertyDescriptor property : ft.getDescriptors()) {

			String identifier = property.getName().getLocalPart();
			if (identifier.equals("the_geom")) {
				continue;
			}
			String datatype = TranslateDataTypeToXSD((property.getType().getBinding().getName()));
			Query q = new Query();
			triplesMaps.put(typeName, triplesMaps.get(typeName)
					+ printPredicateObjectMap(identifier, identifier, datatype, typeName));

		}
		// triplesMaps.put(typeName,
		// triplesMaps.get(typeName) + printPredicateObjectMap(true,
		// "hasGeometry",
		// baseURI + (baseURI.endsWith("/") ? "" : "/") + typeNameGeo +
		// "/{GeoTriplesID}", null,
		// typeName, true));
		triplesMaps
				.put(typeName,
						triplesMaps.get(typeName) + printPredicateObjectMap(true, "hasGeometry",
								baseURI + (baseURI.endsWith("/") ? "" : "/") + typeName
										+ "/Geometry/{GeoTriplesID}",
								null, null, "ogc", null, typeName, true, false));
		triplesMaps.put(typeNameGeo, "");
		triplesMaps.put(typeNameGeo, triplesMaps.get(typeNameGeo) + printTriplesMap(typeNameGeo));
		triplesMaps.put(typeNameGeo, triplesMaps.get(typeNameGeo) + printLogicalSource(typeName));
		triplesMaps.put(typeNameGeo, triplesMaps.get(typeNameGeo) + printSubjectMap(baseURI, typeName, null, true));
		triplesMaps.put(typeNameGeo, triplesMaps.get(typeNameGeo) + printGEOPredicateObjectMaps());
	}
	printmapping();
	printontology();
}
 
Example 18
Source File: OmsShapefileFeatureWriter.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void writeFeatureCollection() throws IOException {
    if (!concatOr(!hasWritten, doReset)) {
        return;
    }

    pm.beginTask("Writing features to shapefile...", -1);

    if (!file.endsWith(".shp")) {
        file = file + ".shp";
    }
    if (geodata != null && geodata.size() != 0) {
        pType = geodata.getSchema();
    }
    File shapeFile = new File(file);
    FileDataStoreFactorySpi factory = FileDataStoreFinder.getDataStoreFactory("shp");

    Map<String, Serializable> map = new HashMap<>();
    map.put("url", shapeFile.toURI().toURL());
    String shpDoIndex = PreferencesHandler.getShpDoIndex();
    if (shpDoIndex != null) {
        map.put("create spatial index", new Boolean(shpDoIndex));
    }

    String shpCharset = PreferencesHandler.getShpCharset();
    if (shpCharset != null) {
        map.put("charset", shpCharset);
    }

    DataStore newDataStore = factory.createNewDataStore(map);
    newDataStore.createSchema(pType);

    Transaction transaction = new DefaultTransaction("create");
    String typeName = newDataStore.getTypeNames()[0];
    SimpleFeatureStore featureStore = (SimpleFeatureStore) newDataStore.getFeatureSource(typeName);

    featureStore.setTransaction(transaction);
    try {
        if (geodata == null) {
            featureStore.addFeatures(new DefaultFeatureCollection());
        } else {
            featureStore.addFeatures(geodata);
        }
        transaction.commit();
    } catch (Exception problem) {
        transaction.rollback();
        throw new IOException(problem.getLocalizedMessage());
    } finally {
        transaction.close();
        pm.done();
    }

    hasWritten = true;
}
 
Example 19
Source File: ShapefileQueryOutputFormat.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Override
public void output(final ResultSet results) {
  int geometryColumn = -1;
  for (int i = 0; i < results.columnCount(); i++) {
    if (Geometry.class.isAssignableFrom(results.columnType(i))) {
      geometryColumn = i;
      break;
    }
  }
  if (geometryColumn < 0) {
    throw new RuntimeException(
        "Unable to output results to a shapefile without a geometry column.");
  }

  final SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
  ftb.setCRS(results.getCRS());
  ftb.setName(typeName);
  for (int i = 0; i < results.columnCount(); i++) {
    final AttributeTypeBuilder atb = new AttributeTypeBuilder();
    atb.setBinding(results.columnType(i));
    atb.nillable(true);
    if (i == geometryColumn) {
      ftb.add(atb.buildDescriptor("the_geom"));
    } else {
      ftb.add(atb.buildDescriptor(results.columnName(i)));
    }
  }
  final SimpleFeatureType sft = ftb.buildFeatureType();

  final SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(sft);
  final AtomicLong nextId = new AtomicLong(0L);
  final Iterator<SimpleFeature> features = Iterators.transform(results, r -> {
    sfb.reset();
    for (int i = 0; i < results.columnCount(); i++) {
      sfb.add(r.columnValue(i));
    }
    final SimpleFeature feature = sfb.buildFeature(Long.toString(nextId.incrementAndGet()));
    return feature;
  });

  final FileDataStoreFactorySpi factory = FileDataStoreFinder.getDataStoreFactory("shp");
  final File file = new File(outputFile);
  final Map<String, Serializable> params = Maps.newHashMap();
  final Transaction transaction = new DefaultTransaction("Write Results");
  try {
    params.put("url", file.toURI().toURL());
    final DataStore dataStore = factory.createNewDataStore(params);
    dataStore.createSchema(sft);
    final SimpleFeatureStore store =
        (SimpleFeatureStore) dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
    store.setTransaction(transaction);
    final SimpleFeatureCollection featureCollection =
        DataUtilities.collection(new SimpleFeatureIterator() {
          @Override
          public boolean hasNext() {
            return features.hasNext();
          }

          @Override
          public SimpleFeature next() throws NoSuchElementException {
            return features.next();
          }

          @Override
          public void close() {}
        });
    store.addFeatures(featureCollection);
    transaction.commit();
  } catch (final Exception e) {
    try {
      transaction.rollback();
    } catch (final IOException ioe) {
      throw new RuntimeException("Encountered an error when rolling back transaction", ioe);
    }
    throw new RuntimeException(
        "Encountered an error when writing the features to the file: " + e.getMessage(),
        e);
  }
}
 
Example 20
Source File: GeoWaveFeatureSourceTest.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void testFull(final Populater populater, final String ext) throws Exception {
  final String typeName = "GeoWaveFeatureSourceTest_full" + ext;
  final SimpleFeatureType type =
      DataUtilities.createType(
          typeName,
          "geometry:Geometry:srid=4326,pop:java.lang.Long,pid:String,when:Date");
  final DataStore dataStore = createDataStore();
  populater.populate(type, dataStore);
  final SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
  final ReferencedEnvelope env = source.getBounds();
  assertEquals(43.454, env.getMaxX(), 0.0001);
  assertEquals(27.232, env.getMinY(), 0.0001);
  assertEquals(28.242, env.getMaxY(), 0.0001);
  final Query query = new Query(typeName, Filter.INCLUDE);
  assertTrue(source.getCount(query) > 2);

  final short internalAdapterId =
      ((GeoWaveGTDataStore) dataStore).getInternalAdapterStore().addTypeName(typeName);
  try (final CloseableIterator<InternalDataStatistics<?, ?, ?>> stats =
      ((GeoWaveGTDataStore) dataStore).getDataStatisticsStore().getDataStatistics(
          internalAdapterId)) {
    assertTrue(stats.hasNext());
    int count = 0;
    BoundingBoxDataStatistics<SimpleFeature, ?> bboxStats = null;
    CountDataStatistics<SimpleFeature> cStats = null;
    FeatureTimeRangeStatistics timeRangeStats = null;
    FeatureNumericRangeStatistics popStats = null;
    while (stats.hasNext()) {
      final InternalDataStatistics<?, ?, ?> statsData = stats.next();
      if (statsData instanceof BoundingBoxDataStatistics) {
        bboxStats = (BoundingBoxDataStatistics<SimpleFeature, ?>) statsData;
      } else if (statsData instanceof CountDataStatistics) {
        cStats = (CountDataStatistics<SimpleFeature>) statsData;
      } else if (statsData instanceof FeatureTimeRangeStatistics) {
        timeRangeStats = (FeatureTimeRangeStatistics) statsData;
      } else if (statsData instanceof FeatureNumericRangeStatistics) {
        popStats = (FeatureNumericRangeStatistics) statsData;
      }
      count++;
    }
    // rather than maintain an exact count on stats as we should be able
    // to add them more dynamically, just make sure that there is some
    // set of base stats found
    assertTrue("Unexpectedly few stats found", count > 5);

    assertEquals(66, popStats.getMin(), 0.001);
    assertEquals(100, popStats.getMax(), 0.001);
    assertEquals(
        DateUtilities.parseISO("2005-05-17T20:32:56Z"),
        timeRangeStats.asTemporalRange().getStartTime());
    assertEquals(
        DateUtilities.parseISO("2005-05-19T20:32:56Z"),
        timeRangeStats.asTemporalRange().getEndTime());
    assertEquals(43.454, bboxStats.getMaxX(), 0.0001);
    assertEquals(27.232, bboxStats.getMinY(), 0.0001);
    assertEquals(3, cStats.getCount());
  }
}