org.locationtech.jts.io.WKBWriter Java Examples

The following examples show how to use org.locationtech.jts.io.WKBWriter. 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 File: GeoUtils.java    From elasticsearch-plugin-geoshape with MIT License 6 votes vote down vote up
public static String exportWkbTo(BytesRef wkb, InternalGeoShape.OutputFormat output_format, GeoJsonWriter geoJsonWriter)
        throws ParseException {
    switch (output_format) {
        case WKT:
            Geometry geom = new WKBReader().read(wkb.bytes);
            return new WKTWriter().write(geom);
        case WKB:
            return WKBWriter.toHex(wkb.bytes);
        default:
            Geometry geo = new WKBReader().read(wkb.bytes);
            return geoJsonWriter.write(geo);
    }
}
 
Example #2
Source File: GeoUtils.java    From elasticsearch-plugin-geoshape with MIT License 5 votes vote down vote up
public static String exportGeoTo(Geometry geom, InternalGeoShape.OutputFormat outputFormat, GeoJsonWriter geoJsonWriter) {
    switch (outputFormat) {
        case WKT:
            return new WKTWriter().write(geom);
        case WKB:
            return WKBWriter.toHex(new WKBWriter().write(geom));
        default:
            return geoJsonWriter.write(geom);
    }
}
 
Example #3
Source File: AccumuloRangeQueryTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies equality for interning is still working as expected (topologically), as the the
 * largeQuery() test has a dependency on this;
 *
 * @throws ParseException
 */
@Test
public void testInterning() throws ParseException {
  final Geometry g =
      GeometryUtils.GEOMETRY_FACTORY.createPolygon(
          new Coordinate[] {
              new Coordinate(0, 0),
              new Coordinate(1, 0),
              new Coordinate(1, 1),
              new Coordinate(0, 1),
              new Coordinate(0, 0)});
  final Geometry gNewInstance =
      GeometryUtils.GEOMETRY_FACTORY.createPolygon(
          new Coordinate[] {
              new Coordinate(0, 0),
              new Coordinate(1, 0),
              new Coordinate(1, 1),
              new Coordinate(0, 1),
              new Coordinate(0, 0)});
  final WKBWriter wkbWriter = new WKBWriter();
  final byte[] b = wkbWriter.write(g);
  final byte[] b2 = new byte[b.length];
  System.arraycopy(b, 0, b2, 0, b.length);
  final WKBReader wkbReader = new WKBReader();
  final Geometry gSerialized = wkbReader.read(b);
  final Geometry gSerializedArrayCopy = wkbReader.read(b2);

  Assert.assertEquals(g, gNewInstance);
  Assert.assertEquals(g, gSerializedArrayCopy);
  Assert.assertEquals(gSerialized, gSerializedArrayCopy);
  Assert.assertEquals(gSerialized, gSerializedArrayCopy);
}
 
Example #4
Source File: GeometryUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a JTS geometry to binary using JTS a Well Known Binary writer
 *
 * @param geometry The JTS geometry
 * @return The binary representation of the geometry
 */
public static byte[] geometryToBinary(
    final Geometry geometry,
    final @Nullable Integer precision) {
  if (precision == null) {
    return new WKBWriter().write(geometry);
  }
  return new TWKBWriter(precision).write(geometry);
}
 
Example #5
Source File: Geometry.java    From datawave with Apache License 2.0 4 votes vote down vote up
private byte[] write() {
    if (geometry != null) {
        return new WKBWriter().write(geometry);
    }
    return new byte[] {};
}
 
Example #6
Source File: GeoExtensionProcessor.java    From elasticsearch-plugin-geoshape with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public IngestDocument execute(IngestDocument ingestDocument) throws IOException, ParseException {
    List<String> geo_objects_list = getGeoShapeFieldsFromDoc(ingestDocument);
    for (String geoShapeField : geo_objects_list) {

        Object geoShapeObject = ingestDocument.getFieldValue(geoShapeField, Object.class);

        if (geoShapeObject == null) {
            continue;
        }

        ShapeBuilder<?,?, ?> shapeBuilder = getShapeBuilderFromObject(geoShapeObject);

        Shape shape = null;
        try {
            shape = shapeBuilder.buildS4J();
        }
        catch (InvalidShapeException ignored) {}

        if (shape == null && fixedField == null) {
            throw new IllegalArgumentException("unable to parse shape [" + shapeBuilder.toWKT() + "]");
        }

        Geometry geom = new WKTReader().read(shapeBuilder.toWKT());

        // fix shapes if needed
        if (shape == null && fixedField != null) {
            geom = GeoUtils.removeDuplicateCoordinates(geom);
        }

        ingestDocument.removeField(geoShapeField);

        if (keepShape) {
            ingestDocument.setFieldValue(geoShapeField + "." + shapeField, geoShapeObject);
        }

        if (fixedField != null) {
            ingestDocument.setFieldValue(geoShapeField + "." + fixedField, new WKTWriter().write(geom));
        }

        // compute and add extra geo sub-fields
        byte[] wkb = new WKBWriter().write(geom);  // elastic will auto-encode this as b64

        if (hashField != null) ingestDocument.setFieldValue(
                geoShapeField + ".hash", String.valueOf(GeoUtils.getHashFromWKB(new BytesRef(wkb))));
        if (wkbField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + wkbField, wkb);
        if (typeField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + typeField, geom.getGeometryType());
        if (areaField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + areaField, geom.getArea());
        if (centroidField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + centroidField, GeoUtils.getCentroidFromGeom(geom));
        if (bboxField != null) {
            Coordinate[] coords = geom.getEnvelope().getCoordinates();
            if (coords.length >= 4) ingestDocument.setFieldValue(
                    geoShapeField + "." + bboxField,
                    GeoUtils.getBboxFromCoords(coords));
        }
    }
    return ingestDocument;
}
 
