@Test
  public void testAttributeReaderIndexed() throws IOException {
    URL u = TestData.url(TestCaseSupport.class, SHPFILE);
    File shpFile = DataUtilities.urlToFile(u);

    // open the test shapefile
    // creates both indexed and regular shapefile data store
    ShapefileDataStore indexedstore = new ShapefileDataStore(shpFile.toURI().toURL());

    // get a random feature id from one of the stores
    SimpleFeatureIterator it = indexedstore.getFeatureSource().getFeatures().features();
    FeatureId fid = it.next().getIdentifier();
    it.close();

    // query the datastore
    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    Filter idFilter = ff.id(Collections.singleton(fid));
    final Query query =
        new Query(
            indexedstore.getSchema().getName().getLocalPart(), idFilter, new String[] {testColumn});
    final SimpleFeatureCollection indexedfeatures =
        indexedstore.getFeatureSource().getFeatures(query);

    // compare the results
    SimpleFeatureIterator indexIterator = indexedfeatures.features();
    SimpleFeature indexedFeature = indexIterator.next();
    indexIterator.close();

    // get the value of the duplicate column & compare it against expectation
    assertEquals(expectedValue, indexedFeature.getAttribute(testColumn));

    // cleanup
    indexedstore.dispose();
  }
  private void addAggregateCFFFeature(
      OutputObject cffObject, int id, int lunghezza, double cff[], SimpleFeature inputFeature)
      throws IOException {

    SimpleFeatureBuilder featureBuilder = cffObject.getBuilder();
    for (int count = 0; count < cff.length; count++) {
      try {
        double cffElement = cff[count];
        featureBuilder.reset();
        // compiles the attributes from target and read feature data, using mappings
        // to match input attributes with output ones
        for (AttributeDescriptor attr : cffObject.getSchema().getAttributeDescriptors()) {
          if (attr.getLocalName().equals("cff")) {
            // compute the aritmetic average
            featureBuilder.add(cffElement / lunghezza);
          } else if (attr.getLocalName().equals("fk_partner")) {
            featureBuilder.add(partner + "");
          } else {
            featureBuilder.add(null);
          }
        }
        String idBersaglio = bersaglio.getProperty(Integer.toString(count + 1));
        String featureid = id + "." + idBersaglio;
        SimpleFeature feature = featureBuilder.buildFeature(featureid);
        feature.getUserData().put(Hints.USE_PROVIDED_FID, true);

        cffObject.getWriter().addFeatures(DataUtilities.collection(feature));
      } catch (NumberFormatException e) {

      }
    }
  }
  private static void convertFeature(
      GeometryStreamConverter converter,
      SimpleFeature feature,
      List<String> keyAttributes,
      String projectionWKT)
      throws Exception {
    int shapeType =
        GeometryStreamUtils.getShapeTypeFromGeometryType(
            feature.getType().getType(0).getName().toString());
    // get shape key by concatenating specified attributes
    String shapeKey = "";
    for (int attrIndex = 0; attrIndex < keyAttributes.size(); attrIndex++) {
      Object attributeObject = feature.getAttribute(keyAttributes.get(attrIndex));
      shapeKey += ShapefileUtilities.forAttribute(attributeObject, String.class);
    }
    IFeatureGeometryStream geomStream =
        new JTSFeatureGeometryStream((Geometry) feature.getDefaultGeometry());
    converter.convertFeature(geomStream, shapeType, shapeKey, projectionWKT);

    /*
    if (debugDBF)
    {
    	// debug: print data
    	String attrs = geometryMetadata.shapeID + ", " + "\"" + shapeKey + '"';
    	for (int i = 1; i < feature.getAttributeCount(); i++)
    		attrs += ", \"" + feature.getAttribute(i) + '"';
    	System.out.println(attrs);
    }
    if (debugCounts)
    {
    	System.out.println(String.format("%s (geom %s) has %s vertices", shapeKey, i, coords.length));
    }
    */
  }
  /**
   * Check that a result set contains a stacked point in the right cell with expected attribute
   * values. Because it's not known in advance what the actual location of a stacked point will be,
   * a nearest-point strategy is used.
   *
   * @param result
   * @param coordinate
   * @param i
   * @param j
   */
  private void checkResultPoint(
      SimpleFeatureCollection result,
      Coordinate testPt,
      int expectedCount,
      int expectedCountUnique,
      Double expectedProportion,
      Double expectedProportionUnique) {

    SimpleFeature f = getResultPoint(result, testPt);
    assertNotNull(f);

    /** Find closest point to loc pt, then check that the attributes match */
    int count = (Integer) f.getAttribute(PointStackerProcess.ATTR_COUNT);
    int countunique = (Integer) f.getAttribute(PointStackerProcess.ATTR_COUNT_UNIQUE);
    double normCount = Double.NaN;
    double normCountUnique = Double.NaN;
    if (expectedProportion != null) {
      normCount = (Double) f.getAttribute(PointStackerProcess.ATTR_NORM_COUNT);
      normCountUnique = (Double) f.getAttribute(PointStackerProcess.ATTR_NORM_COUNT_UNIQUE);
    }

    assertEquals(expectedCount, count);
    assertEquals(expectedCountUnique, countunique);
    if (expectedProportion != null) assertEquals(expectedProportion, normCount, 0.0001);
    if (expectedProportionUnique != null)
      assertEquals(expectedProportionUnique, normCountUnique, 0.0001);
  }
  /**
   * 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;
  }
 /**
  * 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);
 }
Esempio n. 7
0
  public Map<String, Zone> getZonesInsideBoundary(final String zonesBoundaryShapeFileName) {

    final Collection<SimpleFeature> features =
        ShapeFileReader.getAllFeatures(zonesBoundaryShapeFileName);
    if (features.size() != 1) {
      throw new RuntimeException("not exactly one feature in shape file");
    }

    final SimpleFeature feature = features.iterator().next();
    final WKTReader wktreader = new WKTReader();
    final Geometry limitingPolygon;
    try {
      limitingPolygon = wktreader.read(feature.getAttribute("the_geom").toString());
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }

    final Map<String, Zone> result = new LinkedHashMap<String, Zone>();
    for (Map.Entry<String, Zone> id2zoneEntry : this.id2zone.entrySet()) {
      if (limitingPolygon.covers(id2zoneEntry.getValue().getGeometry())) {
        result.put(id2zoneEntry.getKey(), id2zoneEntry.getValue());
      }
    }
    return result;
  }
  /**
   * 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");
    }
  }
Esempio n. 9
0
  /**
   * Extract the coordinate of a FeatureCollection in a HashMap with an ID as a key.
   *
   * @param nStaz
   * @param collection
   * @throws Exception if a fiel of elevation isn't the same of the collection
   */
  private LinkedHashMap<Integer, Coordinate> getCoordinate(
      int nStaz, SimpleFeatureCollection collection, String idField) throws Exception {
    LinkedHashMap<Integer, Coordinate> id2CoordinatesMap = new LinkedHashMap<Integer, Coordinate>();
    FeatureIterator<SimpleFeature> iterator = collection.features();
    Coordinate coordinate = null;
    try {
      while (iterator.hasNext()) {
        SimpleFeature feature = iterator.next();
        int name = ((Number) feature.getAttribute(idField)).intValue();
        coordinate = ((Geometry) feature.getDefaultGeometry()).getCentroid().getCoordinate();
        double z = 0;
        if (fPointZ != null) {
          try {
            z = ((Number) feature.getAttribute(fPointZ)).doubleValue();
          } catch (NullPointerException e) {
            pm.errorMessage(msg.message("kriging.noPointZ"));
            throw new Exception(msg.message("kriging.noPointZ"));
          }
        }
        coordinate.z = z;
        id2CoordinatesMap.put(name, coordinate);
      }
    } finally {
      iterator.close();
    }

    return id2CoordinatesMap;
  }
