@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();
  }
  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. 3
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;
  }
  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();
  }
  @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();
    }
  }
Esempio n. 6
0
  public static SimpleFeatureType toReShapeFeatureType(
      SimpleFeatureCollection delegate, List<Definition> definitionList) {

    SimpleFeature sample = null;
    SimpleFeatureIterator iterator = delegate.features();
    try {
      if (iterator.hasNext()) {
        sample = iterator.next();
      }
    } finally {
      iterator.close(); // good bye
    }

    SimpleFeatureTypeBuilder build = new SimpleFeatureTypeBuilder();
    SimpleFeatureType origional = delegate.getSchema();

    for (Definition def : definitionList) {
      String name = def.name;
      Expression expression = def.expression;

      Object value = null;
      if (sample != null) {
        value = expression.evaluate(sample);
      }
      Class<?> binding = def.binding; // make use of any default binding hint provided by user
      if (value == null) {
        if (expression instanceof PropertyName) {
          PropertyName propertyName = (PropertyName) expression;
          String path = propertyName.getPropertyName();
          AttributeDescriptor descriptor = origional.getDescriptor(name);
          AttributeType attributeType = descriptor.getType();
          binding = attributeType.getBinding();
        }
      } else {
        binding = value.getClass();
      }

      if (binding == null) {
        // note we could consider scanning through additional samples until we get a non null hit
        throw new IllegalArgumentException("Unable to determine type for " + name);
      }

      if (Geometry.class.isAssignableFrom(binding)) {
        CoordinateReferenceSystem crs;
        AttributeType originalAttributeType = origional.getType(name);
        if (originalAttributeType != null && originalAttributeType instanceof GeometryType) {
          GeometryType geometryType = (GeometryType) originalAttributeType;
          crs = geometryType.getCoordinateReferenceSystem();
        } else {
          crs = origional.getCoordinateReferenceSystem();
        }
        build.crs(crs);
        build.add(name, binding);
      } else {
        build.add(name, binding);
      }
    }
    build.setName(origional.getTypeName());
    return build.buildFeatureType();
  }
  /**
   * Creates a buffer from the source shapefile MultiPolygon2 and put the result on the existent
   * shapefile TargetMultiPolygonForBuffer.
   *
   * <p>Check that the featureStore isn't empty and the geometry of the resultant features is
   * MultiPolygon.
   *
   * @throws IOException
   * @throws SchemaException
   * @throws InterruptedException
   * @throws ExecutionException
   */
  @Test
  public void testBufferTask()
      throws IOException, SchemaException, InterruptedException, ExecutionException {

    // initialize the parameters

    firstShp = "MultiPolygon2.shp";
    targetShp = TASK_PATH + "TargetMultiPolygonForBuffer.shp";

    isCreatingNewLayer = false;

    width = 10.0;

    unitOfMeasure = valueOfUnit("m");

    mergeGeometries = false;
    quadrantSegments = 8;
    capStyle = CapStyle.capRound;

    initTaskParameters();

    assertNotNull(task);
    assertNotNull(targetStore);

    // execute

    runTask();

    // obtain the result and check the data.

    SimpleFeatureStore resultStore = (SimpleFeatureStore) future.get();

    assertNotNull(resultStore);

    SimpleFeatureCollection fc = null;
    SimpleFeatureIterator it = null;

    try {
      fc = resultStore.getFeatures();

      assertFalse(fc.isEmpty());
      assertTrue(fc.size() > 0);

      it = fc.features();
      while (it.hasNext()) {

        SimpleFeature f = it.next();
        assertTrue(f.getDefaultGeometry().getClass() == MultiPolygon.class);
      }
    } catch (IOException e) {
      throw e;
    } finally {
      if (it != null) {
        it.close();
      }
    }
  }
 private void checkSorted(
     SortedSimpleFeatureCollection sorted, Comparator<SimpleFeature> comparator) {
   SimpleFeatureIterator fi = sorted.features();
   SimpleFeature prev = null;
   while (fi.hasNext()) {
     SimpleFeature curr = fi.next();
     if (prev != null) {
       assertTrue("Failed on " + prev + " / " + curr, comparator.compare(prev, curr) <= 0);
     }
     prev = curr;
   }
   fi.close();
 }
  /**
   * <b>validateMultipleLayers Purpose:</b> <br>
   *
   * <p>This validation tests for a geometry containing another geometry. Uses JTS'
   * Geometry.contains(Geometry) method. DE-9IM intersection matrix is T*F**F***.
   * <b>Description:</b><br>
   *
   * <p>The function filters the FeatureSources using the given bounding box. It creates iterators
   * over both filtered FeatureSources. It calls contains() using the geometries in the
   * SimpleFeatureSource layers. 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 featureSourceB - the SimpleFeatureSource to pull the other geometries from - these
   *     geometries will be those that may be contained within the first geometry
   * @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 validateMultipleLayers(
      SimpleFeatureSource featureSourceA,
      SimpleFeatureSource featureSourceB,
      boolean expected,
      ValidationResults results,
      Envelope bBox)
      throws Exception {
    boolean success = true;

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

    SimpleFeatureCollection featureResultsA = featureSourceA.getFeatures(filter);
    SimpleFeatureCollection featureResultsB = featureSourceB.getFeatures(filter);

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

      if (fr1 == null) return false;

      while (fr1.hasNext()) {
        SimpleFeature f1 = fr1.next();
        Geometry g1 = (Geometry) f1.getDefaultGeometry();
        fr2 = featureResultsB.features();
        try {
          while (fr2 != null && fr2.hasNext()) {
            SimpleFeature f2 = fr2.next();
            Geometry g2 = (Geometry) f2.getDefaultGeometry();
            if (g1.contains(g2) != expected) {
              results.error(
                  f1,
                  ((Geometry) f1.getDefaultGeometry()).getGeometryType()
                      + " "
                      + getGeomTypeRefA()
                      + " contains "
                      + getGeomTypeRefB()
                      + "("
                      + f2.getID()
                      + "), Result was not "
                      + expected);
              success = false;
            }
          }
        } finally {
          fr2.close();
        }
      }
    } finally {
      fr1.close();
      fr2.close();
    }

    return success;
  }
 private Map<String, Double> fetchPointValues(KmlFeature feature, List<String> parameters) {
   try {
     SimpleFeatureIterator iterator = getIterator();
     while (iterator.hasNext()) {
       SimpleFeature shape = iterator.next();
       Geometry geometry = (Geometry) shape.getDefaultGeometry();
       if (geometry.contains(feature.getGeometry())) return fetchValues(shape, parameters);
     }
     return Collections.emptyMap();
   } catch (Exception e) {
     log.error("failed to fetch point values", e);
     return Collections.emptyMap();
   }
 }
Esempio n. 11
0
 private Id createFidFilter(SimpleFeatureSource fs) throws IOException {
   SimpleFeatureIterator iter = fs.getFeatures().features();
   FilterFactory2 ffac = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
   Set fids = new HashSet();
   try {
     while (iter.hasNext()) {
       String id = iter.next().getID();
       FeatureId fid = ffac.featureId(id);
       fids.add(fid);
     }
     Id filter = ffac.id(fids);
     return filter;
   } finally {
     iter.close();
   }
 }
Esempio n. 12
0
  @Test
  public void testAlternateLookup() throws Exception {
    SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);
    SimpleFeatureCollection fc = source.getFeatures();
    SimpleFeatureIterator features = fc.features();
    try {
      SimpleFeature f = features.next();

      FeatureTemplate template = new FeatureTemplate();
      String result = template.template(f, "dummy.ftl", Dummy.class);

      assertEquals("dummy", result);
    } finally {
      features.close();
    }
  }
    @Override
    public FileGroup next() {
      SimpleFeature next = null;

      // look for cached feature
      if (cachedNext != null) {
        next = cachedNext;
        cachedNext = null;
      } else {
        next = featureIterator.next();
      }

      // Avoid adding the feature to a collection to reduce memory consumption
      // we only take note of the firstFeature
      int groupedFeatures = 0;
      SimpleFeature firstFeature = null;

      // resolve the location
      String granuleLocation = (String) next.getAttribute(locationAttributeName);
      URL resolved = pathType.resolvePath(parentLocation, granuleLocation);
      File file = null;
      if (resolved != null) {
        file = DataUtilities.urlToFile(resolved);
        if (file != null && file.exists()) {
          groupedFeatures++;
          firstFeature = next;
        }
      }
      if (groupedFeatures == 0) {
        return null;
      }

      while (featureIterator.hasNext()) {
        // Group features sharing same location
        next = featureIterator.next();
        String nextLocation = (String) next.getAttribute(locationAttributeName);
        if (granuleLocation.equalsIgnoreCase(nextLocation)) {
          groupedFeatures++;
        } else {
          cachedNext = next;
          break;
        }
      }

      // I have to group the features to get the ranges.
      return buildFileGroup(file, groupedFeatures > 1, firstFeature);
    }
Esempio n. 14
0
  @Test
  public void testTypes() throws IOException, NoSuchElementException {
    if (url == null) return;
    WFS_1_0_0_DataStore wfs;
    try {
      wfs = WFSDataStoreReadTest.getDataStore(url);
    } catch (ConnectException e) {
      e.printStackTrace(System.err);
      return;
    } catch (UnknownHostException e) {
      e.printStackTrace(System.err);
      return;
    } catch (NoRouteToHostException e) {
      e.printStackTrace(System.err);
      return;
    }
    String types[] = wfs.getTypeNames();
    String typeName = "unknown";
    for (int i = 0; i < types.length; i++) {
      typeName = types[i];
      if (typeName.equals("topp:geometrytype")) continue;
      SimpleFeatureType type = wfs.getSchema(typeName);
      type.getTypeName();
      type.getName().getNamespaceURI();

      SimpleFeatureSource source = wfs.getFeatureSource(typeName);
      source.getBounds();

      SimpleFeatureCollection features = source.getFeatures();
      features.getBounds();
      features.getSchema();
      // features.getFeatureType();

      Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already");
      features = source.getFeatures(query);
      features.size();
      SimpleFeatureIterator iterator = features.features();
      try {
        while (iterator.hasNext()) {
          SimpleFeature feature = (SimpleFeature) iterator.next();
        }
      } finally {
        iterator.close();
      }
    }
  }
Esempio n. 15
0
  /**
   * Get the stacked point closest to the provided coordinate
   *
   * @param result
   * @param coordinate
   * @param i
   * @param j
   */
  private SimpleFeature getResultPoint(SimpleFeatureCollection result, Coordinate testPt) {
    /** Find closest point to loc pt, then check that the attributes match */
    double minDist = Double.MAX_VALUE;

    // find nearest result to testPt
    SimpleFeature closest = null;
    for (SimpleFeatureIterator it = result.features(); it.hasNext(); ) {
      SimpleFeature f = it.next();
      Coordinate outPt = ((Point) f.getDefaultGeometry()).getCoordinate();
      double dist = outPt.distance(testPt);
      if (dist < minDist) {
        closest = f;
        minDist = dist;
      }
    }

    return closest;
  }
