Java Code Examples for org.geotools.geometry.jts.JTSFactoryFinder

The following examples show how to use org.geotools.geometry.jts.JTSFactoryFinder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: product-cep   Source File: Disruption.java    License: Apache License 2.0 6 votes vote down vote up
public void end() {
    if (isMultiPolygon) {/*
        ArrayList<Polygon> polygons = new ArrayList<>();
        StringBuilder sb = new StringBuilder("{ \n 'type': 'MultiPolygon', \n 'coordinates': [");
        for(int i=0; i <coords.size();i+=4) {
            if(i!=0) {
                sb.append(",");
            }
            sb.append("[[");
            for(int j=i;j<i+4;j++) {
                if(j!=i)
                    sb.append(",");
                sb.append("[").append(coords.get(i).x).append(",").append(coords.get(i).y).append("]");
            }
            sb.append("]]");
        }
        sb.append("] \n }");
        coordinates = sb.toString();*/

        Coordinate[] c = new Coordinate[coords.size()];
        c = coords.toArray(c);
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        ConvexHull ch = new ConvexHull(c, geometryFactory);
        //System.out.println(ch.getConvexHull().toString());
        setCoordsPoly(ch.getConvexHull().getCoordinates());

    }

}
 
Example 2
Source Project: geowave   Source File: RasterUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Geometry combineIntoOneGeometry(final Collection<Geometry> geometries) {
  final GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(null);

  // note the following geometry collection may be invalid (say with
  // overlapping polygons)
  final Geometry geometryCollection = factory.buildGeometry(geometries);
  // try {
  return geometryCollection.union();
  // }
  // catch (Exception e) {
  // LOGGER.warn("Error creating a union of this geometry collection", e);
  // return geometryCollection;
  // }
}
 
Example 3
Source Project: tutorials   Source File: ShapeFile.java    License: MIT License 5 votes vote down vote up
static void addLocations(SimpleFeatureType CITY, DefaultFeatureCollection collection) {

        Map<String, List<Double>> locations = new HashMap<>();

        double lat = 13.752222;
        double lng = 100.493889;
        addToLocationMap("Bangkok", lat, lng, locations);

        lat = 53.083333;
        lng = -0.15;
        addToLocationMap("New York", lat, lng, locations);

        lat = -33.925278;
        lng = 18.423889;
        addToLocationMap("Cape Town", lat, lng, locations);

        lat = -33.859972;
        lng = 151.211111;
        addToLocationMap("Sydney", lat, lng, locations);

        lat = 45.420833;
        lng = -75.69;
        addToLocationMap("Ottawa", lat, lng, locations);

        lat = 30.07708;
        lng = 31.285909;
        addToLocationMap("Cairo", lat, lng, locations);

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

        locations.entrySet().stream()
          .map(toFeature(CITY, geometryFactory))
          .forEach(collection::add);
    }
 
Example 4
@Override
public Polygon getPolygon() {
    if (polygon == null) {
        // CHECKSTYLE:OFF
        double[][] rawLocations =
                new double[][] {
                    {-4.652710, 54.069059},
                    {-4.634857, 54.075506},
                    {-4.629364, 54.059388},
                    {-4.600525, 54.087590},
                    {-4.574432, 54.102892},
                    {-4.548340, 54.103697},
                    {-4.522247, 54.124626},
                    {-4.476929, 54.143132},
                    {-4.470062, 54.162434},
                    {-4.428864, 54.169670},
                    {-4.383545, 54.194583},
                    {-4.398651, 54.209846},
                    {-4.397278, 54.223496},
                    {-4.373932, 54.229919},
                    {-4.364319, 54.249180},
                    {-4.301147, 54.303704},
                    {-4.372559, 54.315722},
                    {-4.380798, 54.344550},
                    {-4.365692, 54.389354},
                    {-4.364319, 54.420528},
                    {-4.459076, 54.402946},
                    {-4.534607, 54.373359},
                    {-4.578552, 54.322931},
                    {-4.601898, 54.285270},
                    {-4.636230, 54.258807},
                    {-4.671936, 54.237143},
                    {-4.703522, 54.229919},
                    {-4.728241, 54.187352},
                    {-4.743347, 54.173689},
                    {-4.735107, 54.143132},
                    {-4.755707, 54.110138},
                    {-4.783173, 54.101281},
                    {-4.777679, 54.086784},
                    {-4.822998, 54.049714},
                    {-4.737854, 54.066642},
                    {-4.709015, 54.082757},
                    {-4.682922, 54.062612},
                    {-4.652710, 54.069059},
                };
        // CHECKSTYLE:ON

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] coords = new Coordinate[rawLocations.length];
        int index = 0;
        for (double[] point : rawLocations) {
            Coordinate c = new Coordinate(point[0], point[1]);

            coords[index] = c;

            index++;
        }

        LinearRing ring = geometryFactory.createLinearRing(coords);
        LinearRing holes[] = null; // use LinearRing[] to represent holes
        polygon = geometryFactory.createPolygon(ring, holes);
    }
    return polygon;
}
 
