/**
   * <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;
  }
  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();
  }
Пример #3
0
  @Test
  public void testWithNull() throws Exception {

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

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

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

    } finally {
      i.close();
    }
  }
  @Test
  public void testGetFeaturesFeatureSource() throws Exception {
    // check the schemas in feature source and feature collection
    SimpleFeatureSource fs = rts.getFeatureSource(RENAMED);
    assertEquals(primitive, fs.getSchema());
    SimpleFeatureCollection fc = fs.getFeatures();
    assertEquals(primitive, fc.getSchema());
    assertTrue(fc.size() > 0);

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

    assertEquals(primitive, sf.getFeatureType());

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

    // check mappings occurred
    assertEquals("description-f001", sf.getAttribute("description"));
    assertTrue(
        new WKTReader()
            .read("MULTIPOINT(39.73245 2.00342)")
            .equalsExact((Geometry) sf.getAttribute("pointProperty")));
    assertEquals(new Long(155), sf.getAttribute("intProperty"));
    assertNull(sf.getAttribute("newProperty"));
  }
Пример #5
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();
      }
    }
  }
  public void selectFeatures(int x, int y) {
    int pixelDelta = 2;
    LatLon clickUL = Main.map.mapView.getLatLon(x - pixelDelta, y - pixelDelta);
    LatLon clickLR = Main.map.mapView.getLatLon(x + pixelDelta, y + pixelDelta);

    Envelope envelope =
        new Envelope(
            Math.min(clickUL.lon(), clickLR.lon()),
            Math.max(clickUL.lon(), clickLR.lon()),
            Math.min(clickUL.lat(), clickLR.lat()),
            Math.max(clickUL.lat(), clickLR.lat()));

    ReferencedEnvelope mapArea = new ReferencedEnvelope(envelope, crsOSMI);

    Intersects filter = ff.intersects(ff.property("msGeometry"), ff.literal(mapArea));
    //
    // Select features in all layers
    //
    content.layers().clear();

    // Iterate through features and build a list that intersects the above
    // envelope
    for (int idx = 0; idx < arrFeatures.size(); ++idx) {
      OSMIFeatureTracker tracker = arrFeatures.get(idx);
      FeatureCollection<SimpleFeatureType, SimpleFeature> features = tracker.getFeatures();

      SimpleFeatureSource tempfs = DataUtilities.source(features);
      FeatureCollection<SimpleFeatureType, SimpleFeature> selectedFeatures;

      try {
        selectedFeatures = tempfs.getFeatures(filter);
        Set<FeatureId> IDs = new HashSet<>();

        try (FeatureIterator<SimpleFeature> iter = selectedFeatures.features()) {

          Main.info("Selected features " + selectedFeatures.size());

          while (iter.hasNext()) {
            SimpleFeature feature = iter.next();
            IDs.add(feature.getIdentifier());
          }
        }

        geometryType = selectGeomType.get(idx + layerOffset);
        Style style = createDefaultStyle(idx + layerOffset, IDs);
        content.addLayer(new FeatureLayer(features, style));
      } catch (IOException e) {
        Main.error(e);
      }
    }

    bIsChanged = true;
  }
Пример #7
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();
  }
  @Override
  public boolean getCreateFeature(GridElement el) {
    Coordinate c = ((PolygonElement) el).getCenter();
    Geometry p = gf.createPoint(c);
    Filter filter = ff2.intersects(ff2.property("the_geom"), ff2.literal(p));
    boolean result = false;

    try {
      result = !source.getFeatures(filter).isEmpty();
    } catch (IOException ex) {
      throw new IllegalStateException(ex);
    }

    return result;
  }
Пример #9
0
  /**
   * Generate squares inside given bounds
   *
   * @param bounds
   * @param size
   * @return
   * @throws IOException
   */
  private SimpleFeatureIterator squares(ReferencedEnvelope bounds, double size) throws IOException {

    // Limit squares to bounding box
    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
    Filter filter = ff.bbox(ff.property(GEOM), bounds);

    // Align bound to square size and expand by 150%
    bounds = align(bounds, size, 1.5);

    // Create grid for given bounds
    SimpleFeatureSource grid = Grids.createSquareGrid(bounds, size);

    // Finished
    return grid.getFeatures(filter).features();
  }
  @Before
  public void findFeature() throws Exception {

    SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);
    SimpleFeatureCollection features = source.getFeatures();
    FeatureIterator<SimpleFeature> iterator = features.features();
    while (iterator.hasNext()) {
      SimpleFeature f = iterator.next();
      if (f.getAttribute("dateProperty") != null) {
        feature = f;
        break;
      }
    }
    features.close(iterator);
  }