Esempio n. 16
0
  @Test
  public void testRawValue() throws Exception {
    SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);
    SimpleFeatureCollection fc = source.getFeatures();
    SimpleFeatureIterator i = fc.features();
    try {
      SimpleFeature f = (SimpleFeature) i.next();

      FeatureTemplate template = new FeatureTemplate();
      try {
        template.template(f, "rawValues.ftl", FeatureTemplateTest.class);
      } catch (Exception e) {
        e.printStackTrace();
        throw (e);
      }
    } finally {
      i.close();
    }
  }
Esempio n. 17
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;
    }
Esempio n. 18
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 testAttributeReader() throws IOException {
    URL u = TestData.url(TestCaseSupport.class, SHPFILE);
    File shpFile = DataUtilities.urlToFile(u);

    // open the test shapefile
    ShapefileDataStore store = new ShapefileDataStore(shpFile.toURI().toURL());
    SimpleFeatureSource source = store.getFeatureSource();

    // read the first feature
    SimpleFeatureIterator iter = source.getFeatures().features();
    SimpleFeature feature = iter.next();
    iter.close();

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

    // cleanup
    store.dispose();
  }
 private Map<String, Double> fetchPolygonValues(KmlFeature feature, List<String> parameters) {
   try {
     double totalArea = feature.getGeometry().getArea();
     if (totalArea == 0) return Collections.emptyMap();
     Map<SimpleFeature, Double> shares = new HashMap<>();
     SimpleFeatureIterator iterator = getIterator();
     while (iterator.hasNext()) {
       SimpleFeature shape = iterator.next();
       Geometry shapeGeo = (Geometry) shape.getDefaultGeometry();
       Geometry featureGeo = feature.getGeometry();
       if (!featureGeo.intersects(shapeGeo)) continue;
       double area = featureGeo.intersection(shapeGeo).getArea();
       shares.put(shape, area / totalArea);
     }
     return fetchValues(shares, parameters);
   } catch (Exception e) {
     log.error("failed to fetch polygon parameters", e);
     return Collections.emptyMap();
   }
 }
