org.geotools.data.simple.SimpleFeatureSource Java Examples

The following examples show how to use org.geotools.data.simple.SimpleFeatureSource. 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: 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 #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: OmsShapefileFeatureReader.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@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: 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 #6
Source File: Utils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a default Style ofr the featureSource.
 *
 * @param featureSource
 *            the source on which to create the style.
 * @return the style created.
 */
public static Style createStyle2(final SimpleFeatureSource featureSource) {
	final SimpleFeatureType schema = featureSource.getSchema();
	final Class<?> geomType = schema.getGeometryDescriptor().getType().getBinding();

	if (Polygon.class.isAssignableFrom(geomType) || MultiPolygon.class.isAssignableFrom(geomType)) {
		return createPolygonStyle();

	} else if (LineString.class.isAssignableFrom(geomType) || MultiLineString.class.isAssignableFrom(geomType)) {
		return createLineStyle();

	} else {
		return createPointStyle();
	}
}
 
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: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SimpleFeatureSource getFeatureSource() throws LayerException {
	if (!featureModelUsable) {
		retryInitFeatures();
	}
	return super.getFeatureSource();
}
 
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
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 #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: GamaOsmFile.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public OSMInfo(final URL url, final long modificationStamp) {
	super(modificationStamp);
	CoordinateReferenceSystem crs = null;
	ReferencedEnvelope env2 = new ReferencedEnvelope();

	int number = 0;
	try {
		final File f = new File(url.toURI());
		final GamaOsmFile osmfile = new GamaOsmFile(null, f.getAbsolutePath());
		attributes.putAll(osmfile.getOSMAttributes(GAMA.getRuntimeScope()));

		final SimpleFeatureType TYPE = DataUtilities.createType("geometries", "geom:LineString");
		final ArrayList<SimpleFeature> list = new ArrayList<>();
		for (final IShape shape : osmfile.iterable(null)) {
			list.add(SimpleFeatureBuilder.build(TYPE, new Object[] { shape.getInnerGeometry() }, null));
		}
		final SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, list);
		final SimpleFeatureSource featureSource = DataUtilities.source(collection);

		env2 = featureSource.getBounds();
		number = osmfile.nbObjects;
		crs = osmfile.getOwnCRS(null);
	} catch (final Exception e) {
		DEBUG.ERR("Error in reading metadata of " + url);
		hasFailed = true;

	} finally {

		// approximation of the width and height in meters.
		width = env2 != null ? env2.getWidth() * (Math.PI / 180) * 6378137 : 0;
		height = env2 != null ? env2.getHeight() * (Math.PI / 180) * 6378137 : 0;
		itemNumber = number;
		this.crs = crs;
	}

}
 
Example #14
Source File: SimpleConfigurator.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static Style showDialog(final Shell parent, final SimpleFeatureSource featureSource, final Style style)
		throws IOException {
	final SimpleFeatureCollection features = featureSource.getFeatures();
	final SimpleConfigurator tmp = new SimpleConfigurator(parent, features, style);
	tmp.setBlockOnOpen(true);
	tmp.open();
	return tmp.getStyle();
}
 
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#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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: DataSourceInfo.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the feature collection.
 *
 * @return the feature collection
 */
public SimpleFeatureCollection getFeatureCollection() {
    SimpleFeatureCollection featureCollection = null;
    try {
        if (dataStore != null) {
            SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
            featureCollection = source.getFeatures();
        }
    } catch (IOException e) {
        ConsoleManager.getInstance().exception(this, e);
    }
    return featureCollection;
}
 
Example #22
Source File: SimpleConfigurator.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public static Style showDialog(final Shell parent, final Layer layer) throws IOException {
	final SimpleFeatureSource featureSource = (SimpleFeatureSource) layer.getFeatureSource();
	final Style style = layer.getStyle();
	showDialog(parent, featureSource, style);
	return null;
}
 
Example #23
Source File: DataSourceInfo.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Gets the feature collection.
 *
 * @return the feature collection
 */
public SimpleFeatureCollection getFeatureCollection() {
    SimpleFeatureCollection featureCollection = null;
    try {
        if(dataStore != null)
        {
            SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
            featureCollection = source.getFeatures();
        }
    } catch (IOException e) {
        ConsoleManager.getInstance().exception(this, e);
    }
    return featureCollection;
}
 
Example #24
Source File: InLineFeatureModel.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Populate.
 *
 * @param userLayer the user layer
 */
