/**
   * Writes out the current feature.
   *
   * @throws IOException
   * @see org.geotools.data.FeatureWriter#write()
   */
  public void write() throws IOException {
    // DJB: I modified this so it doesnt throw an error if you
    //     do an update and you didnt actually change anything.
    //     (We do the work)
    if ((live != null)) {
      // We have a modification to record!
      diff.modify(live.getID(), current);

      ReferencedEnvelope bounds = new ReferencedEnvelope((CoordinateReferenceSystem) null);
      bounds.include(live.getBounds());
      bounds.include(current.getBounds());
      fireNotification(FeatureEvent.FEATURES_CHANGED, bounds);
      live = null;
      current = null;
    } else if ((live == null) && (current != null)) {
      // We have new content to record
      //
      diff.add(current.getID(), current);
      fireNotification(
          FeatureEvent.FEATURES_ADDED, ReferencedEnvelope.reference(current.getBounds()));
      current = null;
    } else {
      throw new IOException("No feature available to write");
    }
  }
  @Test
  public void testGetFeaturesFeatureSource() throws Exception {
    // check the schemas in feature source and feature collection
    SimpleFeatureSource fs = rts.getFeatureSource(RENAMED);
    assertEquals(primitive, fs.getSchema());
    SimpleFeatureCollection fc = fs.getFeatures();
    assertEquals(primitive, fc.getSchema());
    assertTrue(fc.size() > 0);

    // make sure the feature schema is good as well
    FeatureIterator<SimpleFeature> it = fc.features();
    SimpleFeature sf = it.next();
    it.close();

    assertEquals(primitive, sf.getFeatureType());

    // check the feature ids have been renamed as well
    assertTrue(
        "Feature id has not been renamed, it's still " + sf.getID(),
        sf.getID().startsWith(RENAMED));

    // check mappings occurred
    assertEquals("description-f001", sf.getAttribute("description"));
    assertTrue(
        new WKTReader()
            .read("MULTIPOINT(39.73245 2.00342)")
            .equalsExact((Geometry) sf.getAttribute("pointProperty")));
    assertEquals(new Long(155), sf.getAttribute("intProperty"));
    assertNull(sf.getAttribute("newProperty"));
  }
  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;
  }
  /**
   * <b>validateSingleLayer Purpose:</b> <br>
   *
   * <p>This validation tests for a geometry containing part of itself. Uses JTS'
   * Geometry.contains(Geometry) method. DE-9IM intersection matrix is T*F**F***.
   * <b>Description:</b><br>
   *
   * <p>The function filters the SimpleFeatureSource using the given bounding box. It creates
   * iterators over the filtered FeatureSource. It calls contains() using the geometries in the
   * SimpleFeatureSource layer. Tests the results of the method call against the given expected
   * results. Returns true if the returned results and the expected results are true, false
   * otherwise. * Author: bowens<br>
   * Created on: Apr 27, 2004<br>
   *
   * @param featureSourceA - the SimpleFeatureSource to pull the original geometries from. This
   *     geometry is the one that is tested for containing the other
   * @param expected - boolean value representing the user's expected outcome of the test
   * @param results - ValidationResults
   * @param bBox - Envelope - the bounding box within which to perform the contains()
   * @return boolean result of the test
   * @throws Exception - IOException if iterators improperly closed
   */
  private boolean validateSingleLayer(
      SimpleFeatureSource featureSourceA,
      boolean expected,
      ValidationResults results,
      Envelope bBox)
      throws Exception {
    boolean success = true;

    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    Filter filter = null;

    SimpleFeatureCollection featureResults = featureSourceA.getFeatures(filter);

    SimpleFeatureIterator fr1 = null;
    SimpleFeatureIterator fr2 = null;
    try {
      fr1 = featureResults.features();

      if (fr1 == null) return false;

      while (fr1.hasNext()) {
        SimpleFeature f1 = fr1.next();
        Geometry g1 = (Geometry) f1.getDefaultGeometry();
        fr2 = featureResults.features();

        while (fr2 != null && fr2.hasNext()) {
          SimpleFeature f2 = fr2.next();
          Geometry g2 = (Geometry) f2.getDefaultGeometry();
          if (!f1.getID()
              .equals(f2.getID())) // if they are the same feature, move onto the next one
          {
            if (g1.contains(g2) != expected) {
              results.error(
                  f1,
                  ((Geometry) f1.getDefaultGeometry()).getGeometryType()
                      + " "
                      + getGeomTypeRefA()
                      + " contains "
                      + getGeomTypeRefA()
                      + "("
                      + f2.getID()
                      + "), Result was not "
                      + expected);
              success = false;
            }
          }
        }
      }
    } finally {
      fr1.close();
      if (fr2 != null) fr2.close();
    }

    return success;
  }
  @Test
  public void testGetFeaturesReader() throws Exception {
    FeatureReader<SimpleFeatureType, SimpleFeature> fr;
    fr = rts.getFeatureReader(new Query(RENAMED), Transaction.AUTO_COMMIT);
    SimpleFeature sf = fr.next();
    fr.close();

    assertEquals(primitive, sf.getFeatureType());

    // check the feature ids have been renamed as well
    assertTrue(
        "Feature id has not been renamed, it's still " + sf.getID(),
        sf.getID().startsWith(RENAMED));
  }
  /**
   * Implementation for tests of fid -> fid unmapping.
   *
   * @param idExpression
   * @throws Exception
   */
  private void checkUnrollIdExpression(Expression idExpression) throws Exception {
    AttributeMapping featureMapping = null;
    Name featurePath = mapping.getTargetFeature().getName();
    QName featureName = Types.toQName(featurePath);
    for (Iterator it = mapping.getAttributeMappings().iterator(); it.hasNext(); ) {
      AttributeMapping attMapping = (AttributeMapping) it.next();
      StepList targetXPath = attMapping.getTargetXPath();
      if (targetXPath.size() > 1) {
        continue;
      }
      Step step = (Step) targetXPath.get(0);
      if (featureName.equals(step.getName())) {
        featureMapping = attMapping;
        break;
      }
    }
    featureMapping.setIdentifierExpression(idExpression);
    this.visitor = new UnmappingFilterVisitor(this.mapping);

    // retrieve a single sample feature
    Feature sourceFeature = DataUtilities.first(mapping.getSource().getFeatures());
    String fid = sourceFeature.getIdentifier().toString();
    Id fidFilter = ff.id(Collections.singleton(ff.featureId(fid)));
    Filter unrolled = (Filter) fidFilter.accept(visitor, null);
    assertNotNull(unrolled);
    assertTrue(unrolled instanceof Id);

    FeatureCollection<SimpleFeatureType, SimpleFeature> results =
        mapping.getSource().getFeatures(unrolled);
    assertEquals(1, getCount(results));

    SimpleFeature unmappedFeature = DataUtilities.first(results);

    assertEquals(fid, unmappedFeature.getID());
  }
  @Test
  public void testScale() throws IOException {

    final ByteArrayId adapterId = new ByteArrayId(ftype.getTypeName());
    final Random r = new Random(3434);
    for (int i = 0; i < 10000; i++) {
      final SimpleFeature feature =
          createTestFeature(
              "f" + i,
              new Coordinate(
                  round(30.0 + (r.nextGaussian() * 0.0001)),
                  round(30.0 + (r.nextGaussian() * 0.0001))));
      mapDriver.addInput(new GeoWaveInputKey(adapterId, new ByteArrayId(feature.getID())), feature);
    }

    final List<Pair<PartitionDataWritable, AdapterWithObjectWritable>> mapperResults =
        mapDriver.run();

    final List<Pair<PartitionDataWritable, List<AdapterWithObjectWritable>>> partitions =
        getReducerDataFromMapperInput(mapperResults);

    reduceDriver.addAll(partitions);

    reduceDriver
        .getConfiguration()
        .setInt(
            GeoWaveConfiguratorBase.enumToConfKey(
                NNMapReduce.class, ClusteringParameters.Clustering.MINIMUM_SIZE),
            10);

    final List<Pair<GeoWaveInputKey, ObjectWritable>> reduceResults = reduceDriver.run();
    assertTrue(reduceResults.size() > 0);
  }
 /**
  * Override error.
  *
  * <p>Description ...
  *
  * @see org.geotools.validation.ValidationResults#error(org.geotools.feature.SimpleFeature,
  *     java.lang.String)
  * @param feature
  * @param message
  */
 public void error(SimpleFeature feature, String message) {
   // add the error to our list of failed features + failure messages
   if (message == null) message = ""; // $NON-NLS-1$
   failedFeatures.add(feature);
   failureMessages.add(feature.getID() + ": " + message); // $NON-NLS-1$
   // find the layer of the current feature
   IMap activeMap = ApplicationGIS.getActiveMap();
   List<ILayer> layers = new ArrayList<ILayer>();
   if (activeMap != ApplicationGIS.NO_MAP) {
     layers.addAll(activeMap.getMapLayers());
   }
   Layer layer = null;
   for (Iterator i = layers.listIterator(); i.hasNext(); ) {
     Layer thisLayer = (Layer) i.next();
     if (feature.getName().getLocalPart().equals(thisLayer.getName())) {
       layer = thisLayer;
       break;
     }
   }
   // add the error to the issues list
   FeatureIssue issue =
       new FeatureIssue(
           Priority.HIGH,
           message,
           layer,
           feature,
           Messages.GenericValidationResults_validationError);
   issues.add(issue);
 }
  FeatureId addFeature(
      SimpleFeature feature, FeatureWriter<SimpleFeatureType, SimpleFeature> writer)
      throws IOException {
    // grab next feature and populate it
    // JD: worth a note on how we do this... we take a "pull" approach
    // because the raw schema we are inserting into may not match the
    // schema of the features we are inserting
    SimpleFeature toWrite = writer.next();
    for (int i = 0; i < toWrite.getType().getAttributeCount(); i++) {
      String name = toWrite.getType().getDescriptor(i).getLocalName();
      toWrite.setAttribute(name, feature.getAttribute(name));
    }

    // copy over the user data
    if (feature.getUserData().size() > 0) {
      toWrite.getUserData().putAll(feature.getUserData());
    }

    // pass through the fid if the user asked so
    boolean useExisting = Boolean.TRUE.equals(feature.getUserData().get(Hints.USE_PROVIDED_FID));
    if (getQueryCapabilities().isUseProvidedFIDSupported() && useExisting) {
      ((FeatureIdImpl) toWrite.getIdentifier()).setID(feature.getID());
    }

    // perform the write
    writer.write();

    // copy any metadata from the feature that was actually written
    feature.getUserData().putAll(toWrite.getUserData());

    // add the id to the set of inserted
    FeatureId id = toWrite.getIdentifier();
    return id;
  }