Example 5
Source Project: sldeditor   Source File: ExampleLineImpl.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public LineString getLine() {
    if (line == null) {
        // CHECKSTYLE:OFF
        double[][] rawLocations =
                new double[][] {
                    {-123.167725, 48.502048},
                    {-123.464355, 48.297812},
                    {-124.738770, 48.603858},
                    {-125.189209, 48.828566},
                    {-125.112305, 48.951366},
                    {-125.507812, 48.929718},
                    {-125.870361, 49.145784},
                    {-126.035156, 49.167339},
                    {-126.112061, 49.253465},
                    {-126.243896, 49.282140},
                    {-126.287842, 49.360912},
                    {-126.397705, 49.410973},
                    {-126.573486, 49.375220},
                    {-126.584473, 49.560852},
                    {-126.815186, 49.610710},
                    {-127.012939, 49.745781},
                    {-126.947021, 49.788357},
                    {-127.166748, 49.852152},
                    {-127.518311, 50.113533},
                    {-127.814941, 50.078295},
                    {-127.957764, 50.120578},
                    {-127.825928, 50.254230},
                    {-128.012695, 50.331436},
                    {-127.946777, 50.450509},
                    {-128.122559, 50.457504},
                    {-128.364258, 50.652943},
                    {-128.342285, 50.792047},
                    {-128.100586, 50.882243},
                    {-127.858887, 50.944584},
                    {-127.518311, 50.798991},
                    {-127.221680, 50.639010}
                };
        // CHECKSTYLE:ON
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] coords = new Coordinate[rawLocations.length];
        int index = 0;
        for (double[] point : rawLocations) {
            Coordinate c = new Coordinate(point[0], point[1]);

            coords[index] = c;

            index++;
        }

        line = geometryFactory.createLineString(coords);
    }
    return line;
}
 
Example 6
Source Project: sldeditor   Source File: ExamplePolygonImpl.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public Polygon getPolygon() {
    if (polygon == null) {
        // CHECKSTYLE:OFF
        double[][] rawLocations =
                new double[][] {
                    {-4.49210295036, 54.4153472858},
                    {-4.4634856663, 54.4269825687},
                    {-4.43426958965, 54.4117153967},
                    {-4.40869623532, 54.4326291409},
                    {-4.32782927985, 54.4641980089},
                    {-4.3659606463, 54.4197683392},
                    {-4.33467823679, 54.4265693547},
                    {-4.32454274819, 54.4024986924},
                    {-4.34126081686, 54.3660155026},
                    {-4.3424304253, 54.3042112639},
                    {-4.37506398925, 54.3014094498},
                    {-4.41392105869, 54.2658635384},
                    {-4.44375514123, 54.2532227674},
                    {-4.44763651915, 54.196776024},
                    {-4.48315404347, 54.1850220956},
                    {-4.52311962815, 54.1455956993},
                    {-4.58362722513, 54.1091637546},
                    {-4.62431015799, 54.0527236394},
                    {-4.71452726534, 54.0188283696},
                    {-4.71863162723, 54.0497614848},
                    {-4.75157122164, 54.0647816773},
                    {-4.79755603397, 54.0685543663},
                    {-4.79717105693, 54.122792557},
                    {-4.74451711581, 54.1875314993},
                    {-4.73842361793, 54.2081776896},
                    {-4.71656215204, 54.2185876346},
                    {-4.71759940991, 54.2322672444},
                    {-4.73514361565, 54.2446507516},
                    {-4.69488449392, 54.2771110727},
                    {-4.65558887927, 54.2914459801},
                    {-4.65220617099, 54.3116519242},
                    {-4.63949760848, 54.3400051903},
                    {-4.58879948143, 54.3629767901},
                    {-4.57315512904, 54.3829958979},
                    {-4.54023908795, 54.387968746},
                    {-4.51678123729, 54.4207829193},
                    {-4.50855200379, 54.405875113},
                    {-4.49210295036, 54.4153472858},
                };
        // CHECKSTYLE:ON

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] coords = new Coordinate[rawLocations.length];
        int index = 0;
        for (double[] point : rawLocations) {
            Coordinate c = new Coordinate(point[0], point[1]);

            coords[index] = c;

            index++;
        }

        LinearRing ring = geometryFactory.createLinearRing(coords);
        LinearRing holes[] = null; // use LinearRing[] to represent holes
        polygon = geometryFactory.createPolygon(ring, holes);
    }
    return polygon;
}
 