public void populate(UserLayer userLayer) {
    this.userLayer = userLayer;
    featureCollection = null;
    geometryFieldIndex = -1;

    columnList.clear();

    if ((userLayer != null) && (userLayer.getInlineFeatureType() != null)) {
        String typeName = userLayer.getInlineFeatureType().getTypeName();
        try {
            SimpleFeatureSource featureSource =
                    userLayer.getInlineFeatureDatastore().getFeatureSource(typeName);
            if (featureSource != null) {
                featureCollection = featureSource.getFeatures();
            }
        } catch (IOException e) {
            ConsoleManager.getInstance().exception(this, e);
        }

        if (featureCollection != null) {
            // Populate field names
            List<AttributeDescriptor> descriptorList =
                    featureCollection.getSchema().getAttributeDescriptors();
            int index = 0;
            for (AttributeDescriptor descriptor : descriptorList) {
                if (descriptor instanceof GeometryDescriptorImpl) {
                    geometryFieldIndex = index;
                }
                columnList.add(descriptor.getLocalName());
                index++;
            }
        }
    }

    this.fireTableStructureChanged();
    this.fireTableDataChanged();

    // Set up the editor to handle editing the table cells
    InlineCellEditor editor = new InlineCellEditor(this);

    if ((featureTable != null) && (featureTable.getColumnModel().getColumnCount() > 0)) {
        TableColumn column = featureTable.getColumnModel().getColumn(0);
        column.setCellEditor(editor);
        featureTable.setCellEditor(editor);
    }
}
 
Example #25
Source File: InLineFeatureModel.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/** Adds the new column. */
public void addNewColumn() {
    if (featureCollection != null) {
        String attributeName = getUniqueAttributeName();

        columnList.add(attributeName);

        // Populate field names
        SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder();
        featureTypeBuilder.init(featureCollection.getSchema());
        featureTypeBuilder.add(attributeName, String.class);

        SimpleFeatureType newFeatureType = featureTypeBuilder.buildFeatureType();

        String typeName = userLayer.getInlineFeatureType().getTypeName();
        try {
            SimpleFeatureSource featureSource =
                    userLayer.getInlineFeatureDatastore().getFeatureSource(typeName);

            SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(newFeatureType);

            ArrayList<SimpleFeature> featureList = new ArrayList<>();

            SimpleFeatureIterator it = featureSource.getFeatures().features();
            try {
                while (it.hasNext()) {
                    SimpleFeature sf = it.next();
                    sfb.addAll(sf.getAttributes());
                    sfb.add(new String(""));
                    featureList.add(sfb.buildFeature(null));
                }
            } finally {
                it.close();
            }

            SimpleFeatureCollection collection =
                    new ListFeatureCollection(newFeatureType, featureList);

            featureCollection = collection;
            cachedFeature = null;
            lastRow = -1;
            DataStore dataStore = DataUtilities.dataStore(collection);
            userLayer.setInlineFeatureDatastore(dataStore);
            userLayer.setInlineFeatureType(newFeatureType);

        } catch (IOException e) {
            ConsoleManager.getInstance().exception(this, e);
        }

        this.fireTableStructureChanged();
        this.fireTableDataChanged();

        if (parentObj != null) {
            parentObj.inlineFeatureUpdated();
        }
    }
}
 
Example #26
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 #27
Source File: InLineFeatureModel.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Removes the column.
 *
 * @param columnName the column name
 */
public void removeColumn(String columnName) {
    if (featureCollection != null) {
        if (columnList.contains(columnName)) {
            columnList.remove(columnName);

            // Find field name to remote
            SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder();
            featureTypeBuilder.init(featureCollection.getSchema());
            featureTypeBuilder.remove(columnName);

            SimpleFeatureType newFeatureType = featureTypeBuilder.buildFeatureType();

            int attributeToRemoveIndex = 0;
            for (AttributeDescriptor descriptor : newFeatureType.getAttributeDescriptors()) {
                if (descriptor.getLocalName().compareTo(columnName) == 0) {
                    break;
                }
                attributeToRemoveIndex++;
            }

            String typeName = userLayer.getInlineFeatureType().getTypeName();
            try {
                SimpleFeatureSource featureSource =
                        userLayer.getInlineFeatureDatastore().getFeatureSource(typeName);

                SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(newFeatureType);

                ArrayList<SimpleFeature> featureList = new ArrayList<>();

                SimpleFeatureIterator it = featureSource.getFeatures().features();
                try {
                    while (it.hasNext()) {
                        SimpleFeature sf = it.next();
                        List<Object> attributes = sf.getAttributes();
                        attributes.remove(attributeToRemoveIndex);

                        sfb.addAll(attributes);
                        featureList.add(sfb.buildFeature(null));
                    }
                } finally {
                    it.close();
                }

                SimpleFeatureCollection collection =
                        new ListFeatureCollection(newFeatureType, featureList);

                featureCollection = collection;
                cachedFeature = null;
                lastRow = -1;
                DataStore dataStore = DataUtilities.dataStore(collection);
                userLayer.setInlineFeatureDatastore(dataStore);
                userLayer.setInlineFeatureType(newFeatureType);

            } catch (IOException e) {
                ConsoleManager.getInstance().exception(this, e);
            }

            this.fireTableStructureChanged();
            this.fireTableDataChanged();

            if (parentObj != null) {
                parentObj.inlineFeatureUpdated();
            }
        }
    }
}
 
