@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();
  }
  /**
   * <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;
  }
Exemple #3
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();
  }
  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();
    }
  }
  /**
   * 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();
 }
 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();
   }
 }
  @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();
    }
  }
  @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();
      }
    }
  }
  @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();
    }
  }
Exemple #12
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 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();
    }
  }
  @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();
  }
  @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();
  }
  @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();
      }
    }
  }
  @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();
    }
  }
  /**
   * Writing test that only engages against a remote geoserver.
   *
   * <p>Makes reference to the standard featureTypes that geoserver ships with. NOTE: Ignoring this
   * test for now because it edits topp:states and GeoServer doesn't return the correct Feature IDs
   * on transactions against shapefiles
   */
  @Test
  @Ignore
  public void testWrite()
      throws NoSuchElementException, IllegalFilterException, IOException,
          IllegalAttributeException {
    if (url == null) return;

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

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

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

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

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

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

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

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

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

      WFSDataStoreWriteOnlineTest.doDelete(post, ft, fp);
      WFSDataStoreWriteOnlineTest.doUpdate(post, ft, ATTRIBUTE_TO_EDIT, NEW_EDIT_VALUE);
      // assertFalse("events not fired", watcher.count == 0);
    } finally {
      try {
        ((SimpleFeatureStore) fs).removeFeatures(filterFac.not(startingFeatures));
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
    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();
 }
  private void run2(final Network network) throws Exception {
    log.info("running " + this.getClass().getName() + " module...");
    NetworkExpandNode neModule =
        new NetworkExpandNode(network, expansionRadius, this.linkSeparation);

    TreeMap<String, TreeMap<Integer, Id<Link>>> mSequences = new TreeMap<>();

    try (FileInputStream fis = new FileInputStream(this.mpDbfFileName)) {
      DbaseFileReader r =
          new DbaseFileReader(fis.getChannel(), true, IOUtils.CHARSET_WINDOWS_ISO88591);
      // get header indices
      int mpIdNameIndex = -1;
      int mpSeqNrNameIndex = -1;
      int mpTrpelIDNameIndex = -1;
      for (int i = 0; i < r.getHeader().getNumFields(); i++) {
        if (r.getHeader().getFieldName(i).equals(MP_ID_NAME)) {
          mpIdNameIndex = i;
        }
        if (r.getHeader().getFieldName(i).equals(MP_SEQNR_NAME)) {
          mpSeqNrNameIndex = i;
        }
        if (r.getHeader().getFieldName(i).equals(MP_TRPELID_NAME)) {
          mpTrpelIDNameIndex = i;
        }
      }
      if (mpIdNameIndex < 0) {
        throw new NoSuchFieldException("Field name '" + MP_ID_NAME + "' not found.");
      }
      if (mpSeqNrNameIndex < 0) {
        throw new NoSuchFieldException("Field name '" + MP_SEQNR_NAME + "' not found.");
      }
      if (mpTrpelIDNameIndex < 0) {
        throw new NoSuchFieldException("Field name '" + MP_TRPELID_NAME + "' not found.");
      }
      log.trace("  FieldName-->Index:");
      log.trace("    " + MP_ID_NAME + "-->" + mpIdNameIndex);
      log.trace("    " + MP_SEQNR_NAME + "-->" + mpSeqNrNameIndex);
      log.trace("    " + MP_TRPELID_NAME + "-->" + mpTrpelIDNameIndex);

      // create mp data structure
      // TreeMap<mpId,TreeMap<mpSeqNr,linkId>>
      log.info("  parsing meneuver paths dbf file...");
      while (r.hasNext()) {
        Object[] entries = r.readEntry();
        String mpId = entries[mpIdNameIndex].toString();
        int mpSeqNr = Integer.parseInt(entries[mpSeqNrNameIndex].toString());
        Id<Link> linkId = Id.create(entries[mpTrpelIDNameIndex].toString(), Link.class);
        TreeMap<Integer, Id<Link>> mSequence = mSequences.get(mpId);
        if (mSequence == null) {
          mSequence = new TreeMap<>();
          mSequences.put(mpId, mSequence);
        }
        if (mSequence.put(mpSeqNr, linkId) != null) {
          fis.close();
          throw new IllegalArgumentException(
              MP_ID_NAME + "=" + mpId + ": " + MP_SEQNR_NAME + " " + mpSeqNr + " already exists.");
        }
      }
      log.info("    " + mSequences.size() + " maneuvers sequences stored.");
      log.info("  done.");
      r.close();
    }

    // store the maneuver list of the nodes
    // TreeMap<NodeId,ArrayList<Tuple<MnId,MnFeatType>>>
    log.info("  parsing meneuver shape file...");
    TreeMap<Id<Node>, ArrayList<Tuple<String, Integer>>> maneuvers = new TreeMap<>();
    SimpleFeatureSource fs = ShapeFileReader.readDataFile(this.mnShpFileName);
    SimpleFeatureIterator fIt = fs.getFeatures().features();
    while (fIt.hasNext()) {
      SimpleFeature f = fIt.next();
      int featType = Integer.parseInt(f.getAttribute(MN_FEATTYP_NAME).toString());
      if ((featType == 2103) || (featType == 2102) || (featType == 2101)) {
        // keep 'Prohibited Maneuver' (2103), 'Restricted Maneuver' (2102) and 'Calculated/Derived
        // Prohibited Maneuver' (2101)
        Id<Node> nodeId = Id.create(f.getAttribute(MN_JNCTID_NAME).toString(), Node.class);
        ArrayList<Tuple<String, Integer>> ms = maneuvers.get(nodeId);
        if (ms == null) {
          ms = new ArrayList<>();
        }
        Tuple<String, Integer> m = new Tuple<>(f.getAttribute(MN_ID_NAME).toString(), featType);
        ms.add(m);
        maneuvers.put(nodeId, ms);
      } else if ((featType == 9401) || (featType == 2104)) {
        // ignore 'Bifurcation' (9401) and 'Priority Maneuver' (2104)
      } else {
        throw new IllegalArgumentException(
            "mnId="
                + f.getAttribute(MN_ID_NAME)
                + ": "
                + MN_FEATTYP_NAME
                + "="
                + featType
                + " not known.");
      }
    }
    fIt.close();
    log.info("    " + maneuvers.size() + " nodes with maneuvers stored.");
    log.info("  done.");

    // create a maneuver matrix for each given node and
    // expand those nodes
    log.info("  expand nodes according to the given manveuvers...");
    int nodesIgnoredCnt = 0;
    int nodesAssignedCnt = 0;
    int maneuverIgnoredCnt = 0;
    int maneuverAssignedCnt = 0;
    int virtualNodesCnt = 0;
    int virtualLinksCnt = 0;
    for (Map.Entry<Id<Node>, ArrayList<Tuple<String, Integer>>> entry : maneuvers.entrySet()) {
      Id<Node> nodeId = entry.getKey();
      if (network.getNodes().get(nodeId) == null) {
        log.trace(
            "  nodeid="
                + nodeId
                + ": maneuvers exist for that node but node is missing. Ignoring and proceeding anyway...");
        nodesIgnoredCnt++;
      } else {
        // node found
        Node n = network.getNodes().get(nodeId);
        // init maneuver matrix
        // TreeMap<fromLinkId,TreeMap<toLinkId,turnAllowed>>
        TreeMap<Id<Link>, TreeMap<Id<Link>, Boolean>> mmatrix = new TreeMap<>();
        // assign maneuvers for given node to the matrix
        ArrayList<Tuple<String, Integer>> ms = entry.getValue();
        for (Tuple<String, Integer> m : ms) {
          // get maneuver path sequence for given maneuver
          TreeMap<Integer, Id<Link>> mSequence = mSequences.get(m.getFirst());
          if (mSequence == null) {
            throw new Exception(
                "nodeid=" + nodeId + "; mnId=" + m.getFirst() + ": no maneuver sequence given.");
          }
          if (mSequence.size() < 2) {
            throw new Exception(
                "nodeid="
                    + nodeId
                    + "; mnId="
                    + m.getFirst()
                    + ": mSequenceSize="
                    + mSequence.size()
                    + " not alowed!");
          }
          // get the first element of the sequence, defining the start link for the maneuver
          Id<Link> firstLinkid = mSequence.values().iterator().next();
          // go through each other element (target link of the maneuver) of the sequence by sequence
          // number
          for (Id<Link> otherLinkId : mSequence.values()) {
            // get the start link and the target link of the maneuver
            Link inLink = n.getInLinks().get(Id.create(firstLinkid + "FT", Link.class));
            if (inLink == null) {
              inLink = n.getInLinks().get(Id.create(firstLinkid + "TF", Link.class));
            }
            Link outLink = n.getOutLinks().get(Id.create(otherLinkId + "FT", Link.class));
            if (outLink == null) {
              outLink = n.getOutLinks().get(Id.create(otherLinkId + "TF", Link.class));
            }
            if ((inLink != null) && (outLink != null)) {
              // start and target link found and they are incident to the given node
              if (m.getSecond() == 2102) {
                // restricted maneuver: given start and target link path is allowed to drive
                // store it to the matrix
                TreeMap<Id<Link>, Boolean> outLinkMap = mmatrix.get(inLink.getId());
                if (outLinkMap == null) {
                  outLinkMap = new TreeMap<>();
                }
                outLinkMap.put(outLink.getId(), Boolean.TRUE);
                mmatrix.put(inLink.getId(), outLinkMap);
              } else {
                // prohibited maneuver: given start and target link path is not allowed to drive
                // store it to the matrix
                TreeMap<Id<Link>, Boolean> outLinkMap = mmatrix.get(inLink.getId());
                if (outLinkMap == null) {
                  outLinkMap = new TreeMap<>();
                }
                outLinkMap.put(outLink.getId(), Boolean.FALSE);
                mmatrix.put(inLink.getId(), outLinkMap);
              }
              maneuverAssignedCnt++;
            } else {
              maneuverIgnoredCnt++;
            }
          }
        }
        // complete the matrix
        for (TreeMap<Id<Link>, Boolean> fromLinkEntry : mmatrix.values()) {
          // detect inlinks with restricted maneuvers
          boolean hasRestrictedManeuver = false;
          for (Boolean b : fromLinkEntry.values()) {
            if (b) {
              hasRestrictedManeuver = true;
            }
          }
          // add missing toLink maneuvers
          for (Id<Link> toLinkId : n.getOutLinks().keySet()) {
            if (!fromLinkEntry.containsKey(toLinkId)) {
              fromLinkEntry.put(toLinkId, !hasRestrictedManeuver);
            }
          }
        }
        // add allowed maneuvers for fromLinks which were not assigned yet.
        for (Id<Link> fromLinkId : n.getInLinks().keySet()) {
          if (!mmatrix.containsKey(fromLinkId)) {
            mmatrix.put(fromLinkId, new TreeMap<Id<Link>, Boolean>());
            for (Id<Link> toLinkId : n.getOutLinks().keySet()) {
              mmatrix.get(fromLinkId).put(toLinkId, Boolean.TRUE);
            }
          }
        }
        // remove all U-turns from the matrix
        if (this.removeUTurns) {
          for (Id<Link> fromLinkId : n.getInLinks().keySet()) {
            String str1 = fromLinkId.toString().substring(0, fromLinkId.toString().length() - 2);
            for (Id<Link> toLinkId : n.getOutLinks().keySet()) {
              String str2 = toLinkId.toString().substring(0, toLinkId.toString().length() - 2);
              if (str1.equals(str2)) {
                mmatrix.get(fromLinkId).put(toLinkId, Boolean.FALSE);
              }
            }
          }
        }
        // create arraylist with turn tuples
        ArrayList<TurnInfo> turns = new ArrayList<>();
        for (Map.Entry<Id<Link>, TreeMap<Id<Link>, Boolean>> fromLinkEntry : mmatrix.entrySet()) {
          Id<Link> fromLinkId = fromLinkEntry.getKey();
          for (Map.Entry<Id<Link>, Boolean> toLinkEntry : fromLinkEntry.getValue().entrySet()) {
            if (toLinkEntry.getValue()) {
              turns.add(new TurnInfo(fromLinkId, toLinkEntry.getKey()));
            }
          }
        }
        // expand the node
        Tuple<List<Node>, List<Link>> t = neModule.expandNode(nodeId, turns);
        virtualNodesCnt += t.getFirst().size();
        virtualLinksCnt += t.getSecond().size();
        nodesAssignedCnt++;
      }
    }
    log.info("    " + nodesAssignedCnt + " nodes expanded.");
    log.info("    " + maneuverAssignedCnt + " maneuvers assigned.");
    log.info("    " + virtualNodesCnt + " new nodes created.");
    log.info("    " + virtualLinksCnt + " new links created.");
    log.info(
        "    " + nodesIgnoredCnt + " nodes with given maneuvers (2103, 2102 or 2101) ignored.");
    log.info("    " + maneuverIgnoredCnt + " maneuvers ignored (while node was found).");
    log.info("  done.");
    log.info("done.");
  }
  private SimpleFeatureCollection createNewCollection(SimpleFeatureType simpleFeatureType) {
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
    SimpleFeatureIterator stationsIter = pOldVector.features();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType);

    // create the features.
    try {
      while (stationsIter.hasNext()) {
        SimpleFeature networkFeature = stationsIter.next();
        try {
          // add the geometry.
          builder.add(networkFeature.getDefaultGeometry());
          // add the ID.
          Integer field = ((Integer) networkFeature.getAttribute(TrentoPFeatureType.ID_STR));
          if (field == null) {

            throw new IllegalArgumentException();
          }
          builder.add(field);

          // add the area.
          Double value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DRAIN_AREA_STR));
          if (value == null) {

            throw new IllegalArgumentException();
          }
          builder.add(value);
          // add the percentage of the area which is dry.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.PERCENTAGE_OF_DRY_AREA));
          builder.add(value);
          // the pipes elevation is the elevation of the
          // terrain minus the depth.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DEPTH_INITIAL_PIPE_STR));
          builder.add(value);
          // the pipes elevation is the elevation of the
          // terrain minus the depth.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DEPTH_FINAL_PIPE_STR));
          builder.add(value);
          // add the runoff coefficent.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.RUNOFF_COEFFICIENT_STR));
          builder.add(value);
          // add the average residence time.
          value =
              ((Double) networkFeature.getAttribute(TrentoPFeatureType.AVERAGE_RESIDENCE_TIME_STR));
          builder.add(value);
          // add the ks.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.KS_STR));
          builder.add(value);
          // add the average slope.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.AVERAGE_SLOPE_STR));
          builder.add(value);
          // add the diameters.
          value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DIAMETER_STR));
          builder.add(value);
          // build the feature
          SimpleFeature feature = builder.buildFeature(null);
          featureCollection.add(feature);
        } catch (NullPointerException e) {
          throw new IllegalArgumentException();
        }
      }

    } finally {
      stationsIter.close();
    }

    return featureCollection;
  }
    private void initialize() {

      AttributeDescriptor attributeDescriptor =
          featureCollection.getSchema().getDescriptor(attributeName);
      if (attributeDescriptor == null) {
        throw new RuntimeException(attributeName + " not found");
      }

      Class<?> attClass = attributeDescriptor.getType().getBinding();
      if (!Number.class.isAssignableFrom(attClass)) {
        throw new RuntimeException(attributeName + " is not numeric type");
      }

      try {
        checkTransform();

        gridGeometry =
            new GridGeometry2D(
                new GridEnvelope2D(0, 0, coverageWidth, coverageHeight), coverageEnvelope);

        // NOTE:  assumes transformation results in equal length scales across both axes!
        if (mimimumLengthPixels > 0) {
          Point2D s0 = new Point(0, 0);
          Point2D d0 = gridGeometry.getGridToCRS2D().transform(s0, null);
          Point2D s1 = new Point(mimimumLengthPixels, 0);
          Point2D d1 = gridGeometry.getGridToCRS2D().transform(s1, null);
          minimumLengthMeters = d1.distance(d0);
        } else {
          minimumLengthMeters = -1;
        }

      } catch (TransformException ex) {
        throw new RuntimeException("Unable to transform", ex);
      }

      createImage();

      String featureCollectionId = featureCollection.getSchema().getName().getURI();

      baselineFeaturesMap = new LinkedHashMap<Integer, LinkedList<SimpleFeature>>();

      AttributeRange attributeRange = null;

      LOGGER.log(
          Level.INFO,
          "Calculating attribute value range for {}:{}",
          new Object[] {featureCollectionId, attributeName});
      SimpleFeatureIterator iterator = null;
      try {
        iterator = featureCollection.features();
        double minimum = Double.MAX_VALUE;
        double maximum = -Double.MAX_VALUE;
        while (iterator.hasNext()) {
          SimpleFeature feature = iterator.next();
          double value = ((Number) feature.getAttribute(attributeName)).doubleValue();
          if (Math.abs(value) < 1e10) {
            if (value > maximum) {
              maximum = value;
            }
            if (value < minimum) {
              minimum = value;
            }
          }

          Object baselineIdObject = feature.getAttribute(Constants.BASELINE_ID_ATTR);
          // this is needed for older files w/o baseline ID, null is a valid map key
          Integer baselineId =
              baselineIdObject instanceof Number ? ((Number) baselineIdObject).intValue() : null;
          LinkedList<SimpleFeature> baselineFeatures = baselineFeaturesMap.get(baselineId);
          if (baselineFeatures == null) {
            baselineFeatures = new LinkedList<SimpleFeature>();
            baselineFeaturesMap.put(baselineId, baselineFeatures);
          }
          baselineFeatures.add(feature);
        }
        if (minimum < maximum) {
          attributeRange = new AttributeRange(minimum, maximum);
          LOGGER.log(
              Level.INFO,
              "Attribute value range for {}:{} {}",
              new Object[] {featureCollectionId, attributeName, attributeRange});
        }
      } finally {
        if (iterator != null) {
          iterator.close();
        }
      }
      if (attributeRange != null) {
        attributeRange =
            (attributeRange.min < 0)
                ? attributeRange.zeroInflect(invert)
                : invert
                    ? new AttributeRange(attributeRange.max, 0)
                    : new AttributeRange(0, attributeRange.max);
        colorMap = new JetColorMap(attributeRange);
      }
    }
 @Override
 public void close() throws IOException {
   featureIterator.close();
 }
  private SimpleFeatureCollection calculateRisk(
      SimpleFeatureCollection features,
      JDBCDataStore dataStore,
      String storeName,
      Integer precision,
      String connectionParams,
      int processing,
      int formula,
      int target,
      String materials,
      String scenarios,
      String entities,
      String severeness,
      String fpfield,
      int batch,
      boolean simulation,
      Geometry damageArea,
      Map<Integer, Double> damageValues,
      List<TargetInfo> changedTargets,
      Map<Integer, Map<Integer, Double>> cffs,
      List<String> psc,
      Map<Integer, Map<Integer, Double>> padrs,
      Map<Integer, Double> piss,
      List<Integer> distances,
      boolean extendedSchema)
      throws IOException, SQLException {

    if (precision == null) {
      precision = 3;
    }

    DefaultTransaction transaction = new DefaultTransaction();
    Connection conn = null;
    try {
      conn = dataStore.getConnection(transaction);

      // output FeatureType (risk)
      //  - id_geo_arco
      //  - geometria
      //  - rischio1
      //  - rischio2
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.add(
          "id_geo_arco", features.getSchema().getDescriptor("id_geo_arco").getType().getBinding());
      tb.add(
          "geometria",
          MultiLineString.class,
          features.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem());

      if (extendedSchema) {
        tb.add("rischio_sociale", Double.class);
        tb.add("rischio_ambientale", Double.class);
        tb.add("nr_corsie", Integer.class);
        tb.add("lunghezza", Integer.class);
        tb.add("nr_incidenti", Integer.class);
      } else {
        tb.add("rischio1", Double.class);
        tb.add("rischio2", Double.class);
      }
      // fake layer name (risk) used for WPS output. Layer risk must be defined in GeoServer
      // catalog
      tb.setName(new NameImpl(features.getSchema().getName().getNamespaceURI(), "risk"));
      SimpleFeatureType ft = tb.buildFeatureType();

      // feature level (1, 2, 3)
      int level = FormulaUtils.getLevel(features);

      LOGGER.info("Doing calculus for level " + level);

      Formula formulaDescriptor = Formula.load(conn, processing, formula, target);

      if (formulaDescriptor == null) {
        throw new ProcessException("Unable to load formula " + formula);
      }

      if (((!formulaDescriptor.hasGrid() && level == 3)
              || (!formulaDescriptor.hasNoGrid() && level < 3))
          && !extendedSchema) {
        LOGGER.info("Formula not supported on this level, returning empty collection");
        return new EmptyFeatureCollection(ft);
      } else {
        // iterator on source
        SimpleFeatureIterator iter = features.features();

        // result builder
        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(ft);
        ListFeatureCollection result = new ListFeatureCollection(ft);
        int count = 0;
        Double[] risk = new Double[] {0.0, 0.0};

        // iterate source features
        try {
          // we will calculate risk in batch of arcs
          // we store each feature of the batch in a map
          // indexed by id
          Map<Number, SimpleFeature> temp = new HashMap<Number, SimpleFeature>();
          StringBuilder ids = new StringBuilder();
          String fk_partner = null;

          while (iter.hasNext()) {
            SimpleFeature feature = iter.next();
            Number id = (Number) feature.getAttribute("id_geo_arco");
            fk_partner = (String) feature.getAttribute("fk_partner");
            fb.add(id);
            fb.add(feature.getDefaultGeometry());
            if (formulaDescriptor.takeFromSource()) {
              risk[0] = ((Number) feature.getAttribute("rischio1")).doubleValue();
              risk[1] = ((Number) feature.getAttribute("rischio2")).doubleValue();
            }
            fb.add(risk[0]);
            fb.add(risk[1]);
            if (extendedSchema) {
              fb.add((Number) feature.getAttribute("nr_corsie"));
              fb.add((Number) feature.getAttribute("lunghezza"));
              fb.add((Number) feature.getAttribute("nr_incidenti"));
            }
            temp.put(id.intValue(), fb.buildFeature(id + ""));

            if (simulation) {
              Double pis = piss.get(id.intValue());
              Map<Integer, Double> padr = padrs.get(id.intValue());
              Map<Integer, Double> cff = cffs.get(id.intValue());

              Map<Integer, Map<Integer, Double>> simulationTargets =
                  new HashMap<Integer, Map<Integer, Double>>();

              if (!changedTargets.isEmpty()) {
                for (int distance : distances) {
                  Geometry buffer =
                      BufferUtils.iterativeBuffer(
                          (Geometry) feature.getDefaultGeometry(), (double) distance, 100);
                  for (TargetInfo targetInfo : changedTargets) {
                    if (targetInfo.getGeometry() != null) {
                      Geometry intersection = buffer.intersection(targetInfo.getGeometry());
                      if (intersection != null && intersection.getArea() > 0) {
                        Map<Integer, Double> distancesMap =
                            simulationTargets.get(targetInfo.getType());
                        if (distancesMap == null) {
                          distancesMap = new HashMap<Integer, Double>();
                          simulationTargets.put(targetInfo.getType(), distancesMap);
                        }
                        double value = 0.0;
                        if (targetInfo.isHuman()) {
                          value =
                              intersection.getArea()
                                  / targetInfo.getGeometry().getArea()
                                  * targetInfo.getValue();
                        } else {
                          value = intersection.getArea();
                        }
                        if (targetInfo.isRemoved()) {
                          value = -value;
                        }
                        distancesMap.put(distance, value);
                      }
                    }
                  }
                }
              }

              FormulaUtils.calculateSimulationFormulaValuesOnSingleArc(
                  conn,
                  level,
                  processing,
                  formulaDescriptor,
                  id.intValue(),
                  fk_partner,
                  materials,
                  scenarios,
                  entities,
                  severeness,
                  fpfield,
                  target,
                  simulationTargets,
                  temp,
                  precision,
                  cff,
                  psc,
                  padr,
                  pis,
                  null,
                  extendedSchema);

              result.addAll(temp.values());
              temp = new HashMap<Number, SimpleFeature>();
            } else if (damageArea != null) {
              Geometry arcGeometry = (Geometry) feature.getDefaultGeometry();
              if (arcGeometry != null && arcGeometry.intersects(damageArea)) {
                FormulaUtils.calculateSimulationFormulaValuesOnSingleArc(
                    conn,
                    level,
                    processing,
                    formulaDescriptor,
                    id.intValue(),
                    fk_partner,
                    materials,
                    scenarios,
                    entities,
                    severeness,
                    fpfield,
                    target,
                    null,
                    temp,
                    precision,
                    null,
                    null,
                    null,
                    null,
                    damageValues,
                    extendedSchema);
                result.addAll(temp.values());
              }
              temp = new HashMap<Number, SimpleFeature>();
            } else {
              ids.append("," + id);
              count++;
              // calculate batch items a time
              if (count % batch == 0) {
                LOGGER.info("Calculated " + count + " values");
                FormulaUtils.calculateFormulaValues(
                    conn,
                    level,
                    processing,
                    formulaDescriptor,
                    ids.toString().substring(1),
                    fk_partner,
                    materials,
                    scenarios,
                    entities,
                    severeness,
                    fpfield,
                    target,
                    temp,
                    precision,
                    extendedSchema);
                result.addAll(temp.values());
                ids = new StringBuilder();
                temp = new HashMap<Number, SimpleFeature>();
              }
            }
          }

          // final calculus for remaining items not in batch size
          LOGGER.info("Calculating remaining items");
          if (ids.length() > 0) {
            FormulaUtils.calculateFormulaValues(
                conn,
                level,
                processing,
                formulaDescriptor,
                ids.toString().substring(1),
                fk_partner,
                materials,
                scenarios,
                entities,
                severeness,
                fpfield,
                target,
                temp,
                precision,
                extendedSchema);
          }
          result.addAll(temp.values());

          LOGGER.info("Calculated " + result.size() + " values");

        } finally {
          iter.close();
        }
        return result;
      }

    } finally {
      transaction.close();
      if (conn != null) {
        conn.close();
      }
    }
  }
  @Override
  /**
   * inputData a HashMap of the input data:
   *
   * @param inputObservations: the observations
   * @param inputAuthoritativeData: the polygons
   * @param bufferSize: the size of the buffer around the polygons results a HashpMap of the
   *     results:
   * @result result: the input data with the polygon attributes attached, null values for no match
   * @result qual_result: the matched input only data with polygon attributes attached
   */
  public Map<String, IData> run(Map<String, List<IData>> inputData) throws ExceptionReport {

    HashMap<String, Object> metadataMap = new HashMap<String, Object>();
    ArrayList<SimpleFeature> list = new ArrayList<SimpleFeature>();
    List<IData> inputObs = inputData.get("inputObservations");
    List<IData> inputAuth = inputData.get("inputAuthoritativeData");
    List<IData> inputLit = inputData.get("bufferSize");
    IData observations = inputObs.get(0);
    IData authoritative = inputAuth.get(0);

    IData buffersize = inputLit.get(0);

    double doubleB = (Double) buffersize.getPayload();

    FeatureCollection obsFC = ((GTVectorDataBinding) observations).getPayload();
    FeatureCollection authFC = ((GTVectorDataBinding) authoritative).getPayload();

    SimpleFeatureIterator obsIt = (SimpleFeatureIterator) obsFC.features();

    SimpleFeatureIterator authIt = (SimpleFeatureIterator) authFC.features();

    // setup result feature

    SimpleFeature obsItFeat = obsIt.next();

    SimpleFeature obsItAuth = authIt.next();

    Collection<Property> property = obsItFeat.getProperties();
    Collection<Property> authProperty = obsItAuth.getProperties();

    // setup result type builder
    SimpleFeatureTypeBuilder resultTypeBuilder = new SimpleFeatureTypeBuilder();
    resultTypeBuilder.setName("typeBuilder");

    Iterator<Property> pItObs = property.iterator();
    Iterator<Property> pItAuth = authProperty.iterator();

    metadataMap.put("element", "elementBufferedMetadata");
    File metadataFile = createXMLMetadata(metadataMap);

    while (pItObs.hasNext() == true) {

      try {
        Property tempProp = pItObs.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        resultTypeBuilder.add(name, valueClass);

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }
    int i = 0;
    while (pItAuth.hasNext() == true) {
      try {
        Property tempProp = pItAuth.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        if (i > 3) {

          resultTypeBuilder.add(name, valueClass);
        }

        i++;

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }

    obsIt.close();
    authIt.close();
    resultTypeBuilder.add("withinBuffer", Integer.class);

    // set up result feature builder

    SimpleFeatureType type = resultTypeBuilder.buildFeatureType();
    SimpleFeatureBuilder resultFeatureBuilder = new SimpleFeatureBuilder(type);

    // process data here:

    SimpleFeatureIterator obsIt2 = (SimpleFeatureIterator) obsFC.features();

    int within = 0;

    FeatureCollection resultFeatureCollection = DefaultFeatureCollections.newCollection();

    while (obsIt2.hasNext() == true) {
      within = 0;
      SimpleFeature tempObs = obsIt2.next();
      Geometry obsGeom = (Geometry) tempObs.getDefaultGeometry();

      for (Property obsProperty : tempObs.getProperties()) {

        String name = obsProperty.getName().getLocalPart();
        Object value = obsProperty.getValue();

        resultFeatureBuilder.set(name, value);
        // LOGGER.warn("obs Property set " + name);
      }

      double bufferSizeDouble = doubleB;

      Geometry bufferGeom = obsGeom.buffer(bufferSizeDouble);

      int j = 0;
      SimpleFeatureIterator authIt2 = (SimpleFeatureIterator) authFC.features();
      while (authIt2.hasNext() == true) {

        SimpleFeature tempAuth = authIt2.next();
        Geometry authGeom = (Geometry) tempAuth.getDefaultGeometry();

        if (bufferGeom.intersects(authGeom) == true) {
          within = 1;
          j = 0;

          LOGGER.warn("Intersection = true");
          for (Property authProperty1 : tempAuth.getProperties()) {

            String name = authProperty1.getName().getLocalPart();
            Object value = authProperty1.getValue();
            // Class valueClass = (Class<String>)authProperty1.getType().getBinding();

            //		LOGGER.warn("Auth property " + name);
            if (j > 3) {
              resultFeatureBuilder.set(name, value);
              //	LOGGER.warn("Auth property set " + name);

            }

            j++;
          }
        }
      }
      resultFeatureBuilder.set("withinBuffer", within);

      SimpleFeature resultFeature = resultFeatureBuilder.buildFeature(tempObs.getName().toString());
      Geometry geom = (Geometry) tempObs.getDefaultGeometry();
      resultFeature.setDefaultGeometry(geom);

      list.add(resultFeature);

      // resultFeatureCollection.add(resultFeature);
      // LOGGER.warn("RESULT FEATURE " + resultFeatureCollection.getSchema().toString());
      // resultFeatureCollection = obsFC;
    }

    ListFeatureCollection listFeatureCollection = new ListFeatureCollection(type, list);
    LOGGER.warn("Result Feature Size " + listFeatureCollection.size());

    // sort HashMap
    GenericFileData gf = null;
    try {
      gf = new GenericFileData(metadataFile, "text/xml");
    } catch (IOException e) {
      LOGGER.error("GenericFileData " + e);
    }

    HashMap<String, IData> results = new HashMap<String, IData>();
    results.put("result", new GTVectorDataBinding((FeatureCollection) obsFC));
    results.put("qual_result", new GTVectorDataBinding((FeatureCollection) listFeatureCollection));
    results.put("metadata", new GenericFileDataBinding(gf));

    return results;
  }
  @Override
  /**
   * @param inputData a HashMap of the input data: inputObservations: the observations
   *     inputAuthoritativeData: the authoritative points inputDistance: the distance threshold
   *     minNumber: the minimum number of named features to pass fieldName: the name of the field
   *     within the observations to match
   * @result results a HashpMap of the results: result: the input data with the polygon attributes
   *     attached, null values for no match qual_result: the matched input only data with polygon
   *     attributes attached
   */
  public Map<String, IData> run(Map<String, List<IData>> inputData) throws ExceptionReport {

    List obsList = inputData.get("inputObservations");
    List authList = inputData.get("inputAuthoritativeData");
    List distList = inputData.get("inputDistance");
    List minList = inputData.get("minNumber");
    List fieldList = inputData.get("fieldName");

    FeatureCollection obsFc = ((GTVectorDataBinding) obsList.get(0)).getPayload();
    FeatureCollection authFc = ((GTVectorDataBinding) authList.get(0)).getPayload();
    double dist = ((LiteralDoubleBinding) distList.get(0)).getPayload();
    int minNum = ((LiteralIntBinding) minList.get(0)).getPayload();
    String fieldName = ((LiteralStringBinding) fieldList.get(0)).getPayload();

    ArrayList<SimpleFeature> resultFeatures = new ArrayList<SimpleFeature>();
    ArrayList<SimpleFeature> returnFeatures = new ArrayList<SimpleFeature>();

    SimpleFeatureIterator obsIt = (SimpleFeatureIterator) obsFc.features();
    SimpleFeatureIterator authIt = (SimpleFeatureIterator) authFc.features();

    SimpleFeatureIterator sfi = (SimpleFeatureIterator) obsFc.features();
    SimpleFeatureType fType = null;
    SimpleFeature tempPropFeature = sfi.next();
    CoordinateReferenceSystem inputObsCrs = obsFc.getSchema().getCoordinateReferenceSystem();

    Collection<Property> obsProp = tempPropFeature.getProperties();

    SimpleFeatureTypeBuilder resultTypeBuilder = new SimpleFeatureTypeBuilder();
    resultTypeBuilder.setName("typeBuilder");
    resultTypeBuilder.setCRS(inputObsCrs);

    Iterator<Property> pItObs = obsProp.iterator();

    sfi.close();
    while (pItObs.hasNext() == true) {

      try {

        Property tempProp = pItObs.next();
        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        resultTypeBuilder.add(name, valueClass);

        // LOG.warn ("Obs property " + name + " " + valueClass + " " +type.toString());
      } catch (Exception e) {
        LOG.error("property error " + e);
      }
    }

    // add DQ_Field

    resultTypeBuilder.add("DQ_SA_SimilarF", Double.class);
    SimpleFeatureType typeF = resultTypeBuilder.buildFeatureType();
    // LOG.warn("Get Spatial Accuracy Feature Type " + typeF.toString());

    SimpleFeatureBuilder resultFeatureBuilder = new SimpleFeatureBuilder(typeF);

    obsIt.close();

    SimpleFeatureIterator obsIt2 = (SimpleFeatureIterator) obsFc.features();

    while (obsIt2.hasNext()) {
      SimpleFeature tempFeature = obsIt2.next();

      fType = tempFeature.getType();

      // LOG.warn("fieldName " + fieldName + " featureName " + featureN + " tempFeature Type " +
      // fType);
      // LOG.warn("TableFeatureName " + tempFeature.getProperty(fieldName).getValue());

      String tempFeatureName = (String) tempFeature.getProperty(fieldName).getValue();

      Geometry geom = (Geometry) tempFeature.getDefaultGeometry();
      for (Property obsProperty : tempFeature.getProperties()) {

        String name = obsProperty.getName().toString();
        Object value = obsProperty.getValue();

        resultFeatureBuilder.set(name, value);
      }

      Geometry bufferGeom = geom.buffer(dist);

      SimpleFeatureIterator authIt2 = (SimpleFeatureIterator) authFc.features();

      int count = 0;
      int within = 0;

      while (authIt2.hasNext() && count <= minNum) {
        SimpleFeature tempAuth = authIt2.next();
        String featureN = (String) tempAuth.getProperty(fieldName).getValue();

        Geometry tempGeom = (Geometry) tempAuth.getDefaultGeometry();

        String authProperty = (String) tempAuth.getProperty(fieldName).getValue();

        if (tempGeom.within(bufferGeom) && authProperty.equalsIgnoreCase(featureN)) {

          count++;

          if (count >= minNum) {
            within = 1;
          }
        }
      }
      LOG.warn("HERE " + within);
      resultFeatureBuilder.set("DQ_SA_SimilarF", within);

      SimpleFeature result = resultFeatureBuilder.buildFeature(tempFeature.getID());
      result.setDefaultGeometry(geom);
      LOG.warn("HERE " + result);
      returnFeatures.add(result);

      if (within == 1) {
        resultFeatures.add(result);
      }

      authIt2.close();
    }
    obsIt2.close();

    ListFeatureCollection qualResult = new ListFeatureCollection(fType, resultFeatures);
    ListFeatureCollection returns = new ListFeatureCollection(fType, returnFeatures);

    LOG.warn("HERE 2 " + qualResult.size() + " " + returns.size());

    Map<String, IData> results = new HashMap<String, IData>();
    results.put("qual_result", new GTVectorDataBinding(qualResult));
    results.put("result", new GTVectorDataBinding(returns));

    return results;
  }
  @Execute
  /**
   * inputData a HashMap of the input data:
   *
   * @param inputObservations: the observations
   * @param inputAuthoritativeData: the polygons
   * @param bufferSize: the size of the buffer in the same units as the input data (degrees for
   *     lat/long) results a HashpMap of the results:
   * @result result: the input data with the polygon attributes attached, null values for no match
   * @result qual_result: the matched input only data with polygon attributes attached
   * @result metadata: an unused output that was supposed to return an XML document for GeoNetwork
   */
  public void runBuffer() {

    Logger LOGGER = Logger.getLogger(BufferAuthoritativeDataComparison.class);

    SimpleFeatureIterator obsIt = (SimpleFeatureIterator) obsFC.features();

    SimpleFeatureIterator authIt = (SimpleFeatureIterator) authFC.features();

    // setup result feature

    SimpleFeature obsItFeat = obsIt.next();

    SimpleFeature obsItAuth = authIt.next();

    Collection<Property> property = obsItFeat.getProperties();
    Collection<Property> authProperty = obsItAuth.getProperties();

    // setup result type builder
    SimpleFeatureTypeBuilder resultTypeBuilder = new SimpleFeatureTypeBuilder();
    resultTypeBuilder.setName("typeBuilder");

    Iterator<Property> pItObs = property.iterator();
    Iterator<Property> pItAuth = authProperty.iterator();

    metadataMap.put("element", "elementBufferedMetadata");
    metadataFile = createXMLMetadata(metadataMap);

    while (pItObs.hasNext() == true) {

      try {
        Property tempProp = pItObs.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        resultTypeBuilder.add(name, valueClass);

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }
    int i = 0;
    while (pItAuth.hasNext() == true) {
      try {
        Property tempProp = pItAuth.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        if (i > 3) {

          resultTypeBuilder.add(name, valueClass);
        }

        i++;

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }

    obsIt.close();
    authIt.close();
    resultTypeBuilder.add("withinBuffer", Integer.class);

    // set up result feature builder

    SimpleFeatureType type = resultTypeBuilder.buildFeatureType();
    SimpleFeatureBuilder resultFeatureBuilder = new SimpleFeatureBuilder(type);

    // process data here:

    SimpleFeatureIterator obsIt2 = (SimpleFeatureIterator) obsFC.features();

    int within = 0;

    resultFeatureCollection = DefaultFeatureCollections.newCollection();

    while (obsIt2.hasNext() == true) {
      within = 0;
      SimpleFeature tempObs = obsIt2.next();
      Geometry obsGeom = (Geometry) tempObs.getDefaultGeometry();

      for (Property obsProperty : tempObs.getProperties()) {

        String name = obsProperty.getName().getLocalPart();
        Object value = obsProperty.getValue();

        resultFeatureBuilder.set(name, value);
        // LOGGER.warn("obs Property set " + name);
      }

      double bufferSizeDouble = Double.parseDouble(bufferSize);

      Geometry bufferGeom = obsGeom.buffer(bufferSizeDouble);

      int j = 0;
      SimpleFeatureIterator authIt2 = (SimpleFeatureIterator) authFC.features();
      while (authIt2.hasNext() == true) {

        SimpleFeature tempAuth = authIt2.next();
        Geometry authGeom = (Geometry) tempAuth.getDefaultGeometry();

        if (bufferGeom.intersects(authGeom) == true) {
          within = 1;
          j = 0;

          LOGGER.warn("Intersection = true");
          for (Property authProperty1 : tempAuth.getProperties()) {

            String name = authProperty1.getName().getLocalPart();
            Object value = authProperty1.getValue();
            // Class valueClass = (Class<String>)authProperty1.getType().getBinding();

            //		LOGGER.warn("Auth property " + name);
            if (j > 3) {
              resultFeatureBuilder.set(name, value);
              //	LOGGER.warn("Auth property set " + name);

            }

            j++;
          }
        }
      }
      resultFeatureBuilder.set("withinBuffer", within);

      SimpleFeature resultFeature = resultFeatureBuilder.buildFeature(tempObs.getName().toString());
      Geometry geom = (Geometry) tempObs.getDefaultGeometry();
      resultFeature.setDefaultGeometry(geom);

      list.add(resultFeature);

      // resultFeatureCollection.add(resultFeature);
      // LOGGER.warn("RESULT FEATURE " + resultFeatureCollection.getSchema().toString());
      // resultFeatureCollection = obsFC;
    }

    listFeatureCollection = new ListFeatureCollection(type, list);
    LOGGER.warn("Result Feature Size " + listFeatureCollection.size());
  }