Example 7
Source Project: sldeditor   Source File: GeometryValuesTest.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Test method for {@link
 * com.sldeditor.rendertransformation.types.GeometryValues#GeometryValues()}.
 */
@Test
void testGeometryValues() {
    GeometryValues testObj = new GeometryValues();
    testObj.createInstance();

    assertEquals(
            Arrays.asList(
                    Geometry.class,
                    LineString.class,
                    Point.class,
                    Polygon.class,
                    GridCoverage2D.class),
            testObj.getType());

    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    Geometry geometry = null;
    WKTReader reader = new WKTReader(geometryFactory);
    try {
        Point point = (Point) reader.read("POINT (1 1)");
        geometry = point;
    } catch (ParseException e) {
        e.printStackTrace();
        fail("");
    }

    testObj.setDefaultValue(geometry);
    String p = geometry.toString();
    assertEquals(testObj.getExpression().toString(), p);

    // Geometry value
    testObj.setValue(geometry);
    assertEquals(testObj.getExpression().toString(), p);

    // Literal expression
    Expression expectedExpression = ff.literal(p);
    testObj.setValue(expectedExpression);
    assertEquals(testObj.getExpression().toString(), p);

    // Attribute expression
    expectedExpression = ff.property("test");
    testObj.setValue(expectedExpression);
    assertEquals(expectedExpression, testObj.getExpression());

    // Not set
    testObj.setValue("");
    assertNull(testObj.getExpression());

    FieldConfigBase field =
            testObj.getField(
                    new FieldConfigCommonData(
                            GeometryValues.class,
                            FieldIdEnum.INITIAL_GAP,
                            "label",
                            true,
                            false,
                            false));
    assertEquals(FieldConfigGeometry.class, field.getClass());

    // Increase code coverage
    TestGeometryValues testObj2 = new TestGeometryValues();
    testObj2.populateSymbolType(null);
}
 
Example 8
Source Project: traffic-engine   Source File: OSMUtils.java    License: GNU General Public License v3.0 4 votes vote down vote up
static public void toShapefile( List<SpatialDataItem> segs, String filename ) throws SchemaException, IOException {
	final SimpleFeatureType TYPE = DataUtilities.createType("Location",
               "the_geom:LineString:srid=4326," +
               "name:String"
       );
       System.out.println("TYPE:"+TYPE);
       
       List<SimpleFeature> features = new ArrayList<SimpleFeature>();
       
       /*
        * GeometryFactory will be used to create the geometry attribute of each feature,
        * using a Point object for the location.
        */
       GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

       SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
       
       for( SpatialDataItem seg : segs ){
       	featureBuilder.add( seg.getGeometry() );
       	featureBuilder.add( seg.id );
       	SimpleFeature feature = featureBuilder.buildFeature(null);
       	features.add( feature );
       }
       
       File newFile = new File( filename );
       ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
       
       Map<String, Serializable> params = new HashMap<String, Serializable>();
       params.put("url", newFile.toURI().toURL());
       params.put("create spatial index", Boolean.TRUE);

       ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);

       /*
        * TYPE is used as a template to describe the file contents
        */
       newDataStore.createSchema(TYPE);
       
       ContentFeatureSource cfs = newDataStore.getFeatureSource();
       if (cfs instanceof SimpleFeatureStore) {
           SimpleFeatureStore featureStore = (SimpleFeatureStore) cfs;
           
           SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
           try {
               featureStore.addFeatures(collection);
           } catch (Exception problem) {
               problem.printStackTrace();
           } finally {
           }
       }
}
 
