/** * Forces the specified CRS on geometry attributes (all or some, depends on the parameters). * * @param schema the original schema * @param crs the forced crs * @param forceOnlyMissing if true, will force the specified crs only on the attributes that do * miss one * @return * @throws SchemaException */ public static SimpleFeatureType transform( SimpleFeatureType schema, CoordinateReferenceSystem crs, boolean forceOnlyMissing) throws SchemaException { SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.setName(schema.getTypeName()); tb.setNamespaceURI(schema.getName().getNamespaceURI()); tb.setAbstract(schema.isAbstract()); GeometryDescriptor defaultGeometryType = null; for (int i = 0; i < schema.getAttributeCount(); i++) { AttributeDescriptor attributeType = schema.getDescriptor(i); if (attributeType instanceof GeometryDescriptor) { GeometryDescriptor geometryType = (GeometryDescriptor) attributeType; AttributeDescriptor forced; tb.descriptor(geometryType); if (!forceOnlyMissing || geometryType.getCoordinateReferenceSystem() == null) { tb.crs(crs); } tb.add(geometryType.getLocalName(), geometryType.getType().getBinding()); } else { tb.add(attributeType); } } if (schema.getGeometryDescriptor() != null) { tb.setDefaultGeometry(schema.getGeometryDescriptor().getLocalName()); } tb.setSuperType((SimpleFeatureType) schema.getSuper()); return tb.buildFeatureType(); }
private static Object[] copyAttributes( SimpleFeatureType destSchema, SimpleFeature source, Map<String, Iterator<? extends Geometry>> geometries, Map<String, String> attributeMap, MathTransform mt) { Object[] attributes = new Object[destSchema.getAttributeCount()]; for (int i = 0; i < attributes.length; i++) { String sourceAttributeName = destSchema.getDescriptor(i).getName().getLocalPart(); String name = attributeMap.get(sourceAttributeName); if (name != null) attributes[i] = source.getAttribute(name); else { attributes[i] = destSchema.getDescriptor(i).getDefaultValue(); } if (attributes[i] instanceof Geometry) { Class<? extends Geometry> geomType = (Class<? extends Geometry>) destSchema.getDescriptor(i).getType().getBinding(); if (!geomType.isAssignableFrom(attributes[i].getClass())) { Collection<? extends Geometry> geom = createCompatibleGeometry((Geometry) attributes[i], geomType); Iterator<? extends Geometry> giter = geom.iterator(); attributes[i] = giter.next(); if (giter.hasNext()) geometries.put(sourceAttributeName, giter); } attributes[i] = transformGeom((Geometry) attributes[i], mt); } } return attributes; }
public void testImportCSV() throws Exception { File dir = unpack("csv/locations.zip"); ImportContext context = importer.createContext(new SpatialFile(new File(dir, "locations.csv"))); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); assertEquals(ImportTask.State.NO_CRS, task.getState()); LayerInfo layer = task.getLayer(); ResourceInfo resource = layer.getResource(); resource.setSRS("EPSG:4326"); assertTrue("Item not ready", importer.prep(task)); assertEquals(ImportTask.State.READY, task.getState()); context.updated(); assertEquals(ImportContext.State.PENDING, context.getState()); importer.run(context); assertEquals(ImportContext.State.COMPLETE, context.getState()); FeatureTypeInfo fti = (FeatureTypeInfo) resource; SimpleFeatureType featureType = (SimpleFeatureType) fti.getFeatureType(); GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor(); assertNull("Expecting no geometry", geometryDescriptor); assertEquals(4, featureType.getAttributeCount()); }
/** * This method joins the feature type with the types maintained by this object. Geometry attribute * is not added into the join geometry. It must be computed by the client and setted using the * setGeometry Method. * * @see setGeometry * @param featureType */ public FeatureTypeUnionBuilder add(final SimpleFeatureType featureType) { // adds the attribute types of this feature type, if there are name // collisions // the method appends the number "2" at the name to avoid name // duplication. // The geometry attribute will be omitted. for (int i = 0; i < featureType.getAttributeCount(); i++) { AttributeDescriptor attributeType = featureType.getDescriptor(i); if (!(attributeType instanceof GeometryDescriptor)) { String attrUnionName = attributeType.getLocalName(); if (this.mapUnionAttributes.containsKey(attrUnionName)) { StringBuffer duplicatedName = new StringBuffer(attrUnionName); duplicatedName.append("2"); attrUnionName = duplicatedName.toString(); } AttributeTypeBuilder builder = new AttributeTypeBuilder(); builder.setBinding(attributeType.getType().getBinding()); builder.setNillable(attributeType.isNillable()); AttributeDescriptor newAttribute = builder.buildDescriptor(attrUnionName); mapUnionAttributes.put(attrUnionName, newAttribute); mapOriginalUnion.put( new UnionKey(featureType.getTypeName(), attributeType.getLocalName()), attrUnionName); } } return this; }
/** * Next Feature from reader or new content. * * @see org.geotools.data.FeatureWriter#next() */ public SimpleFeature next() throws IOException { SimpleFeatureType type = getFeatureType(); if (hasNext()) { // hasNext() will take care recording // any modifications to current try { live = next; // update live value next = null; // hasNext will need to search again current = SimpleFeatureBuilder.copy(live); return current; } catch (IllegalAttributeException e) { throw (IOException) new IOException("Could not modify content").initCause(e); } } else { // Create new content // created with an empty ID // (The real writer will supply a FID later) try { live = null; next = null; current = SimpleFeatureBuilder.build( type, new Object[type.getAttributeCount()], "new" + diff.nextFID); diff.nextFID++; return current; } catch (IllegalAttributeException e) { throw new IOException("Could not create new content"); } } }
/** Maps attributes with the same name and same types to each other. */ @SuppressWarnings("unchecked") private static void performDirectMapping( SimpleFeatureType sourceSchema, SimpleFeatureType targetSchema, Map<String, String> queryAttributes) { for (int i = 0; i < sourceSchema.getAttributeCount(); i++) { AttributeDescriptor source = sourceSchema.getDescriptor(i); for (int j = 0; j < targetSchema.getAttributeCount(); j++) { AttributeDescriptor target = targetSchema.getDescriptor(j); // don't worry about case of attribute name if (target.getName().getLocalPart().equalsIgnoreCase(source.getName().getLocalPart()) && target.getType().getBinding().isAssignableFrom(source.getType().getBinding())) { queryAttributes.put(target.getName().getLocalPart(), source.getName().getLocalPart()); } } } }
private void checkSchemaCorrect(SimpleFeatureType ft, boolean includeProportionColumns) { if (includeProportionColumns) { assertEquals(5, ft.getAttributeCount()); } else { assertEquals(3, ft.getAttributeCount()); } assertEquals(Point.class, ft.getGeometryDescriptor().getType().getBinding()); assertEquals( Integer.class, ft.getDescriptor(PointStackerProcess.ATTR_COUNT).getType().getBinding()); assertEquals( Integer.class, ft.getDescriptor(PointStackerProcess.ATTR_COUNT_UNIQUE).getType().getBinding()); if (includeProportionColumns) { assertEquals( Double.class, ft.getDescriptor(PointStackerProcess.ATTR_NORM_COUNT).getType().getBinding()); assertEquals( Double.class, ft.getDescriptor(PointStackerProcess.ATTR_NORM_COUNT_UNIQUE).getType().getBinding()); } }
public void testImportCSVIndirect() throws Exception { File dir = unpack("csv/locations.zip"); String wsName = getCatalog().getDefaultWorkspace().getName(); DataStoreInfo h2DataStore = createH2DataStore(wsName, "csvindirecttest"); SpatialFile importData = new SpatialFile(new File(dir, "locations.csv")); ImportContext context = importer.createContext(importData, h2DataStore); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); TransformChain transformChain = task.getTransform(); transformChain.add(new AttributesToPointGeometryTransform("LAT", "LON")); assertEquals(ImportTask.State.NO_CRS, task.getState()); LayerInfo layer = task.getLayer(); ResourceInfo resource = layer.getResource(); resource.setSRS("EPSG:4326"); assertTrue("Item not ready", importer.prep(task)); assertEquals(ImportTask.State.READY, task.getState()); context.updated(); assertEquals(ImportContext.State.PENDING, context.getState()); importer.run(context); assertEquals(ImportContext.State.COMPLETE, context.getState()); FeatureTypeInfo fti = (FeatureTypeInfo) resource; SimpleFeatureType featureType = (SimpleFeatureType) fti.getFeatureType(); GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor(); assertNotNull("Expecting geometry", geometryDescriptor); assertEquals("Invalid geometry name", "location", geometryDescriptor.getLocalName()); assertEquals(3, featureType.getAttributeCount()); FeatureSource<? extends FeatureType, ? extends Feature> featureSource = fti.getFeatureSource(null, null); FeatureCollection<? extends FeatureType, ? extends Feature> features = featureSource.getFeatures(); assertEquals(9, features.size()); FeatureIterator<? extends Feature> featureIterator = features.features(); assertTrue("Expected features", featureIterator.hasNext()); SimpleFeature feature = (SimpleFeature) featureIterator.next(); assertNotNull(feature); assertEquals("Invalid city attribute", "Trento", feature.getAttribute("CITY")); assertEquals("Invalid number attribute", 140, feature.getAttribute("NUMBER")); Object geomAttribute = feature.getAttribute("location"); assertNotNull("Expected geometry", geomAttribute); Point point = (Point) geomAttribute; Coordinate coordinate = point.getCoordinate(); assertEquals("Invalid x coordinate", 11.12, coordinate.x, 0.1); assertEquals("Invalid y coordinate", 46.07, coordinate.y, 0.1); featureIterator.close(); }
public void write() throws IOException { try { SimpleFeatureType target = getFeatureType(); for (int i = 0; i < target.getAttributeCount(); i++) { AttributeDescriptor at = target.getDescriptor(i); Object value = retyped.getAttribute(i); current.setAttribute(at.getLocalName(), value); } delegate.write(); } catch (IllegalAttributeException e) { throw (IOException) new IOException("Error occurred while retyping feature").initCause(e); } }
/** * DOCUMENT ME! * * @param featureType DOCUMENT ME! * @param properties DOCUMENT ME! * @return DOCUMENT ME! * @throws SchemaException DOCUMENT ME! */ public static SimpleFeatureType createSubType(SimpleFeatureType featureType, String[] properties) throws SchemaException { if (properties == null) { return featureType; } boolean same = featureType.getAttributeCount() == properties.length; for (int i = 0; (i < featureType.getAttributeCount()) && same; i++) { same = featureType.getDescriptor(i).getLocalName().equals(properties[i]); } if (same) { return featureType; } SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.setName(featureType.getName()); for (int i = 0; i < properties.length; i++) { tb.add(featureType.getDescriptor(properties[i])); } return tb.buildFeatureType(); }
/** * Checks if the feature type specified is a GridCoverage wrapper * * @param featureType * @return */ public static boolean isWrappedCoverage(SimpleFeatureType featureType) { if (!"GridCoverage".equals(featureType.getName().getLocalPart())) return false; if (featureType.getAttributeCount() != 2) return false; AttributeDescriptor polyDescriptor = featureType.getDescriptor("geom"); if (polyDescriptor == null || !Polygon.class.equals(polyDescriptor.getType().getBinding())) return false; AttributeDescriptor gridDescriptor = featureType.getDescriptor("grid"); if (gridDescriptor == null || !GridCoverage.class.equals(gridDescriptor.getType().getBinding())) return false; return true; }
/** * A new feature type using the attribute names of all joined feature type. * * @return a new feature type * @throws IllegalAttributeException * @throws SchemaException */ public SimpleFeature getFeature() throws IllegalAttributeException, SchemaException { SimpleFeatureType unionFeatureType = getFeatureType(); // adds the attributes values Object[] attrList = new Object[unionFeatureType.getAttributeCount()]; for (SimpleFeature feature : this.unionFeatures) { SimpleFeatureType featureType = feature.getFeatureType(); for (int j = 0; j < featureType.getAttributeCount(); j++) { // gets the attribute value AttributeDescriptor attrType = featureType.getDescriptor(j); if (!(attrType instanceof GeometryDescriptor)) { Object attrValue = feature.getAttribute(j); // gets the position in the union String unionAttrName = findAttributeName(featureType.getTypeName(), attrType.getLocalName()); int unionAttrPosition = unionFeatureType.indexOf(unionAttrName); // set the value in union attrList[unionAttrPosition] = attrValue; } } } // creates the new feature SimpleFeatureBuilder builder = new SimpleFeatureBuilder(unionFeatureType); builder.addAll(attrList); // SimpleFeature product = unionFeatureType.create(attrList); SimpleFeature product = builder.buildFeature(null); product.setDefaultGeometry(this.geometry); return product; }
/** * tests that the schema for the defined tests tables are returned. * * @throws IOException DOCUMENT ME! * @throws SeException */ @Test public void testGetSchema() throws IOException, SeException { SimpleFeatureType schema; schema = store.getSchema(testData.getTempTableName()); assertNotNull(schema); // ROW_ID is not included in TEST_TABLE_COLS assertEquals(TEST_TABLE_COLS.length, schema.getAttributeCount()); for (int i = 0; i < TEST_TABLE_COLS.length; i++) { assertEquals("at index" + i, TEST_TABLE_COLS[i], schema.getDescriptor(i).getLocalName()); } assertFalse(schema.getDescriptor(0).isNillable()); assertTrue(schema.getDescriptor(1).isNillable()); }
@Override public void parseRecords(int offset, int numRecords) throws IOException { featureCollection = new ListFeatureCollection(simpleFeatureType); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType); skipToLine(offset); String line; long featureCount = offset; while ((numRecords == -1 || featureCount < offset + numRecords) && (line = stream.readLine()) != null) { String[] tokens = getTokens(line); if (tokens == null) { break; } int expectedTokenCount = simpleFeatureType.getAttributeCount(); expectedTokenCount += hasFeatureId ? 1 : 0; if (tokens.length != expectedTokenCount) { continue; } builder.reset(); String featureId = "" + featureCount++; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (i == 0 && hasFeatureId) { featureId = token; } else { try { Object value = null; int currentIndex = i; currentIndex -= hasFeatureId ? 1 : 0; if (!VectorDataNodeIO.NULL_TEXT.equals(token)) { value = converters[currentIndex].parse(token); } builder.set(simpleFeatureType.getDescriptor(currentIndex).getLocalName(), value); } catch (ConversionException e) { BeamLogManager.getSystemLogger() .warning(String.format("Problem in '%s': %s", csv.getPath(), e.getMessage())); } } } SimpleFeature simpleFeature = builder.buildFeature(featureId); featureCollection.add(simpleFeature); bytePositionForOffset.put(featureCount, stream.getStreamPosition()); } recordsParsed = true; }
PRMSAnimationAttributeReader( PRMSAnimationFileMetaData animationFileMetaData, SimpleFeatureType featureType) throws IOException { this.featureType = featureType; this.animationFileMetaData = animationFileMetaData; this.readerAttributeCount = featureType.getAttributeCount(); this.readerRecordIndex = 0; readerAttributeToRecordEntryIndices = new int[readerAttributeCount]; for (int readerAttributeIndex = 0; readerAttributeIndex < readerAttributeCount; ++readerAttributeIndex) { readerAttributeToRecordEntryIndices[readerAttributeIndex] = animationFileMetaData.getRecordEntryIndex( featureType.getDescriptor(readerAttributeIndex).getLocalName()); } readerRecordBuffer = new PRMSAnimationRecordBuffer(animationFileMetaData); }
static SimpleFeature retype(SimpleFeature source, SimpleFeatureBuilder builder) throws IllegalAttributeException { SimpleFeatureType target = builder.getFeatureType(); for (int i = 0; i < target.getAttributeCount(); i++) { AttributeDescriptor attributeType = target.getDescriptor(i); Object value = null; if (source.getFeatureType().getDescriptor(attributeType.getName()) != null) { value = source.getAttribute(attributeType.getName()); } builder.add(value); } FeatureId id = reTypeId(source.getIdentifier(), source.getFeatureType(), target); SimpleFeature retyped = builder.buildFeature(id.getID()); retyped.getUserData().putAll(source.getUserData()); return retyped; }
/** Maps the default geometry attribute regardless of whether they are the same type. */ @SuppressWarnings("unchecked") private static void mapGeometryAttributes( SimpleFeatureType sourceSchema, SimpleFeatureType targetSchema, Map<String, String> queryAttributes) { // Now we'll match the geometry on type only. I don't care if it has the same type name. GeometryDescriptor defaultGeometry = targetSchema.getGeometryDescriptor(); if (defaultGeometry == null) { return; } else if (!queryAttributes.containsKey(defaultGeometry.getName())) { // first check source's default geom and see if it matches Class<?> binding = sourceSchema.getGeometryDescriptor().getType().getBinding(); if (defaultGeometry.getType().getBinding().isAssignableFrom(binding)) { queryAttributes.put( defaultGeometry.getName().getLocalPart(), sourceSchema.getGeometryDescriptor().getName().getLocalPart()); } else { // we have to look through all the source attributes looking for a geometry that // matches. boolean found = false; for (int i = 0; i < sourceSchema.getAttributeCount(); i++) { AttributeDescriptor source = sourceSchema.getDescriptor(i); if (defaultGeometry .getType() .getBinding() .isAssignableFrom(source.getType().getBinding())) { queryAttributes.put( defaultGeometry.getName().getLocalPart(), source.getName().getLocalPart()); found = true; break; } } // ok so we're going to have to do some transformations. Match default geometries // then. if (!found) { queryAttributes.put( defaultGeometry.getName().getLocalPart(), sourceSchema.getGeometryDescriptor().getName().getLocalPart()); } } } }
/** * Create a new Features from the provided coordinates and of the type indicated by geomType * * @param coordCRS The crs of the coordinates provided * @param destinationCRS The desired crs of the geometry * @param type the feature type of the object created * @param coordinates the coordinates that will be used to create the new feature * @param geomType the type of geometry that will be created * @return A new features. * @throws Exception */ public static <T extends Geometry> SimpleFeature createFeature( CoordinateReferenceSystem coordCRS, CoordinateReferenceSystem destinationCRS, SimpleFeatureType type, Coordinate[] coordinates, Class<T> geomType) throws Exception { transform(coordCRS, destinationCRS, coordinates); Object[] attrs = new Object[type.getAttributeCount()]; for (int i = 0; i < attrs.length; i++) { attrs[i] = setDefaultValue(type.getDescriptor(i)); } final SimpleFeature newFeature = SimpleFeatureBuilder.build(type, attrs, null); // Class geomType = type.getDefaultGeometry().getType(); T geom = GeometryBuilder.create().safeCreateGeometry(geomType, coordinates); newFeature.setDefaultGeometry(geom); return newFeature; }
@Override public Object[] parseRecords(final int offset, final int numRecords, final String rowName) throws IOException { AttributeDescriptor attributeDescriptor = simpleFeatureType.getDescriptor(rowName); int expectedTokenCount = simpleFeatureType.getAttributeCount(); expectedTokenCount += hasFeatureId ? 1 : 0; int rowIndex = simpleFeatureType.getAttributeDescriptors().indexOf(attributeDescriptor); int tokenIndex = rowIndex + (hasFeatureId ? 1 : 0); List<Object> values = new ArrayList<>(numRecords); skipToLine(offset); String line; long featureCount = offset; while ((numRecords == -1 || featureCount < offset + numRecords) && (line = stream.readLine()) != null) { String[] tokens = getTokens(line); if (tokens == null) { break; } if (tokens.length != expectedTokenCount) { continue; } featureCount++; String token = tokens[tokenIndex]; try { Object value = null; if (!VectorDataNodeIO.NULL_TEXT.equals(token)) { value = converters[rowIndex].parse(token); } values.add(value); } catch (ConversionException e) { BeamLogManager.getSystemLogger() .warning(String.format("Problem in '%s': %s", csv.getPath(), e.getMessage())); } bytePositionForOffset.put(featureCount, stream.getStreamPosition()); } return values.toArray(); }
/** * Creates the bounding box filters (one for each geometric attribute) needed to query a <code> * Layer</code>'s feature source to return just the features for the target rendering extent * * @param schema the layer's feature source schema * @param bbox the expression holding the target rendering bounding box * @return an or'ed list of bbox filters, one for each geometric attribute in <code>attributes * </code>. If there are just one geometric attribute, just returns its corresponding <code> * GeometryFilter</code>. * @throws IllegalFilterException if something goes wrong creating the filter */ private static Filter createBBoxFilter(SimpleFeatureType schema, Envelope bbox) throws IllegalFilterException { List filters = new ArrayList(); for (int j = 0; j < schema.getAttributeCount(); j++) { AttributeDescriptor attType = schema.getDescriptor(j); if (attType instanceof GeometryDescriptor) { Filter gfilter = filterFactory.bbox( attType.getLocalName(), bbox.getMinX(), bbox.getMinY(), bbox.getMaxX(), bbox.getMaxY(), null); filters.add(gfilter); } } if (filters.size() == 0) return Filter.INCLUDE; else if (filters.size() == 1) return (Filter) filters.get(0); else return filterFactory.or(filters); }
public static IGlobeFeatureCollection< IVector2, ? extends IBoundedGeometry2D<? extends IFinite2DBounds<?>>> readFeatures(final DataStore dataStore, final String layerName, final GProjection projection) throws Exception { final SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName); final SimpleFeatureCollection featuresCollection = featureSource.getFeatures(); final GIntHolder validCounter = new GIntHolder(0); // final GIntHolder polygonsWithHolesCounter = new GIntHolder(0); final GIntHolder invalidCounter = new GIntHolder(0); // final GIntHolder validVerticesCounter = new GIntHolder(0); final GIntHolder polygonsCounter = new GIntHolder(0); final GIntHolder linesCounter = new GIntHolder(0); final GIntHolder pointsCounter = new GIntHolder(0); final int featuresCount = featuresCollection.size(); final ArrayList<IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>> euclidFeatures = new ArrayList< IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>( featuresCount); final GProgress progress = new GProgress(featuresCount) { @Override public void informProgress( final double percent, final long elapsed, final long estimatedMsToFinish) { // System.out.println("Loading \"" + fileName.buildPath() + "\" " // + progressString(percent, elapsed, // estimatedMsToFinish)); System.out.println( "Loading data from data storage: " + layerName + " " + progressString(percent, elapsed, estimatedMsToFinish)); } }; final FeatureIterator<SimpleFeature> iterator = featuresCollection.features(); while (iterator.hasNext()) { final SimpleFeature feature = iterator.next(); final GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty(); final GeometryType type = geometryAttribute.getType(); if (type.getBinding() == com.vividsolutions.jts.geom.MultiPolygon.class) { polygonsCounter.increment(); final com.vividsolutions.jts.geom.MultiPolygon multipolygon = (com.vividsolutions.jts.geom.MultiPolygon) geometryAttribute.getValue(); final int geometriesCount = multipolygon.getNumGeometries(); final List<IPolygon2D> polygons = new ArrayList<IPolygon2D>(geometriesCount); for (int i = 0; i < geometriesCount; i++) { final com.vividsolutions.jts.geom.Polygon jtsPolygon = (com.vividsolutions.jts.geom.Polygon) multipolygon.getGeometryN(i); try { final IPolygon2D euclidPolygon = createEuclidPolygon(projection, jtsPolygon); if (euclidPolygon != null) { // euclidFeatures.add(createFeature(euclidPolygon, feature)); polygons.add(euclidPolygon); validCounter.increment(); } } catch (final IllegalArgumentException e) { // System.err.println(e.getMessage()); } } if (!polygons.isEmpty()) { if (polygons.size() == 1) { euclidFeatures.add(createFeature(polygons.get(0), feature)); } else { euclidFeatures.add(createFeature(new GMultiGeometry2D<IPolygon2D>(polygons), feature)); } } } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiLineString.class) { linesCounter.increment(); final com.vividsolutions.jts.geom.MultiLineString multiline = (com.vividsolutions.jts.geom.MultiLineString) geometryAttribute.getValue(); final int geometriesCount = multiline.getNumGeometries(); final List<IPolygonalChain2D> lines = new ArrayList<IPolygonalChain2D>(geometriesCount); for (int i = 0; i < geometriesCount; i++) { final com.vividsolutions.jts.geom.LineString jtsLine = (com.vividsolutions.jts.geom.LineString) multiline.getGeometryN(i); try { final IPolygonalChain2D euclidLine = createLine(jtsLine.getCoordinates(), projection); // euclidFeatures.add(createFeature(euclidLines, feature)); lines.add(euclidLine); } catch (final IllegalArgumentException e) { // System.err.println(e.getMessage()); } } if (!lines.isEmpty()) { if (lines.size() == 1) { euclidFeatures.add(createFeature(lines.get(0), feature)); } else { euclidFeatures.add( createFeature(new GMultiGeometry2D<IPolygonalChain2D>(lines), feature)); } } validCounter.increment(); } else if (type.getBinding() == com.vividsolutions.jts.geom.Point.class) { pointsCounter.increment(); final IVector2 euclidPoint = createPoint( ((com.vividsolutions.jts.geom.Point) geometryAttribute.getValue()).getCoordinate(), projection); euclidFeatures.add(createFeature(euclidPoint, feature)); validCounter.increment(); } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiPoint.class) { final IBoundedGeometry2D<? extends IFinite2DBounds<?>> euclidMultipoint = createEuclidMultiPoint(geometryAttribute, projection); euclidFeatures.add(createFeature(euclidMultipoint, feature)); validCounter.increment(); } else { invalidCounter.increment(); System.out.println("invalid type: " + type); } progress.stepDone(); } dataStore.dispose(); euclidFeatures.trimToSize(); System.out.println(); System.out.println("Features: " + featuresCount); System.out.println(); System.out.println("Read " + validCounter.get() + " valid geometries"); System.out.println(" => " + polygonsCounter.get() + " valid polygons"); System.out.println(" => " + linesCounter.get() + " valid lines"); System.out.println(" => " + pointsCounter.get() + " valid points"); System.out.println(); if (invalidCounter.get() > 0) { System.out.println("Ignored " + invalidCounter.get() + " invalid geometries"); } System.out.println(); final SimpleFeatureType schema = featureSource.getSchema(); final int fieldsCount = schema.getAttributeCount(); final List<GField> fields = new ArrayList<GField>(fieldsCount); System.out.println("Fields count: " + fieldsCount); for (int i = 0; i < fieldsCount; i++) { final String fieldName = schema.getType(i).getName().getLocalPart(); System.out.println("Fieldname: " + fieldName); final Class<?> fieldType = schema.getType(i).getBinding(); fields.add(new GField(fieldName, fieldType)); } return new GListFeatureCollection<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>( GProjection.EPSG_4326, fields, euclidFeatures, "uniqueId_000"); }
/** * Write SQL string to create tables in the test database based on the property files. * * @param propertyFiles Property files from app-schema-test suite. * @param parser The parser (WKT or an SC4O one for 3D tests) * @throws IllegalAttributeException * @throws NoSuchElementException * @throws IOException */ private void createTables(Map<String, File> propertyFiles, String parser) throws IllegalAttributeException, NoSuchElementException, IOException { StringBuffer buf = new StringBuffer(); StringBuffer spatialIndex = new StringBuffer(); // drop table procedure I copied from Victor's Oracle_Data_ref_set.sql buf.append("CREATE OR REPLACE PROCEDURE DROP_TABLE_OR_VIEW(TabName in Varchar2) IS ") .append("temp number:=0;") .append(" tes VARCHAR2 (200) := TabName;") .append(" drp_stmt VARCHAR2 (200):=null;") .append("BEGIN select count(*) into temp from user_tables where TABLE_NAME = tes;") .append("if temp = 1 then drp_stmt := 'Drop Table '||tes;") .append("EXECUTE IMMEDIATE drp_stmt;") // drop views too .append("else select count(*) into temp from user_views where VIEW_NAME = tes;") .append("if temp = 1 then drp_stmt := 'Drop VIEW '||tes;") .append("EXECUTE IMMEDIATE drp_stmt;end if;end if;") .append("EXCEPTION WHEN OTHERS THEN ") .append( "raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);") .append("END DROP_TABLE_OR_VIEW;\n"); for (String fileName : propertyFiles.keySet()) { File file = new File(propertyFiles.get(fileName), fileName); try (PropertyFeatureReader reader = new PropertyFeatureReader("test", file)) { SimpleFeatureType schema = reader.getFeatureType(); String tableName = schema.getName().getLocalPart().toUpperCase(); // drop table if exists buf.append("CALL DROP_TABLE_OR_VIEW('").append(tableName).append("')\n"); // create the table buf.append("CREATE TABLE ").append(tableName).append("("); // + pkey int size = schema.getAttributeCount() + 1; String[] fieldNames = new String[size]; List<String> createParams = new ArrayList<String>(); int j = 0; String type; String field; int spatialIndexCounter = 0; for (PropertyDescriptor desc : schema.getDescriptors()) { field = desc.getName().toString().toUpperCase(); fieldNames[j] = field; if (desc instanceof GeometryDescriptor) { type = "SDO_GEOMETRY"; // Update spatial index int srid = getSrid(((GeometryType) desc.getType())); spatialIndex .append("DELETE FROM user_sdo_geom_metadata WHERE table_name = '") .append(tableName) .append("'\n"); spatialIndex .append("Insert into user_sdo_geom_metadata ") .append("(TABLE_NAME,COLUMN_NAME,DIMINFO,SRID)") .append("values ('") .append(tableName) .append("','") .append(field) .append("',MDSYS.SDO_DIM_ARRAY(MDSYS.SDO_DIM_ELEMENT('X',140.962,144.909,0.00001),") .append("MDSYS.SDO_DIM_ELEMENT('Y',-38.858,-33.98,0.00001)") .append( // support 3d index ((GeometryDescriptor) desc).getCoordinateReferenceSystem() != null && ((GeometryDescriptor) desc) .getCoordinateReferenceSystem() .getCoordinateSystem() .getDimension() == 3 ? ", MDSYS.SDO_DIM_ELEMENT('Z',-100000, 100000, 1) )," : "),") .append(srid) .append(")\n"); // ensure it's <= 30 characters to avoid Oracle exception String indexName = (tableName.length() <= 26 ? tableName : tableName.substring(0, 26)) + "_IDX"; if (spatialIndexCounter > 0) { // to avoid duplicate index name when there are > 1 geometry in the same table indexName += spatialIndexCounter; } spatialIndex .append("CREATE INDEX \"") .append(indexName) .append("\" ON \"") .append(tableName) .append("\"(\"") .append(field) .append("\") ") .append("INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\"\n"); spatialIndexCounter++; } else { type = Classes.getShortName(desc.getType().getBinding()); if (type.equalsIgnoreCase("String")) { type = "NVARCHAR2(250)"; } else if (type.equalsIgnoreCase("Double")) { type = "NUMBER"; } // etc. assign as required } createParams.add(field + " " + type); j++; } // Add numeric PK for sorting fieldNames[j] = "PKEY"; createParams.add("PKEY VARCHAR2(30)"); buf.append(StringUtils.join(createParams.iterator(), ", ")); buf.append(")\n"); buf.append( "ALTER TABLE " + tableName + " ADD CONSTRAINT " + tableName + " PRIMARY KEY (PKEY)\n"); // then insert rows SimpleFeature feature; FeatureId id; while (reader.hasNext()) { buf.append("INSERT INTO ").append(tableName).append("("); feature = reader.next(); buf.append(StringUtils.join(fieldNames, ", ")); buf.append(") "); buf.append("VALUES ("); Collection<Property> properties = feature.getProperties(); String[] values = new String[size]; int valueIndex = 0; for (Property prop : properties) { Object value = prop.getValue(); if (value instanceof Geometry) { // use wkt writer to convert geometry to string, so third dimension can be supported // if present. Geometry geom = (Geometry) value; value = new WKTWriter(geom.getCoordinate().z == Double.NaN ? 2 : 3).write(geom); } if (value == null || value.toString().equalsIgnoreCase("null")) { values[valueIndex] = "null"; } else if (prop.getType() instanceof GeometryType) { int srid = getSrid(((GeometryType) prop.getType())); StringBuffer geomValue = new StringBuffer(parser + "('"); geomValue.append(value).append("'"); if (srid > -1) { // attach srid geomValue.append(", ").append(srid); } geomValue.append(")"); values[valueIndex] = geomValue.toString(); } else if (prop.getType().getBinding().getSimpleName().equalsIgnoreCase("DATE")) { values[valueIndex] = "TO_DATE('" + value + "', 'yyyy-MM-dd')"; } else { values[valueIndex] = "'" + value + "'"; } valueIndex++; } id = feature.getIdentifier(); // insert primary key values[valueIndex] = "'" + id.toString() + "'"; buf.append(StringUtils.join(values, ",")); buf.append(")\n"); } } buf.append(spatialIndex.toString()); spatialIndex.delete(0, spatialIndex.length()); if (buf.length() > 0) { this.sql = buf.toString(); } } }
public static SimpleFeatureType createSubType( SimpleFeatureType featureType, String[] properties, CoordinateReferenceSystem override, String typeName, URI namespace) throws SchemaException { if ((properties == null) && (override == null)) { return featureType; } if (properties == null) { properties = new String[featureType.getAttributeCount()]; for (int i = 0; i < properties.length; i++) { properties[i] = featureType.getDescriptor(i).getLocalName(); } } String namespaceURI = namespace != null ? namespace.toString() : null; boolean same = featureType.getAttributeCount() == properties.length && featureType.getTypeName().equals(typeName) && Utilities.equals(featureType.getName().getNamespaceURI(), namespaceURI); for (int i = 0; (i < featureType.getAttributeCount()) && same; i++) { AttributeDescriptor type = featureType.getDescriptor(i); same = type.getLocalName().equals(properties[i]) && (((override != null) && type instanceof GeometryDescriptor) ? assertEquals( override, ((GeometryDescriptor) type).getCoordinateReferenceSystem()) : true); } if (same) { return featureType; } AttributeDescriptor[] types = new AttributeDescriptor[properties.length]; for (int i = 0; i < properties.length; i++) { types[i] = featureType.getDescriptor(properties[i]); if ((override != null) && types[i] instanceof GeometryDescriptor) { AttributeTypeBuilder ab = new AttributeTypeBuilder(); ab.init(types[i]); ab.setCRS(override); types[i] = ab.buildDescriptor(types[i].getLocalName(), ab.buildGeometryType()); } } if (typeName == null) typeName = featureType.getTypeName(); if (namespace == null && featureType.getName().getNamespaceURI() != null) try { namespace = new URI(featureType.getName().getNamespaceURI()); } catch (URISyntaxException e) { throw new RuntimeException(e); } SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.setName(typeName); tb.setNamespaceURI(namespace); tb.addAll(types); return tb.buildFeatureType(); }
@Override public int getAttributeCount() { return featureType.getAttributeCount(); }