Beispiel #10
0
  public void rollback(IProgressMonitor monitor) throws Exception {
    editBlackboard.removeGeometries(Collections.singleton(first));

    EditGeom newGeom =
        editBlackboard.newGeom(
            oldshape.getEditGeom().getFeatureIDRef().get(), oldshape.getEditGeom().getShapeType());

    for (int i = 0; i < oldshape.getNumCoords(); i++) {
      editBlackboard.addCoordinate(oldshape.getCoord(i), newGeom.getShell());
    }

    if (currentShapeSet) setCurrentShape(newGeom.getShell());

    FeatureStore<SimpleFeatureType, SimpleFeature> store =
        layer.getResource(FeatureStore.class, new SubProgressMonitor(monitor, 1));

    FilterFactory factory = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
    Set<FeatureId> ids = new HashSet<FeatureId>();
    for (FeatureId id : newFids) {
      ids.add(id);
    }
    Id filter = factory.id(ids);

    store.removeFeatures(filter);
    Geometry oldType = (Geometry) oldFeature.getDefaultGeometry();
    GeometryDescriptor newType = store.getSchema().getGeometryDescriptor();
    store.modifyFeatures(
        newType, oldType, factory.id(FeatureUtils.stringToId(factory, oldFeature.getID())));
    oldFeature.setDefaultGeometry(oldGeometry);
    newFids.clear();
  }
  protected void modifyFeatures(
      AttributeDescriptor[] type,
      Object[] value,
      FeatureWriter<SimpleFeatureType, SimpleFeature> writer)
      throws DataSourceException, IOException {
    SimpleFeature feature;
    try {
      while (writer.hasNext()) {
        feature = writer.next();

        for (int i = 0; i < type.length; i++) {
          try {
            feature.setAttribute(type[i].getLocalName(), value[i]);
          } catch (IllegalAttributeException e) {
            throw new DataSourceException(
                "Could not update feature "
                    + feature.getID()
                    + " with "
                    + type[i].getLocalName()
                    + "="
                    + value[i],
                e);
          }
        }

        writer.write();
      }
    } finally {
      writer.close();
    }
  }
 private void writeImplementation(SimpleFeature f) throws IOException {
   writer.next();
   writer.writeFeatureID(f.getID());
   for (int i = 0; i < f.getAttributeCount(); i++) {
     if (f.getAttribute(i) == null) writer.write(i, "<null>");
     else writer.write(i, f.getAttribute(i));
   }
 }
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    String networkPath = args[0];
    String newNetworkPath = args[1];
    String shapeFilePath = args[2];

    // String shapeFile = "C:/Work/Roadpricing Scenarios/SiouxFalls/Network/SiouxFalls_nodes.shp";

    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    new NetworkReaderMatsimV1(scenario).parse(networkPath);
    Network network = scenario.getNetwork();
    Map<Id<Node>, ? extends Node> nodes = network.getNodes();

    Double x = 0.0;
    Double y = 0.0;

    System.out.println(shapeFilePath);
    ShapeFileReader shapeFileReader = new ShapeFileReader();
    Collection<SimpleFeature> fts = shapeFileReader.readFileAndInitialize(shapeFilePath);
    log.info("Shape file contains " + fts.size() + " features!");

    for (SimpleFeature ft : fts) {
      Geometry geo = (Geometry) ft.getDefaultGeometry();
      Coordinate[] coordinates = geo.getCoordinates();
      Collection<Property> properties = ft.getProperties("Id");

      System.out.println(
          "Feature: "
              + ft.getID()
              + ","
              + ft.getIdentifier().toString()
              + ","
              + ft.getName().toString());

      for (int i = 0; i < coordinates.length; i++) {
        System.out.print(coordinates[i].x + "," + coordinates[i].y + "   ");
        x = coordinates[i].x;
        y = coordinates[i].y;
      }

      for (Property p : properties) {
        System.out.println("Value: " + p.getValue().toString());
        Node node = nodes.get(Id.create(p.getValue().toString(), Node.class));
        node.getCoord().setXY(x, y);
        System.out.println("Name: " + p.getName().toString());
        System.out.println("Descriptor: " + p.getDescriptor().toString());
      }
      System.out.println();
      System.out.println();

      NetworkWriter writer = new NetworkWriter(network);
      writer.write(newNetworkPath);
    }
  }
