private void collectAttributes( SimpleFeatureType schema, List<String> retainedAttributes, SimpleFeatureTypeBuilder tb) { for (AttributeDescriptor descriptor : schema.getAttributeDescriptors()) { // check whether descriptor has been selected in the attribute list boolean isInRetainList = true; if (retainedAttributes != null) { isInRetainList = retainedAttributes.contains(descriptor.getLocalName()); logger.fine("Checking " + descriptor.getLocalName() + " --> " + isInRetainList); } if (!isInRetainList || schema.getGeometryDescriptor() == descriptor) { continue; } // build the attribute to return AttributeTypeBuilder builder = new AttributeTypeBuilder(); builder.setName(schema.getName().getLocalPart() + "_" + descriptor.getName()); builder.setNillable(descriptor.isNillable()); builder.setBinding(descriptor.getType().getBinding()); builder.setMinOccurs(descriptor.getMinOccurs()); builder.setMaxOccurs(descriptor.getMaxOccurs()); builder.setDefaultValue(descriptor.getDefaultValue()); builder.setCRS(schema.getCoordinateReferenceSystem()); AttributeDescriptor intersectionDescriptor = builder.buildDescriptor( schema.getName().getLocalPart() + "_" + descriptor.getName(), descriptor.getType()); tb.add(intersectionDescriptor); tb.addBinding(descriptor.getType()); } }
public static SimpleFeatureType toReShapeFeatureType( SimpleFeatureCollection delegate, List<Definition> definitionList) { SimpleFeature sample = null; SimpleFeatureIterator iterator = delegate.features(); try { if (iterator.hasNext()) { sample = iterator.next(); } } finally { iterator.close(); // good bye } SimpleFeatureTypeBuilder build = new SimpleFeatureTypeBuilder(); SimpleFeatureType origional = delegate.getSchema(); for (Definition def : definitionList) { String name = def.name; Expression expression = def.expression; Object value = null; if (sample != null) { value = expression.evaluate(sample); } Class<?> binding = def.binding; // make use of any default binding hint provided by user if (value == null) { if (expression instanceof PropertyName) { PropertyName propertyName = (PropertyName) expression; String path = propertyName.getPropertyName(); AttributeDescriptor descriptor = origional.getDescriptor(name); AttributeType attributeType = descriptor.getType(); binding = attributeType.getBinding(); } } else { binding = value.getClass(); } if (binding == null) { // note we could consider scanning through additional samples until we get a non null hit throw new IllegalArgumentException("Unable to determine type for " + name); } if (Geometry.class.isAssignableFrom(binding)) { CoordinateReferenceSystem crs; AttributeType originalAttributeType = origional.getType(name); if (originalAttributeType != null && originalAttributeType instanceof GeometryType) { GeometryType geometryType = (GeometryType) originalAttributeType; crs = geometryType.getCoordinateReferenceSystem(); } else { crs = origional.getCoordinateReferenceSystem(); } build.crs(crs); build.add(name, binding); } else { build.add(name, binding); } } build.setName(origional.getTypeName()); return build.buildFeatureType(); }
private GeometryProjector makeGeometryProjecter(String projectionName) throws AlgorithmExecutionException { SimpleFeatureType featureSchema = featureCollection.getSchema(); CoordinateReferenceSystem originalCRS = featureSchema.getCoordinateReferenceSystem(); return new GeometryProjector(originalCRS, projectionName); }
/** * Creates the resultant features. * * @param splitGeometries List with the new geometries. * @param feature The old feature. * @throws OperationNotFoundException * @throws TransformException */ private List<SimpleFeature> createSplitFeatures( final List<Geometry> splitGeometries, final SimpleFeature feature) throws OperationNotFoundException, TransformException { final SimpleFeatureType featureType = feature.getFeatureType(); final CoordinateReferenceSystem featureCrs = featureType.getCoordinateReferenceSystem(); Class<? extends Geometry> geometryType = (Class<? extends Geometry>) featureType.getGeometryDescriptor().getType().getBinding(); List<SimpleFeature> splitFeatureList = new LinkedList<SimpleFeature>(); for (Geometry splittedPart : splitGeometries) { splittedPart = GeoToolsUtils.reproject(splittedPart, desiredCRS, featureCrs); splittedPart = GeometryUtil.adapt(splittedPart, geometryType); SimpleFeature newFeature = DataUtilities.template(featureType); GeoToolsUtils.copyAttributes(feature, newFeature); newFeature.setDefaultGeometry(splittedPart); splitFeatureList.add(newFeature); } return splitFeatureList; }
/** * @param dataStore A ShapeFileDataStore containing geometries to convert. * @param keyAttributes The names of attributes to be concatenated to generate record keys. * @throws Exception */ public static void convertFeatures( GeometryStreamConverter converter, ShapefileDataStore dataStore, List<String> keyAttributes) throws Exception { SimpleFeatureType schema = dataStore.getSchema(); int numFeatures = dataStore.getCount(Query.ALL); FeatureReader<SimpleFeatureType, SimpleFeature> reader = null; try { List<AttributeDescriptor> attrDesc = schema.getAttributeDescriptors(); String header = "\"the_geom_id\", \"the_geom_key\""; for (int i = 1; i < attrDesc.size(); i++) { String colName = attrDesc.get(i).getLocalName(); if (GeometryStreamConverter.debugDBF) header += ", \"" + colName + '"'; // if any specified attribute matches colName, case insensitive, overwrite specified // attribute name with name having correct case for (int j = 0; j < keyAttributes.size(); j++) if (keyAttributes.get(j).equalsIgnoreCase(colName)) keyAttributes.set(j, colName); } // debug: read schema and print it out if (GeometryStreamConverter.debugDBF) System.out.println(header); // loop through features and parse them long startTime = System.currentTimeMillis(), endTime = startTime, debugInterval = 60000, nextDebugTime = startTime + debugInterval; int featureCount = 0; reader = dataStore.getFeatureReader(); CoordinateReferenceSystem projection = schema.getCoordinateReferenceSystem(); // may be null String projectionWKT = projection == null ? null : projection.toWKT(); while (reader.hasNext()) { endTime = System.currentTimeMillis(); if (GeometryStreamConverter.debugTime && endTime > nextDebugTime) { System.out.println( String.format( "Processing %s/%s features, %s minutes elapsed", featureCount, numFeatures, (endTime - startTime) / 60000.0)); while (endTime > nextDebugTime) nextDebugTime += debugInterval; } convertFeature(converter, reader.next(), keyAttributes, projectionWKT); featureCount++; } if (GeometryStreamConverter.debugTime && endTime - startTime > debugInterval) System.out.println( String.format( "Processing %s features completed in %s minutes", numFeatures, (endTime - startTime) / 60000.0)); } catch (OutOfMemoryError e) { e.printStackTrace(); throw e; } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } }
private SimpleFeatureType createForceFeatureType(SimpleFeatureType featureType, String path) { SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setAttributes(featureType.getAttributeDescriptors()); builder.setName(new NameImpl(featureType.getName().getNamespaceURI(), path)); builder.setCRS(featureType.getCoordinateReferenceSystem()); featureType = builder.buildFeatureType(); return featureType; }
public CoordinateReferenceSystem getCoordinateReferenceSystem() { if (layerInfo != null) { return layerInfo.getResource().getCRS(); } if (remoteFeatureSource != null) { SimpleFeatureType schema = remoteFeatureSource.getSchema(); return schema.getCoordinateReferenceSystem(); } throw new IllegalStateException(); }
public IntersectedFeatureCollection( SimpleFeatureCollection delegate, List<String> firstAttributes, SimpleFeatureCollection features, List<String> sndAttributes, IntersectionMode intersectionMode, boolean percentagesEnabled, boolean areasEnabled) { super(delegate); this.features = features; this.firstAttributes = firstAttributes; this.sndAttributes = sndAttributes; this.intersectionMode = intersectionMode; this.percentagesEnabled = percentagesEnabled; this.areasEnabled = areasEnabled; SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); SimpleFeatureType firstFeatureCollectionSchema = delegate.getSchema(); SimpleFeatureType secondFeatureCollectionSchema = features.getSchema(); if (intersectionMode == IntersectionMode.FIRST) { geomType = firstFeatureCollectionSchema.getGeometryDescriptor(); } if (intersectionMode == IntersectionMode.SECOND) { geomType = secondFeatureCollectionSchema.getGeometryDescriptor(); } if (intersectionMode == IntersectionMode.INTERSECTION) { geomType = getIntersectionType(delegate, features); } tb.add(geomType); // gather the attributes from the first feature collection and skip collectAttributes(firstFeatureCollectionSchema, firstAttributes, tb); // gather the attributes from the second feature collection collectAttributes(secondFeatureCollectionSchema, sndAttributes, tb); // add the dyamic attributes as needed if (percentagesEnabled) { tb.add("percentageA", Double.class); tb.add("percentageB", Double.class); } if (areasEnabled) { tb.add("areaA", Double.class); tb.add("areaB", Double.class); } tb.add("INTERSECTION_ID", Integer.class); tb.setDescription(firstFeatureCollectionSchema.getDescription()); tb.setCRS(firstFeatureCollectionSchema.getCoordinateReferenceSystem()); tb.setAbstract(firstFeatureCollectionSchema.isAbstract()); tb.setSuperType((SimpleFeatureType) firstFeatureCollectionSchema.getSuper()); tb.setName(firstFeatureCollectionSchema.getName()); this.fb = new SimpleFeatureBuilder(tb.buildFeatureType()); }
/** Initializes the builder with state from a pre-existing feature type. */ public void init(SimpleFeatureType type) { init(); if (type == null) return; uri = type.getName().getNamespaceURI(); local = type.getName().getLocalPart(); description = type.getDescription(); restrictions = null; restrictions().addAll(type.getRestrictions()); this.defaultCrs = type.getCoordinateReferenceSystem(); this.defaultCrsSet = true; attributes = null; attributes().addAll(type.getAttributeDescriptors()); isAbstract = type.isAbstract(); superType = (SimpleFeatureType) type.getSuper(); }
CopyFeatureCollection( SimpleFeatureType schema, FeatureCollection<SimpleFeatureType, SimpleFeature> features, IProgressMonitor monitor, int[] worked, MathTransform mt, HashMap<String, String> attributeMap, MathTransform toWorld) { super("copyCollection", schema); this.schema = schema; this.features = features; this.monitor = monitor; this.worked = worked; this.mt = mt; this.attributeMap = attributeMap; this.env = new ReferencedEnvelope(schema.getCoordinateReferenceSystem()); this.toWorld = toWorld; }
/** @param query */ protected ReferencedEnvelope getBoundsInternal(Query query) { ReferencedEnvelope envelope = new ReferencedEnvelope(featureType.getCoordinateReferenceSystem()); FeatureIterator<SimpleFeature> iterator = collection.features(); try { if (iterator.hasNext()) { int count = 1; Filter filter = query.getFilter(); while (iterator.hasNext() && (count < query.getMaxFeatures())) { SimpleFeature feature = iterator.next(); if (filter.evaluate(feature)) { count++; envelope.expandToInclude( ((Geometry) feature.getDefaultGeometry()).getEnvelopeInternal()); } } } } finally { iterator.close(); } return envelope; }
/** * Loads the feature collection based on the current styling and the scale denominator. If no * feature is going to be returned a null feature collection will be returned instead * * @param featureSource * @param layer * @param mapContent * @param wms * @param scaleDenominator * @return * @throws Exception */ public static SimpleFeatureCollection loadFeatureCollection( SimpleFeatureSource featureSource, Layer layer, WMSMapContent mapContent, WMS wms, double scaleDenominator) throws Exception { SimpleFeatureType schema = featureSource.getSchema(); Envelope envelope = mapContent.getRenderingArea(); ReferencedEnvelope aoi = new ReferencedEnvelope(envelope, mapContent.getCoordinateReferenceSystem()); CoordinateReferenceSystem sourceCrs = schema.getCoordinateReferenceSystem(); boolean reprojectBBox = (sourceCrs != null) && !CRS.equalsIgnoreMetadata(aoi.getCoordinateReferenceSystem(), sourceCrs); if (reprojectBBox) { aoi = aoi.transform(sourceCrs, true); } Filter filter = createBBoxFilter(schema, aoi); // now build the query using only the attributes and the bounding // box needed Query q = new Query(schema.getTypeName()); q.setFilter(filter); // now, if a definition query has been established for this layer, // be sure to respect it by combining it with the bounding box one. Query definitionQuery = layer.getQuery(); if (definitionQuery != Query.ALL) { if (q == Query.ALL) { q = (Query) definitionQuery; } else { q = (Query) DataUtilities.mixQueries(definitionQuery, q, "KMLEncoder"); } } // handle startIndex requested by client query q.setStartIndex(definitionQuery.getStartIndex()); // check the regionating strategy RegionatingStrategy regionatingStrategy = null; String stratname = (String) mapContent.getRequest().getFormatOptions().get("regionateBy"); if (("auto").equals(stratname)) { Catalog catalog = wms.getGeoServer().getCatalog(); Name name = layer.getFeatureSource().getName(); stratname = catalog .getFeatureTypeByName(name) .getMetadata() .get("kml.regionateStrategy", String.class); if (stratname == null || "".equals(stratname)) { stratname = "best_guess"; LOGGER.log( Level.FINE, "No default regionating strategy has been configured in " + name + "; using automatic best-guess strategy."); } } if (stratname != null) { regionatingStrategy = findStrategyByName(stratname); // if a strategy was specified but we did not find it, let the user // know if (regionatingStrategy == null) throw new ServiceException("Unknown regionating strategy " + stratname); } // try to load less features by leveraging regionating strategy and the // SLD Filter regionatingFilter = Filter.INCLUDE; if (regionatingStrategy != null) regionatingFilter = regionatingStrategy.getFilter(mapContent, layer); Filter ruleFilter = summarizeRuleFilters( getLayerRules(featureSource.getSchema(), layer.getStyle()), scaleDenominator); Filter finalFilter = joinFilters(q.getFilter(), ruleFilter, regionatingFilter); if (finalFilter == Filter.EXCLUDE) { // if we don't have any feature to return return null; } q.setFilter(finalFilter); // make sure we output in 4326 since that's what KML mandates CoordinateReferenceSystem wgs84; try { wgs84 = CRS.decode("EPSG:4326"); } catch (Exception e) { throw new RuntimeException( "Cannot decode EPSG:4326, the CRS subsystem must be badly broken..."); } if (sourceCrs != null && !CRS.equalsIgnoreMetadata(wgs84, sourceCrs)) { return new ReprojectFeatureResults(featureSource.getFeatures(q), wgs84); } return featureSource.getFeatures(q); }
public List<FeatureId> addFeatures(FeatureCollection<SimpleFeatureType, SimpleFeature> collection) throws IOException { WFSTransactionState ts = null; if (trans == Transaction.AUTO_COMMIT) { ts = new WFSTransactionState(ds); } else { ts = (WFSTransactionState) trans.getState(ds); } List<FeatureId> r = new LinkedList<FeatureId>(); SimpleFeatureType schema = getSchema(); LenientBuilder build = new LenientBuilder(schema); boolean isLenient = true; if (schema.getUserData().containsKey("lenient")) { isLenient = (Boolean) schema.getUserData().get("lenient"); } if (isLenient) { build.setFeatureFactory(new LenientFeatureFactory()); } List<AttributeDescriptor> atrs = schema.getAttributeDescriptors(); FeatureIterator<SimpleFeature> iter = collection.features(); try { ReferencedEnvelope bounds = null; while (iter.hasNext()) { try { SimpleFeature newFeature; try { SimpleFeature f = iter.next(); String nextFid = ts.nextFid(schema.getTypeName()); Object[] values = f.getAttributes().toArray(); build.addAll(values); newFeature = build.buildFeature(nextFid); r.add(newFeature.getIdentifier()); } catch (IllegalAttributeException e) { throw (IOException) new IOException(e.getLocalizedMessage()); } for (int i = 0; i < atrs.size(); i++) { AttributeDescriptor att = atrs.get(i); if (att instanceof GeometryDescriptor) { Object geom = newFeature.getAttribute(i); if (geom instanceof Geometry) { Geometry g = (Geometry) geom; CoordinateReferenceSystem cs = ((GeometryDescriptor) att).getCoordinateReferenceSystem(); if (g == null) continue; if (cs != null && !cs.getIdentifiers().isEmpty()) g.setUserData(cs.getIdentifiers().iterator().next().toString()); if (bounds == null) { bounds = new ReferencedEnvelope( g.getEnvelopeInternal(), schema.getCoordinateReferenceSystem()); } else { bounds.expandToInclude(g.getEnvelopeInternal()); } } } } ts.addAction(schema.getTypeName(), new InsertAction(newFeature)); } catch (NoSuchElementException e) { WFS_1_0_0_DataStore.LOGGER.warning(e.toString()); throw new IOException(e.toString()); } } // Fire a notification. // JE if (bounds == null) { // if bounds are null then send an envelope to say that features were added but // at an unknown location. bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem()); ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( schema.getTypeName(), getTransaction(), bounds, false); } else { ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( schema.getTypeName(), getTransaction(), bounds, false); } } finally { iter.close(); } if (trans == Transaction.AUTO_COMMIT) { ts.commit(); String[] fids = ts.getFids(schema.getTypeName()); int i = 0; for (String fid : fids) { FeatureId identifier = r.get(i); if (identifier instanceof FeatureIdImpl) { ((FeatureIdImpl) identifier).setID(fid); } i++; } return r; } return r; }