Пример #11
0
 private Id createFidFilter(SimpleFeatureSource fs) throws IOException {
   SimpleFeatureIterator iter = fs.getFeatures().features();
   FilterFactory2 ffac = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
   Set fids = new HashSet();
   try {
     while (iter.hasNext()) {
       String id = iter.next().getID();
       FeatureId fid = ffac.featureId(id);
       fids.add(fid);
     }
     Id filter = ffac.id(fids);
     return filter;
   } finally {
     iter.close();
   }
 }
Пример #12
0
  @Test
  public void testAlternateLookup() throws Exception {
    SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);
    SimpleFeatureCollection fc = source.getFeatures();
    SimpleFeatureIterator features = fc.features();
    try {
      SimpleFeature f = features.next();

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

      assertEquals("dummy", result);
    } finally {
      features.close();
    }
  }
Пример #13
0
  @DescribeResult(name = "result", description = "The grid")
  public SimpleFeatureCollection execute(
      @DescribeParameter(name = "features", description = "The grid bounds")
          ReferencedEnvelope bounds,
      @DescribeParameter(
              name = "width",
              description = "Cell width (in the same uom as the bounds referencing system)")
          double width,
      @DescribeParameter(
              name = "height",
              description =
                  "Cell height (optional, used only for rectangular grids, "
                      + "if not provided it is assumed equals to the width)",
              min = 0)
          Double height,
      @DescribeParameter(
              name = "vertexSpacing",
              description =
                  "Distance between vertices (used to create densified "
                      + "sides suitable for reprojection)",
              min = 0)
          Double vertexSpacing,
      @DescribeParameter(name = "mode", description = "The type of grid to be generated", min = 0)
          GridMode mode)
      throws ProcessException {
    final GridFeatureBuilder builder =
        new GridFeatureBuilderImpl(bounds.getCoordinateReferenceSystem());
    double h = height != null ? height : width;

    SimpleFeatureSource source;
    if (mode == null || mode == GridMode.Rectangular) {
      source = Oblongs.createGrid(bounds, width, h, builder);
    } else if (mode == GridMode.HexagonFlat) {
      source = Hexagons.createGrid(bounds, width, HexagonOrientation.FLAT, builder);
    } else {
      source = Hexagons.createGrid(bounds, width, HexagonOrientation.ANGLED, builder);
    }

    try {
      return source.getFeatures();
    } catch (IOException e) {
      throw new ProcessException("Unexpected exception while grabbing features", e);
    }
  }
Пример #14
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();
    }
  }
Пример #15
0
  @Test
  public void testRawValue() throws Exception {
    SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);
    SimpleFeatureCollection fc = source.getFeatures();
    SimpleFeatureIterator i = fc.features();
    try {
      SimpleFeature f = (SimpleFeature) i.next();

      FeatureTemplate template = new FeatureTemplate();
      try {
        template.template(f, "rawValues.ftl", FeatureTemplateTest.class);
      } catch (Exception e) {
        e.printStackTrace();
        throw (e);
      }
    } finally {
      i.close();
    }
  }
  @Test
  public void testFeautureSourceFidFilter() throws Exception {
    // grab the last feature in the collection (there are more than one)
    SimpleFeatureSource fs = rts.getFeatureSource(RENAMED);

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

    SimpleFeatureCollection fc = fs.getFeatures(new Query(RENAMED, fidFilter));
    assertEquals(RENAMED, fc.getSchema().getName().getLocalPart());
    assertEquals(1, fc.size());
    FeatureIterator<SimpleFeature> it = fc.features();
    assertTrue(it.hasNext());
    SimpleFeature sf = it.next();
    assertFalse(it.hasNext());
    it.close();
    assertEquals(fid, sf.getID());
  }
  @Test
  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();
  }
