org.geotools.data.shapefile.ShapefileDataStore Java Examples
The following examples show how to use
org.geotools.data.shapefile.ShapefileDataStore.
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: GamaShapeFile.java From gama with GNU General Public License v3.0 | 6 votes |
@Override protected CoordinateReferenceSystem getOwnCRS(final IScope scope) { ShapefileDataStore store = null; try { final URL url = getFile(scope).toURI().toURL(); store = getDataStore(url); CoordinateReferenceSystem crs = store.getFeatureSource().getInfo().getCRS(); if (crs == null) { crs = GISUtils.manageGoogleCRS(url); } return crs; } catch (final IOException e) { return null; } finally { if (store != null) { store.dispose(); } } }
Example #2
Source File: ShapeInMemFeatureModelTest.java From geomajas-project-server with GNU Affero General Public License v3.0 | 6 votes |
@Before public void setUp() throws Exception { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); URL url = classloader.getResource(SHAPE_FILE); DataStore dataStore = new ShapefileDataStore(url); featureModel = new ShapeInMemFeatureModel(dataStore, LAYER_NAME, 4326, converterService); featureModel.setLayerInfo(layerInfo); FeatureSource<SimpleFeatureType, SimpleFeature> fs = featureModel.getFeatureSource(); FeatureIterator<SimpleFeature> fi = fs.getFeatures().features(); feature = fi.next(); feature = fi.next(); feature = fi.next(); feature = fi.next(); feature = fi.next(); fi.close(); }
Example #3
Source File: GamaShapeFile.java From gama with GNU General Public License v3.0 | 6 votes |
@Override public Envelope3D computeEnvelope(final IScope scope) { if (gis == null) { ShapefileDataStore store = null; try { store = getDataStore(getFile(scope).toURI().toURL()); final Envelope3D env = Envelope3D.of(store.getFeatureSource().getBounds()); computeProjection(scope, env); } catch (final IOException e) { return Envelope3D.EMPTY; } finally { if (store != null) { store.dispose(); } } } return gis.getProjectedEnvelope(); }
Example #4
Source File: OmsShapefileFeatureReader.java From hortonmachine with GNU General Public License v3.0 | 6 votes |
@Execute public void readFeatureCollection() throws IOException { if (!concatOr(geodata == null, doReset)) { return; } try { File shapeFile = new File(file); pm.beginTask("Reading features from shapefile: " + shapeFile.getName(), -1); FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile); if (store instanceof ShapefileDataStore) { ShapefileDataStore shpStore = (ShapefileDataStore) store; String shpCharset = PreferencesHandler.getShpCharset(); if (shpCharset != null) { shpStore.setCharset(Charset.forName(shpCharset)); } } SimpleFeatureSource featureSource = store.getFeatureSource(); geodata = featureSource.getFeatures(); store.dispose(); } finally { pm.done(); } }
Example #5
Source File: GeoToolsFeatureModelTest.java From geomajas-project-server with GNU Affero General Public License v3.0 | 6 votes |
@Before public void init() throws Exception { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); URL url = classloader.getResource(SHAPE_FILE); DataStore dataStore = new ShapefileDataStore(url); featureModel = new GeoToolsFeatureModel(dataStore, LAYER_NAME, 4326, converterService); featureModel.setLayerInfo(layerInfo); FeatureSource<SimpleFeatureType, SimpleFeature> fs = featureModel.getFeatureSource(); FeatureIterator<SimpleFeature> fi = fs.getFeatures().features(); feature = fi.next(); feature = fi.next(); feature = fi.next(); feature = fi.next(); feature = fi.next(); }
Example #6
Source File: CreateExternalDataSource.java From sldeditor with GNU General Public License v3.0 | 6 votes |
/** * 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 #7
Source File: ExportGeometryAction.java From snap-desktop with GNU General Public License v3.0 | 5 votes |
static void writeEsriShapefile(Class<?> geomType, List<SimpleFeature> features, File file) throws IOException { String geomName = geomType.getSimpleName(); String basename = file.getName(); if (basename.endsWith(FILE_EXTENSION_SHAPEFILE)) { basename = basename.substring(0, basename.length() - 4); } File file1 = new File(file.getParentFile(), basename + "_" + geomName + FILE_EXTENSION_SHAPEFILE); SimpleFeature simpleFeature = features.get(0); SimpleFeatureType simpleFeatureType = changeGeometryType(simpleFeature.getType(), geomType); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); Map<String, Serializable> map = Collections.singletonMap("url", file1.toURI().toURL()); ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(map); dataStore.createSchema(simpleFeatureType); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); DefaultTransaction transaction = new DefaultTransaction("X"); if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; SimpleFeatureCollection collection = new ListFeatureCollection(simpleFeatureType, features); featureStore.setTransaction(transaction); // I'm not sure why the next line is necessary (mp/20170627) // Without it is not working, the wrong feature type is used for writing // But it is not mentioned in the tutorials dataStore.getEntry(featureSource.getName()).getState(transaction).setFeatureType(simpleFeatureType); try { featureStore.addFeatures(collection); transaction.commit(); } catch (Exception problem) { transaction.rollback(); throw new IOException(problem); } finally { transaction.close(); } } else { throw new IOException(typeName + " does not support read/write access"); } }
Example #8
Source File: ShapeFile.java From tutorials with MIT License | 5 votes |
private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception { // If you decide to use the TYPE type and create a Data Store with it, // You will need to uncomment this line to set the Coordinate Reference System // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); try { featureStore.addFeatures(collection); transaction.commit(); } catch (Exception problem) { problem.printStackTrace(); transaction.rollback(); } finally { transaction.close(); } System.exit(0); // success! } else { System.out.println(typeName + " does not support read/write access"); System.exit(1); } }
Example #9
Source File: ShapeFile.java From tutorials with MIT License | 5 votes |
private static ShapefileDataStore setDataStoreParams(ShapefileDataStoreFactory dataStoreFactory, Map<String, Serializable> params, File shapeFile, SimpleFeatureType CITY) throws Exception { params.put("url", shapeFile.toURI() .toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); dataStore.createSchema(CITY); return dataStore; }
Example #10
Source File: ShpParser.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
public void write(SimpleFeatureCollection obj, OutputStream output, SimpleFeatureType sft, String layerId) throws IOException { File shpFile = File.createTempFile("shpFile", ".shp"); ShapefileDataStoreFactory fact = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put(ShapefileDataStoreFactory.URLP.key, shpFile.toURI().toURL()); params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE); ShapefileDataStore shpDataStore = (ShapefileDataStore) fact.createNewDataStore(params); shpDataStore.createSchema(sft); SimpleFeatureStore store = (SimpleFeatureStore) shpDataStore.getFeatureSource(shpDataStore.getTypeNames()[0]); Transaction transaction = new DefaultTransaction("create"); store.setTransaction(transaction); store.addFeatures(obj); transaction.commit(); ZipOutputStream os = new ZipOutputStream(output); final String fileName = shpFile.getName().substring(0, shpFile.getName().lastIndexOf(".")); File[] shpFiles = new File(shpFile.getParent()).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(fileName); } }); for (File file : shpFiles) { os.putNextEntry(new ZipEntry(layerId + file.getName().substring(file.getName().lastIndexOf(".")))); IOUtils.copy(new FileInputStream(file), os); file.delete(); } os.close(); output.flush(); }
Example #11
Source File: GeoToolsLayerBeanFactory.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
private VectorLayerInfo generateDefaultInfo(URL url) throws Exception { ShapefileDataStore store = new ShapefileDataStore(url); SimpleFeatureType schema = store.getFeatureSource().getSchema(); VectorLayerInfo info = new VectorLayerInfo(); setCRS(info, schema.getCoordinateReferenceSystem()); setLayerType(info, schema.getGeometryDescriptor()); setMaxExtent(info); setFeatureInfo(info, schema); setRandomStyle(info, schema); return info; }
Example #12
Source File: OmsEpanetProjectFilesGenerator.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
private void makeLineLayer( IEpanetType[] types, File baseFolder, CoordinateReferenceSystem mapCrs ) throws MalformedURLException, IOException { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); String shapefileName = types[0].getShapefileName(); String typeName = types[0].getName(); b.setName(typeName); b.setCRS(mapCrs); b.add("the_geom", LineString.class); for( IEpanetType type : types ) { b.add(type.getAttributeName(), type.getClazz()); } SimpleFeatureType tanksType = b.buildFeatureType(); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); File file = new File(baseFolder, shapefileName); Map<String, Serializable> create = new HashMap<String, Serializable>(); create.put("url", file.toURI().toURL()); ShapefileDataStore newDataStore = (ShapefileDataStore) factory.createNewDataStore(create); newDataStore.createSchema(tanksType); Transaction transaction = new DefaultTransaction(); SimpleFeatureStore featureStore = (SimpleFeatureStore) newDataStore.getFeatureSource(); featureStore.setTransaction(transaction); try { featureStore.addFeatures(new DefaultFeatureCollection()); transaction.commit(); } catch (Exception problem) { problem.printStackTrace(); transaction.rollback(); } finally { transaction.close(); } }
Example #13
Source File: OmsEpanetProjectFilesGenerator.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
private void makePointLayer( IEpanetType[] types, File baseFolder, CoordinateReferenceSystem mapCrs ) throws MalformedURLException, IOException { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); String shapefileName = types[0].getShapefileName(); String typeName = types[0].getName(); b.setName(typeName); b.setCRS(mapCrs); b.add("the_geom", Point.class); for( IEpanetType type : types ) { b.add(type.getAttributeName(), type.getClazz()); } SimpleFeatureType tanksType = b.buildFeatureType(); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); File file = new File(baseFolder, shapefileName); Map<String, Serializable> create = new HashMap<String, Serializable>(); create.put("url", file.toURI().toURL()); ShapefileDataStore newDataStore = (ShapefileDataStore) factory.createNewDataStore(create); newDataStore.createSchema(tanksType); Transaction transaction = new DefaultTransaction(); SimpleFeatureStore featureStore = (SimpleFeatureStore) newDataStore.getFeatureSource(); featureStore.setTransaction(transaction); try { featureStore.addFeatures(new DefaultFeatureCollection()); transaction.commit(); } catch (Exception problem) { problem.printStackTrace(); transaction.rollback(); } finally { transaction.close(); } }
Example #14
Source File: GamaShapeFile.java From gama with GNU General Public License v3.0 | 5 votes |
static ShapefileDataStore getDataStore(final URL url) { final ShapefileDataStore store = new ShapefileDataStore(url); store.setGeometryFactory(GeometryUtils.GEOMETRY_FACTORY); store.setBufferCachingEnabled(true); store.setMemoryMapped(true); store.setCharset(Charset.forName("UTF8")); return store; }
Example #15
Source File: ShapeFileViewer.java From gama with GNU General Public License v3.0 | 5 votes |
@Override public void init(final IEditorSite site, final IEditorInput input) throws PartInitException { setSite(site); final FileEditorInput fi = (FileEditorInput) input; file = fi.getFile(); final IPath path = fi.getPath(); final File f = path.makeAbsolute().toFile(); try { pathStr = f.getAbsolutePath(); final ShapefileDataStore store = new ShapefileDataStore(f.toURI().toURL()); store.setCharset(Charset.forName("UTF8")); content = new MapContent(); featureSource = store.getFeatureSource(); style = Utils.createStyle2(featureSource); layer = new FeatureLayer(featureSource, style); mode = determineMode(featureSource.getSchema(), "Polygon"); final List<FeatureTypeStyle> ftsList = style.featureTypeStyles(); if (ftsList.size() > 0) { fts = ftsList.get(0); } else { fts = null; } if (fts != null) { this.setFillColor(PreferencesHelper.SHAPEFILE_VIEWER_FILL.getValue(), mode, fts); this.setStrokeColor(PreferencesHelper.SHAPEFILE_VIEWER_LINE_COLOR.getValue(), mode, fts); ((StyleLayer) layer).setStyle(style); } content.addLayer(layer); } catch (final IOException e) { DEBUG.ERR("Unable to view file " + path); } this.setPartName(path.lastSegment()); setInput(input); }
Example #16
Source File: ShapefileTool.java From geowave with Apache License 2.0 | 4 votes |
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Directories may alreadybe there") public static void writeShape(final String typeName, final File dir, final Geometry[] shapes) throws IOException { FileUtils.deleteDirectory(dir); dir.mkdirs(); final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(createFeatureType(typeName, shapes[0] instanceof Point)); final ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); final Map<String, Serializable> params = new HashMap<>(); params.put("url", new File(dir.getAbsolutePath() + "/" + typeName + ".shp").toURI().toURL()); params.put("create spatial index", Boolean.TRUE); final ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(createFeatureType(typeName, shapes[0] instanceof Point)); final Transaction transaction = new DefaultTransaction("create"); try (final FeatureWriter<SimpleFeatureType, SimpleFeature> writer = newDataStore.getFeatureWriterAppend(typeName, transaction)) { final int i = 1; for (final Geometry shape : shapes) { featureBuilder.add(shape); featureBuilder.add(Integer.valueOf(i)); final SimpleFeature feature = featureBuilder.buildFeature(null); final SimpleFeature copy = writer.next(); for (final AttributeDescriptor attrD : feature.getFeatureType().getAttributeDescriptors()) { // the null case should only happen for geometry if (copy.getFeatureType().getDescriptor(attrD.getName()) != null) { copy.setAttribute(attrD.getName(), feature.getAttribute(attrD.getName())); } } // shape files force geometry name to be 'the_geom'. So isolate // this change copy.setDefaultGeometry(feature.getDefaultGeometry()); writer.write(); } } catch (final IOException e) { LOGGER.warn("Problem with the FeatureWritter", e); transaction.rollback(); } finally { transaction.commit(); transaction.close(); } }
Example #17
Source File: ShapefileTool.java From geowave with Apache License 2.0 | 4 votes |
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Directories may alreadybe there") public static void writeShape(final File dir, final List<SimpleFeature> shapes) throws IOException { FileUtils.deleteDirectory(dir); dir.mkdirs(); final ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); final String typeName = shapes.get(0).getType().getTypeName(); final Map<String, Serializable> params = new HashMap<>(); params.put("url", new File(dir.getAbsolutePath() + "/" + typeName + ".shp").toURI().toURL()); params.put("create spatial index", Boolean.TRUE); final ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(shapes.get(0).getFeatureType()); final Transaction transaction = new DefaultTransaction("create"); try (final FeatureWriter<SimpleFeatureType, SimpleFeature> writer = newDataStore.getFeatureWriterAppend(typeName, transaction)) { for (final SimpleFeature shape : shapes) { final SimpleFeature copy = writer.next(); for (final AttributeDescriptor attrD : copy.getFeatureType().getAttributeDescriptors()) { // the null case should only happen for geometry if (copy.getFeatureType().getDescriptor(attrD.getName()) != null) { copy.setAttribute(attrD.getName(), shape.getAttribute(attrD.getName())); } } // shape files force geometry name to be 'the_geom'. So isolate // this change copy.setDefaultGeometry(shape.getDefaultGeometry()); writer.write(); } } catch (final IOException e) { LOGGER.warn("Problem with the FeatureWritter", e); transaction.rollback(); } finally { transaction.commit(); transaction.close(); } }
Example #18
Source File: GamaShapeFile.java From gama with GNU General Public License v3.0 | 4 votes |
protected void readShapes(final IScope scope) { scope.getGui().getStatus(scope).beginSubStatus("Reading file " + getName(scope)); ShapefileDataStore store = null; final File file = getFile(scope); final IList list = getBuffer(); int size = 0; try { store = getDataStore(file.toURI().toURL()); final ContentFeatureSource source = store.getFeatureSource(); final Envelope3D env = Envelope3D.of(source.getBounds()); size = source.getCount(Query.ALL); int index = 0; computeProjection(scope, env); try (FeatureReader reader = store.getFeatureReader()) { while (reader.hasNext()) { index++; if (index % 20 == 0) { scope.getGui().getStatus(scope).setSubStatusCompletion(index / (double) size); } final Feature feature = reader.next(); Geometry g = (Geometry) feature.getDefaultGeometryProperty().getValue(); if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) { if (!with3D && !g.isValid()) { g = GeometryUtils.cleanGeometry(g); } g = gis.transform(g); if (!with3D) { g.apply(ZERO_Z); g.geometryChanged(); } g = multiPolygonManagement(g); GamaGisGeometry gt = new GamaGisGeometry(g, feature); if (gt.getInnerGeometry() != null) list.add(gt); } else if (g == null) { // See Issue 725 GAMA.reportError(scope, GamaRuntimeException .warning("GamaShapeFile.fillBuffer; geometry could not be added as it is " + "nil: " + feature.getIdentifier(), scope), false); } } } } catch (final IOException e) { throw GamaRuntimeException.create(e, scope); } finally { if (store != null) { store.dispose(); } scope.getGui().getStatus(scope).endSubStatus("Reading file " + getName(scope)); } if (size > list.size()) { GAMA.reportError(scope, GamaRuntimeException.warning("Problem with file " + getFile(scope) + ": only " + list.size() + " of the " + size + " geometries could be added", scope), false); } }
Example #19
Source File: ShapeFile.java From tutorials with MIT License | 4 votes |
public static void main(String[] args) throws Exception { DefaultFeatureCollection collection = new DefaultFeatureCollection(); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String"); SimpleFeatureType CITY = createFeatureType(); addLocations(CITY, collection); File shapeFile = getNewShapeFile(); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); ShapefileDataStore dataStore = setDataStoreParams(dataStoreFactory, params, shapeFile, CITY); writeToFile(dataStore, collection); }
Example #20
Source File: OSMUtils.java From traffic-engine with GNU General Public License v3.0 | 4 votes |
static public void toShapefile( List<SpatialDataItem> segs, String filename ) throws SchemaException, IOException { final SimpleFeatureType TYPE = DataUtilities.createType("Location", "the_geom:LineString:srid=4326," + "name:String" ); System.out.println("TYPE:"+TYPE); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); /* * GeometryFactory will be used to create the geometry attribute of each feature, * using a Point object for the location. */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); for( SpatialDataItem seg : segs ){ featureBuilder.add( seg.getGeometry() ); featureBuilder.add( seg.id ); SimpleFeature feature = featureBuilder.buildFeature(null); features.add( feature ); } File newFile = new File( filename ); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); /* * TYPE is used as a template to describe the file contents */ newDataStore.createSchema(TYPE); ContentFeatureSource cfs = newDataStore.getFeatureSource(); if (cfs instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) cfs; SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features); try { featureStore.addFeatures(collection); } catch (Exception problem) { problem.printStackTrace(); } finally { } } }