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

The following examples show how to use org.geotools.data.DataStore#dispose() . 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: DatabaseClient.java    From sldeditor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Connect to datastore.
 *
 * @param dataStore the data store
 */
private void connectToDatastore(DataStore dataStore) {
    try {
        List<Name> nameList = dataStore.getNames();

        if (nameList != null) {
            for (Name name : nameList) {
                if (hasGeometryField(dataStore, name)) {
                    featureClassList.add(name.getLocalPart());
                }
            }
        }

        dataStore.dispose();
        connected = true;
    } catch (Exception e) {
        ConsoleManager.getInstance().exception(this, e);
    }
}
 
Example 3
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 4
Source File: TestUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static SimpleFeature resourceToFeature(final URL filterResource) throws IOException {
  final Map<String, Object> map = new HashMap<>();
  DataStore dataStore = null;
  map.put("url", filterResource);
  final SimpleFeature savedFilter;
  SimpleFeatureIterator sfi = null;
  try {
    dataStore = DataStoreFinder.getDataStore(map);
    if (dataStore == null) {
      LOGGER.error("Could not get dataStore instance, getDataStore returned null");
      throw new IOException("Could not get dataStore instance, getDataStore returned null");
    }
    // just grab the first feature and use it as a filter
    sfi = dataStore.getFeatureSource(dataStore.getNames().get(0)).getFeatures().features();
    savedFilter = sfi.next();

  } finally {
    if (sfi != null) {
      sfi.close();
    }
    if (dataStore != null) {
      dataStore.dispose();
    }
  }
  return savedFilter;
}
 
Example 5
Source File: AbstractGeotoolsDataStoreImporter.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
@Override
final public void importDatasource(Datasource datasource, List<String> geographyScope, List<String> temporalScope, List<String> datasourceLocation) throws Exception {
    DataStore dataStore = getDataStoreForDatasource(datasource);
    FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = GeotoolsDataStoreUtils.getFeatureReader(dataStore, getTypeNameForDatasource(datasource));

    // Load attribute values
    withSubjects(featureReader, dataStore, (feature, subject) -> {
        timedValueBuffer.addAll(buildTimedValuesFromFeature(datasource, feature, subject));
        fixedValueBuffer.addAll(buildFixedValuesFromFeature(datasource, feature, subject));
    });

    featureReader.close();
    dataStore.dispose();
}
 
Example 6
Source File: GeoToolsVectorDataStoreIngestPlugin.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsFile(final URL file) {
  DataStore dataStore = null;
  try {
    dataStore = getDataStore(file);
    if (dataStore != null) {
      dataStore.dispose();
    }
  } catch (final Exception e) {
    LOGGER.info("GeoTools was unable to read data source for file '" + file.getPath() + "'", e);
  }
  return dataStore != null;
}
 
Example 7
Source File: SeaRouting.java    From searoute with European Union Public License 1.2 4 votes vote down vote up
public SeaRouting(int resKM) {
	try {

		//load marnet
		DataStore store = null;
		SimpleFeatureCollection fc = null;
		/*try {
			URL url = getClass().getResource("/marnet/marnet_plus_"+resKM+"km.gpkg");
			HashMap<String, Object> map = new HashMap<>();
			map.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg");
			map.put(GeoPkgDataStoreFactory.DATABASE.key, url.getFile());
			map.put("url", url);
			store = DataStoreFinder.getDataStore(map);
			fc = store.getFeatureSource(store.getTypeNames()[0]).getFeatures();
		} catch (Exception e) {*/
			//URL url = new URL(path);
			HashMap<String, Object> map = new HashMap<>();
			map.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg");
			map.put(GeoPkgDataStoreFactory.DATABASE.key, "marnet/marnet_plus_"+resKM+"km.gpkg");
			map.put("url", "marnet/marnet_plus_"+resKM+"km.gpkg");
			store = DataStoreFinder.getDataStore(map);
			fc = store.getFeatureSource(store.getTypeNames()[0]).getFeatures();
		//}

		//build graph
		FeatureIterator<?> it = fc.features();
		FeatureGraphGenerator gGen = new FeatureGraphGenerator(new LineStringGraphGenerator());
		while(it.hasNext()) gGen.add(it.next());
		g = gGen.getGraph();
		it.close();
		store.dispose();
	} catch (Exception e) { e.printStackTrace(); }

	//link nodes around the globe
	for(Object o : g.getNodes()){
		Node n = (Node)o;
		Coordinate c = ((Point)n.getObject()).getCoordinate();
		if(c.x==180) {
			Node n_ = getNode(new Coordinate(-c.x,c.y));
			if(LOGGER.isTraceEnabled()) LOGGER.trace(c + " -> " + ((Point)n_.getObject()).getCoordinate());
			BasicEdge be = new BasicEdge(n, n_);
			n.add(be);
			n_.add(be);
			g.getEdges().add(be);
		}
	}

	//define weighters
	defaultWeighter = buildEdgeWeighter(true, true);
	noSuezWeighter = buildEdgeWeighter(false, true);
	noPanamaWeighter = buildEdgeWeighter(true, false);
	noSuezNoPanamaWeighter = buildEdgeWeighter(false, false);
}
 