Пример #18
0
  @Test
  public void testWithDateAndBoolean() throws Exception {

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

      FeatureTemplate template = new FeatureTemplate();
      try {
        template.description(f);
      } catch (Exception e) {
        e.printStackTrace();
        fail("template threw exception on null value");
      }
    } finally {
      i.close();
    }
  }
  public String wfsRequest() {
    // String getCapabilities =
    // "http://"+host+":"+port+"/geoserver/"+workspace+"/wfs?REQUEST=GetCapabilities&version=1.0.0";
    String getCapabilities =
        "http://"
            + host
            + ":"
            + port
            + "/geoserver/"
            + workspace
            + "/ows?REQUEST=GetCapabilities&version=1.1.1&service=WFS";
    Map connectionParameters = new HashMap();
    connectionParameters.put("WFSDataStoreFactory:GET_CAPABILITIES_URL", getCapabilities);
    connectionParameters.put("WFSDataStoreFactory:USERNAME", "admin");
    connectionParameters.put("WFSDataStoreFactory:PASSWORD", "geoserver");
    connectionParameters.put("WFSDataStoreFactory:WFS_STRATEGY", "geoserver");
    connectionParameters.put("WFSDataStoreFactory:MAXFEATURES", 1000);
    WFSDataStoreFactory dsf = new WFSDataStoreFactory();
    try {
      // WFS_1_0_0_DataStore wfs = dsf.createDataStore(connectionParameters);
      WFSDataStore dataStore = dsf.createDataStore(connectionParameters);

      String[] typeNames = dataStore.getTypeNames();
      System.out.println(ArrayUtils.toString(typeNames));

      SimpleFeatureSource source = dataStore.getFeatureSource(workspace + ":" + layer);
      SimpleFeatureCollection fc = source.getFeatures();
      StringWriter writer = new StringWriter();
      while (fc.features().hasNext()) {
        SimpleFeature sf = fc.features().next();
        System.out.println(sf.getAttribute("myname"));
        FeatureJSON fjson = new FeatureJSON();
        fjson.writeFeature(sf, writer);
      }
      String geojson = writer.toString();
      return geojson;
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return null;
  }
  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.");
  }
Пример #21
0
  public static void getAIDMemBound(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 + ".");

    int sum = 0;
    List<double[]> mbrList = new ArrayList<double[]>(sizeFeatureCollection);
    try (SimpleFeatureIterator iterator = featureCollection.features()) {
      while (iterator.hasNext()) {
        BoundingBox a1b = iterator.next().getBounds();
        double[] a1m = new double[4];
        a1m[0] = a1b.getMinX();
        a1m[1] = a1b.getMaxX();
        a1m[2] = a1b.getMinY();
        a1m[3] = a1b.getMaxY();
        mbrList.add(a1m);
      }
    }
    for (int i = 0; i < sizeFeatureCollection; i++) {
      int inter = 0;
      double[] a1m = mbrList.get(i);
      for (int j = i + 1; j < sizeFeatureCollection; j++) {
        double[] a2m = mbrList.get(j);
        if (GeometryRelated.rectangleIntersect(a1m, a2m)) {
          sum += 2;
          inter++;
        }
      }
      if (inter > 200) {
        System.out.println(inter + "," + i);
      }
    }

    store.dispose();
    //		sum -= sizeFeatureCollection;
    System.out.println("Total MBR Intersection:" + sum);
    System.out.println(
        "Average Intersection Degree: " + ((double) sum / ((double) sizeFeatureCollection)));
  }
Пример #22
0
  public static void getAIDNoBuffer(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 + ".");

    int sum = 0;
    //		List<Geometry> GeometryList = new ArrayList<Geometry>(sizeFeatureCollection);
    try (SimpleFeatureIterator iterator = featureCollection.features()) {
      while (iterator.hasNext()) {
        try (SimpleFeatureIterator iterator2 = featureCollection.features()) {
          SimpleFeature feature = iterator.next();
          String a1ID = feature.getID();
          //				System.out.println(a1ID);
          BoundingBox a1b = feature.getBounds();
          double[] a1m = new double[4];
          a1m[0] = a1b.getMinX();
          a1m[1] = a1b.getMaxX();
          a1m[2] = a1b.getMinY();
          a1m[3] = a1b.getMaxY();

          // original code that is not chunk
          while (iterator2.hasNext()) {
            SimpleFeature feature2 = iterator2.next();
            String a2ID = feature2.getID();
            if (!a1ID.equals(a2ID)) {
              BoundingBox a2b = feature2.getBounds();
              double[] a2m = new double[4];
              a2m[0] = a2b.getMinX();
              a2m[1] = a2b.getMaxX();
              a2m[2] = a2b.getMinY();
              a2m[3] = a2b.getMaxY();
              if (GeometryRelated.rectangleIntersect(a1m, a2m)) {
                sum += 1;
              }
            }
          }
        }
      }
    }

    store.dispose();

    System.out.println("Total MBR Intersection:" + sum);
    System.out.println(
        "Average Intersection Degree: " + ((double) sum / ((double) sizeFeatureCollection)));
  }