Esempio n. 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();
  }
  /**
   * Analyzes the feature list, take the features that are neighbour and if they meet the
   * requirements, add a vertex to them.
   *
   * @return The builder instance.
   * @throws SplitFeatureBuilderFailException
   */
  public SplitFeatureBuilder buildNeighbours() throws SplitFeatureBuilderFailException {

    this.neighbourResultList = new ArrayList<SimpleFeature>();
    try {
      for (SimpleFeature feature : featureList) {

        Geometry geom = (Geometry) feature.getDefaultGeometry();
        CoordinateReferenceSystem featureCRS =
            feature.getFeatureType().getCoordinateReferenceSystem();
        geom = GeoToolsUtils.reproject(geom, featureCRS, desiredCRS);

        if (!canSplit(geom) && (requireVertex(geom))) {

          Geometry geomWithAddedVertex = addVertexToNeighbour(geom);
          geomWithAddedVertex =
              GeoToolsUtils.reproject(geomWithAddedVertex, desiredCRS, featureCRS);
          feature.setDefaultGeometry(geomWithAddedVertex);
          this.neighbourResultList.add(feature);
        }
      }
    } catch (Exception e) {
      throw makeFailException(e);
    }
    return this;
  }
  /**
   * Creates the resultant features.
   *
   * @param splitGeometries List with the new geometries.
   * @param feature The old feature.
   * @throws OperationNotFoundException
   * @throws TransformException
   */
  private List<SimpleFeature> createSplitFeatures(
      final List<Geometry> splitGeometries, final SimpleFeature feature)
      throws OperationNotFoundException, TransformException {

    final SimpleFeatureType featureType = feature.getFeatureType();
    final CoordinateReferenceSystem featureCrs = featureType.getCoordinateReferenceSystem();

    Class<? extends Geometry> geometryType =
        (Class<? extends Geometry>) featureType.getGeometryDescriptor().getType().getBinding();

    List<SimpleFeature> splitFeatureList = new LinkedList<SimpleFeature>();
    for (Geometry splittedPart : splitGeometries) {

      splittedPart = GeoToolsUtils.reproject(splittedPart, desiredCRS, featureCrs);

      splittedPart = GeometryUtil.adapt(splittedPart, geometryType);
      SimpleFeature newFeature = DataUtilities.template(featureType);
      GeoToolsUtils.copyAttributes(feature, newFeature);
      newFeature.setDefaultGeometry(splittedPart);

      splitFeatureList.add(newFeature);
    }

    return splitFeatureList;
  }
  /**
   * Analyze the feature list, and for those features that can suffer split operation, they'll be
   * split.
   *
   * @return The builder instance.
   * @throws SplitFeatureBuilderFailException if the operation fail
   * @throws CannotSplitException if the split line cannot divide the feature's geometry
   */
  public SplitFeatureBuilder buildSplit()
      throws SplitFeatureBuilderFailException, CannotSplitException {

    try {
      this.splitResultList = new LinkedList<SimpleFeature>();
      boolean existSplit = false;
      for (SimpleFeature feature : this.featureList) {

        Geometry geomToSplit = (Geometry) feature.getDefaultGeometry();
        assert geomToSplit.isValid() : "No Valid Geometry: " + geomToSplit.toText(); // $NON-NLS-1$
        CoordinateReferenceSystem featureCrs =
            feature.getFeatureType().getCoordinateReferenceSystem();
        geomToSplit = GeoToolsUtils.reproject(geomToSplit, featureCrs, this.desiredCRS);

        if (canSplit(geomToSplit)) {
          existSplit = true;
          this.featuresThatSufferedSplit.add(feature);

          List<Geometry> splitGeometriesResult = split(geomToSplit);
          this.splitResultList.addAll(createSplitFeatures(splitGeometriesResult, feature));
        }
      }
      if (!existSplit) {
        throw new CannotSplitException("The split line cannot split any features"); // $NON-NLS-1$
      }
    } catch (OperationNotFoundException e) {
      throw makeFailException(e);
    } catch (TransformException e) {
      throw makeFailException(e);
    }
    return this;
  }
  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();
    }
  }
  /** @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();
    }
  }
Esempio n. 16
0
  @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);
  }
  public void testPerserveUserData() throws Exception {
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName("foo");
    tb.setSRS("epsg:4326");
    tb.add("geom", Point.class);

    SimpleFeatureBuilder b = new SimpleFeatureBuilder(tb.buildFeatureType());
    b.add(new WKTReader().read("POINT(1 1)"));
    SimpleFeature f = b.buildFeature(null);
    f.getUserData().put("foo", "bar");

    DefaultFeatureCollection features = new DefaultFeatureCollection(null, b.getFeatureType());
    features.add(f);

    FeatureIterator it = features.features();

    try {
      assertEquals("bar", it.next().getUserData().get("foo"));
    } finally {
      it.close();
    }

    ReprojectingFeatureCollection reprojected =
        new ReprojectingFeatureCollection(features, CRS.decode("EPSG:3005"));
    it = reprojected.features();

    try {
      assertEquals("bar", it.next().getUserData().get("foo"));
    } finally {
      it.close();
    }
  }
    private LineSegment extractShorelineInterect(SimpleFeature feature) {

      Object sceObject = ((Double) feature.getAttribute(Constants.SCE_ATTR));
      Object nsdObject = feature.getAttribute(Constants.NSD_ATTR);

      Geometry geometry = (Geometry) feature.getDefaultGeometry();
      Coordinate[] coordinates = geometry.getCoordinates();
      LineSegment segment = new LineSegment(coordinates[0], coordinates[1]);

      double length = segment.getLength();

      double sce = sceObject instanceof Number ? ((Number) sceObject).doubleValue() : Double.NaN;
      double nsd = nsdObject instanceof Number ? ((Number) nsdObject).doubleValue() : Double.NaN;

      if (sce == sce && nsd == nsd) {
        return extractShorelineInterectAndCheckLength(segment, nsd, sce);
      } else {
        if (sce != sce && nsd != nsd) {
          return extractShorelineInterectAndCheckLength(segment, 0, length);
        }
        if (sce != sce) {
          sce = length - nsd;
        } else /* if nsd != nsd */ {
          nsd = length - sce;
        }
        return extractShorelineInterectAndCheckLength(segment, nsd, sce);
      }
    }