Example 9
Source Project: geowave   Source File: SpatialQueryExample.java    License: Apache License 2.0 4 votes vote down vote up
/** This query will use a specific Bounding Box, and will find only 1 point. */
private void pointQuery() throws ParseException, IOException {
  log.info("Running Point Query Case 2");
  // First, we need to obtain the adapter for the SimpleFeature we want to
  // query.
  // We'll query complex-feature in this example.
  // Obtain adapter for our "complex-feature" type
  final String typeName = "complex-feature";

  // Define the geometry to query. We'll find all points that fall inside
  // that geometry.
  final String queryPolygonDefinition =
      "POLYGON (( "
          + "-118.50059509277344 33.75688594085081, "
          + "-118.50059509277344 34.1521587488017, "
          + "-117.80502319335938 34.1521587488017, "
          + "-117.80502319335938 33.75688594085081, "
          + "-118.50059509277344 33.75688594085081"
          + "))";

  final Geometry queryPolygon =
      new WKTReader(JTSFactoryFinder.getGeometryFactory()).read(queryPolygonDefinition);

  // Perform the query.Parameters are
  /**
   * 1- Adapter previously obtained from the feature name. 2- Default spatial index. 3- A
   * SpatialQuery, which takes the query geometry - aka Bounding box 4- Filters. For this example,
   * no filter is used. 5- Limit. Same as standard SQL limit. 0 is no limits. 6- authorizations.
   * For our example, "root" works. In a real , whatever authorization is associated to the user
   * in question.
   */
  int count = 0;

  final VectorQueryBuilder bldr = VectorQueryBuilder.newBuilder();
  try (final CloseableIterator<SimpleFeature> iterator =
      dataStore.query(
          bldr.addTypeName(typeName).indexName("SPATIAL_IDX").addAuthorization(
              "root").constraints(
                  bldr.constraintsFactory().spatialTemporalConstraints().spatialConstraints(
                      queryPolygon).build()).build())) {

    while (iterator.hasNext()) {
      final SimpleFeature sf = iterator.next();
      log.info(
          "Obtained SimpleFeature "
              + sf.getName().toString()
              + " - "
              + sf.getAttribute("filter"));
      count++;
      System.out.println("Query match: " + sf.getID());
    }
    log.info("Should have obtained 1 feature. -> " + (count == 1));
  }
}
 
