Java Code Examples for org.geotools.data.simple.SimpleFeatureSource

The following examples show how to use org.geotools.data.simple.SimpleFeatureSource. 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
Source Project: amodeus   Source File: MultiPolygons.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static Set<MultiPolygon> initializeFrom(File shapeFile) throws IOException {
    URL shapeFileURL = shapeFile.toURI().toURL();
    Map<String, URL> inputMap = new HashMap<>();
    inputMap.put("url", shapeFileURL);

    DataStore dataStore = DataStoreFinder.getDataStore(inputMap);
    SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
    SimpleFeatureCollection collection = DataUtilities.collection(featureSource.getFeatures());
    dataStore.dispose();

    Set<MultiPolygon> polygons = new HashSet<>();
    SimpleFeatureIterator iterator = collection.features();
    while (iterator.hasNext())
        polygons.add((MultiPolygon) iterator.next().getDefaultGeometry());
    return polygons;
}
 
Example 2
/**
 * 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
@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 4
Source Project: geowave   Source File: GeoWaveFeatureSourceTest.java    License: 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 5
@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 6
Source Project: sldeditor   Source File: DataSourceInfo.java    License: 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 7
Source Project: sldeditor   Source File: DatabaseClient.java    License: 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 8
Source Project: sldeditor   Source File: DataSourceInfo.java    License: 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 9
Source Project: sldeditor   Source File: DataSourceInfoTest.java    License: 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 10
Source Project: sldeditor   Source File: DataSourceInfoTest.java    License: 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 11
Source Project: sldeditor   Source File: DataSourceInfoTest.java    License: 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 12
Source Project: sldeditor   Source File: DataSourceInfoTest.java    License: 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 13
Source Project: sldeditor   Source File: DataSourceInfoTest.java    License: 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 14
Source Project: gama   Source File: SimpleConfigurator.java    License: 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 Project: gama   Source File: Utils.java    License: 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 16
Source Project: gama   Source File: GamaOsmFile.java    License: 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 17
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 18
Source Project: geowave   Source File: GeoWaveFeatureSourceTest.java    License: 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 19
@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 20
/**
 * 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 21
@Override
public SimpleFeatureSource getFeatureSource() throws LayerException {
	if (!featureModelUsable) {
		retryInitFeatures();
	}
	return super.getFeatureSource();
}
 
Example 22
Source Project: tutorials   Source File: ShapeFile.java    License: 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 23
Source Project: sldeditor   Source File: InLineFeatureModel.java    License: 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 24
Source Project: sldeditor   Source File: InLineFeatureModel.java    License: 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 25
Source Project: sldeditor   Source File: InLineFeatureModel.java    License: 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 26
Source Project: sldeditor   Source File: InLineFeatureModel.java    License: 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 27
Source Project: sldeditor   Source File: InLineFeatureModel.java    License: 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();
    }
}
 
Example 28
Source Project: sldeditor   Source File: InLineFeatureModel.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Removes the feature.
 *
 * @param selectedRow the selected row
 */
public void removeFeature(int selectedRow) {
    if ((selectedRow < 0) || (selectedRow >= getRowCount())) {
        return;
    }

    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 {
            int index = 0;
            while (it.hasNext()) {
                SimpleFeature sf = it.next();

                if (index != selectedRow) {
                    List<Object> attributeValueList = sf.getAttributes();
                    sfb.addAll(attributeValueList);
                    featureList.add(sfb.buildFeature(null));
                }
                index++;
            }
        } 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();
    }
}
 
Example 29
Source Project: gama   Source File: SimpleConfigurator.java    License: 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 30
public static ReferencedEnvelope readEnvelope( String filePath ) throws Exception {
    File shapeFile = new File(filePath);
    FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile);
    SimpleFeatureSource featureSource = store.getFeatureSource();
    return featureSource.getBounds();
}