org.geotools.data.simple.SimpleFeatureStore Java Examples

The following examples show how to use org.geotools.data.simple.SimpleFeatureStore. 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: IFeatureShape.java    From hortonmachine with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Add a feature to the store.
 * 
 * @param feature the feature to add.
 */
default public void addFeature( SimpleFeature feature) {
    FeatureStoreInfo featureStoreInfo = getFeatureStoreInfo();
    SimpleFeatureStore featureStore = featureStoreInfo.getFeatureStore();
    if (featureStore != null) {
        Transaction transaction = new DefaultTransaction("add");
        featureStore.setTransaction(transaction);
        
        try {
            DefaultFeatureCollection fc = new DefaultFeatureCollection();
            fc.add(feature);
            featureStore.addFeatures(fc);
            transaction.commit();
        } catch (Exception eek) {
            try {
                transaction.rollback();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example #2
Source File: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 */
@Transactional(readOnly = true)
public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {
	FeatureSource<SimpleFeatureType, SimpleFeature> source = getFeatureSource();
	try {
		if (source instanceof FeatureStore<?, ?>) {
			SimpleFeatureStore store = (SimpleFeatureStore) source;
			transactionSynchronization.synchTransaction(store);
		}
		Query query = new Query();
		query.setFilter(filter);
		query.setMaxFeatures(maxResultSize > 0 ? maxResultSize : Integer.MAX_VALUE);
		query.setStartIndex(offset);
		FeatureCollection<SimpleFeatureType, SimpleFeature> fc = source.getFeatures(query);
		FeatureIterator<SimpleFeature> it = fc.features();
		transactionSynchronization.addIterator(it);
		return new JavaIterator(it);
	} catch (Throwable t) { // NOSONAR avoid errors (like NPE) as well
		throw new LayerException(t, ExceptionCode.UNEXPECTED_PROBLEM);
	}
}
 
Example #3
Source File: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Envelope getBounds(Filter filter) throws LayerException {
	FeatureSource<SimpleFeatureType, SimpleFeature> source = getFeatureSource();
	if (source instanceof FeatureStore<?, ?>) {
		SimpleFeatureStore store = (SimpleFeatureStore) source;
		transactionSynchronization.synchTransaction(store);
	}
	try {
		FeatureCollection<SimpleFeatureType, SimpleFeature> fc;
		if (null == filter) {
			fc = source.getFeatures();
		} else {
			fc = source.getFeatures(filter);
		}
		FeatureIterator<SimpleFeature> it = fc.features();
		transactionSynchronization.addIterator(it);
		return fc.getBounds();
	} catch (Throwable t) { // NOSONAR avoid errors (like NPE) as well
		throw new LayerException(t, ExceptionCode.UNEXPECTED_PROBLEM);
	}
}
 
Example #4
Source File: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = { Throwable.class })
public void delete(String featureId) throws LayerException {
	SimpleFeatureSource source = getFeatureSource();
	if (source instanceof SimpleFeatureStore) {
		SimpleFeatureStore store = (SimpleFeatureStore) source;
		Filter filter = filterService.createFidFilter(new String[] { featureId });
		transactionSynchronization.synchTransaction(store);
		try {
			store.removeFeatures(filter);
			if (log.isDebugEnabled()) {
				log.debug("Deleted feature {} in {}", featureId, getFeatureSourceName());
			}
		} catch (IOException ioe) {
			featureModelUsable = false;
			throw new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);
		}
	} else {
		log.error("Don't know how to delete from " + getFeatureSourceName() + ", class "
				+ source.getClass().getName() + " does not implement SimpleFeatureStore");
		throw new LayerException(ExceptionCode.DELETE_NOT_IMPLEMENTED, getFeatureSourceName(), source.getClass()
				.getName());
	}
}
 
Example #5
Source File: FeatureCollectionLinesLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Build the layer.
 * 
 * @param title layer name.
 * @param featureCollectionLL the featurecollection in latlong.
 * @param featureStore the feature store. If not null, then the feature attributes will be editable.
 * @param field2ValuesMap an optional map of fields and possible values.
 */
public FeatureCollectionLinesLayer( String title, SimpleFeatureCollection featureCollectionLL,
        SimpleFeatureStore featureStore, HashMap<String, String[]> field2ValuesMap ) {
    this.title = title;
    this.featureStore = featureStore;
    this.featureStoreInfo = new FeatureStoreInfo(featureStore, field2ValuesMap);
    this.featureCollectionLL = featureCollectionLL;

    AirspaceAttributes attrs = new BasicAirspaceAttributes();
    attrs.setDrawInterior(true);
    attrs.setDrawOutline(true);
    attrs.setInteriorMaterial(new Material(Color.WHITE));
    attrs.setOutlineMaterial(new Material(Color.BLACK));
    attrs.setOutlineWidth(2);
    attrs.setEnableAntialiasing(true);
    highlightAttrs = new BasicAirspaceAttributes(attrs);
    highlightAttrs.setOutlineMaterial(new Material(Color.RED));

    setStyle(null);
    loadData();
}
 
Example #6
Source File: OmsEpanetProjectFilesGenerator.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
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 #7
Source File: ShapeFile.java    From tutorials with MIT License 5 votes vote down vote up
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 #8
Source File: ShpParser.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #9
Source File: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Update an existing feature. Made package private for testing purposes.
 *
 * @param feature feature to update
 * @throws LayerException oops
 */
void update(Object feature) throws LayerException {
	SimpleFeatureSource source = getFeatureSource();
	if (source instanceof SimpleFeatureStore) {
		SimpleFeatureStore store = (SimpleFeatureStore) source;
		String featureId = getFeatureModel().getId(feature);
		Filter filter = filterService.createFidFilter(new String[] { featureId });
		transactionSynchronization.synchTransaction(store);
		List<Name> names = new ArrayList<Name>();
		Map<String, Attribute> attrMap = getFeatureModel().getAttributes(feature);
		List<Object> values = new ArrayList<Object>();
		for (Map.Entry<String, Attribute> entry : attrMap.entrySet()) {
			String name = entry.getKey();
			names.add(store.getSchema().getDescriptor(name).getName());
			values.add(entry.getValue().getValue());
		}

		try {
			store.modifyFeatures(names.toArray(new Name[names.size()]), values.toArray(), filter);
			store.modifyFeatures(store.getSchema().getGeometryDescriptor().getName(), getFeatureModel()
					.getGeometry(feature), filter);
			log.debug("Updated feature {} in {}", featureId, getFeatureSourceName());
		} catch (IOException ioe) {
			featureModelUsable = false;
			throw new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);
		}
	} else {
		log.error("Don't know how to create or update " + getFeatureSourceName() + ", class "
				+ source.getClass().getName() + " does not implement SimpleFeatureStore");
		throw new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source
				.getClass().getName());
	}
}
 