Example 8
Source File: ShapeFileParser.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
public List<TableDef> getTablesDefs() throws Exception {
	DataStore dataStore = null;
	List<ColumnDef> columns = null;
	TableDef onlytable = null;
	Set<Key> primkeys = new HashSet<Key>();
	List<TableDef> tables = new ArrayList<TableDef>();
	try {
		Map<String, URL> connect = new HashMap<String, URL>();
		connect.put("url", shapefile.toURI().toURL());
		dataStore = DataStoreFinder.getDataStore(connect);
		String[] typeNames = dataStore.getTypeNames();
		for (int i = 0; i < typeNames.length; ++i) {
			String typeName = typeNames[i];
			FeatureSource<?, ?> featureSource = dataStore
					.getFeatureSource(typeName);

			FeatureType ft = featureSource.getSchema();
			columns = new ArrayList<ColumnDef>();
			for (PropertyDescriptor property : ft.getDescriptors()) {

				Identifier identifier = Identifier.createDelimited(property
						.getName().getLocalPart());
				DataType datatype = TableDefUtils.TranslateDataTypeToSQLType((property
						.getType().getBinding().getName()));
				ColumnDef col = new ColumnDef(identifier, datatype,
						property.isNillable());
				columns.add(col);
			}
			//Identifier identifier = Identifier.createDelimited("gid");
			//ColumnDef col = new ColumnDef(identifier, TranslateDataTypeToSQLType("Int"), false);
			//columns.add(col);
			//primkeys.add(Key.create(identifier));
			TableName tablename = TableName.create(null, null,
					Identifier.create(true, dataStore.getTypeNames()[0]));
			onlytable = new TableDef(tablename, columns, null, primkeys,
					new HashSet<ForeignKey>());
			tables.add(onlytable);
		}

	} catch (Throwable e) {
		throw new Exception(e.getMessage());
	} finally {
		dataStore.dispose();

	}
	return tables;

}
 
Example 9
Source File: ShapeFileParserGDAL.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
public List<TableDef> getTablesDefs() throws Exception {
	DataStore dataStore = null;
	List<ColumnDef> columns = null;
	TableDef onlytable = null;
	Set<Key> primkeys = new HashSet<Key>();
	List<TableDef> tables = new ArrayList<TableDef>();
	try {
		Map<String, URL> connect = new HashMap<String, URL>();
		connect.put("url", shapefile.toURI().toURL());
		dataStore = DataStoreFinder.getDataStore(connect);
		String[] typeNames = dataStore.getTypeNames();
		for (int i = 0; i < typeNames.length; ++i) {
			String typeName = typeNames[i];
			FeatureSource<?, ?> featureSource = dataStore.getFeatureSource(typeName);

			FeatureType ft = featureSource.getSchema();
			columns = new ArrayList<ColumnDef>();
			for (PropertyDescriptor property : ft.getDescriptors()) {

				Identifier identifier = Identifier.createDelimited(property.getName().getLocalPart());
				DataType datatype = TableDefUtils
						.TranslateDataTypeToSQLType((property.getType().getBinding().getName()));
				ColumnDef col = new ColumnDef(identifier, datatype, property.isNillable());
				columns.add(col);
			}
			// Identifier identifier = Identifier.createDelimited("gid");
			// ColumnDef col = new ColumnDef(identifier,
			// TranslateDataTypeToSQLType("Int"), false);
			// columns.add(col);
			// primkeys.add(Key.create(identifier));
			TableName tablename = TableName.create(null, null,
					Identifier.create(true, dataStore.getTypeNames()[0]));
			onlytable = new TableDef(tablename, columns, null, primkeys, new HashSet<ForeignKey>());
			tables.add(onlytable);
		}

	} catch (Throwable e) {
		throw new Exception(e.getMessage());
	} finally {
		dataStore.dispose();

	}
	return tables;

}
 
