Ejemplo n.º 1
0
  /**
   * <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;
  }
Ejemplo n.º 2
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();
  }
Ejemplo 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();
  }
Ejemplo n.º 5
0
  /**
   * 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();
      }
    }
  }
Ejemplo n.º 6
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());
    }
  }
 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();
 }
Ejemplo n.º 8
0
 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();
   }
 }
Ejemplo n.º 9
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();
   }
 }
    @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);
    }
Ejemplo n.º 11
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();
      }
    }
  }
Ejemplo n.º 12
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;
  }
Ejemplo n.º 13
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();
    }
  }
Ejemplo n.º 14
0
 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();
   }
 }
Ejemplo n.º 15
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();
  }
Ejemplo n.º 16
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++;
    }
  }
Ejemplo n.º 17
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();
      }
    }
  }
Ejemplo n.º 18
0
  @Override
  public void draw(MapGraphicContext context) {

    // Initialize
    ILayer graticule = context.getLayer();
    GraticuleStyle style = GraticuleStyle.getStyle(graticule);

    // Ensure CRS?
    if (graticule instanceof Layer) {
      // Initialize CRS?
      if (style.isInitCRS()) {
        // Only initialize once
        style.setInitCRS(false);
        // Apply CRS from context
        GraticuleCRSConfigurator.apply((Layer) graticule, context.getCRS());
      } else if (mismatch(graticule, style)) {
        // Apply CRS from
        GraticuleCRSConfigurator.apply((Layer) graticule, style.getCRS());
      }
    }

    // Sanity checks
    if (MAX_SCALE < context.getMap().getViewportModel().getScaleDenominator()) {
      graticule.setStatus(ILayer.ERROR);
      graticule.setStatusMessage(Messages.GraticuleGraphic_Maximum_Scale + MAX_SCALE);
      return;
    }
    Unit<?> unit = CRSUtilities.getUnit(graticule.getCRS().getCoordinateSystem());
    if (!SI.METER.equals(unit)) {
      graticule.setStatus(ILayer.ERROR);
      graticule.setStatusMessage(Messages.GraticuleGraphic_Illegal_CRS);
      return;
    }
    final IWorkbench workbench = PlatformUI.getWorkbench();
    if (workbench == null) return;

    // Start working on layer
    graticule.setStatus(ILayer.WORKING);
    graticule.setStatusMessage(null);

    // Get display to work on
    final Display display = workbench.getDisplay();

    // Set styles
    Font plain = GraticuleStyle.getFontStyle(context).getFont();
    Font bold = plain.deriveFont(Font.BOLD);

    // Initialize the graphics handle
    ViewportGraphics g = context.getGraphics();

    // Set font size
    g.setFont(bold);

    // Get bounds of viewport
    ReferencedEnvelope bounds = context.getViewportModel().getBounds();

    try {

      // Get square size limited to minimum size of 100 pixels
      double size = size(context, unit, 100);

      // Sanity check
      if (size < 100) return;

      // Convert square size to pixels
      int sx = (int) (size / context.getViewportModel().getPixelSize().x);
      int sy = (int) (size / context.getViewportModel().getPixelSize().y);

      // Make transform from Graticule to map CRS
      MathTransform transform = CRS.findMathTransform(graticule.getCRS(), context.getCRS(), false);

      // Transform bounds into Graticule CRS
      bounds = bounds.transform(graticule.getCRS(), true);

      // Get squares inside bounds
      SimpleFeatureIterator it = squares(bounds, size);

      // Draw one squares at the time (only top and left lines are drawn)
      while (it.hasNext()) {

        // Initialize states
        int i = 0;
        Point current = null;

        // Initialize lines
        List<Line> lines = new ArrayList<Line>(2);
        List<Label> labels = new ArrayList<Label>(2);

        // Get next geometry
        Geometry geom = (Geometry) it.next().getDefaultGeometry();

        // Get coordinates in graticule CRS
        Coordinate[] coords = geom.getCoordinates();

        // Get x-coordinate label from upper left corner
        String tx = getLabel(coords[0].x, size, unit, style);

        // Get y-coordinate label from lower left corner
        String ty = getLabel(coords[2].y, size, unit, style);

        // Insert gap with label?
        boolean vgap = isGap(tx, unit, style);
        boolean hgap = isGap(ty, unit, style);

        // Transform coordinates into Map CRS
        coords = JTS.transform(geom, transform).getCoordinates();

        // Create lines and labels for this square
        for (Coordinate c : coords) {

          // Build paths
          switch (i) {
            case 1:

              // -----------------------
              // Vertical line
              // -----------------------

              // Create line path
              current =
                  vert(
                      display,
                      g,
                      sy,
                      style.getLineWidth(),
                      current,
                      context.worldToPixel(c),
                      hgap,
                      vgap,
                      lines);

              // Add xx label?
              if (hgap) {
                labels.add(new Label(current, tx, vgap ? bold : plain));
                current = context.worldToPixel(c);
              }

              break;
            case 2:

              // -----------------------
              // Horizontal line
              // -----------------------

              // Create line path
              current =
                  horz(
                      display,
                      g,
                      sx,
                      style.getLineWidth(),
                      current,
                      context.worldToPixel(c),
                      vgap,
                      hgap,
                      lines);

              // Add yy label?
              if (vgap) {
                labels.add(new Label(current, ty, hgap ? bold : plain));
                current = context.worldToPixel(c);
              }

              break;

            default:
              current = context.worldToPixel(c);
              break;
          }
          i++;
        }

        // Draw lines
        for (Line line : lines) line.draw(g, style);

        // Draw labels?
        if (style.isShowLabels()) for (Label label : labels) label.draw(g, style);
      }

      // // Get lower left corner coordinates
      // int x = llc.x;
      // int y = llc.y;
      //
      // // Print borders
      // g.setColor(lc);
      // g.setStroke(ViewportGraphics.LINE_SOLID, 5);
      //
      // // Inner rectangle
      // g.drawRect(x + d + l, y + d + l, w - 2 * (d + l), h - 2 * (d + l));
      //
      // // Make white border
      // g.setColor(Color.WHITE);
      //
      // // Left
      // g.drawRect(x, y, d, h);
      // g.fillRect(x, y, d, h);
      //
      // // Bottom
      // g.drawRect(x, y, w, d);
      // g.fillRect(x, y, w, d);
      //
      // // Right
      // g.drawRect(x + w - d, y, d, h);
      // g.fillRect(x + w - d, y, d, h);
      //
      // // Top
      // g.drawRect(x, y + h - d, w, d);
      // g.fillRect(x, y + h - d, w, d);

    } catch (IOException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    } catch (FactoryException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    } catch (MismatchedDimensionException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    } catch (TransformException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    }

    // Finished working on layer
    graticule.setStatus(ILayer.DONE);
  }
    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;
    }
 @Override
 public boolean hasNext() {
   return featureIterator.hasNext() || cachedNext != null;
 }
Ejemplo n.º 21
0
  @Test
  public void testInfiniteLoopAvoidance() throws Exception {
    final Exception sentinel =
        new RuntimeException("This is the one that should be thrown in hasNext()");

    // setup the mock necessary to have the renderer hit into the exception in hasNext()
    SimpleFeatureIterator it2 = createNiceMock(SimpleFeatureIterator.class);
    expect(it2.hasNext()).andThrow(sentinel).anyTimes();
    replay(it2);

    SimpleFeatureCollection fc = createNiceMock(SimpleFeatureCollection.class);
    expect(fc.features()).andReturn(it2);
    expect(fc.size()).andReturn(200);
    expect(fc.getSchema()).andReturn(testLineFeatureType).anyTimes();
    replay(fc);

    SimpleFeatureSource fs = createNiceMock(SimpleFeatureSource.class);
    expect(fs.getFeatures((Query) anyObject())).andReturn(fc);
    expect(fs.getSchema()).andReturn(testLineFeatureType).anyTimes();
    expect(fs.getSupportedHints()).andReturn(new HashSet()).anyTimes();
    replay(fs);

    // build map context
    MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
    mapContext.addLayer(fs, createLineStyle());

    // setup the renderer and listen for errors
    final StreamingRenderer sr = new StreamingRenderer();
    sr.setContext(mapContext);
    sr.addRenderListener(
        new RenderListener() {
          public void featureRenderer(SimpleFeature feature) {
            features++;
          }

          public void errorOccurred(Exception e) {
            errors++;

            if (errors > 2) {
              // we dont' want to block the loop in case of regression on this bug
              sr.stopRendering();
            }

            // but we want to make sure we're getting
            Throwable t = e;
            while (t != sentinel && t.getCause() != null) t = t.getCause();
            assertSame(sentinel, t);
          }
        });
    errors = 0;
    features = 0;
    BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR);
    ReferencedEnvelope reWgs =
        new ReferencedEnvelope(new Envelope(-180, -170, 20, 40), DefaultGeographicCRS.WGS84);
    sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200), reWgs);

    // we should get two errors since there are two features that cannot be
    // projected but the renderer itself should not throw exceptions
    assertEquals(0, features);
    assertEquals(1, errors);
  }
Ejemplo n.º 22
0
  /**
   * Writing test that only engages against a remote geoserver.
   *
   * <p>Makes reference to the standard featureTypes that geoserver ships with. NOTE: Ignoring this
   * test for now because it edits topp:states and GeoServer doesn't return the correct Feature IDs
   * on transactions against shapefiles
   */
  @Test
  @Ignore
  public void testWrite()
      throws NoSuchElementException, IllegalFilterException, IOException,
          IllegalAttributeException {
    if (url == null) return;

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

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

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

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

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

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

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

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

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

      WFSDataStoreWriteOnlineTest.doDelete(post, ft, fp);
      WFSDataStoreWriteOnlineTest.doUpdate(post, ft, ATTRIBUTE_TO_EDIT, NEW_EDIT_VALUE);
      // assertFalse("events not fired", watcher.count == 0);
    } finally {
      try {
        ((SimpleFeatureStore) fs).removeFeatures(filterFac.not(startingFeatures));
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
  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.");
  }
  @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;
  }
