Java Code Examples for org.geotools.data.shapefile.ShapefileDataStoreFactory

The following examples show how to use org.geotools.data.shapefile.ShapefileDataStoreFactory. These examples are extracted from open source projects. 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
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 2
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 3
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 4
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 5
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 6
Source Project: tutorials   Source File: ShapeFile.java    License: MIT License 5 votes vote down vote up
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 7
Source Project: traffic-engine   Source File: OSMUtils.java    License: GNU General Public License v3.0 4 votes vote down vote up
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 {
           }
       }
}
 
Example 8
Source Project: geowave   Source File: ShapefileTool.java    License: Apache License 2.0 4 votes vote down vote up
@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 9
Source Project: geowave   Source File: ShapefileTool.java    License: Apache License 2.0 4 votes vote down vote up
@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 10
/**
 * Creates a suitable {@link DataStore} for the specified parameters.
 * 
 * @param parameters list of GeoTools parameters.
 * @return data store, never null
 * @throws IOException could not create data store
 */
public static DataStore create(Map<String, Object> parameters) throws IOException {
	Object url = parameters.get(ShapefileDataStoreFactory.URLP.key);
	Logger log = LoggerFactory.getLogger(DataStoreFactory.class);
	if (url instanceof String) {
		parameters.put(ShapefileDataStoreFactory.URLP.key, ResourceUtils.getURL((String) url).toExternalForm());
	}
	if (DATASTORE_CACHE.containsKey(parameters)) {
		return DATASTORE_CACHE.get(parameters);
	}
	DataStore store = DataStoreFinder.getDataStore(parameters);
	Object typed = parameters.get(USE_TYPED_FIDS);
	if (typed instanceof String) {
		Boolean t = Boolean.valueOf((String) typed);
		if (!t) {
			if (store != null) {
				log.warn("Non-typed FIDs are only supported by first-generation JDBC datastores, "
						+ "using default fid format for datastore class " + store.getClass().getName());
			}
		}
	}
	if (null == store) {
		StringBuilder availableStr = new StringBuilder();
		StringBuilder missingStr = new StringBuilder();
		Iterator<DataStoreFactorySpi> all = DataStoreFinder.getAllDataStores();
		while (all.hasNext()) {
			DataStoreFactorySpi factory = all.next();
			if (!factory.isAvailable()) {
				log.warn("Datastore factory " + factory.getDisplayName() + "(" + factory.getDescription()
						+ ") is not available");
				if (missingStr.length() != 0) {
					missingStr.append(",");
				}
				missingStr.append(factory.getDisplayName());
			} else {
				if (availableStr.length() != 0) {
					availableStr.append(",");
				}
				availableStr.append(factory.getDisplayName());
			}
		}
		throw new IOException(
				"No datastore found. Possible causes are missing factory or missing library for your datastore"
						+ " (e.g. database driver).\nCheck the isAvailable() method of your"
						+ " DataStoreFactory class to find out which libraries are needed.\n"
						+ "Unavailable factories : " + missingStr + "\n" + "Available factories : " + availableStr
						+ "\n");
	}
	DATASTORE_CACHE.put(parameters, store);
	return store;
}
 
Example 11
/**
 * Finish initializing the layer.
 *
 * @throws LayerException oops
 */
@PostConstruct
protected void initFeatures() throws LayerException {
	if (null == layerInfo) {
		return;
	}
	crs = geoService.getCrs2(layerInfo.getCrs());
	setFeatureSourceName(layerInfo.getFeatureInfo().getDataSourceName());
	try {
		if (null == super.getDataStore()) {
			Map<String, Object> params = new HashMap<String, Object>();
			if (null != url) {
				params.put(ShapefileDataStoreFactory.URLP.key, url);
			}
			if (null != dbtype) {
				params.put(JDBCDataStoreFactory.DBTYPE.key, dbtype);
			}
			if (null != parameters) {
				for (Parameter parameter : parameters) {
					params.put(parameter.getName(), parameter.getValue());
				}
			}
			if (null != dataSource) {
				params.put(JDBCDataStoreFactory.DATASOURCE.key, dataSource);
				// these are apparently required but not used
				params.put(JDBCDataStoreFactory.DATABASE.key, "some_database");
				params.put(JDBCDataStoreFactory.USER.key, "some_user");
				params.put(JDBCDataStoreFactory.PASSWD.key, "some_password");
				params.put(JDBCDataStoreFactory.HOST.key, "some host");
				params.put(JDBCDataStoreFactory.PORT.key, "0");
			}
			DataStore store = DataStoreFactory.create(params);
			super.setDataStore(store);
		}
		if (null == super.getDataStore()) {
			return;
		}
		this.featureModel = new GeoToolsFeatureModel(super.getDataStore(), layerInfo.getFeatureInfo()
				.getDataSourceName(), geoService.getSridFromCrs(layerInfo.getCrs()), converterService);
		featureModel.setLayerInfo(layerInfo);
		featureModelUsable = true;

	} catch (IOException ioe) {
		if (MAGIC_STRING_LIBRARY_MISSING.equals(ioe.getMessage())) {
			throw new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION, url);
		} else {
			featureModelUsable = false;
			log.warn("The layer could not be correctly initialized: " + getId(), ioe);
		}
	} catch (LayerException le) {
		featureModelUsable = false;
		log.warn("The layer could not be correctly initialized: " + getId(), le);
	} catch (RuntimeException e) {
		featureModelUsable = false;
		log.warn("The layer could not be correctly initialized: " + getId(), e);
	}
}
 
Example 12
Source Project: tutorials   Source File: ShapeFile.java    License: MIT License 4 votes vote down vote up
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);
    }