Beispiel #14
0
    public SimpleFeature next() throws NoSuchElementException {
      SimpleFeature feature = delegate.next();

      for (Definition def : definition) {
        Object value = def.expression.evaluate(feature);
        fb.add(value);
      }
      SimpleFeature created = fb.buildFeature(feature.getID());
      return created;
    }
 @Test
 public void testFeatureReaderFidFilter() throws Exception {
   FeatureReader<SimpleFeatureType, SimpleFeature> fr;
   fr = rts.getFeatureReader(new Query(RENAMED, fidFilter), Transaction.AUTO_COMMIT);
   assertEquals(primitive, fr.getFeatureType());
   assertTrue(fr.hasNext());
   SimpleFeature sf = fr.next();
   assertFalse(fr.hasNext());
   fr.close();
   assertEquals(fid, sf.getID());
 }
    @Override
    public void map(Text key, SimpleFeature value, Context context)
        throws IOException, InterruptedException {
      Counter counter =
          context.getCounter(CountersEnum.class.getName(), CountersEnum.FEATURES.toString());
      counter.increment(1);

      Object[] values = new Object[] {value.getAttribute("dtg"), value.getAttribute("geom")};
      SimpleFeature feature = new ScalaSimpleFeature(value.getID(), sft, values);
      context.write(text, feature);
    }