Example 10
Source Project: geowave   Source File: SpatialQueryExample.java    License: Apache License 2.0 4 votes vote down vote up
private void ingestPolygonFeature() throws ParseException {
  log.info("Ingesting polygon data");
  // First, we'll build our third kind of SimpleFeature, which we'll call
  // "polygon-feature"
  // We need the type builder to build the feature type
  final SimpleFeatureTypeBuilder sftBuilder = new SimpleFeatureTypeBuilder();
  // AttributeTypeBuilder for the attributes of the SimpleFeature
  final AttributeTypeBuilder attrBuilder = new AttributeTypeBuilder();
  // Here we're setting the SimpleFeature name. Later on, we'll be able to
  // query GW just by this particular feature.
  sftBuilder.setName("polygon-feature");
  // Add the attributes to the feature
  // Add the geometry attribute, which is mandatory for GeoWave to be able
  // to construct an index out of the SimpleFeature
  // Will be any arbitrary geometry; in this case, a polygon.
  sftBuilder.add(attrBuilder.binding(Geometry.class).nillable(false).buildDescriptor("geometry"));
  // Add another attribute just to be able to filter by it in CQL
  sftBuilder.add(attrBuilder.binding(String.class).nillable(false).buildDescriptor("filter"));

  // Create the SimpleFeatureType
  final SimpleFeatureType sfType = sftBuilder.buildFeatureType();
  // We need the adapter for all our operations with GeoWave
  final FeatureDataAdapter sfAdapter = new FeatureDataAdapter(sfType);

  // Now we build the actual features. We'll create one polygon.
  // First point
  final SimpleFeatureBuilder sfBuilder = new SimpleFeatureBuilder(sfType);

  // For ease of use, we'll create the polygon geometry with WKT format.
  final String polygonDefinition =
      "POLYGON (( "
          + "-80.3045654296875 25.852426562716428, "
          + "-80.123291015625 25.808545671771615, "
          + "-80.19195556640625 25.7244467526159, "
          + "-80.34233093261719 25.772068899816585, "
          + "-80.3045654296875 25.852426562716428"
          + "))";
  final Geometry geom =
      new WKTReader(JTSFactoryFinder.getGeometryFactory()).read(polygonDefinition);
  sfBuilder.set("geometry", geom);
  sfBuilder.set("filter", "Polygon");
  // When calling buildFeature, we need to pass an unique id for that
  // feature, or it will be overwritten.
  final SimpleFeature polygon = sfBuilder.buildFeature("1");

  final ArrayList<SimpleFeature> features = new ArrayList<>();
  features.add(polygon);

  // Ingest the data. For that purpose, we need the feature adapter,
  // the index type (the default spatial index is used here),
  // and an iterator of SimpleFeature
  ingest(sfAdapter, new SpatialIndexBuilder().createIndex(), features);
  log.info("Polygon data ingested");
}
 
Example 11
Source Project: geowave   Source File: SpatialQueryExample.java    License: Apache License 2.0 4 votes vote down vote up
/** This query will find a polygon/polygon intersection, returning one match. */
private void polygonQuery() throws ParseException, IOException {
  log.info("Running Point Query Case 4");
  // First, we need to obtain the adapter for the SimpleFeature we want to
  // query.
  // We'll query polygon-feature in this example.
  // Obtain adapter for our "polygon-feature" type
  final String typeName = "polygon-feature";
  // Define the geometry to query. We'll find all polygons that intersect
  // with this geometry.
  final String queryPolygonDefinition =
      "POLYGON (( "
          + "-80.4037857055664 25.81596330265488, "
          + "-80.27915954589844 25.788144792391982, "
          + "-80.34370422363281 25.8814655232439, "
          + "-80.44567108154297 25.896291175546626, "
          + "-80.4037857055664  25.81596330265488"
          + "))";

  final Geometry queryPolygon =
      new WKTReader(JTSFactoryFinder.getGeometryFactory()).read(queryPolygonDefinition);

  // Perform the query.Parameters are
  /**
   * 1- Adapter previously obtained from the feature name. 2- Default spatial index. 3- A
   * SpatialQuery, which takes the query geometry - aka Bounding box 4- Filters. For this example,
   * no filter is used. 5- Limit. Same as standard SQL limit. 0 is no limits. 6- authorizations.
   * For our example, "root" works. In a real , whatever authorization is associated to the user
   * in question.
   */
  int count = 0;

  final VectorQueryBuilder bldr = VectorQueryBuilder.newBuilder();
  try (final CloseableIterator<SimpleFeature> iterator =
      dataStore.query(
          bldr.addTypeName(typeName).indexName("SPATIAL_IDX").addAuthorization(
              "root").constraints(
                  bldr.constraintsFactory().spatialTemporalConstraints().spatialConstraints(
                      queryPolygon).build()).build())) {

    while (iterator.hasNext()) {
      final SimpleFeature sf = iterator.next();
      log.info(
          "Obtained SimpleFeature "
              + sf.getName().toString()
              + " - "
              + sf.getAttribute("filter"));
      count++;
      System.out.println("Query match: " + sf.getID());
    }
    log.info("Should have obtained 1 feature. -> " + (count == 1));
  }
}
 
