예제 #1
0
 private static IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>
     createFeature(
         final IBoundedGeometry2D<? extends IFinite2DBounds<?>> geometry,
         final SimpleFeature feature) {
   return new GGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>(
       geometry, feature.getAttributes());
 }
  public List<FeatureId> addFeatures(FeatureCollection<SimpleFeatureType, SimpleFeature> collection)
      throws IOException {
    List<FeatureId> addedFids = new LinkedList<FeatureId>();
    String typeName = getSchema().getTypeName();
    SimpleFeature feature = null;
    SimpleFeature newFeature;
    FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
        getDataStore().getFeatureWriterAppend(typeName, getTransaction());

    Iterator iterator = collection.iterator();
    try {

      while (iterator.hasNext()) {
        feature = (SimpleFeature) iterator.next();
        newFeature = (SimpleFeature) writer.next();
        try {
          newFeature.setAttributes(feature.getAttributes());
        } catch (Exception writeProblem) {
          throw new DataSourceException(
              "Could not create " + typeName + " out of provided feature: " + feature.getID(),
              writeProblem);
        }

        // preserve the FID, it could come from another node
        ((MutableFIDFeature) newFeature).setID(feature.getID());

        writer.write();
        addedFids.add(newFeature.getIdentifier());
      }
    } finally {
      collection.close(iterator);
      writer.close();
    }
    return addedFids;
  }
 @Override
 public AdapterPersistenceEncoding encode(
     final SimpleFeature entry, final CommonIndexModel indexModel) {
   final PersistentDataset<Object> extendedData = new PersistentDataset<Object>();
   extendedData.addValue(
       new PersistentValue<Object>(
           new ByteArrayId(""), entry.getAttributes().toArray(new Object[] {})));
   final AdapterPersistenceEncoding encoding = super.encode(entry, indexModel);
   return new WholeFeatureAdapterEncoding(
       getAdapterId(), getDataId(entry), encoding.getCommonData(), extendedData);
 }
  /**
   * Handles the feature creation/update/deletion strategy. You may want to override this in a
   * subclass to handle workflow.
   *
   * @param feature the feature that is about to be split
   * @param geoms new geometries that are the result of splitting
   * @param filter filter to get at feature
   * @param localStore the store we're working against
   * @param localStrategy the strategy in use
   * @return A list of FeatureIds is returned, one for each feature in the order created. However,
   *     these might not be assigned until after a commit has been performed.
   * @throws Exception if an error occurs modifying the data source, converting the geometry or an
   *     illegal argument was given
   */
  protected List<FeatureId> handleStrategy(
      SimpleFeature feature,
      List<? extends Geometry> geoms,
      Filter filter,
      SimpleFeatureStore localStore,
      String localStrategy)
      throws Exception {

    List<SimpleFeature> newFeats = new ArrayList();
    GeometryTypeConverterFactory cf = new GeometryTypeConverterFactory();
    Converter c =
        cf.createConverter(
            Geometry.class,
            localStore.getSchema().getGeometryDescriptor().getType().getBinding(),
            null);
    GeometryType type = localStore.getSchema().getGeometryDescriptor().getType();
    String geomAttribute = localStore.getSchema().getGeometryDescriptor().getLocalName();
    boolean firstFeature = true;
    for (Geometry newGeom : geoms) {
      if (firstFeature) {
        if (localStrategy.equalsIgnoreCase("replace")) {
          // use first/largest geom to update existing feature geom
          feature.setAttribute(geomAttribute, c.convert(newGeom, type.getBinding()));
          feature = this.handleExtraData(feature);
          Object[] attributevalues =
              feature.getAttributes().toArray(new Object[feature.getAttributeCount()]);
          AttributeDescriptor[] attributes =
              feature
                  .getFeatureType()
                  .getAttributeDescriptors()
                  .toArray(new AttributeDescriptor[feature.getAttributeCount()]);
          localStore.modifyFeatures(attributes, attributevalues, filter);
          firstFeature = false;
          continue;
        } else if (localStrategy.equalsIgnoreCase("add")) {
          // delete the source feature, new ones will be created
          localStore.removeFeatures(filter);
          firstFeature = false;
        } else {
          throw new IllegalArgumentException(
              "Unknown strategy '" + localStrategy + "', cannot split");
        }
      }
      // create + add new features
      SimpleFeature newFeat =
          DataUtilities.createFeature(
              feature.getType(), DataUtilities.encodeFeature(feature, false));
      newFeat.setAttribute(geomAttribute, c.convert(newGeom, type.getBinding()));
      newFeats.add(newFeat);
    }
    newFeats = this.handleExtraData(newFeats);
    return localStore.addFeatures(DataUtilities.collection(newFeats));
  }
  /**
   * Replace with contents of reader.
   *
   * <p>Equivelent to:
   *
   * <pre><code>
   * FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriter( typeName, false, transaction );
   * Feature feature, newFeature;
   * while( writer.hasNext() ){
   *    feature = writer.next();
   *    writer.remove();
   * }
   * while( reader.hasNext() ){
   *    newFeature = reader.next();
   *    feature = writer.next();
   *    newFeature.setAttributes( feature.getAttributes( null ) );
   *    writer.write();
   * }
   * reader.close();
   * writer.close();
   * </code>
   * </pre>
   *
   * <p>Subclasses may override this method to perform the appropriate optimization for this result.
   *
   * @param reader Contents to replace with
   * @throws IOException
   */
  public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader)
      throws IOException {
    String typeName = getSchema().getTypeName();
    FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
        getDataStore().getFeatureWriter(typeName, getTransaction());
    SimpleFeature feature;
    SimpleFeature newFeature;

    try {
      while (writer.hasNext()) {
        feature = writer.next();
        LOGGER.finer("removing feature " + feature);
        writer.remove();
      }

      while (reader.hasNext()) {
        try {
          feature = reader.next();
        } catch (Exception readProblem) {
          throw new DataSourceException(
              "Could not add Features, problem with provided reader", readProblem);
        }

        newFeature = (SimpleFeature) writer.next();

        try {
          newFeature.setAttributes(feature.getAttributes());
        } catch (IllegalAttributeException writeProblem) {
          throw new DataSourceException(
              "Could not create " + typeName + " out of provided feature: " + feature.getID(),
              writeProblem);
        }
        LOGGER.finer("writing feature " + newFeature);
        writer.write();
      }
    } finally {
      reader.close();
      writer.close();
    }
  }
  /**
   * Add Features from reader to this FeatureStore.
   *
   * <p>Equivelent to:
   *
   * <pre><code>
   * Set set = new HashSet();
   * FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriter( typeName, true, transaction );
   * Featrue feature, newFeature;
   * while( reader.hasNext() ){
   *    feature = reader.next();
   *    newFeature = writer.next();
   *    newFeature.setAttributes( feature.getAttribtues( null ) );
   *    writer.write();
   *    set.add( newfeature.getID() );
   * }
   * reader.close();
   * writer.close();
   *
   * return set;
   * </code>
   * </pre>
   *
   * <p>(If you don't have a FeatureReader<SimpleFeatureType, SimpleFeature> handy
   * DataUtilities.reader() may be able to help out)
   *
   * <p>Subclasses may override this method to perform the appropriate optimization for this result.
   *
   * @param reader
   * @return The Set of FeatureIDs added
   * @throws IOException
   * @see org.geotools.data.FeatureStore#addFeatures(org.geotools.data.FeatureReader)
   */
  public Set addFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader)
      throws IOException {
    Set addedFids = new HashSet();
    String typeName = getSchema().getTypeName();
    SimpleFeature feature = null;
    SimpleFeature newFeature;
    FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
        getDataStore().getFeatureWriterAppend(typeName, getTransaction());

    try {
      while (reader.hasNext()) {
        try {
          feature = reader.next();
        } catch (Exception e) {
          throw new DataSourceException("Could not add Features, problem with provided reader", e);
        }

        newFeature = (SimpleFeature) writer.next();

        try {
          newFeature.setAttributes(feature.getAttributes());
        } catch (IllegalAttributeException writeProblem) {
          throw new DataSourceException(
              "Could not create " + typeName + " out of provided feature: " + feature.getID(),
              writeProblem);
        }

        writer.write();
        addedFids.add(newFeature.getID());
      }
    } finally {
      reader.close();
      writer.close();
    }
    return addedFids;
  }
    public boolean hasNext() {
      //   logger.info("qui");
      logger.finer("HAS NEXT");
      while ((next == null && delegate.hasNext()) || (next == null && added)) {
        //     logger.info("qui nel while");
        if (complete) {
          first = delegate.next();
          intersectedGeometries = null;
        }
        //               logger.info("qui dopo check if (complete)");
        // logger.finer("control HAS NEXT");
        for (Object attribute : first.getAttributes()) {
          if (attribute instanceof Geometry && attribute.equals(first.getDefaultGeometry())) {
            Geometry currentGeom = (Geometry) attribute;

            if (intersectedGeometries == null && !added) {
              intersectedGeometries = filteredCollection(currentGeom, subFeatureCollection);
              iterator = intersectedGeometries.features();
            }
            try {
              while (iterator.hasNext()) {
                added = false;
                SimpleFeature second = iterator.next();
                if (currentGeom
                    .getEnvelope()
                    .intersects(((Geometry) second.getDefaultGeometry()))) {
                  // compute geometry
                  if (intersectionMode == IntersectionMode.INTERSECTION) {
                    attribute = currentGeom.intersection((Geometry) second.getDefaultGeometry());

                    GeometryFilterImpl filter =
                        new GeometryFilterImpl(geomType.getType().getBinding());
                    ((Geometry) attribute).apply(filter);
                    attribute = filter.getGeometry();
                  } else if (intersectionMode == IntersectionMode.FIRST) {
                    attribute = currentGeom;
                  } else if (intersectionMode == IntersectionMode.SECOND) {
                    attribute = (Geometry) second.getDefaultGeometry();
                  }
                  if (((Geometry) attribute).getNumGeometries() > 0) {
                    fb.add(attribute);
                    fb.set("INTERSECTION_ID", id++);
                    // add the non geometric attributes
                    addAttributeValues(first, retainAttributesFst, fb);
                    addAttributeValues(second, retainAttributesSnd, fb);
                    // add the dynamic attributes
                    if (percentagesEnabled) {
                      addPercentages(currentGeom, second);
                    }
                    if (areasEnabled) {
                      addAreas(currentGeom, second);
                    }

                    // build the feature
                    next = fb.buildFeature(iterationIndex.toString());

                    // update iterator status
                    if (iterator.hasNext()) {
                      complete = false;
                      added = true;
                      iterationIndex++;
                      return next != null;
                    }
                    iterationIndex++;
                  }
                }
                complete = false;
              }
              complete = true;
            } finally {
              if (!added) {
                iterator.close();
              }
            }
          }
        }
      }
      return next != null;
    }
  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;
  }