Beispiel #17
0
  public Map sectionSigns(DirectPosition2D eventCoords) {
    Point2D eventPoint = new DirectPosition2D();
    eventPoint.setLocation(eventCoords);
    if (eventCoords != null) {
      try {
        AffineTransform transform_affine = map.getViewport().getWorldToScreen();
        transform_affine.transform(eventPoint, eventPoint);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    Map result = new HashMap();
    for (Iterator it1 = signsdb.keySet().iterator(); it1.hasNext(); ) {
      SimpleFeature feature = (SimpleFeature) it1.next();
      StructOffset offset = (StructOffset) signsdb.get(feature);
      int width = 60, height = 40;

      Point point = (Point) feature.getAttribute("the_geom");
      DirectPosition2D geoCoords = new DirectPosition2D(point.getX(), point.getY());
      // 经纬度坐标转换为屏幕坐标
      MathTransform transform_math;
      try {
        transform_math =
            CRS.findMathTransform(
                DefaultGeographicCRS.WGS84, map.getViewport().getCoordinateReferenceSystem(), true);
        transform_math.transform(geoCoords, geoCoords);
        AffineTransform transform_affine = map.getViewport().getWorldToScreen();
        transform_affine.transform(geoCoords, geoCoords);

        int signx = (int) (geoCoords.x + offset.getX() + offsetX);
        int signy = (int) (geoCoords.y + offset.getY() + offsetY);
        //				System.out.println(signsCoords.x+":"+signsCoords.y);
        if (inSection(signx, signy, width, height, (DirectPosition2D) eventPoint)) {
          result.put(feature.getID(), feature.getID());
        }
      } catch (Exception e) {

      }
    }
    return result;
  }
  /**
   * Print information of the features contained in the list.
   *
   * @param featureList A list of features.
   * @return An string containing information about all those features.
   */
  private static String prettyPrint(List<SimpleFeature> featureList) {

    StringBuilder strBuilder = new StringBuilder("\n"); // $NON-NLS-1$
    for (SimpleFeature f : featureList) {
      strBuilder
          .append("Feature Id -- Geometry: ")
          .append(f.getID()) // $NON-NLS-1$
          .append(" -- ")
          .append(f.getDefaultGeometry())
          .append("\n"); // $NON-NLS-1$ //$NON-NLS-2$
    }
    return strBuilder.toString();
  }
  /**
   * Returns 0 if the features are the same. 1 if the attributes are the same but have different
   * featureIDs and -1 if attributes are different or are of different featureTypes.
   *
   * @param feature1
   * @param feature2
   * @return
   */
  public static int same(SimpleFeature feature1, SimpleFeature feature2) {
    if (DataUtilities.compare(feature1.getFeatureType(), feature2.getFeatureType()) != 0) {
      return -1;
    }
    for (int i = 0; i < feature1.getAttributeCount(); i++) {
      if (feature1.getAttribute(i) == null) {
        if (feature2.getAttribute(i) != null) return -1;
        else continue;
      }
      if (feature1.getAttribute(i) instanceof Geometry) {
        Geometry geom1 = (Geometry) feature1.getAttribute(i);
        if (feature2.getAttribute(i) instanceof Geometry) {
          Geometry geom2 = (Geometry) feature2.getAttribute(i);
          if (geom1.equalsExact(geom2)) continue;
          else return -1;
        } else return -1;
      }
      if (!feature1.getAttribute(i).equals(feature2.getAttribute(i))) return -1;
    }

    return feature1.getID().equals(feature2.getID()) ? 0 : 1;
  }
 /** @see org.geotools.data.FeatureWriter#remove() */
 public void remove() throws IOException {
   if (live != null) {
     // mark live as removed
     diff.remove(live.getID());
     fireNotification(
         FeatureEvent.FEATURES_REMOVED, ReferencedEnvelope.reference(live.getBounds()));
     live = null;
     current = null;
   } else if (current != null) {
     // cancel additional content
     current = null;
   }
 }
Beispiel #21
0
  public int compare(SimpleFeature o1, SimpleFeature o2) {

    String id1 = o1.getID();
    String id2 = o2.getID();

    // we're going to try to strip out the same section and see if the remaining is a number
    // this is so that id.2 will be sorted before id.10
    // assumption is that the number is at the end... not always a good assumption.
    int i = 1;
    while (i < id2.length() && i < id1.length() && id2.regionMatches(0, id1, 0, i)) {
      i++;
    }
    String diff1 = id1.substring(i - 1);
    String diff2 = id2.substring(i - 1);

    try {
      Integer num1 = Integer.valueOf(diff1);
      Integer num2 = Integer.valueOf(diff2);
      return dir * num1.compareTo(num2);
    } catch (NumberFormatException e) {
      // oh well it was worth a try.
    }
    return dir * id1.compareTo(id2);
  }
  /**
   * 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 BugInfo(SimpleFeature next, long idx) throws IndexOutOfBoundsException, ParseException {

      bugId = idx;
      attributes = new HashMap<>();
      Collection<Property> properties = next.getProperties();
      Iterator<Property> it = properties.iterator();
      while (it.hasNext()) {
        Property p = it.next();
        attributes.put(p.getName().toString(), p.getValue().toString());
      }
      this.geom = (Geometry) next.getAttribute(0);
      this.desc = (String) next.getAttribute("error_desc");
      this.id = next.getID();
      name = next.getName();
    }
  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()) {
        try {
          feature = (SimpleFeature) iterator.next();
        } catch (Exception e) {
          throw new DataSourceException("Could not add Features, problem with provided reader", e);
        }

        newFeature = (SimpleFeature) writer.next();

        try {
          // JD: we may have a case that the source feature type does not
          // match exactly the target feature type, so build attributes
          // based oin target
          // newFeature.setAttributes(feature.getAttributes(null));
          Object[] attributes = new Object[newFeature.getAttributeCount()];
          for (int i = 0; i < attributes.length; i++) {
            AttributeDescriptor type = newFeature.getFeatureType().getDescriptor(i);
            attributes[i] = feature.getAttribute(type.getLocalName());
          }
          newFeature.setAttributes(attributes);

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

        writer.write();
        addedFids.add(newFeature.getIdentifier());
      }
    } finally {
      collection.close(iterator);
      writer.close();
    }

    return addedFids;
  }
Beispiel #25
0
  @SuppressWarnings({"unchecked"})
  private void modifyOldFeature(final FeatureStore<SimpleFeatureType, SimpleFeature> store)
      throws IOException, IllegalAttributeException {
    FilterFactory fac = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
    Filter filter = fac.id(FeatureUtils.stringToId(fac, oldFeature.getID()));

    Geometry g = GeometryCreationUtil.createGeom(LineString.class, first.getShell(), true);
    if (store
        .getSchema()
        .getGeometryDescriptor()
        .getType()
        .getBinding()
        .isAssignableFrom(MultiLineString.class))
      g = new GeometryFactory().createMultiLineString(new LineString[] {(LineString) g});

    store.modifyFeatures(store.getSchema().getGeometryDescriptor(), g, filter);
    oldFeature.setDefaultGeometry(g);
  }
Beispiel #26
0
  public static void printID(String filename) {
    File file = new File(filename);
    FileDataStore store = null;
    try {
      store = FileDataStoreFinder.getDataStore(file);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    SimpleFeatureSource featureSource = null;
    try {
      featureSource = store.getFeatureSource();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    SimpleFeatureCollection featureCollection = null;
    try {
      featureCollection = featureSource.getFeatures();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } // get features from source
    int sizeFeatureCollection = featureCollection.size();
    System.out.println(
        "The number of features in the shapefile is: " + sizeFeatureCollection + ".");

    SimpleFeatureIterator iterator = featureCollection.features();

    //		List<Geometry> GeometryList = new ArrayList<Geometry>(sizeFeatureCollection);
    try {
      while (iterator.hasNext()) {

        SimpleFeature feature = iterator.next();

        System.out.println(feature.getID());
      }
    } finally {
      iterator.close();

      store.dispose();
    }
  }
  @Test
  public void testFeautureSourceFidFilter() throws Exception {
    // grab the last feature in the collection (there are more than one)
    SimpleFeatureSource fs = rts.getFeatureSource(RENAMED);

    // build a filter that will retrieve that feature only
    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    final String fid = RENAMED + ".f001";
    Filter fidFilter = ff.id(Collections.singleton(ff.featureId(fid)));

    SimpleFeatureCollection fc = fs.getFeatures(new Query(RENAMED, fidFilter));
    assertEquals(RENAMED, fc.getSchema().getName().getLocalPart());
    assertEquals(1, fc.size());
    FeatureIterator<SimpleFeature> it = fc.features();
    assertTrue(it.hasNext());
    SimpleFeature sf = it.next();
    assertFalse(it.hasNext());
    it.close();
    assertEquals(fid, sf.getID());
  }
 /**
  * Test that a filter query issued.
  *
  * @param filter filter to be passed in the query to determine the subset of features to be
  *     returned, or null for all features
  * @param expectedFeatureIds integer id for returned features, matching the expected row ids
  * @throws Exception
  */
 private void runFilterTest(Filter filter, int[] expectedFeatureIds) throws Exception {
   DataStore datastore = null;
   try {
     datastore = DataStoreFinder.getDataStore(getParams());
     assertNotNull(datastore);
     Query query = new DefaultQuery(TEST_TABLE_NAME, filter);
     FeatureReader<SimpleFeatureType, SimpleFeature> reader = null;
     try {
       /*
        * List of all the integer feature ids seen in the features returned for this query.
        */
       List<Integer> featureIds = new ArrayList<Integer>();
       reader = datastore.getFeatureReader(query, Transaction.AUTO_COMMIT);
       for (SimpleFeature feature = null; reader.hasNext(); ) {
         feature = reader.next();
         /*
          * Convert long feature id of the form test_table_name.1234 to the numeric id
          * used when creating the row. This relies on the behaviour of the postgis fid
          * mapper.
          */
         Integer id = Integer.valueOf(feature.getID().replace(TEST_TABLE_NAME + ".", ""));
         featureIds.add(id);
       }
       /*
        * The query succeeded as expected if and only if the sorted lists of returned and
        * expected ids are equal. The expected ids are converted to a List of Integers to
        * leverage Collections comparison.
        */
       assertEquals(sortedList(expectedFeatureIds), sorted(featureIds));
     } finally {
       if (reader != null) {
         reader.close();
       }
     }
   } finally {
     if (datastore != null) {
       datastore.dispose();
     }
   }
 }
  /**
   * 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();
    }
  }
  /**
   * Gets the allocation rule.
   *
   * @return the allocation rule
   * @throws Exception the exception
   */
  @Test(
      enabled = true,
      groups = {"setup", "geo", "database"})
  public void getAllocationRule() throws Exception {

    LOGGER.debug("getAllocationRule: {}");
    final AllocationScenario allocationScenario =
        allocationScenarioService.getAllocationScenario(WifKeys.TEST_ALLOCATION_SCENARIO_ID);
    final AllocationLU residentiallu = project.getExistingLandUseByLabel("Conservation");
    final String existingLULabel = project.getExistingLUAttributeName();
    final String scoreLabel = residentiallu.getAssociatedLU().getFeatureFieldName();

    final ALURule rule =
        geodataFilterer.getAllocationRule(
            residentiallu, allocationScenario, scoreLabel, existingLULabel, "", "", null, 0.0);
    final Query ruleQuery = rule.getRuleQuery();
    // ruleQuery.
    final SimpleFeatureCollection sortedUazCollection =
        featureStore.getFeatures(rule.getRuleQuery());
    LOGGER.debug("sortedUazCollection size: {}", sortedUazCollection.size());
    // Assert.assertEquals(sortedUazCollection.size(), 7834);
    final SimpleFeatureIterator its = sortedUazCollection.features();
    // 2. for each ORDERED UAZ
    int remaining = 0;
    final String areaLabel = allocationScenario.getWifProject().getAreaLabel();
    while (its.hasNext() && remaining < 10) {
      // 3. while there is a still area to allocate
      final SimpleFeature uazFeature = its.next();

      final String id = uazFeature.getID();
      LOGGER.debug("Allocating feature id: {}", id);
      final Double featureArea = (Double) uazFeature.getAttribute(areaLabel);
      LOGGER.debug(
          "feature suitability score= {}, feature area = {},",
          uazFeature.getAttribute(scoreLabel),
          featureArea);
      remaining++;
    }
  }