Esempio n. 21
0
  @Test
  public void testWithDateAndBoolean() throws Exception {

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

      FeatureTemplate template = new FeatureTemplate();
      try {
        template.description(f);
      } catch (Exception e) {
        e.printStackTrace();
        fail("template threw exception on null value");
      }
    } finally {
      i.close();
    }
  }
Esempio n. 22
0
  /**
   * 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++;
    }
  }
Esempio n. 23
0
  @Test
  public void testSingleType() throws IOException, NoSuchElementException {
    if (url == null) return;
    WFS_1_0_0_DataStore wfs;
    try {
      wfs = WFSDataStoreReadTest.getDataStore(url);
    } catch (ConnectException e) {
      e.printStackTrace(System.err);
      return;
    } catch (UnknownHostException e) {
      e.printStackTrace(System.err);
      return;
    } catch (NoRouteToHostException e) {
      e.printStackTrace(System.err);
      return;
    }
    String typeName = "tiger:poi";
    SimpleFeatureType type = wfs.getSchema(typeName);
    type.getTypeName();
    type.getName().getNamespaceURI();

    SimpleFeatureSource source = wfs.getFeatureSource(typeName);
    source.getBounds();

    SimpleFeatureCollection features = source.getFeatures();
    features.getBounds();
    features.getSchema();
    // features.getFeatureType();

    Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already");
    features = source.getFeatures(query);
    features.size();

    SimpleFeatureIterator iterator = features.features();
    while (iterator.hasNext()) {
      SimpleFeature feature = iterator.next();
    }
    iterator.close();
  }
Esempio n. 24
0
  @Test
  public void testSimplifyFilter() throws Exception {
    if (url == null) return;
    Map m = new HashMap();
    m.put(WFSDataStoreFactory.URL.key, url);
    m.put(WFSDataStoreFactory.TIMEOUT.key, new Integer(100000));
    WFS_1_0_0_DataStore wfs = (WFS_1_0_0_DataStore) (new WFSDataStoreFactory()).createDataStore(m);
    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());

    WFSFeatureSource fs = wfs.getFeatureSource("topp:states");

    // build a filter with bits that cannot be encoded in OGC filter, but can be simplified
    // to one that can
    Filter f =
        ff.or(
            Arrays.asList(
                Filter.EXCLUDE,
                ff.and(Filter.INCLUDE, ff.greater(ff.property("PERSONS"), ff.literal(10000000)))));
    SimpleFeatureCollection fc = fs.getFeatures(f);

    // force calling a HITS query, it used to throw an exception
    int size = fc.size();

    // force making a GetFeature, it used to blow up
    SimpleFeatureIterator fi = null;
    try {
      fi = fc.features();
      if (fi.hasNext()) {
        fi.next();
      }
    } finally {
      if (fi != null) {
        fi.close();
      }
    }
  }
Esempio n. 25
0
  public void testAssorted() {
    TreeSetFeatureCollection copy = new TreeSetFeatureCollection();
    copy.addAll(features);
    copy.clear();
    assertTrue(copy.isEmpty());
    copy.addAll(features);
    assertTrue(!copy.isEmpty());

    List<SimpleFeature> list = DataUtilities.list(features);
    SimpleFeature[] f1 = (SimpleFeature[]) list.toArray(new SimpleFeature[list.size()]);
    SimpleFeature[] f2 = (SimpleFeature[]) features.toArray(new SimpleFeature[list.size()]);
    assertEquals(f1.length, f2.length);
    for (int i = 0; i < f1.length; i++) {
      assertSame(f1[i], f2[i]);
    }
    SimpleFeatureIterator copyIterator = copy.features();
    SimpleFeatureIterator featuresIterator = features.features();
    while (copyIterator.hasNext() && featuresIterator.hasNext()) {
      assertEquals(copyIterator.next(), featuresIterator.next());
    }
  }
 @Override
 public void close() throws IOException {
   featureIterator.close();
 }
 @Override
 public boolean hasNext() {
   return featureIterator.hasNext() || cachedNext != null;
 }
    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 void close() {
   delegate.close();
 }
  @SuppressWarnings("unchecked")
  public void _testParseGetFeature() throws Exception {
    File tmp = File.createTempFile("geoserver-DescribeFeatureType", "xml");
    tmp.deleteOnExit();

    InputStream in = getClass().getResourceAsStream("geoserver-DescribeFeatureType.xml");
    Files.copy(in, tmp.toPath());

    in = getClass().getResourceAsStream("geoserver-GetFeature.xml");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(in);

    // http://cite.opengeospatial.org/gmlsf
    // http://localhost:8080/geoserver/wfs?service=WFS&amp;version=1.1.0&amp;request=DescribeFeatureType&amp;typeName=sf:PrimitiveGeoFeature
    String schemaLocation =
        doc.getDocumentElement()
            .getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation");
    String absolutePath = DataUtilities.fileToURL(tmp).toExternalForm();

    schemaLocation =
        schemaLocation.replaceAll(
            "http://cite.opengeospatial.org/gmlsf .*",
            "http://cite.opengeospatial.org/gmlsf " + absolutePath);
    doc.getDocumentElement()
        .setAttributeNS(
            "http://www.w3.org/2001/XMLSchema-instance", "schemaLocation", schemaLocation);

    tmp = File.createTempFile("geoserver-GetFeature", "xml");
    tmp.deleteOnExit();

    Transformer tx = TransformerFactory.newInstance().newTransformer();
    tx.transform(new DOMSource(doc), new StreamResult(tmp));

    in = new FileInputStream(tmp);

    Parser parser = new Parser(configuration);
    FeatureCollectionType fc = (FeatureCollectionType) parser.parse(in);
    assertNotNull(fc);

    List featureCollections = fc.getMember();
    assertEquals(1, featureCollections.size());

    SimpleFeatureCollection featureCollection;
    featureCollection = (SimpleFeatureCollection) featureCollections.get(0);
    assertEquals(5, featureCollection.size());

    SimpleFeatureIterator features = featureCollection.features();

    try {
      assertTrue(features.hasNext());

      SimpleFeature f = features.next();

      assertEquals("PrimitiveGeoFeature.f001", f.getID());
      assertNull(f.getDefaultGeometry());

      assertNotNull(f.getAttribute("pointProperty"));
      Point p = (Point) f.getAttribute("pointProperty");

      assertEquals(39.73245, p.getX(), 0.1);
      assertEquals(2.00342, p.getY(), 0.1);

      Object intProperty = f.getAttribute("intProperty");
      assertNotNull(intProperty);
      assertTrue(intProperty.getClass().getName(), intProperty instanceof BigInteger);

      assertEquals(BigInteger.valueOf(155), intProperty);
      assertEquals(new URI("http://www.opengeospatial.org/"), f.getAttribute("uriProperty"));
      assertEquals(new Float(12765.0), f.getAttribute("measurand"));
      assertTrue(f.getAttribute("dateProperty") instanceof Date);
      assertEquals(BigDecimal.valueOf(5.03), f.getAttribute("decimalProperty"));
    } finally {
      features.close();
    }
  }