/** * Creates a new SimpleFeature for <code>targetType</code> that holds the common attributes from * <code>sourceFeature</code> and the buffered geometry. * * @param sourceFeature the original SimpleFeature from which to extract matching attributes for * the new SimpleFeature, or <code>null</code> if the new SimpleFeature has to have empty * attributes other than the default geometry. * @param targetType * @param bufferedGeometry the product geometry of running {@link BufferOp} over the default * geometry of <code>sourceFeature</code> with the parameters provided to this operation. * @return a new SimpleFeature of type <code>targetType</code> holding the common attributes with * <code>sourceFeature</code> and <code>bufferedGeometry</code> as the feature's default * geometry * @throws SOProcessException */ @SuppressWarnings("unchecked") private SimpleFeature createBufferedFeature( SimpleFeature sourceFeature, SimpleFeatureType targetType, Geometry bufferedGeometry) throws SOProcessException { SimpleFeature newFeature; try { newFeature = DataUtilities.template(targetType); final GeometryDescriptor targetGeometryType = targetType.getDefaultGeometry(); if (sourceFeature != null) { GeoToolsUtils.match(sourceFeature, newFeature); } final String attName = targetGeometryType.getLocalName(); final Class geomClass = targetGeometryType.getType().getBinding(); bufferedGeometry = GeometryUtil.adapt(bufferedGeometry, geomClass); newFeature.setAttribute(attName, bufferedGeometry); } catch (IllegalAttributeException e) { throw new SOProcessException(e.getMessage(), e); } return newFeature; }
/** * Put together a map of VPF files and their corresponding TableRows * * @param file * @param row */ private Map generateFileRowMap(VPFFile file, SimpleFeature row) throws IOException { String tileFileName = null; Map rows = new HashMap(); rows.put(file, row); Iterator joinIter = featureType.getFeatureClass().getJoinList().iterator(); while (joinIter.hasNext()) { ColumnPair columnPair = (ColumnPair) joinIter.next(); VPFFile primaryFile = getVPFFile(columnPair.column1); VPFFile joinFile = null; joinFile = getVPFFile(columnPair.column2); if (!rows.containsKey(joinFile) && rows.containsKey(primaryFile)) { SimpleFeature joinRow = (SimpleFeature) rows.get(primaryFile); try { int joinID = Integer.parseInt(joinRow.getAttribute(columnPair.column1.getName()).toString()); rows.put( joinFile, getVPFFile(columnPair.column2).getRowFromId(columnPair.column2.getName(), joinID)); } catch (NullPointerException exc) { // Non-matching joins - just put in a NULL rows.put(joinFile, null); } catch (IllegalAttributeException exc) { // I really don't expect to see this one exc.printStackTrace(); rows.put(joinFile, null); } } } return rows; }
/** @see org.geotools.data.FeatureStore#setFeatures(org.geotools.data.FeatureReader) */ public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader) throws IOException { WFSTransactionState ts = null; if (trans == Transaction.AUTO_COMMIT) { ts = new WFSTransactionState(ds); } else { ts = (WFSTransactionState) trans.getState(ds); } ts.addAction( getSchema().getTypeName(), new DeleteAction(getSchema().getTypeName(), Filter.INCLUDE)); ReferencedEnvelope bounds = null; while (reader.hasNext()) { try { SimpleFeature f = reader.next(); List<AttributeDescriptor> atrs = f.getFeatureType().getAttributeDescriptors(); for (int i = 0; i < atrs.size(); i++) { if (atrs.get(i) instanceof GeometryDescriptor) { Geometry g = (Geometry) f.getAttribute(i); CoordinateReferenceSystem cs = ((GeometryDescriptor) atrs.get(i)).getCoordinateReferenceSystem(); if (cs != null && !cs.getIdentifiers().isEmpty()) g.setUserData(cs.getIdentifiers().iterator().next().toString()); if (g == null) continue; if (bounds == null) { bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs); } else { bounds.expandToInclude(g.getEnvelopeInternal()); } } } ts.addAction(getSchema().getTypeName(), new InsertAction(f)); } catch (NoSuchElementException e) { WFS_1_0_0_DataStore.LOGGER.warning(e.toString()); } catch (IllegalAttributeException e) { WFS_1_0_0_DataStore.LOGGER.warning(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( getSchema().getTypeName(), getTransaction(), bounds, false); } else { ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } if (trans == Transaction.AUTO_COMMIT) { ts.commit(); } }
public static void main(String[] args) { System.out.println("WFS Demo"); try { // URL url = new // URL("http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap?version=1.0.0&request=getcapabilities&service=wfs"); URL url = new URL("http://www.refractions.net:8080/geoserver/wfs?REQUEST=GetCapabilities"); Map m = new HashMap(); m.put(WFSDataStoreFactory.URL.key, url); m.put(WFSDataStoreFactory.TIMEOUT.key, new Integer(10000)); m.put(WFSDataStoreFactory.PROTOCOL.key, Boolean.FALSE); DataStore wfs = (new WFSDataStoreFactory()).createNewDataStore(m); Query query = new DefaultQuery(wfs.getTypeNames()[1]); FeatureReader<SimpleFeatureType, SimpleFeature> ft = wfs.getFeatureReader(query, Transaction.AUTO_COMMIT); int count = 0; while (ft.hasNext()) if (ft.next() != null) count++; System.out.println("Found " + count + " features"); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchElementException e) { e.printStackTrace(); } catch (IllegalAttributeException e) { e.printStackTrace(); } }
/** * Read a row and determine if it matches the feature type Three possibilities here: row is null * -- hasNext = false, do not try again row matches -- hasNext = true, do not try again row does * not match -- hasNext is undefined because we must try again * * @return Whether we need to read again */ private boolean readNext() throws IOException { boolean result = true; VPFFile file = (VPFFile) featureType.getFeatureClass().getFileList().get(0); hasNext = false; SimpleFeature row = null; try { if (file.hasNext()) { row = file.readFeature(); } } catch (IOException exc1) { // TODO Auto-generated catch block exc1.printStackTrace(); } catch (IllegalAttributeException exc1) { // TODO Auto-generated catch block exc1.printStackTrace(); } if ((row == null)) { hasNext = false; result = false; } // Exclude objects with a different FACC Code else if (featureType.getFaccCode() != null) { try { Object temp = null; for (int i = 0; temp == null && i < ALLOWED_FCODE_ATTRIBUTES.length; i++) { temp = row.getAttribute(ALLOWED_FCODE_ATTRIBUTES[i]); } String faccCode = temp.toString().trim(); if (featureType.getFaccCode().equals(faccCode)) { retrieveObject(file, row); hasNext = true; result = false; } } catch (RuntimeException exc) { // Ignore this case because it typically means the f_code is invalid } } return result; }
/** * Get the values from all of the columns based on their presence (or absense) in the rows * * <p>Potential cases: simple column join column non-matching join null value geometry * * @param file the file * @param row the row */ private void retrieveObject(VPFFile file, SimpleFeature row) throws IOException { VPFFile secondFile = null; VPFColumn column = null; Map rows = generateFileRowMap(file, row); List<AttributeDescriptor> attributes = featureType.getFeatureClass().getAttributeDescriptors(); Object[] values = new Object[featureType.getAttributeCount()]; Object value = null; String featureId = null; // Pass 1 - identify the feature identifier for (int inx = 0; inx < attributes.size(); inx++) { // I am thinking it is probably safer to look this up // by column name than by position, but if it breaks, // it is easy enough to change if (attributes.get(inx).getLocalName().equals("id")) { value = row.getAttribute(inx); if (value != null) { featureId = value.toString(); } break; } } try { currentFeature = SimpleFeatureBuilder.build(featureType, values, featureId); } catch (IllegalAttributeException exc) { // This shouldn't happen since everything should be nillable exc.printStackTrace(); } // Pass 2 - get the attributes, including the geometry for (int inx = 0; inx < attributes.size(); inx++) { try { if (attributes .get(inx) .getLocalName() .equals(AnnotationFeatureType.ANNOTATION_ATTRIBUTE_NAME)) { try { // TODO: are we sure this is the intended action? Hard-coding an attribute to "nam"? currentFeature.setAttribute(inx, "nam"); } catch (IllegalAttributeException exc) { exc.printStackTrace(); } continue; } column = (VPFColumn) attributes.get(inx); value = null; secondFile = getVPFFile(column); SimpleFeature tempRow = (SimpleFeature) rows.get(secondFile); if (tempRow != null) { value = tempRow.getAttribute(column.getName()); if (column.isAttemptLookup()) { try { // Attempt to perform a lookup and conversion String featureClassName = getVPFFile(column).getFileName(); String intVdtFileName = featureType .getFeatureClass() .getDirectoryName() .concat(File.separator) .concat("int.vdt"); VPFFile intVdtFile = VPFFileFactory.getInstance().getFile(intVdtFileName); Iterator intVdtIter = intVdtFile.readAllRows().iterator(); while (intVdtIter.hasNext()) { SimpleFeature intVdtRow = (SimpleFeature) intVdtIter.next(); if (intVdtRow.getAttribute("table").toString().trim().equals(featureClassName) && (Short.parseShort(intVdtRow.getAttribute("value").toString()) == Short.parseShort(value.toString()) && (intVdtRow .getAttribute("attribute") .toString() .trim() .equals(column.getName())))) { value = intVdtRow.getAttribute("description").toString().trim(); break; } } // If there is a problem, forget about mapping and continue } catch (IOException exc) { } catch (RuntimeException exc) { } } } try { currentFeature.setAttribute(inx, value); } catch (ArrayIndexOutOfBoundsException exc) { // TODO Auto-generated catch block exc.printStackTrace(); } catch (IllegalAttributeException exc) { // TODO Auto-generated catch block exc.printStackTrace(); } } catch (ClassCastException exc2) { try { // This is the area geometry case featureType .getFeatureClass() .getGeometryFactory() .createGeometry(featureType, currentFeature); } catch (IllegalAttributeException exc) { // TODO Auto-generated catch block exc.printStackTrace(); } catch (SQLException exc) { // TODO Auto-generated catch block exc.printStackTrace(); } } } }
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; }