예제 #9
0
  /**
   * Writing test that only engages against a remote geoserver.
   *
   * <p>Makes reference to the standard featureTypes that geoserver ships with. NOTE: Ignoring this
   * test for now because it edits topp:states and GeoServer doesn't return the correct Feature IDs
   * on transactions against shapefiles
   */
  @Test
  @Ignore
  public void testWrite()
      throws NoSuchElementException, IllegalFilterException, IOException,
          IllegalAttributeException {
    if (url == null) return;

    Map m = new HashMap();
    m.put(WFSDataStoreFactory.URL.key, url);
    m.put(WFSDataStoreFactory.TIMEOUT.key, new Integer(10000000));
    DataStore post = (WFS_1_0_0_DataStore) (new WFSDataStoreFactory()).createDataStore(m);
    String typename = TO_EDIT_TYPE;
    SimpleFeatureType ft = post.getSchema(typename);
    SimpleFeatureSource fs = post.getFeatureSource(typename);
    class Watcher implements FeatureListener {
      public int count = 0;

      public void changed(FeatureEvent featureEvent) {
        System.out.println("Event " + featureEvent);
        count++;
      }
    }
    Watcher watcher = new Watcher();
    fs.addFeatureListener(watcher);

    Id startingFeatures = createFidFilter(fs);
    FilterFactory2 filterFac = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
    try {
      GeometryFactory gf = new GeometryFactory();
      MultiPolygon mp =
          gf.createMultiPolygon(
              new Polygon[] {
                gf.createPolygon(
                    gf.createLinearRing(
                        new Coordinate[] {
                          new Coordinate(-88.071564, 37.51099),
                          new Coordinate(-88.467644, 37.400757),
                          new Coordinate(-90.638329, 42.509361),
                          new Coordinate(-89.834618, 42.50346),
                          new Coordinate(-88.071564, 37.51099)
                        }),
                    new LinearRing[] {})
              });
      mp.setUserData("http://www.opengis.net/gml/srs/epsg.xml#" + EPSG_CODE);

      PropertyName geometryAttributeExpression =
          filterFac.property(ft.getGeometryDescriptor().getLocalName());
      PropertyIsNull geomNullCheck = filterFac.isNull(geometryAttributeExpression);
      Query query = new Query(typename, filterFac.not(geomNullCheck), 1, Query.ALL_NAMES, null);
      SimpleFeatureIterator inStore = fs.getFeatures(query).features();

      SimpleFeature f, f2;
      try {
        SimpleFeature feature = inStore.next();

        SimpleFeature copy = SimpleFeatureBuilder.deep(feature);
        SimpleFeature copy2 = SimpleFeatureBuilder.deep(feature);

        f = SimpleFeatureBuilder.build(ft, copy.getAttributes(), null);
        f2 = SimpleFeatureBuilder.build(ft, copy2.getAttributes(), null);
        assertFalse("Max Feature failed", inStore.hasNext());
      } finally {
        inStore.close();
      }

      org.geotools.util.logging.Logging.getLogger("org.geotools.data.wfs").setLevel(Level.FINE);
      SimpleFeatureCollection inserts = DataUtilities.collection(new SimpleFeature[] {f, f2});
      Id fp = WFSDataStoreWriteOnlineTest.doInsert(post, ft, inserts);

      // / okay now count ...
      FeatureReader<SimpleFeatureType, SimpleFeature> count =
          post.getFeatureReader(new Query(ft.getTypeName()), Transaction.AUTO_COMMIT);
      int i = 0;
      while (count.hasNext() && i < 3) {
        f = count.next();
        i++;
      }
      count.close();

      WFSDataStoreWriteOnlineTest.doDelete(post, ft, fp);
      WFSDataStoreWriteOnlineTest.doUpdate(post, ft, ATTRIBUTE_TO_EDIT, NEW_EDIT_VALUE);
      // assertFalse("events not fired", watcher.count == 0);
    } finally {
      try {
        ((SimpleFeatureStore) fs).removeFeatures(filterFac.not(startingFeatures));
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }