use of org.geotools.data.FeatureSource in project GeoGig by boundlessgeo.
the class ImportOp method _call.
/**
* Executes the import operation using the parameters that have been specified. Features will be
* added to the working tree, and a new working tree will be constructed. Either {@code all} or
* {@code table}, but not both, must be set prior to the import process.
*
* @return RevTree the new working tree
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected RevTree _call() {
// check preconditions and get the actual list of type names to import
final String[] typeNames = checkPreconditions();
for (int i = 0; i < typeNames.length; i++) {
try {
typeNames[i] = URLDecoder.decode(typeNames[i], Charsets.UTF_8.displayName());
} catch (UnsupportedEncodingException e) {
// shouldn't reach here.
}
}
ProgressListener progressListener = getProgressListener();
progressListener.started();
// use a local variable not to alter the command's state
boolean overwrite = this.overwrite;
if (alter) {
overwrite = false;
}
final WorkingTree workTree = workingTree();
RevFeatureType destPathFeatureType = null;
final boolean destPathProvided = destPath != null;
if (destPathProvided) {
destPathFeatureType = this.command(ResolveFeatureType.class).setRefSpec(destPath).call().orNull();
// only the last one will be imported.
if (overwrite) {
try {
workTree.delete(destPath);
} catch (Exception e) {
throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT);
}
overwrite = false;
}
}
int tableCount = 0;
for (String typeName : typeNames) {
{
tableCount++;
String tableName = String.format("%-16s", typeName);
if (typeName.length() > 16) {
tableName = tableName.substring(0, 13) + "...";
}
progressListener.setDescription("Importing " + tableName + " (" + tableCount + "/" + typeNames.length + ")... ");
}
FeatureSource featureSource = getFeatureSource(typeName);
SimpleFeatureType featureType = (SimpleFeatureType) featureSource.getSchema();
final String fidPrefix = featureType.getTypeName() + ".";
String path;
if (destPath == null) {
path = featureType.getTypeName();
} else {
NodeRef.checkValidPath(destPath);
path = destPath;
featureType = forceFeatureTypeName(featureType, path);
}
featureType = overrideGeometryName(featureType);
featureSource = new ForceTypeAndFidFeatureSource<FeatureType, Feature>(featureSource, featureType, fidPrefix);
boolean hasPrimaryKey = hasPrimaryKey(typeName);
boolean forbidSorting = !usePaging || !hasPrimaryKey;
((ForceTypeAndFidFeatureSource) featureSource).setForbidSorting(forbidSorting);
if (destPathFeatureType != null && adaptToDefaultFeatureType && !alter) {
featureSource = new FeatureTypeAdapterFeatureSource<FeatureType, Feature>(featureSource, destPathFeatureType.type());
}
ProgressListener taskProgress = subProgress(100.f / typeNames.length);
if (overwrite) {
try {
workTree.delete(path);
workTree.createTypeTree(path, featureType);
} catch (Exception e) {
throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT);
}
}
if (alter) {
// first we modify the feature type and the existing features, if needed
workTree.updateTypeTree(path, featureType);
Iterator<Feature> transformedIterator = transformFeatures(featureType, path);
try {
final Integer collectionSize = collectionSize(featureSource);
workTree.insert(path, transformedIterator, taskProgress, null, collectionSize);
} catch (Exception e) {
throw new GeoToolsOpException(StatusCode.UNABLE_TO_INSERT);
}
}
try {
insert(workTree, path, featureSource, taskProgress);
} catch (GeoToolsOpException e) {
throw e;
} catch (Exception e) {
throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT);
}
}
progressListener.setProgress(100.f);
progressListener.complete();
return workTree.getTree();
}
use of org.geotools.data.FeatureSource in project GeoGig by boundlessgeo.
the class WorkingTreeTest method testInsertNonPagingFeatureSource.
@Test
public void testInsertNonPagingFeatureSource() throws Exception {
assertEquals(2, super.getGeogig().getPlatform().availableProcessors());
final List<SimpleFeature> features = ImmutableList.of((SimpleFeature) points1, (SimpleFeature) points2, (SimpleFeature) points3);
MemoryDataStore store = new MemoryDataStore();
store.addFeatures(features);
final QueryCapabilities caps = mock(QueryCapabilities.class);
when(caps.isOffsetSupported()).thenReturn(true);
@SuppressWarnings("rawtypes") FeatureSource source = store.getFeatureSource(pointsName);
assertFalse(source.getQueryCapabilities().isOffsetSupported());
String treePath = "target_typename";
workTree.insert(treePath, source, Query.ALL, LISTENER);
assertEquals(3, workTree.countUnstaged(treePath).featureCount());
}
use of org.geotools.data.FeatureSource in project sldeditor by robward-scisys.
the class MapRender method renderSymbol.
/**
* Render symbol.
*
* @param mapContent the map content
* @param styledLayer the styled layer
* @param style the style
*/
private void renderSymbol(MapContent mapContent, StyledLayer styledLayer, Style style) {
for (Layer layer : mapContent.layers()) {
mapContent.removeLayer(layer);
}
switch(geometryType) {
case RASTER:
{
GridReaderLayer gridLayer = new GridReaderLayer(gridCoverage, (org.geotools.styling.Style) style);
mapContent.addLayer(gridLayer);
mapContent.getViewport().setBounds(gridLayer.getBounds());
if (gridCoverage != null) {
mapPane.setDisplayArea(gridCoverage.getOriginalEnvelope());
}
}
break;
case POINT:
case LINE:
case POLYGON:
{
FeatureSource<SimpleFeatureType, SimpleFeature> tmpFeatureList = null;
if (styledLayer instanceof UserLayer) {
if (userLayerFeatureListMap != null) {
tmpFeatureList = userLayerFeatureListMap.get(styledLayer);
}
} else {
tmpFeatureList = featureList;
}
if (tmpFeatureList != null) {
mapContent.addLayer(new FeatureLayer(tmpFeatureList, (org.geotools.styling.Style) style));
try {
mapPane.setDisplayArea(tmpFeatureList.getBounds());
} catch (IOException e) {
ConsoleManager.getInstance().exception(this, e);
}
}
}
break;
default:
break;
}
wmsEnvVarValues.setMapBounds(mapBounds);
EnvironmentVariableManager.getInstance().setWMSEnvVarValues(wmsEnvVarValues);
}
use of org.geotools.data.FeatureSource in project sldeditor by robward-scisys.
the class DataSourceImplTest method testConnectToInlineDataSource.
/**
* Test method for {@link com.sldeditor.datasource.impl.DataSourceImpl#connect()}.
*/
@Test
public void testConnectToInlineDataSource() {
DataSourceImpl ds = new DataSourceImpl();
DummyInlineSLDFile editorFile = new DummyInlineSLDFile();
DummyDataSourceUpdate dataSourceUpdateListener = new DummyDataSourceUpdate();
ds.addListener(dataSourceUpdateListener);
CreateDataSourceInterface internalDataSource = new DummyCreateDataSource();
CreateDataSourceInterface externalDataSource = new DummyCreateDataSource();
CreateDataSourceInterface inlineDataSource = new CreateInlineDataSource();
ds.setDataSourceCreation(internalDataSource, externalDataSource, inlineDataSource);
ds.connect("typeName", editorFile, null);
assertTrue(dataSourceUpdateListener.hasBeenCalled());
assertEquals(GeometryTypeEnum.UNKNOWN, dataSourceUpdateListener.geometryType);
assertFalse(dataSourceUpdateListener.isConnectedToDataSourceFlag);
Collection<PropertyDescriptor> fieldList = ds.getPropertyDescriptorList();
assertNull(fieldList);
FeatureSource<SimpleFeatureType, SimpleFeature> exampleLayer = ds.getExampleFeatureSource();
assertNull(exampleLayer);
Map<UserLayer, FeatureSource<SimpleFeatureType, SimpleFeature>> userLayerMap = ds.getUserLayerFeatureSource();
assertEquals(1, userLayerMap.size());
assertFalse(dataSourceUpdateListener.hasBeenCalled());
ds.updateUserLayers();
assertTrue(dataSourceUpdateListener.hasBeenCalled());
DataSourcePropertiesInterface dsi = ds.getDataConnectorProperties();
assertNotNull(dsi);
}
use of org.geotools.data.FeatureSource in project spatial-portal by AtlasOfLivingAustralia.
the class PointGenerationComposer method onFinish.
@Override
public boolean onFinish() {
SelectedArea sa = getSelectedArea();
double[][] bbox = null;
if (sa.getMapLayer() != null && sa.getMapLayer().getMapLayerMetadata() != null) {
List<Double> bb = sa.getMapLayer().getMapLayerMetadata().getBbox();
bbox = new double[2][2];
bbox[0][0] = bb.get(0);
bbox[0][1] = bb.get(1);
bbox[1][0] = bb.get(2);
bbox[1][1] = bb.get(3);
} else {
List<Double> bb = Util.getBoundingBox(sa.getWkt());
bbox = new double[][] { { bb.get(0), bb.get(1) }, { bb.get(2), bb.get(3) } };
}
// with bounding box, cut points
try {
String wkt = (sa.getMapLayer() != null ? sa.getMapLayer().getWKT() : sa.getWkt());
StringBuilder sb = new StringBuilder();
sb.append("longitude,latitude");
int count = 0;
int width = (int) Math.ceil((bbox[1][0] - bbox[0][0]) / resolution.getValue());
int height = (int) Math.ceil((bbox[1][1] - bbox[0][1]) / resolution.getValue());
double startx = Math.floor(bbox[0][0] / resolution.getValue()) * resolution.getValue();
double starty = Math.floor(bbox[0][1] / resolution.getValue()) * resolution.getValue();
if (wkt == null) {
if (sa.getFacets() != null) {
double[][] points = new double[(width + 1) * (height + 1)][2];
int pos = 0;
for (int i = 0; i <= width; i++) {
for (int j = 0; j <= height; j++) {
double lng = startx + i * resolution.getValue();
double lat = starty + j * resolution.getValue();
points[pos][0] = lng;
points[pos][1] = lat;
pos = pos + 1;
}
}
List<String> fields = new ArrayList<String>();
for (Facet f : sa.getFacets()) {
fields.add(f.getFields()[0]);
}
List<String[]> result = Sampling.sampling(fields, points);
for (int i = 0; i < result.size(); i++) {
Facet f = sa.getFacets().get(i);
String[] intersection = result.get(i);
for (int j = 0; j < intersection.length; j++) {
if (f.isValid("\"" + intersection[j] + "\"")) {
sb.append("\n");
sb.append(points[j][0]).append(",").append(points[j][1]);
count++;
}
}
}
} else {
LOGGER.error("invalid area selected for point generation");
getMapComposer().showMessage("Unsupported area selected for point generation. Choose a different area.");
return false;
}
} else {
// write temporary shapefile
File tmp = File.createTempFile("tmp", ".shp");
ShapefileUtils.saveShapefile(tmp, wkt, "tmp");
FileDataStore store = FileDataStoreFinder.getDataStore(tmp);
FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
FeatureCollection featureCollection = featureSource.getFeatures();
GeometryFactory gf = new GeometryFactory();
List<Geometry> geometry = new ArrayList<Geometry>();
FeatureIterator it = featureCollection.features();
while (it.hasNext()) {
SimpleFeature feature = (SimpleFeature) it.next();
geometry.add((Geometry) feature.getDefaultGeometry());
}
try {
it.close();
} catch (Exception e) {
}
for (int i = 0; i <= width; i++) {
for (int j = 0; j <= height; j++) {
double lng = startx + i * resolution.getValue();
double lat = starty + j * resolution.getValue();
Coordinate c = new Coordinate(lng, lat);
Geometry point = gf.createPoint(c);
for (Geometry geom : geometry) {
if (geom.contains(point)) {
sb.append("\n");
sb.append(lng).append(",").append(lat);
count++;
}
}
}
}
// close tmp file
try {
store.dispose();
} catch (Exception e) {
}
// delete tmp files
try {
FileUtils.deleteQuietly(tmp);
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".shx")));
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".fix")));
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".dbf")));
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".prj")));
} catch (Exception e) {
}
}
if (count <= 0) {
getMapComposer().showMessage("No points generated. Try again with a smaller resolution or larger area.");
} else if (count > Integer.parseInt(CommonData.getSettings().getProperty("max_record_count_upload"))) {
getMapComposer().showMessage(count + " points generated. Maximum is " + CommonData.getSettings().getProperty("generated_points_max") + ".\n" + "Try again with a larger resolution or smaller area.");
} else {
String name = tToolName.getValue();
try {
UploadSpeciesController.loadUserPoints(new UserDataDTO(name), new StringReader(sb.toString()), true, name, "points in " + getSelectedAreaDisplayName() + " on " + resolution.getValue() + " degree resolution grid.", getMapComposer(), null);
detach();
return true;
} catch (Exception e) {
LOGGER.error("failed to upload points");
}
}
} catch (Exception e) {
}
return false;
}
Aggregations