Example #7
Source File: GeoPkgGeomWriter.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
void write(Geometry g, OutStream out) throws IOException {
    if (g == null) {
        return;
    }

    GeometryHeaderFlags flags = new GeometryHeaderFlags((byte) 0);

    flags.setBinaryType(GeopackageBinaryType.StandardGeoPackageBinary);
    flags.setEmpty(g.isEmpty());
    flags.setEndianess(ByteOrderValues.BIG_ENDIAN);
    flags.setEnvelopeIndicator(config.isWriteEnvelope() ? EnvelopeType.XY : EnvelopeType.NONE);

    GeometryHeader h = new GeometryHeader();
    h.setVersion((byte) 0);
    h.setFlags(flags);
    h.setSrid(g.getSRID());
    if (config.isWriteEnvelope()) {
        h.setEnvelope(g.getEnvelopeInternal());
    }

    // write out magic + flags + srid + envelope
    byte[] buf = new byte[8];
    buf[0] = 0x47;
    buf[1] = 0x50;
    buf[2] = h.getVersion();
    buf[3] = flags.toByte();
    out.write(buf, 4);

    int order = flags.getEndianess();
    ByteOrderValues.putInt(g.getSRID(), buf, order);
    out.write(buf, 4);

    if (flags.getEnvelopeIndicator() != EnvelopeType.NONE) {
        Envelope env = g.getEnvelopeInternal();
        ByteOrderValues.putDouble(env.getMinX(), buf, order);
        out.write(buf, 8);

        ByteOrderValues.putDouble(env.getMaxX(), buf, order);
        out.write(buf, 8);

        ByteOrderValues.putDouble(env.getMinY(), buf, order);
        out.write(buf, 8);

        ByteOrderValues.putDouble(env.getMaxY(), buf, order);
        out.write(buf, 8);
    }

    new WKBWriter(dim, order).write(g, out);
}
 
Example #8
Source File: GeoWaveGrpcVectorService.java    From geowave with Apache License 2.0 4 votes vote down vote up
private void setAttributeBuilderValue(
    final Object simpleFeatureAttribute,
    final FeatureAttributeProtos.Builder attBuilder) {
  if (simpleFeatureAttribute != null) {
    switch (simpleFeatureAttribute.getClass().getSimpleName()) {
      case "String":
        attBuilder.setValString((String) simpleFeatureAttribute);
        break;

      case "Integer":
        attBuilder.setValInt32((Integer) simpleFeatureAttribute);
        break;

      case "Long":
        attBuilder.setValInt64((Long) simpleFeatureAttribute);
        break;

      case "Float":
        attBuilder.setValFloat((Float) simpleFeatureAttribute);
        break;

      case "Double":
        attBuilder.setValDouble((Double) simpleFeatureAttribute);
        break;

      case "Date":
        attBuilder.setValDate(Timestamps.fromMillis(((Date) simpleFeatureAttribute).getTime()));
        break;
      case "Geometry":
      case "Point":
      case "LineString":
      case "Polygon":
      case "GeometryCollection":
        attBuilder.setValGeometry(
            ByteString.copyFrom((new WKBWriter().write((Geometry) simpleFeatureAttribute))));
        break;
      default:
        break;
    };
  }
}
 