Пример #23
0
  // Not efficient: for each a1, a2 will iterate over the whole dataset
  public static void getAIDSemiBuffer(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 + ".");

    int sum = 0;
    int it1 = 0;
    int buf1 = 0;
    List<double[]> tempGeometryList1 = new ArrayList<double[]>();
    //		List<Geometry> GeometryList = new ArrayList<Geometry>(sizeFeatureCollection);
    try (SimpleFeatureIterator iterator = featureCollection.features()) {
      while (iterator.hasNext()) {

        buf1++;
        SimpleFeature feature = iterator.next();
        BoundingBox a1b = feature.getBounds();
        double[] a1m = new double[4];
        a1m[0] = a1b.getMinX();
        a1m[1] = a1b.getMaxX();
        a1m[2] = a1b.getMinY();
        a1m[3] = a1b.getMaxY();
        tempGeometryList1.add(a1m);
        if (buf1 % 10000 == 0) {
          for (double[] a1m1 : tempGeometryList1) {
            it1++;
            // TODO: don't get g2 for each a11 in g1, but share it!
            try (SimpleFeatureIterator iterator2 = featureCollection.features()) {
              int it2 = 0;
              int buf2 = 0;
              List<double[]> tempGeometryList2 = new ArrayList<double[]>();
              while (iterator2.hasNext()) {
                it2++;
                SimpleFeature feature2 = iterator2.next();
                //							String a2ID = feature2.getID();
                if (it1 != it2) {
                  buf2++;
                  BoundingBox a2b = feature2.getBounds();
                  double[] a2m = new double[4];
                  a2m[0] = a2b.getMinX();
                  a2m[1] = a2b.getMaxX();
                  a2m[2] = a2b.getMinY();
                  a2m[3] = a2b.getMaxY();
                  tempGeometryList2.add(a2m);
                }
                if (buf2 % 10000 == 0) {
                  for (double[] a2m1 : tempGeometryList2) {
                    if (GeometryRelated.rectangleIntersect(a1m1, a2m1)) {
                      sum += 1;
                    }
                  }
                  tempGeometryList2 = new ArrayList<double[]>();
                }
              }
              for (double[] a2m1 : tempGeometryList2) {
                if (GeometryRelated.rectangleIntersect(a1m1, a2m1)) {
                  sum += 1;
                }
              }
            }
          }
          tempGeometryList1 = new ArrayList<double[]>();
        }
      }
      for (double[] a1m1 : tempGeometryList1) {
        it1++;
        try (SimpleFeatureIterator iterator2 = featureCollection.features()) {
          int it2 = 0;
          int buf2 = 0;
          List<double[]> tempGeometryList2 = new ArrayList<double[]>();
          while (iterator2.hasNext()) {
            it2++;
            SimpleFeature feature2 = iterator2.next();
            //							String a2ID = feature2.getID();
            if (it1 != it2) {
              buf2++;
              BoundingBox a2b = feature2.getBounds();
              double[] a2m = new double[4];
              a2m[0] = a2b.getMinX();
              a2m[1] = a2b.getMaxX();
              a2m[2] = a2b.getMinY();
              a2m[3] = a2b.getMaxY();
              tempGeometryList2.add(a2m);
            }
            if (buf2 % 10000 == 0) {
              for (double[] a2m1 : tempGeometryList2) {
                if (GeometryRelated.rectangleIntersect(a1m1, a2m1)) {
                  sum += 1;
                }
              }
              tempGeometryList2 = new ArrayList<double[]>();
            }
          }
          for (double[] a2m1 : tempGeometryList2) {
            if (GeometryRelated.rectangleIntersect(a1m1, a2m1)) {
              sum += 1;
            }
          }
        }
      }

    } finally {
      store.dispose();
    }
    System.out.println("Total MBR Intersection:" + sum);
    System.out.println(
        "Average Intersection Degree: " + ((double) sum / ((double) sizeFeatureCollection)));
  }
