use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.
the class OracleExport method runInternal.
/**
* Executes the export command using the provided options.
*
* @param cli
*/
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
if (args.isEmpty()) {
printUsage(cli);
throw new CommandFailedException();
}
String path = args.get(0);
String tableName = args.get(1);
checkParameter(tableName != null && !tableName.isEmpty(), "No table name specified");
DataStore dataStore = getDataStore();
ObjectId featureTypeId = null;
if (!Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
SimpleFeatureType outputFeatureType;
if (sFeatureTypeId != null) {
// Check the feature type id string is a correct id
Optional<ObjectId> id = cli.getGeogig().command(RevParse.class).setRefSpec(sFeatureTypeId).call();
checkParameter(id.isPresent(), "Invalid feature type reference", sFeatureTypeId);
TYPE type = cli.getGeogig().command(ResolveObjectType.class).setObjectId(id.get()).call();
checkParameter(type.equals(TYPE.FEATURETYPE), "Provided reference does not resolve to a feature type: ", sFeatureTypeId);
outputFeatureType = (SimpleFeatureType) cli.getGeogig().command(RevObjectParse.class).setObjectId(id.get()).call(RevFeatureType.class).get().type();
featureTypeId = id.get();
} else {
try {
SimpleFeatureType sft = getFeatureType(path, cli);
outputFeatureType = new SimpleFeatureTypeImpl(new NameImpl(tableName), sft.getAttributeDescriptors(), sft.getGeometryDescriptor(), sft.isAbstract(), sft.getRestrictions(), sft.getSuper(), sft.getDescription());
} catch (GeoToolsOpException e) {
throw new CommandFailedException("No features to export.", e);
}
}
try {
dataStore.createSchema(outputFeatureType);
} catch (IOException e) {
throw new CommandFailedException("Cannot create new table in database", e);
}
} else {
if (!overwrite) {
throw new CommandFailedException("The selected table already exists. Use -o to overwrite");
}
}
SimpleFeatureSource featureSource = dataStore.getFeatureSource(tableName);
if (!(featureSource instanceof SimpleFeatureStore)) {
throw new CommandFailedException("Can't write to the selected table");
}
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
if (overwrite) {
try {
featureStore.removeFeatures(Filter.INCLUDE);
} catch (IOException e) {
throw new CommandFailedException("Error accessing table: " + e.getMessage(), e);
}
}
ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
if (defaultType) {
op.exportDefaultFeatureType();
}
try {
op.setProgressListener(cli.getProgressListener()).call();
} catch (IllegalArgumentException iae) {
throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
} catch (GeoToolsOpException e) {
switch(e.statusCode) {
case MIXED_FEATURE_TYPES:
throw new CommandFailedException("The selected tree contains mixed feature types. Use --defaulttype or --featuretype <feature_type_ref> to export.", e);
default:
throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
}
}
cli.getConsole().println(path + " exported successfully to " + tableName);
}
use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.
the class GeoJsonExport method runInternal.
/**
* Executes the export command using the provided options.
*/
@Override
protected void runInternal(GeogigCLI cli) throws InvalidParameterException, CommandFailedException, IOException {
if (args.isEmpty()) {
printUsage(cli);
throw new CommandFailedException();
}
String path = args.get(0);
String geojson = args.get(1);
File file = new File(geojson);
if (file.exists() && !overwrite) {
throw new CommandFailedException("The selected GeoJSON file already exists. Use -o to overwrite");
}
SimpleFeatureType outputFeatureType;
ObjectId featureTypeId;
if (sFeatureTypeId != null) {
// Check the feature type id string is a correct id
Optional<ObjectId> id = cli.getGeogig().command(RevParse.class).setRefSpec(sFeatureTypeId).call();
checkParameter(id.isPresent(), "Invalid feature type reference", sFeatureTypeId);
TYPE type = cli.getGeogig().command(ResolveObjectType.class).setObjectId(id.get()).call();
checkParameter(type.equals(TYPE.FEATURETYPE), "Provided reference does not resolve to a feature type: ", sFeatureTypeId);
outputFeatureType = (SimpleFeatureType) cli.getGeogig().command(RevObjectParse.class).setObjectId(id.get()).call(RevFeatureType.class).get().type();
featureTypeId = id.get();
} else {
try {
outputFeatureType = getFeatureType(path, cli);
featureTypeId = null;
} catch (GeoToolsOpException e) {
cli.getConsole().println("No features to export.");
return;
}
}
DataStore dataStore = new MemoryDataStore(outputFeatureType);
final String typeName = dataStore.getTypeNames()[0];
final SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (!(featureSource instanceof SimpleFeatureStore)) {
throw new CommandFailedException("Could not create feature store.");
}
final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
op.setTransactional(false);
if (defaultType) {
op.exportDefaultFeatureType();
}
FileWriter writer = null;
try {
op.setProgressListener(cli.getProgressListener()).call();
FeatureJSON fjson = new FeatureJSON();
@SuppressWarnings("rawtypes") FeatureCollection fc = featureSource.getFeatures();
writer = new FileWriter(file);
fjson.writeFeatureCollection(fc, writer);
} catch (IllegalArgumentException iae) {
throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
} catch (GeoToolsOpException e) {
file.delete();
switch(e.statusCode) {
case MIXED_FEATURE_TYPES:
throw new CommandFailedException("Error: The selected tree contains mixed feature types. Use --defaulttype or --featuretype <feature_type_ref> to export.", e);
default:
throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
}
} finally {
writer.flush();
writer.close();
}
cli.getConsole().println(path + " exported successfully to " + geojson);
}
use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.
the class OSMExportShp method exportRule.
private void exportRule(final MappingRule rule, final GeogigCLI cli, final File shapeFile) throws IOException {
if (shapeFile.exists() && !overwrite) {
throw new CommandFailedException("The selected shapefile already exists. Use -o to overwrite");
}
Function<Feature, Optional<Feature>> function = new Function<Feature, Optional<Feature>>() {
@Override
@Nullable
public Optional<Feature> apply(@Nullable Feature feature) {
Optional<Feature> mapped = rule.apply(feature);
return mapped;
}
};
SimpleFeatureType outputFeatureType = rule.getFeatureType();
String path = getOriginTreesFromOutputFeatureType(outputFeatureType);
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put(ShapefileDataStoreFactory.URLP.key, shapeFile.toURI().toURL());
params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);
DataStore dataStore = dataStoreFactory.createNewDataStore(params);
try {
dataStore.createSchema(outputFeatureType);
final String typeName = dataStore.getTypeNames()[0];
final SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
checkParameter(source instanceof SimpleFeatureStore, "Could not create feature store. Shapefile may be read only");
final SimpleFeatureStore store = (SimpleFeatureStore) source;
ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(store).setPath(path).setFeatureTypeConversionFunction(function);
try {
op.setProgressListener(cli.getProgressListener()).call();
cli.getConsole().println("OSM data exported successfully to " + shapeFile);
} catch (IllegalArgumentException iae) {
shapeFile.delete();
throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
} catch (GeoToolsOpException e) {
shapeFile.delete();
throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
}
} finally {
dataStore.dispose();
}
}
use of org.geotools.data.simple.SimpleFeatureSource in project hale by halestudio.
the class ShapeInstanceReader method execute.
/**
* @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
*/
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
// $NON-NLS-1$
progress.begin(Messages.getString("ShapeSchemaProvider.1"), ProgressIndicator.UNKNOWN);
// DataStore store = new ShapefileDataStoreFactory().createDataStore(location.toURL());
// DataStore store = FileDataStoreFinder.getDataStore(getSource().getLocation().toURL());
ShapefileDataStore store = new ShapefileDataStore(getSource().getLocation().toURL());
store.setCharset(getCharset());
progress.setCurrentTask("Extracting shape instances");
String typename = getParameter(PARAM_TYPENAME).as(String.class);
TypeDefinition defaultType = null;
if (typename != null && !typename.isEmpty()) {
try {
defaultType = getSourceSchema().getType(QName.valueOf(typename));
} catch (Exception e) {
// ignore
}
}
if (defaultType == null) {
// check if typename was supplied w/o namespace
try {
defaultType = getSourceSchema().getType(new QName(ShapefileConstants.SHAPEFILE_NS, typename));
} catch (Exception e) {
// ignore
// TODO report?
}
}
if (defaultType == null) {
reporter.info(new IOMessageImpl("No type name supplied as parameter, trying to auto-detect the schema type.", null));
TypeDefinition dataType = ShapeSchemaReader.readShapeType(getSource());
if (dataType == null) {
throw new IOException("Could not read shapefile structure information");
}
String preferredName = null;
Name name = store.getNames().iterator().next();
if (name != null) {
preferredName = name.getLocalPart();
}
Pair<TypeDefinition, Integer> tp = getMostCompatibleShapeType(getSourceSchema(), dataType, preferredName);
if (tp == null) {
throw new IOProviderConfigurationException("No schema type specified and auto-detection failed");
}
defaultType = tp.getFirst();
reporter.info(new IOMessageImpl(MessageFormat.format("Auto-deteted {0} as schema type, with a {1}% compatibility rating.", defaultType.getName(), tp.getSecond()), null));
}
Map<TypeDefinition, InstanceCollection> collections = new HashMap<>();
// create a collection for each type
for (Name name : store.getNames()) {
SimpleFeatureSource features = store.getFeatureSource(name);
TypeDefinition type = defaultType;
if (type == null) {
QName typeName = new QName(ShapefileConstants.SHAPEFILE_NS, name.getLocalPart());
type = getSourceSchema().getType(typeName);
}
collections.put(type, new ShapesInstanceCollection(features, type, getCrsProvider(), name.getLocalPart()));
}
instances = new PerTypeInstanceCollection(collections);
reporter.setSuccess(true);
return reporter;
}
use of org.geotools.data.simple.SimpleFeatureSource in project sldeditor by robward-scisys.
the class InLineFeatureModel method removeColumn.
/**
* 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<SimpleFeature>();
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();
}
}
}
}
Aggregations