Example 12
Source Project: geowave   Source File: GeoWaveGrpcVectorService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void spatialQuery(
    final SpatialQueryParametersProtos request,
    final StreamObserver<FeatureProtos> responseObserver) {

  final String storeName = request.getBaseParams().getStoreName();
  final StoreLoader storeLoader = new StoreLoader(storeName);

  String typeName = request.getBaseParams().getTypeName();
  String indexName = request.getBaseParams().getIndexName();
  VectorQueryBuilder bldr = VectorQueryBuilder.newBuilder();
  if (typeName.equalsIgnoreCase("")) {
    typeName = null;
  } else {
    bldr = bldr.addTypeName(typeName);
  }
  if (indexName.equalsIgnoreCase("")) {
    indexName = null;
  } else {
    bldr = bldr.indexName(indexName);
  }

  // first check to make sure the data store exists
  if (!storeLoader.loadFromConfig(GeoWaveGrpcServiceOptions.geowaveConfigFile)) {
    throw new ParameterException("Cannot find store name: " + storeLoader.getStoreName());
  }

  final DataStore dataStore = storeLoader.createDataStore();

  Geometry queryGeom = null;

  try {
    queryGeom =
        new WKBReader(JTSFactoryFinder.getGeometryFactory()).read(
            request.getGeometry().toByteArray());
  } catch (final FactoryRegistryException | org.locationtech.jts.io.ParseException e) {
    LOGGER.error("Exception encountered creating query geometry", e);
  }

  try (final CloseableIterator<SimpleFeature> iterator =
      dataStore.query(
          bldr.constraints(
              bldr.constraintsFactory().spatialTemporalConstraints().spatialConstraints(
                  queryGeom).build()).build())) {
    while (iterator.hasNext()) {
      final SimpleFeature simpleFeature = iterator.next();
      final SimpleFeatureType type = simpleFeature.getType();
      final FeatureProtos.Builder b = FeatureProtos.newBuilder();
      final FeatureAttributeProtos.Builder attBuilder = FeatureAttributeProtos.newBuilder();

      for (int i = 0; i < type.getAttributeDescriptors().size(); i++) {
        setAttributeBuilderValue(simpleFeature.getAttribute(i), attBuilder);
        b.putAttributes(type.getAttributeDescriptors().get(i).getLocalName(), attBuilder.build());
      }
      final FeatureProtos f = b.build();
      responseObserver.onNext(f);
    }
    responseObserver.onCompleted();
  }
}
 
Example 13
Source Project: geowave   Source File: GeoWaveGrpcVectorService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void spatialTemporalQuery(
    final SpatialTemporalQueryParametersProtos request,
    final StreamObserver<FeatureProtos> responseObserver) {

  final String storeName = request.getSpatialParams().getBaseParams().getStoreName();
  final StoreLoader storeLoader = new StoreLoader(storeName);

  // first check to make sure the data store exists
  if (!storeLoader.loadFromConfig(GeoWaveGrpcServiceOptions.geowaveConfigFile)) {
    throw new ParameterException("Cannot find store name: " + storeLoader.getStoreName());
  }

  final DataStore dataStore = storeLoader.createDataStore();
  VectorQueryBuilder bldr = VectorQueryBuilder.newBuilder();

  String typeName = request.getSpatialParams().getBaseParams().getTypeName();
  String indexName = request.getSpatialParams().getBaseParams().getIndexName();

  if (typeName.equalsIgnoreCase("")) {
    typeName = null;
  } else {
    bldr = bldr.addTypeName(typeName);
  }
  if (indexName.equalsIgnoreCase("")) {
    indexName = null;
  } else {
    bldr = bldr.indexName(indexName);
  }

  final int constraintCount = request.getTemporalConstraintsCount();
  SpatialTemporalConstraintsBuilder stBldr =
      bldr.constraintsFactory().spatialTemporalConstraints();
  for (int i = 0; i < constraintCount; i++) {
    final TemporalConstraintsProtos t = request.getTemporalConstraints(i);
    stBldr.addTimeRange(
        Interval.of(
            Instant.ofEpochMilli(Timestamps.toMillis(t.getStartTime())),
            Instant.ofEpochMilli(Timestamps.toMillis(t.getEndTime()))));
  }

  Geometry queryGeom = null;

  try {
    queryGeom =
        new WKBReader(JTSFactoryFinder.getGeometryFactory()).read(
            request.getSpatialParams().getGeometry().toByteArray());
    stBldr = stBldr.spatialConstraints(queryGeom);

    stBldr =
        stBldr.spatialConstraintsCompareOperation(
            CompareOperation.valueOf(request.getCompareOperation()));
  } catch (final FactoryRegistryException | org.locationtech.jts.io.ParseException e) {
    LOGGER.error("Exception encountered creating query geometry", e);
  }

  try (final CloseableIterator<SimpleFeature> iterator =
      dataStore.query(bldr.constraints(stBldr.build()).build())) {
    while (iterator.hasNext()) {
      final SimpleFeature simpleFeature = iterator.next();
      final SimpleFeatureType type = simpleFeature.getType();
      final FeatureProtos.Builder b = FeatureProtos.newBuilder();
      final FeatureAttributeProtos.Builder attBuilder = FeatureAttributeProtos.newBuilder();

      for (int i = 0; i < type.getAttributeDescriptors().size(); i++) {
        setAttributeBuilderValue(simpleFeature.getAttribute(i), attBuilder);
        b.putAttributes(type.getAttributeDescriptors().get(i).getLocalName(), attBuilder.build());
      }
      final FeatureProtos f = b.build();
      responseObserver.onNext(f);
    }
    responseObserver.onCompleted();
  }
}
 