Пример #24
0
  public static void getAIDBuffer(String filename, int bufferSize) {

    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 + ".");

    int sum = 0;
    int buf = 0;
    List<double[]> temp1GeometryList = new ArrayList<double[]>();

    try (SimpleFeatureIterator iterator = featureCollection.features()) {
      while (iterator.hasNext()) {
        buf++;
        BoundingBox a1b = iterator.next().getBounds();
        double[] a1m = new double[4];
        a1m[0] = a1b.getMinX();
        a1m[1] = a1b.getMaxX();
        a1m[2] = a1b.getMinY();
        a1m[3] = a1b.getMaxY();
        temp1GeometryList.add(a1m);
        if (buf % bufferSize == 0) {
          System.out.println("Buffer 1.");
          try (SimpleFeatureIterator iterator2 = featureCollection.features()) {
            List<double[]> temp2GeometryList = new ArrayList<double[]>();
            int buf2 = 0;
            while (iterator2.hasNext()) {
              buf2++;
              BoundingBox a2b = iterator2.next().getBounds();
              double[] a2m = new double[4];
              a2m[0] = a2b.getMinX();
              a2m[1] = a2b.getMaxX();
              a2m[2] = a2b.getMinY();
              a2m[3] = a2b.getMaxY();
              temp2GeometryList.add(a2m);
              if (buf2 % bufferSize == 0) {
                System.out.println("Buffer 2.");
                for (double[] a11m : temp1GeometryList) {
                  for (double[] a22m : temp2GeometryList) {
                    if (GeometryRelated.rectangleIntersect(a11m, a22m)) {
                      sum += 1;
                    }
                  }
                }
                temp2GeometryList = new ArrayList<double[]>();
              }
            }
            System.out.println("Buffer 2 left.");
            for (double[] a11m : temp1GeometryList) {
              for (double[] a22m : temp2GeometryList) {
                if (GeometryRelated.rectangleIntersect(a11m, a22m)) {
                  sum += 1;
                }
              }
            }
            temp1GeometryList = new ArrayList<double[]>();
          }
        }
      }
      System.out.println("Buffer 1 left.");
      try (SimpleFeatureIterator iterator2 = featureCollection.features()) {
        List<double[]> temp2GeometryList = new ArrayList<double[]>();

        int buf2 = 0;
        while (iterator2.hasNext()) {
          buf2++;
          BoundingBox a2b = iterator2.next().getBounds();
          double[] a2m = new double[4];
          a2m[0] = a2b.getMinX();
          a2m[1] = a2b.getMaxX();
          a2m[2] = a2b.getMinY();
          a2m[3] = a2b.getMaxY();
          temp2GeometryList.add(a2m);

          if (buf2 % bufferSize == 0) {
            System.out.println("Buffer 2.");
            for (double[] a11m : temp1GeometryList) {
              for (double[] a22m : temp2GeometryList) {
                if (GeometryRelated.rectangleIntersect(a11m, a22m)) {
                  sum += 1;
                }
              }
            }
            temp2GeometryList = new ArrayList<double[]>();
          }
        }
        System.out.println("Buffer 2 left.");
        for (double[] a11m : temp1GeometryList) {
          for (double[] a22m : temp2GeometryList) {
            if (GeometryRelated.rectangleIntersect(a11m, a22m)) {
              sum += 1;
            }
          }
        }
      }
    }

    store.dispose();

    sum -= sizeFeatureCollection;
    System.out.println("Total MBR Intersection#:" + sum);
    System.out.println(
        "Average Intersection Degree: " + ((double) sum / ((double) sizeFeatureCollection)));
  }
Пример #25
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);
  }