Ejemplo n.º 25
0
 public boolean hasNext() {
   return delegate.hasNext();
 }
  @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;
  }
Ejemplo n.º 27
0
    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);
      }
    }
Ejemplo n.º 28
0
  @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();
    }
  }
  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;
  }
Ejemplo n.º 30
0
  private SimpleFeatureType importDataIntoStore(
      SimpleFeatureCollection features, String name, DataStoreInfo storeInfo)
      throws IOException, ProcessException {
    SimpleFeatureType targetType;
    // grab the data store
    DataStore ds = (DataStore) storeInfo.getDataStore(null);

    // decide on the target ft name
    SimpleFeatureType sourceType = features.getSchema();
    if (name != null) {
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.init(sourceType);
      tb.setName(name);
      sourceType = tb.buildFeatureType();
    }

    // create the schema
    ds.createSchema(sourceType);

    // try to get the target feature type (might have slightly different
    // name and structure)
    targetType = ds.getSchema(sourceType.getTypeName());
    if (targetType == null) {
      // ouch, the name was changed... we can only guess now...
      // try with the typical Oracle mangling
      targetType = ds.getSchema(sourceType.getTypeName().toUpperCase());
    }

    if (targetType == null) {
      throw new WPSException(
          "The target schema was created, but with a name "
              + "that we cannot relate to the one we provided the data store. Cannot proceeed further");
    } else {
      // check the layer is not already there
      String newLayerName = storeInfo.getWorkspace().getName() + ":" + targetType.getTypeName();
      LayerInfo layer = catalog.getLayerByName(newLayerName);
      // todo: we should not really reach here and know beforehand what the targetType
      // name is, but if we do we should at least get a way to drop it
      if (layer != null) {
        throw new ProcessException(
            "Target layer " + newLayerName + " already exists in the catalog");
      }
    }

    // try to establish a mapping with old and new attributes. This is again
    // just guesswork until we have a geotools api that will give us the
    // exact mapping to be performed
    Map<String, String> mapping = buildAttributeMapping(sourceType, targetType);

    // start a transaction and fill the target with the input features
    Transaction t = new DefaultTransaction();
    SimpleFeatureStore fstore = (SimpleFeatureStore) ds.getFeatureSource(targetType.getTypeName());
    fstore.setTransaction(t);
    SimpleFeatureIterator fi = features.features();
    SimpleFeatureBuilder fb = new SimpleFeatureBuilder(targetType);
    while (fi.hasNext()) {
      SimpleFeature source = fi.next();
      fb.reset();
      for (String sname : mapping.keySet()) {
        fb.set(mapping.get(sname), source.getAttribute(sname));
      }
      SimpleFeature target = fb.buildFeature(null);
      fstore.addFeatures(DataUtilities.collection(target));
    }
    t.commit();
    t.close();

    return targetType;
  }