Example 14
Source Project: geowave   Source File: GeoWaveAvroFeatureDataAdapterTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void basicTest() throws Exception {

  final GeoWaveAvroFeatureDataAdapter adapter = new GeoWaveAvroFeatureDataAdapter(schema);

  final GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
  final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(schema);

  final int numFeatures = 10;

  final List<SimpleFeature> data = new ArrayList<>();
  final Map<Integer, SimpleFeature> dataMap = new HashMap<>();
  // Write data using the whole feature data adapter
  for (int i = 0; i < numFeatures; i++) {

    final Point point = geometryFactory.createPoint(new Coordinate(i, i));

    featureBuilder.set("geometry", point);
    featureBuilder.set("pop", i);
    featureBuilder.set("when", new Date(0));
    featureBuilder.set("whennot", new Date());

    data.add(featureBuilder.buildFeature(Integer.toString(i)));
    dataMap.put(i, data.get(data.size() - 1));
  }

  ingestCannedData(adapter, data);

  final Coordinate[] coordArray = new Coordinate[5];
  coordArray[0] = new Coordinate(-180, -90);
  coordArray[1] = new Coordinate(180, -90);
  coordArray[2] = new Coordinate(180, 90);
  coordArray[3] = new Coordinate(-180, 90);
  coordArray[4] = new Coordinate(-180, -90);
  // read data using the whole feature data adapter
  VectorQueryBuilder bldr =
      VectorQueryBuilder.newBuilder().addTypeName(adapter.getTypeName()).indexName(INDEX_NAME);
  bldr =
      bldr.constraints(
          bldr.constraintsFactory().spatialTemporalConstraints().spatialConstraints(
              new GeometryFactory().createPolygon(coordArray)).build());
  try (final CloseableIterator<SimpleFeature> itr = dataStore.query(bldr.build())) {

    while (itr.hasNext()) {
      final SimpleFeature feat = itr.next();

      final SimpleFeature feature = dataMap.remove(Integer.parseInt(feat.getID()));
      assertEquals(DataUtilities.encodeFeature(feature), DataUtilities.encodeFeature(feat));
    }
    assertTrue(dataMap.isEmpty());
  }
}
 
Example 15
Source Project: tutorials   Source File: ShapeFile.java    License: MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        DefaultFeatureCollection collection = new DefaultFeatureCollection();

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

        SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String");

        SimpleFeatureType CITY = createFeatureType();

        addLocations(CITY, collection);

        File shapeFile = getNewShapeFile();

        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

        Map<String, Serializable> params = new HashMap<String, Serializable>();

        ShapefileDataStore dataStore = setDataStoreParams(dataStoreFactory, params, shapeFile, CITY);

        writeToFile(dataStore, collection);
    }