Пример #26
0
  /**
   * Loads the feature collection based on the current styling and the scale denominator. If no
   * feature is going to be returned a null feature collection will be returned instead
   *
   * @param featureSource
   * @param layer
   * @param mapContent
   * @param wms
   * @param scaleDenominator
   * @return
   * @throws Exception
   */
  public static SimpleFeatureCollection loadFeatureCollection(
      SimpleFeatureSource featureSource,
      Layer layer,
      WMSMapContent mapContent,
      WMS wms,
      double scaleDenominator)
      throws Exception {
    SimpleFeatureType schema = featureSource.getSchema();

    Envelope envelope = mapContent.getRenderingArea();
    ReferencedEnvelope aoi =
        new ReferencedEnvelope(envelope, mapContent.getCoordinateReferenceSystem());
    CoordinateReferenceSystem sourceCrs = schema.getCoordinateReferenceSystem();

    boolean reprojectBBox =
        (sourceCrs != null)
            && !CRS.equalsIgnoreMetadata(aoi.getCoordinateReferenceSystem(), sourceCrs);
    if (reprojectBBox) {
      aoi = aoi.transform(sourceCrs, true);
    }

    Filter filter = createBBoxFilter(schema, aoi);

    // now build the query using only the attributes and the bounding
    // box needed
    Query q = new Query(schema.getTypeName());
    q.setFilter(filter);

    // now, if a definition query has been established for this layer,
    // be sure to respect it by combining it with the bounding box one.
    Query definitionQuery = layer.getQuery();

    if (definitionQuery != Query.ALL) {
      if (q == Query.ALL) {
        q = (Query) definitionQuery;
      } else {
        q = (Query) DataUtilities.mixQueries(definitionQuery, q, "KMLEncoder");
      }
    }

    // handle startIndex requested by client query
    q.setStartIndex(definitionQuery.getStartIndex());

    // check the regionating strategy
    RegionatingStrategy regionatingStrategy = null;
    String stratname = (String) mapContent.getRequest().getFormatOptions().get("regionateBy");
    if (("auto").equals(stratname)) {
      Catalog catalog = wms.getGeoServer().getCatalog();
      Name name = layer.getFeatureSource().getName();
      stratname =
          catalog
              .getFeatureTypeByName(name)
              .getMetadata()
              .get("kml.regionateStrategy", String.class);
      if (stratname == null || "".equals(stratname)) {
        stratname = "best_guess";
        LOGGER.log(
            Level.FINE,
            "No default regionating strategy has been configured in "
                + name
                + "; using automatic best-guess strategy.");
      }
    }

    if (stratname != null) {
      regionatingStrategy = findStrategyByName(stratname);

      // if a strategy was specified but we did not find it, let the user
      // know
      if (regionatingStrategy == null)
        throw new ServiceException("Unknown regionating strategy " + stratname);
    }

    // try to load less features by leveraging regionating strategy and the
    // SLD
    Filter regionatingFilter = Filter.INCLUDE;

    if (regionatingStrategy != null)
      regionatingFilter = regionatingStrategy.getFilter(mapContent, layer);

    Filter ruleFilter =
        summarizeRuleFilters(
            getLayerRules(featureSource.getSchema(), layer.getStyle()), scaleDenominator);
    Filter finalFilter = joinFilters(q.getFilter(), ruleFilter, regionatingFilter);
    if (finalFilter == Filter.EXCLUDE) {
      // if we don't have any feature to return
      return null;
    }
    q.setFilter(finalFilter);

    // make sure we output in 4326 since that's what KML mandates
    CoordinateReferenceSystem wgs84;
    try {
      wgs84 = CRS.decode("EPSG:4326");
    } catch (Exception e) {
      throw new RuntimeException(
          "Cannot decode EPSG:4326, the CRS subsystem must be badly broken...");
    }
    if (sourceCrs != null && !CRS.equalsIgnoreMetadata(wgs84, sourceCrs)) {
      return new ReprojectFeatureResults(featureSource.getFeatures(q), wgs84);
    }

    return featureSource.getFeatures(q);
  }