Example #28
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());
  }
}
 
Example #29
Source File: InLineFeatureModel.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Update CRS.
 *
 * @param selectedValue the selected value
 */
public void updateCRS(ValueComboBoxData selectedValue) {
    if (selectedValue != null) {
        String crsCode = selectedValue.getKey();

        CoordinateReferenceSystem newCRS = CoordManager.getInstance().getCRS(crsCode);

        SimpleFeatureType newFeatureType =
                SimpleFeatureTypeBuilder.retype(featureCollection.getSchema(), newCRS);

        String typeName = userLayer.getInlineFeatureType().getTypeName();
        try {
            SimpleFeatureSource featureSource =
                    userLayer.getInlineFeatureDatastore().getFeatureSource(typeName);

            SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(newFeatureType);

            ArrayList<SimpleFeature> featureList = new ArrayList<>();

            SimpleFeatureIterator it = featureSource.getFeatures().features();
            try {
                while (it.hasNext()) {
                    SimpleFeature sf = it.next();
                    List<Object> attributeValueList = sf.getAttributes();
                    sfb.addAll(attributeValueList);
                    featureList.add(sfb.buildFeature(null));
                }
            } finally {
                it.close();
            }

            SimpleFeatureCollection collection =
                    new ListFeatureCollection(newFeatureType, featureList);

            featureCollection = collection;
            cachedFeature = null;
            lastRow = -1;
            DataStore dataStore = DataUtilities.dataStore(collection);
            userLayer.setInlineFeatureDatastore(dataStore);
            userLayer.setInlineFeatureType(newFeatureType);

        } catch (IOException e) {
            ConsoleManager.getInstance().exception(this, e);
        }

        this.fireTableStructureChanged();
        this.fireTableDataChanged();

        if (parentObj != null) {
            parentObj.inlineFeatureUpdated();
        }
    }
}
 
Example #30
Source File: InLineFeatureModel.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/** Adds the new feature. */
public void addNewFeature() {
    SimpleFeatureType featureType = userLayer.getInlineFeatureType();

    String typeName = userLayer.getInlineFeatureType().getTypeName();
    try {
        SimpleFeatureSource featureSource =
                userLayer.getInlineFeatureDatastore().getFeatureSource(typeName);

        SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(featureType);

        ArrayList<SimpleFeature> featureList = new ArrayList<>();

        SimpleFeatureIterator it = featureSource.getFeatures().features();
        try {
            while (it.hasNext()) {
                SimpleFeature sf = it.next();
                List<Object> attributeValueList = sf.getAttributes();
                sfb.addAll(attributeValueList);
                featureList.add(sfb.buildFeature(null));
            }
            // Add new feature
            String wktString = "wkt://POINT(0 0)";
            Geometry geometry =
                    WKTConversion.convertToGeometry(wktString, getSelectedCRSCode());
            sfb.add(geometry);
            featureList.add(sfb.buildFeature(null));
        } finally {
            it.close();
        }

        SimpleFeatureCollection collection =
                new ListFeatureCollection(featureType, featureList);

        featureCollection = collection;
        cachedFeature = null;
        lastRow = -1;
        DataStore dataStore = DataUtilities.dataStore(collection);
        userLayer.setInlineFeatureDatastore(dataStore);

    } catch (IOException e) {
        ConsoleManager.getInstance().exception(this, e);
    }

    this.fireTableStructureChanged();
    this.fireTableDataChanged();

    if (parentObj != null) {
        parentObj.inlineFeatureUpdated();
    }
}