Example 10
Source File: TestUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
public static ExpectedResults getExpectedResults(
    final URL[] expectedResultsResources,
    final CoordinateReferenceSystem crs) throws IOException {
  final Map<String, Object> map = new HashMap<>();
  DataStore dataStore = null;
  final Set<Long> hashedCentroids = new HashSet<>();
  int expectedResultCount = 0;
  final MathTransform mathTransform = transformFromCrs(crs);
  final TWKBWriter writer = new TWKBWriter();
  final TWKBReader reader = new TWKBReader();
  for (final URL expectedResultsResource : expectedResultsResources) {
    map.put("url", expectedResultsResource);
    SimpleFeatureIterator featureIterator = null;
    try {
      dataStore = DataStoreFinder.getDataStore(map);
      if (dataStore == null) {
        LOGGER.error("Could not get dataStore instance, getDataStore returned null");
        throw new IOException("Could not get dataStore instance, getDataStore returned null");
      }
      final SimpleFeatureCollection expectedResults =
          dataStore.getFeatureSource(dataStore.getNames().get(0)).getFeatures();

      expectedResultCount += expectedResults.size();
      // unwrap the expected results into a set of features IDs so its
      // easy to check against
      featureIterator = expectedResults.features();
      while (featureIterator.hasNext()) {
        final SimpleFeature feature = featureIterator.next();
        final Geometry geometry = (Geometry) feature.getDefaultGeometry();

        // TODO: Geometry has to be serialized and deserialized here
        // to make the centroid match the one coming out of the
        // database.
        final long centroid =
            hashCentroid(
                reader.read(
                    writer.write(
                        mathTransform != null ? JTS.transform(geometry, mathTransform)
                            : geometry)));
        hashedCentroids.add(centroid);
      }
    } catch (MismatchedDimensionException | TransformException | ParseException e) {
      LOGGER.warn("Unable to transform geometry", e);
      Assert.fail("Unable to transform geometry to CRS: " + crs.toString());
    } finally {
      IOUtils.closeQuietly(featureIterator);
      if (dataStore != null) {
        dataStore.dispose();
      }
    }
  }
  return new ExpectedResults(hashedCentroids, expectedResultCount);
}
 
Example 11
Source File: AbstractGeotoolsDataStoreImporter.java    From TomboloDigitalConnector with MIT License 3 votes vote down vote up
/**
 * getAttributesForDatasource
 * Returns a list of attribute types for a datasource. If your DataStore was
 * a database, this would return the columns in the table to be imported.
 * You will probably use this when setting up the attributes on the Datasource.
 * Note that these are Geotools AttributeTypes and have nothing to do with
 * Tombolo's Attribute objects.
 * @param datasource The datasource being imported
 * @return A list of attributes for the datasource
 * @throws IOException
 */
protected List<AttributeType> getAttributesForDatasource(Datasource datasource) throws IOException {
    DataStore dataStore = null;
    try {
        dataStore = getDataStoreForDatasource(datasource);
        SimpleFeatureType schema = dataStore.getSchema(getTypeNameForDatasource(datasource));
        return schema.getTypes();
    } finally {
        if (null != dataStore) dataStore.dispose();
    }
}