Пример #27
0
  public static void getAIDBufferByID(String filename, int bufferSize) {

    File file = new File(filename);
    String[] splited = filename.split("[\\\\/]");
    String shapefilename = splited[splited.length - 1].split("\\.")[0] + ".";
    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 + ".");

    int sum = 0;

    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());

    int numBuffs = sizeFeatureCollection / bufferSize;
    int buff = 0;
    List<SimpleFeatureCollection> buffers = new ArrayList<SimpleFeatureCollection>();
    for (int i = 0; i < numBuffs; i++) {
      int buffB = buff;
      buff += bufferSize * (i + 1);
      Set<FeatureId> fids = new HashSet<FeatureId>();
      for (int id = buffB + 1; id < buff + 1; id++) {
        fids.add(ff.featureId(shapefilename + id));
      }
      Filter filter = ff.id(fids);
      SimpleFeatureCollection featuresF1 = null;
      try {
        featuresF1 = featureSource.getFeatures(filter);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      buffers.add(featuresF1);
    }
    Set<FeatureId> fids = new HashSet<FeatureId>();
    for (int id = buff + 1; id < sizeFeatureCollection + 1; id++) {
      fids.add(ff.featureId(shapefilename + id));
    }
    Filter filter = ff.id(fids);
    SimpleFeatureCollection featuresF1 = null;
    try {
      featuresF1 = featureSource.getFeatures(filter);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    buffers.add(featuresF1);
    // (i,j) pairs of buffers
    for (int i = 0; i < numBuffs + 1; i++) {
      System.out.println("B1: " + i);
      List<double[]> temp1List = new ArrayList<double[]>();
      SimpleFeatureCollection features1 = buffers.get(i);
      try (SimpleFeatureIterator iterator = features1.features()) {
        while (iterator.hasNext()) {
          BoundingBox a1b = iterator.next().getBounds();
          double[] a1m = new double[4];
          a1m[0] = a1b.getMinX();
          a1m[1] = a1b.getMaxX();
          a1m[2] = a1b.getMinY();
          a1m[3] = a1b.getMaxY();
          temp1List.add(a1m);
        }
      }
      int numF1 = temp1List.size();
      // j=i
      System.out.println("B2: " + i);
      for (int id1 = 0; id1 < numF1; id1++) {
        double[] a1m = temp1List.get(id1);
        for (int id2 = id1 + 1; id2 < numF1; id2++) {
          double[] a2m = temp1List.get(id2);
          if (GeometryRelated.rectangleIntersect(a1m, a2m)) {
            sum += 2;
          }
        }
      }

      // j>i
      for (int j = i + 1; j < numBuffs + 1; j++) {
        System.out.println("B2: " + j);
        List<double[]> temp2List = new ArrayList<double[]>();
        SimpleFeatureCollection features2 = buffers.get(j);
        try (SimpleFeatureIterator iterator = features2.features()) {
          while (iterator.hasNext()) {
            BoundingBox a2b = iterator.next().getBounds();
            double[] a2m = new double[4];
            a2m[0] = a2b.getMinX();
            a2m[1] = a2b.getMaxX();
            a2m[2] = a2b.getMinY();
            a2m[3] = a2b.getMaxY();
            temp2List.add(a2m);
          }
        }
        int numF2 = temp2List.size();
        for (int id1 = 0; id1 < numF1; id1++) {
          double[] a1m = temp1List.get(id1);
          for (int id2 = 0; id2 < numF2; id2++) {
            double[] a2m = temp2List.get(id2);
            if (GeometryRelated.rectangleIntersect(a1m, a2m)) {
              sum += 2;
            }
          }
        }
      }
    }

    store.dispose();

    System.out.println("Total MBR Intersection#:" + sum);
    System.out.println(
        "Average Intersection Degree: " + ((double) sum / ((double) sizeFeatureCollection)));
  }
Пример #28
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);
      }
    }
  }