Example #10
Source File: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = { Throwable.class })
public Object create(Object feature) throws LayerException {
	SimpleFeatureSource source = getFeatureSource();
	if (source instanceof SimpleFeatureStore) {
		SimpleFeatureStore store = (SimpleFeatureStore) source;
		DefaultFeatureCollection collection = new DefaultFeatureCollection();
		collection.add((SimpleFeature) feature);
		transactionSynchronization.synchTransaction(store);
		try {
			List<FeatureId> ids = store.addFeatures(collection);
			// fetch it again to get the generated values !!!
			if (ids.size() == 1) {
				return read(ids.get(0).getID());
			}
		} catch (IOException ioe) {
			featureModelUsable = false;
			throw new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);
		}
		return feature;
	} else {
		log.error("Don't know how to create or update " + getFeatureSourceName() + ", class "
				+ source.getClass().getName() + " does not implement SimpleFeatureStore");
		throw new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source
				.getClass().getName());
	}
}
 
Example #11
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 #12
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
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 #13
Source File: OmsEpanetProjectFilesGenerator.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
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: FeatureCollectionPointsLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public FeatureCollectionPointsLayer( String title, SimpleFeatureCollection featureCollectionLL,
        SimpleFeatureStore featureStore, HashMap<String, String[]> field2ValuesMap, Object imageObject ) {
    this.title = title;
    this.featureCollectionLL = featureCollectionLL;
    this.featureStore = featureStore;
    featureStoreInfo = new FeatureStoreInfo(featureStore, field2ValuesMap);

    basicMarkerAttributes = new PointPlacemarkAttributes();
    basicMarkerAttributes.setLabelMaterial(mFillMaterial);
    basicMarkerAttributes.setLineMaterial(mFillMaterial);
    basicMarkerAttributes.setUsePointAsDefaultImage(true);
    if (imageObject != null) {
        if (imageObject instanceof BufferedImage) {
            BufferedImage image = (BufferedImage) imageObject;
            basicMarkerAttributes.setImage(image);
        } else if (imageObject instanceof String) {
            basicMarkerAttributes.setImageAddress((String) imageObject);
        }
    } else {
        basicMarkerAttributes.setScale(mMarkerSize);
    }
    try {
        loadData();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: IFeatureShape.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Modify the attributes of this feature.
 * 
 * @param names the names of the attributes to modify.
 * @param values the values to set.
 * @return the new feature if the editing has been successful.
 */
default public SimpleFeature modifyFeatureAttribute( String[] names, Object[] values ) {
    FeatureStoreInfo featureStoreInfo = getFeatureStoreInfo();
    SimpleFeatureStore featureStore = featureStoreInfo.getFeatureStore();
    if (featureStore != null) {
        Transaction transaction = new DefaultTransaction("modify");
        featureStore.setTransaction(transaction);

        FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
        Filter filter = ff.id(Collections.singleton(ff.featureId(getFeature().getID())));

        try {
            featureStore.modifyFeatures(names, values, filter);
            transaction.commit();

            SimpleFeature modifiedFeature = featureStore.getFeatures(filter).features().next();
            return modifiedFeature;
        } catch (Exception eek) {
            try {
                transaction.rollback();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
 
Example #16
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 #17
Source File: OSMUtils.java    From traffic-engine with 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 #18
Source File: FeatureStoreInfo.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public SimpleFeatureStore getFeatureStore() {
    return featureStore;
}
 
Example #19
Source File: FeatureStoreInfo.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public FeatureStoreInfo(SimpleFeatureStore featureStore, HashMap<String, String[]> field2ValuesMap) {
    this.featureStore = featureStore;
    this.field2ValuesMap = field2ValuesMap;
}
 
Example #20
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 #21
Source File: FeatureCollectionPolygonLayer.java    From hortonmachine with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Build the layer.
 * 
 * @param title
 *            layer name.
 * @param featureCollectionLL
 *            the featurecollection in latlong.
 * @param featureStore
 *            the feature store. If not null, then the feature attributes
 *            will be editable.
 */
public FeatureCollectionPolygonLayer( String title, SimpleFeatureCollection featureCollectionLL,
        SimpleFeatureStore featureStore, HashMap<String, String[]> field2ValuesMap ) {
    this.title = title;
    this.featureCollectionLL = featureCollectionLL;
    this.featureStore = featureStore;
    this.featureStoreInfo = new FeatureStoreInfo(featureStore, field2ValuesMap);

    setStyle(null);
    loadData();
}