Esempio n. 19
0
  public void addBuildings(final String buildingShapeFileName) {

    final GeometryFactory geometryFactory = new GeometryFactory();
    final WKTReader wktReader = new WKTReader(geometryFactory);

    final ShapeFileReader shapeFileReader = new ShapeFileReader();
    shapeFileReader.readFileAndInitialize(buildingShapeFileName);
    final Collection<SimpleFeature> features = shapeFileReader.getFeatureSet();

    for (SimpleFeature ft : features) {

      try {
        final Geometry geometry = wktReader.read((ft.getAttribute("the_geom")).toString());
        final String buildingType = ft.getAttribute("ANDAMAL_1T").toString();
        final int buildingSize = Integer.valueOf(ft.getAttribute("AREA").toString());
        final Building building = new Building(geometry, buildingSize);
        building.setBuildingType(buildingType);

        for (Zone zone : this.id2zone.values()) {
          if (zone.getGeometry() != null && zone.getGeometry().intersects(geometry)) {
            zone.addBuilding(building);
            break;
          }
        }

      } catch (ParseException e) {
        throw new RuntimeException(e);
      }
    }
  }
Esempio n. 20
0
  /**
   * Must go places!
   *
   * @param selection
   */
  public void showLocation(Object selection) {
    // selection should be an Feture (of some sort)
    SimpleFeature feature = (SimpleFeature) selection;
    Geometry geom = (Geometry) feature.getDefaultGeometry();
    Point point = geom.getCentroid();

    IMap imap = ApplicationGIS.getActiveMap();
    if (imap == ApplicationGIS.NO_MAP) return;

    CoordinateReferenceSystem world = imap.getViewportModel().getCRS();
    CoordinateReferenceSystem wsg84 = DefaultGeographicCRS.WGS84;

    double buffer = 0.01; // how much of the wgs84 world to see
    Envelope view = point.buffer(buffer).getEnvelopeInternal();

    MathTransform transform;
    try {
      transform = CRS.findMathTransform(wsg84, world, true); // relaxed
    } catch (FactoryException e) {
      return; // no go
    }
    Envelope areaOfInterest;
    try {
      areaOfInterest = JTS.transform(view, null, transform, 10);
    } catch (TransformException e) {
      return; // no go
    }

    // NavigationCommandFactory navigate = NavigationCommandFactory.getInstance();

    NavCommand show = new SetViewportBBoxCommand(areaOfInterest, world);
    imap.sendCommandASync(show);
  }
    @Override
    public Feature decorate(Feature feature, KmlEncodingContext context) {
      Placemark pm = (Placemark) feature;
      // while it's possible to have more than one style object, GE will only paint
      // the first one
      Style style = pm.createAndAddStyle();
      List<Symbolizer> symbolizers = context.getCurrentSymbolizers();
      SimpleFeature sf = context.getCurrentFeature();
      if (symbolizers.size() > 0 && sf.getDefaultGeometry() != null) {
        // sort by point, text, line and polygon
        Map<Class, List<Symbolizer>> classified = classifySymbolizers(symbolizers);

        // if no point symbolizers, create a default one
        List<Symbolizer> points = classified.get(PointSymbolizer.class);
        if (points.size() == 0) {
          if (context.isDescriptionEnabled()) {
            setDefaultIconStyle(style, sf, context);
          }
        } else {
          org.geotools.styling.Style wholeStyle = context.getCurrentLayer().getStyle();
          IconProperties properties = IconPropertyExtractor.extractProperties(wholeStyle, sf);
          setIconStyle(style, wholeStyle, properties, context);
        }

        // handle label styles
        List<Symbolizer> texts = classified.get(TextSymbolizer.class);
        if (texts.size() == 0) {
          if (context.isDescriptionEnabled()) {
            setDefaultLabelStyle(style);
          }
        } else {
          // the XML schema allows only one text style, follow painter's model
          // and set the last one
          TextSymbolizer lastTextSymbolizer = (TextSymbolizer) texts.get(texts.size() - 1);
          setLabelStyle(style, sf, lastTextSymbolizer);
        }

        // handle line styles
        List<Symbolizer> lines = classified.get(LineSymbolizer.class);
        // the XML schema allows only one line style, follow painter's model
        // and set the last one
        if (lines.size() > 0) {
          LineSymbolizer lastLineSymbolizer = (LineSymbolizer) lines.get(lines.size() - 1);
          setLineStyle(style, sf, lastLineSymbolizer.getStroke());
        }

        // handle polygon styles
        boolean forceOutiline = lines.size() == 0;
        List<Symbolizer> polygons = classified.get(PolygonSymbolizer.class);
        if (polygons.size() > 0) {
          // the XML schema allows only one polygon style, follow painter's model
          // and set the last one
          PolygonSymbolizer lastPolygonSymbolizer =
              (PolygonSymbolizer) polygons.get(polygons.size() - 1);
          setPolygonStyle(style, sf, lastPolygonSymbolizer, forceOutiline);
        }
      }

      return feature;
    }
  /**
   * The type of filter that returns should be in a single Or filter OR(a,b,c) instead of ((a OR b)
   * or c)
   */
  @Test
  public void testUnrollFid() throws Exception {
    Set<FeatureId> fids = new HashSet();
    String fid1 = "station_no.1"; // exists
    String fid2 = "station_no.500"; // doesn't exists
    fids.add(ff.featureId(fid1));
    fids.add(ff.featureId(fid2));
    Id fidFilter = ff.id(fids);
    Filter unrolled = (Filter) fidFilter.accept(visitor, null);
    assertNotNull(unrolled);
    assertTrue(unrolled instanceof OrImpl);
    List<Filter> filters = ((OrImpl) unrolled).getChildren();
    assertEquals(2, filters.size());
    for (Filter f : filters) {
      assertTrue(f instanceof IsEqualsToImpl);
    }

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

    FeatureIterator<SimpleFeature> features = results.features();
    SimpleFeature unmappedFeature = (SimpleFeature) features.next();

    features.close();

    assertNotNull(unmappedFeature);
    Object object = unmappedFeature.getProperty("station_no").getValue();
    assertEquals(fid1, object);
  }
  public void setupInstance(String shapeFileName) {
    File file = new File(shapeFileName);

    // TODO what if the file doesn't exist?

    ShapefileDataStore store = null;
    SimpleFeatureCollection collection = null;
    try {
      store = (ShapefileDataStore) FileDataStoreFinder.getDataStore(file);
      SimpleFeatureSource featureSource = store.getFeatureSource();
      collection = featureSource.getFeatures();
    } catch (IOException e) {
      logger.error("Could not retrieve collection", e);
      return;
    }
    geometryFactory = new GeometryFactory();

    geometryList = new ArrayList<Geometry>();

    SimpleFeatureIterator iter = collection.features();

    while (iter.hasNext()) {
      SimpleFeature feature = iter.next();
      Geometry geometry = (Geometry) feature.getDefaultGeometry();
      geometryList.add(geometry);
    }
    iter.close();
  }
  /**
   * 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());
  }
Esempio n. 25
0
  @Test
  public void testWithNull() throws Exception {

    SimpleFeatureSource source = getFeatureSource(MockData.BASIC_POLYGONS);
    SimpleFeatureCollection fc = source.getFeatures();
    SimpleFeatureIterator i = fc.features();
    try {
      SimpleFeature f = (SimpleFeature) i.next();

      FeatureTemplate template = new FeatureTemplate();
      template.description(f);

      // set a value to null
      f.setAttribute(1, null);
      try {
        template.description(f);
      } catch (Exception e) {
        e.printStackTrace();
        fail("template threw exception on null value");
      }

    } finally {
      i.close();
    }
  }
  @Test
  public void testSimpleWFSParse() throws URISyntaxException {
    File file = getFile();
    assertThat(file, notNullValue());

    GMLStreamingFeatureCollection fc = new GMLStreamingFeatureCollection(file);
    assertThat(fc, notNullValue());
    assertThat(fc.getBounds(), notNullValue());
    assertThat(fc.getSchema(), notNullValue());
    assertThat(fc.size(), equalTo(324));

    FeatureIterator fi = null;
    try {
      fi = fc.features();
      assertThat(fi, notNullValue());
      assertThat(fi.hasNext(), is(true));
      while (fi.hasNext()) {
        Feature f = fi.next();
        assertThat(f, instanceOf(SimpleFeature.class));
        SimpleFeature sf = (SimpleFeature) f;
        Object go = sf.getDefaultGeometry();
        assertThat(go, instanceOf(Geometry.class));
      }
    } finally {
      if (fi != null) {
        fi.close();
      }
    }
  }
Esempio n. 27
0
  /**
   * 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;
  }
  public void testVectorReprojector() throws Exception {

    SimpleFeatureCollection testFC = HMTestMaps.testFC;

    OmsVectorReprojector reprojector = new OmsVectorReprojector();
    reprojector.inVector = testFC;
    reprojector.pCode = "EPSG:4326";
    reprojector.pm = pm;
    reprojector.process();

    CoordinateReferenceSystem sourceCRS = HMTestMaps.crs;
    CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");

    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);

    SimpleFeatureCollection outFC = reprojector.outVector;
    FeatureIterator<SimpleFeature> featureIterator = outFC.features();
    SimpleFeatureIterator originalFeatureIterator = testFC.features();
    while (featureIterator.hasNext()) {
      SimpleFeature feature = featureIterator.next();
      Geometry geometry = (Geometry) feature.getDefaultGeometry();
      Coordinate coordinate = geometry.getCoordinate();

      SimpleFeature originalFeature = originalFeatureIterator.next();
      Coordinate origCoord = ((Geometry) originalFeature.getDefaultGeometry()).getCoordinate();
      Coordinate reprojected = JTS.transform(origCoord, null, transform);

      assertEquals(reprojected.x, coordinate.x, delta);
      assertEquals(reprojected.y, coordinate.y, delta);
    }
    featureIterator.close();
  }
Esempio n. 29
0
  public static DelaunayNode[] featureCollectionToNodeArray(SimpleFeatureCollection fc) {
    SimpleFeatureIterator iter = fc.features();
    int size = fc.size();
    DelaunayNode[] nodes = new DelaunayNode[size];
    int index = 0;
    while (iter.hasNext()) {
      SimpleFeature next = iter.next();
      Geometry geom = (Geometry) next.getDefaultGeometry();
      Point centroid;
      if (geom instanceof Point) {
        centroid = (Point) geom;
      } else {
        centroid = geom.getCentroid();
      }
      DelaunayNode node = new DelaunayNode();
      node.setCoordinate(centroid.getCoordinate());
      node.setFeature(next);
      if (!(arrayContains(node, nodes, index))) {
        nodes[index] = node;
        index++;
      }
    }

    DelaunayNode[] trimmed = new DelaunayNode[index];
    for (int i = 0; i < index; i++) {
      trimmed[i] = nodes[i];
    }
    return trimmed;
  }
  /**
   * @param outputObject
   * @param id
   * @param lunghezza
   * @param pterr
   * @param inputFeature
   * @throws IOException
   */
  private void addAggregateDissestoFeature(
      OutputObject outputObject,
      int id,
      int lunghezza,
      Set<Integer> pterr,
      SimpleFeature inputFeature)
      throws IOException {
    SimpleFeatureBuilder dissestoFeatureBuilder = outputObject.getBuilder();

    for (int dissesto : pterr) {
      // compiles the attributes from target and read feature data, using mappings
      // to match input attributes with output ones
      for (AttributeDescriptor attr : outputObject.getSchema().getAttributeDescriptors()) {
        if (attr.getLocalName().equals(geoId)) {
          dissestoFeatureBuilder.add(id);
        } else if (attr.getLocalName().equals("id_dissesto")) {
          dissestoFeatureBuilder.add(dissesto);
        } else if (attr.getLocalName().equals("fk_partner")) {
          dissestoFeatureBuilder.add(partner + "");
        } else {
          dissestoFeatureBuilder.add(null);
        }
      }
      String featureid = dissesto + "." + id;
      SimpleFeature feature = dissestoFeatureBuilder.buildFeature(featureid);
      feature.getUserData().put(Hints.USE_PROVIDED_FID, true);

      outputObject.getWriter().addFeatures(DataUtilities.collection(feature));
    }
  }