Пример #29
0
  public static IGlobeFeatureCollection<
          IVector2, ? extends IBoundedGeometry2D<? extends IFinite2DBounds<?>>>
      readFeatures(final DataStore dataStore, final String layerName, final GProjection projection)
          throws Exception {

    final SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);

    final SimpleFeatureCollection featuresCollection = featureSource.getFeatures();

    final GIntHolder validCounter = new GIntHolder(0);
    // final GIntHolder polygonsWithHolesCounter = new GIntHolder(0);
    final GIntHolder invalidCounter = new GIntHolder(0);
    //      final GIntHolder validVerticesCounter = new GIntHolder(0);
    final GIntHolder polygonsCounter = new GIntHolder(0);
    final GIntHolder linesCounter = new GIntHolder(0);
    final GIntHolder pointsCounter = new GIntHolder(0);

    final int featuresCount = featuresCollection.size();
    final ArrayList<IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>
        euclidFeatures =
            new ArrayList<
                IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>(
                featuresCount);

    final GProgress progress =
        new GProgress(featuresCount) {
          @Override
          public void informProgress(
              final double percent, final long elapsed, final long estimatedMsToFinish) {
            //            System.out.println("Loading \"" + fileName.buildPath() + "\" "
            //                               + progressString(percent, elapsed,
            // estimatedMsToFinish));
            System.out.println(
                "Loading data from data storage: "
                    + layerName
                    + " "
                    + progressString(percent, elapsed, estimatedMsToFinish));
          }
        };

    final FeatureIterator<SimpleFeature> iterator = featuresCollection.features();

    while (iterator.hasNext()) {
      final SimpleFeature feature = iterator.next();

      final GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty();

      final GeometryType type = geometryAttribute.getType();

      if (type.getBinding() == com.vividsolutions.jts.geom.MultiPolygon.class) {

        polygonsCounter.increment();

        final com.vividsolutions.jts.geom.MultiPolygon multipolygon =
            (com.vividsolutions.jts.geom.MultiPolygon) geometryAttribute.getValue();
        final int geometriesCount = multipolygon.getNumGeometries();

        final List<IPolygon2D> polygons = new ArrayList<IPolygon2D>(geometriesCount);
        for (int i = 0; i < geometriesCount; i++) {
          final com.vividsolutions.jts.geom.Polygon jtsPolygon =
              (com.vividsolutions.jts.geom.Polygon) multipolygon.getGeometryN(i);

          try {
            final IPolygon2D euclidPolygon = createEuclidPolygon(projection, jtsPolygon);

            if (euclidPolygon != null) {
              //                     euclidFeatures.add(createFeature(euclidPolygon, feature));
              polygons.add(euclidPolygon);
              validCounter.increment();
            }
          } catch (final IllegalArgumentException e) {
            //                     System.err.println(e.getMessage());
          }
        }

        if (!polygons.isEmpty()) {
          if (polygons.size() == 1) {
            euclidFeatures.add(createFeature(polygons.get(0), feature));
          } else {
            euclidFeatures.add(createFeature(new GMultiGeometry2D<IPolygon2D>(polygons), feature));
          }
        }

      } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiLineString.class) {

        linesCounter.increment();

        final com.vividsolutions.jts.geom.MultiLineString multiline =
            (com.vividsolutions.jts.geom.MultiLineString) geometryAttribute.getValue();
        final int geometriesCount = multiline.getNumGeometries();

        final List<IPolygonalChain2D> lines = new ArrayList<IPolygonalChain2D>(geometriesCount);
        for (int i = 0; i < geometriesCount; i++) {
          final com.vividsolutions.jts.geom.LineString jtsLine =
              (com.vividsolutions.jts.geom.LineString) multiline.getGeometryN(i);

          try {
            final IPolygonalChain2D euclidLine = createLine(jtsLine.getCoordinates(), projection);

            // euclidFeatures.add(createFeature(euclidLines, feature));
            lines.add(euclidLine);
          } catch (final IllegalArgumentException e) {
            //                     System.err.println(e.getMessage());
          }
        }

        if (!lines.isEmpty()) {
          if (lines.size() == 1) {
            euclidFeatures.add(createFeature(lines.get(0), feature));
          } else {
            euclidFeatures.add(
                createFeature(new GMultiGeometry2D<IPolygonalChain2D>(lines), feature));
          }
        }

        validCounter.increment();
      } else if (type.getBinding() == com.vividsolutions.jts.geom.Point.class) {

        pointsCounter.increment();

        final IVector2 euclidPoint =
            createPoint(
                ((com.vividsolutions.jts.geom.Point) geometryAttribute.getValue()).getCoordinate(),
                projection);
        euclidFeatures.add(createFeature(euclidPoint, feature));

        validCounter.increment();
      } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiPoint.class) {
        final IBoundedGeometry2D<? extends IFinite2DBounds<?>> euclidMultipoint =
            createEuclidMultiPoint(geometryAttribute, projection);
        euclidFeatures.add(createFeature(euclidMultipoint, feature));

        validCounter.increment();
      } else {
        invalidCounter.increment();
        System.out.println("invalid type: " + type);
      }

      progress.stepDone();
    }

    dataStore.dispose();

    euclidFeatures.trimToSize();

    System.out.println();
    System.out.println("Features: " + featuresCount);

    System.out.println();
    System.out.println("Read " + validCounter.get() + " valid geometries");

    System.out.println("  => " + polygonsCounter.get() + " valid polygons");
    System.out.println("  => " + linesCounter.get() + " valid lines");
    System.out.println("  => " + pointsCounter.get() + " valid points");
    System.out.println();

    if (invalidCounter.get() > 0) {
      System.out.println("Ignored " + invalidCounter.get() + " invalid geometries");
    }

    System.out.println();

    final SimpleFeatureType schema = featureSource.getSchema();
    final int fieldsCount = schema.getAttributeCount();
    final List<GField> fields = new ArrayList<GField>(fieldsCount);
    System.out.println("Fields count: " + fieldsCount);
    for (int i = 0; i < fieldsCount; i++) {
      final String fieldName = schema.getType(i).getName().getLocalPart();
      System.out.println("Fieldname: " + fieldName);
      final Class<?> fieldType = schema.getType(i).getBinding();

      fields.add(new GField(fieldName, fieldType));
    }

    return new GListFeatureCollection<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>(
        GProjection.EPSG_4326, fields, euclidFeatures, "uniqueId_000");
  }