Example #9
Source File: GeoWaveGrpcTestClient.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void vectorIngest(
    final int minLat,
    final int maxLat,
    final int minLon,
    final int maxLon,
    final int latStepDegs,
    final int lonStepDegs)
    throws InterruptedException, UnsupportedEncodingException, ParseException {
  LOGGER.info("Performing Vector Ingest...");
  final VectorStoreParametersProtos baseParams =
      VectorStoreParametersProtos.newBuilder().setStoreName(
          GeoWaveGrpcTestUtils.storeName).setTypeName(GeoWaveGrpcTestUtils.typeName).setIndexName(
              GeoWaveGrpcTestUtils.indexName).build();

  final CountDownLatch finishLatch = new CountDownLatch(1);
  final StreamObserver<StringResponseProtos> responseObserver =
      new StreamObserver<StringResponseProtos>() {

        @Override
        public void onNext(final StringResponseProtos value) {
          try {
            numFeaturesProcessed = Integer.parseInt(value.getResponseValue());
          } catch (final NumberFormatException e) {

          }
          LOGGER.info(value.getResponseValue());
        }

        @Override
        public void onError(final Throwable t) {
          LOGGER.error("Error: Vector Ingest failed.", t);
          finishLatch.countDown();
        }

        @Override
        public void onCompleted() {
          LOGGER.info("Finished Vector Ingest...");
          finishLatch.countDown();
        }
      };
  final StreamObserver<VectorIngestParametersProtos> requestObserver =
      vectorAsyncStub.vectorIngest(responseObserver);

  // Build up and add features to the request here...
  final VectorIngestParametersProtos.Builder requestBuilder =
      VectorIngestParametersProtos.newBuilder();
  final FeatureAttributeProtos.Builder attBuilder = FeatureAttributeProtos.newBuilder();
  for (int longitude = minLon; longitude <= maxLon; longitude += lonStepDegs) {
    for (int latitude = minLat; latitude <= maxLat; latitude += latStepDegs) {
      attBuilder.setValGeometry(
          copyFrom(
              new WKBWriter().write(
                  GeometryUtils.GEOMETRY_FACTORY.createPoint(
                      new Coordinate(longitude, latitude)))));
      requestBuilder.putFeature("geometry", attBuilder.build());

      final TimeZone tz = TimeZone.getTimeZone("UTC");
      final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to
      // indicate UTC,
      // no timezone offset
      df.setTimeZone(tz);
      attBuilder.setValDate(
          Timestamps.fromMillis(
              (df.parse(GeoWaveGrpcTestUtils.temporalQueryStartTime).getTime()
                  + df.parse(GeoWaveGrpcTestUtils.temporalQueryEndTime).getTime()) / 2));
      requestBuilder.putFeature("TimeStamp", attBuilder.build());

      attBuilder.setValDouble(latitude);
      requestBuilder.putFeature("Latitude", attBuilder.build());

      attBuilder.setValDouble(longitude);
      requestBuilder.putFeature("Longitude", attBuilder.build());

      final VectorIngestParametersProtos params =
          requestBuilder.setBaseParams(baseParams).build();
      requestObserver.onNext(params);
      if (finishLatch.getCount() == 0) {
        // RPC completed or errored before we finished sending.
        // Sending further requests won't error, but they will just
        // be thrown away.
        return;
      }
    }
  }
  // Mark the end of requests
  requestObserver.onCompleted();

  // Receiving happens asynchronously
  if (!finishLatch.await(15, TimeUnit.MINUTES)) {
    LOGGER.warn("Vector Ingest can not finish within 5 minutes");
  }
}
 
Example #10
Source File: Feature.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(idIndex);
    dest.writeInt(geometryIndex);
    dest.writeString(tableName);
    dest.writeString(databasePath);
    dest.writeList(attributeNames);
    dest.writeList(attributeTypes);
    for (int i = 0; i < attributeValues.size(); i++) {
        Object obj = attributeValues.get(i);
        if (i == geometryIndex) {
            if (obj == null) {
                dest.writeByteArray(null);
            } else {
                Geometry geom = (Geometry) obj;
                WKBWriter wkbWriter = new WKBWriter();
                dest.writeByteArray(wkbWriter.write(geom));
            }
        } else {
            String type = attributeTypes.get(i);
            EDataType type4Name = EDataType.getType4Name(type);
            switch (type4Name) {
                case TEXT: {
                    if (obj == null) {
                        dest.writeString("null");
                    } else {
                        dest.writeString((String) obj);
                    }
                    break;
                }
                case INTEGER: {
                    if (obj == null) {
                        dest.writeInt(Integer.MIN_VALUE);
                    } else {
                        dest.writeInt(((Number) obj).intValue());
                    }
                    break;
                }
                case FLOAT: {
                    if (obj == null) {
                        dest.writeFloat(Float.NaN);
                    } else {
                        dest.writeFloat(((Number) obj).floatValue());
                    }
                    break;
                }
                case DOUBLE: {
                    if (obj == null) {
                        dest.writeDouble(Double.NaN);
                    } else {
                        dest.writeDouble(((Number) obj).doubleValue());
                    }
                    break;
                }
                case LONG: {
                    if (obj == null) {
                        dest.writeLong(Long.MIN_VALUE);
                    } else {
                        dest.writeLong(((Number) obj).longValue());
                    }
                    break;
                }
                case BLOB: {
                    dest.writeValue(obj);
                    break;
                }
            }

        }
    }
}