Java Code Examples for com.vividsolutions.jts.geom.Geometry#setSRID()

The following examples show how to use com.vividsolutions.jts.geom.Geometry#setSRID() . 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: OaImporter.java    From TomboloDigitalConnector with MIT License 6 votes vote down vote up
@Override
protected void importDatasource(Datasource datasource, List<String> geographyScope, List<String> temporalScope,  List<String> datasourceLocation) throws Exception {
    InputStream inputStream = downloadUtils.fetchInputStream(new URL(OaType.valueOf(datasource.getDatasourceSpec().getId()).datafile), getProvider().getLabel(), ".json");
    FeatureIterator<SimpleFeature> featureIterator = new FeatureJSON().streamFeatureCollection(inputStream);

    List<Subject> subjects = new ArrayList<Subject>();
    while(featureIterator.hasNext()) {
        Feature feature = featureIterator.next();
        Geometry geometry = (Geometry) feature.getDefaultGeometryProperty().getValue();
        geometry.setSRID(Subject.SRID);

        subjects.add(new Subject(
                datasource.getUniqueSubjectType(),
                getFeatureSubjectLabel(feature),
                getFeatureSubjectName(feature),
                geometry
        ));
    }

    saveAndClearSubjectBuffer(subjects);
}
 
Example 2
Source File: HsqlGeometryUserType.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Converts the native geometry object to a JTS <code>Geometry</code>.
 * 
 * @param object
 *            native database geometry object (depends on the JDBC spatial
 *            extension of the database)
 * @return JTS geometry corresponding to geomObj.
 */
public Geometry convert2JTS(Object object) {
	if (object == null) {
		return null;
	}
	String data = (String) object;
	int srid = Integer.parseInt(data.substring(0, data.indexOf("|")));
	Geometry geom;
	try {
		WKTReader reader = new WKTReader();
		geom = reader.read(data.substring(data.indexOf("|") + 1));
	} catch (Exception e) { // NOSONAR
		throw new RuntimeException("Couldn't parse incoming wkt geometry.", e);
	}
	geom.setSRID(srid);
	return geom;
}
 
Example 3
Source File: SimpleDemo.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void showPoland() {
	WKTReader r = new WKTReader();
	try {
		Geometry g = r.read(s);
		g.setSRID(4326);

		Geometry g2 = g.buffer(1);
		Geometry g3 = g2.difference(g);

		JavaScriptObject f1 = parseWKT(g.toString());
		JavaScriptObject f2 = parseWKT(g3.toString());
		JsArray<JavaScriptObject> fs = JsArray.createArray().cast();
		fs.push(f1);
		fs.push(f2);

		addFeatures(mMap, fs);
	} catch (ParseException e) {
		sLogger.log(Level.WARNING, "Unable to parse wkb", e);
	}
}
 
Example 4
Source File: GeoUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Geometry getGeometryFromCoordinatesAndType( FeatureType featureType, String coordinates )
    throws IOException
{
    GeometryJSON geometryJSON = new GeometryJSON();

    if ( featureType.equals( FeatureType.NONE ) || featureType.equals( FeatureType.SYMBOL ) )
    {
        throw new IllegalArgumentException( "Invalid featureType '" + featureType.value() + "'" );
    }

    Geometry geometry = geometryJSON
        .read( String.format( "{\"type\": \"%s\", \"coordinates\": %s}", featureType.value(), coordinates ) );

    geometry.setSRID( SRID );

    return geometry;
}
 
Example 5
Source File: OraReader.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Reads a {@link Geometry} representing the MDSYS.GEOMETRY
 * provided in the STRUCT. The type of geometry created 
 * depends on the Geometry type specified within the STRUCT.
 * The SRID of the created geometry is set to be the same as the input SRID.
 *
 * @param struct The MDSYS.GEOMETRY Object to decode
 * @return the Geometry if one could be created, null otherwise
 * 
 * @throws SQLException if a read error occurs while accessing the struct
  * @throws IllegalArgumentException if an unsupported geometry type or encoding error is found
 */
public Geometry read(STRUCT struct) throws SQLException 
{
	// Return null for null input
	if (struct == null)
		return null;

	Datum data[] = struct.getOracleAttributes();
	
	int gType = OraUtil.toInteger(data[0], 0);
	int SRID = OraUtil.toInteger(data[1], OraGeom.SRID_NULL);
	double point[] = OraUtil.toDoubleArray((STRUCT) data[2], Double.NaN);
	int elemInfo[] = OraUtil.toIntArray((ARRAY) data[3], 0);
	double ordinates[] = OraUtil.toDoubleArray((ARRAY) data[4], Double.NaN);
	OraGeom oraGeom = new OraGeom(gType, SRID, point, elemInfo, ordinates);
	Geometry geom = read(oraGeom);
	
	// Set SRID of created Geometry to be the same as input (regardless of geomFactory SRID)
	if (geom != null)
		geom.setSRID(SRID);
	return geom;
}
 
Example 6
Source File: DefaultSecurityContext.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private Geometry areaCombine(String layerId, AreaCombineGetter areaGetter) {
	if (null == authentications || authentications.size() == 0) {
		// no authorizations, so nothing should be allowed
		return null;
	}

	Layer<?> layer = configurationService.getLayer(layerId);
	if (null == layer) {
		log.error("areaCombine on unknown layer " + layerId);
		return null;
	}
	LayerInfo layerInfo = layer.getLayerInfo();

	// base is the max bounds of the layer
	Envelope maxBounds = converterService.toInternal(layerInfo.getMaxExtent());
	PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.FLOATING);
	int srid = geoService.getSridFromCrs(layer.getLayerInfo().getCrs());
	GeometryFactory geometryFactory = new GeometryFactory(precisionModel, srid);
	Geometry geometry = geometryFactory.toGeometry(maxBounds);

	// limit based on authorizations
	for (Authentication authentication : authentications) {
		for (BaseAuthorization authorization : authentication.getAuthorizations()) {
			if (authorization instanceof AreaAuthorization) {
				geometry = geometry.intersection(areaGetter.get((AreaAuthorization) authorization));
			}
		}
	}
	geometry.setSRID(srid); // force srid, even when not set correctly by security service
	return geometry;
}
 
Example 7
Source File: AbstractGeotoolsDataStoreImporter.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
private Optional<Geometry> extractNormalizedGeometry(SimpleFeature feature, MathTransform crsTransform) throws TransformException {
    try {
        Geometry geom = (Geometry) feature.getDefaultGeometry();
        Geometry transformedGeom = JTS.transform(geom, crsTransform);
        transformedGeom.setSRID(Subject.SRID);
        return Optional.of(transformedGeom);
    } catch (ProjectionException e) {
        log.warn("Rejecting feature {}. You will see this if you have assertions enabled (e.g. " +
                "you run with `-ea`) as GeoTools runs asserts. See source of GeotoolsDataStoreUtils for details on this. " +
                "To fix this, replace `-ea` with `-ea -da:org.geotools...` in your test VM options (probably in" +
                "your IDE) to disable assertions in GeoTools.", feature.getID());
        return Optional.empty();
    }
}
 
Example 8
Source File: HsqlGeometryUserTypeTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testConversion() throws ParseException {

	Geometry geom = reader.read("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))");
	HsqlGeometryUserType type = new HsqlGeometryUserType();
	geom.setSRID(12345);
	String wkt = (String) type.conv2DBGeometry(geom, null);
	Geometry copy = type.convert2JTS(wkt);
	Assert.assertEquals(geom, copy);

}
 
Example 9
Source File: CriteriaVisitor.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private Geometry asGeometry(Object geometry) {
	if (geometry instanceof Geometry) {
		Geometry geom = (Geometry) geometry;
		geom.setSRID(srid);
		return geom;
	} else {
		throw new IllegalStateException("Cannot handle " + geometry + " as geometry.");
	}
}
 
Example 10
Source File: WKBTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
void runGeometry(Geometry g, int dimension, int byteOrder, boolean toHex, int srid)
    throws IOException, ParseException
{
  boolean includeSRID = false;
  if (srid >= 0) {
    includeSRID = true;
    g.setSRID(srid);
  }
  
  WKBWriter wkbWriter = new WKBWriter(dimension, byteOrder, includeSRID);
  byte[] wkb = wkbWriter.write(g);
  String wkbHex = null;
  if (toHex)
    wkbHex = WKBWriter.toHex(wkb);

  if (toHex)
    wkb = WKBReader.hexToBytes(wkbHex);
  Geometry g2 = wkbReader.read(wkb);

  CoordinateSequenceComparator comp = (dimension == 2) ? comp2 : comp3;
  boolean isEqual = (g.compareTo(g2, comp) == 0);
  assertTrue(isEqual);
  
  if (includeSRID) {
    boolean isSRIDEqual = g.getSRID() == g2.getSRID();
    assertTrue(isSRIDEqual);
  }
}
 
Example 11
Source File: GeoJsonWriterTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void runTest(String wkt, int srid, boolean encodeCRS, String expectedGeojson) throws ParseException {
  Geometry geom = read(wkt);
  geom.setSRID(srid);
  geoJsonWriter.setEncodeCRS(encodeCRS);
  String json = this.geoJsonWriter.write(geom);
  json = json.replace('"', '\'');
  assertEquals(json, expectedGeojson);
}
 
Example 12
Source File: OrganisationUnit.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Set the Geometry field using a GeoJSON
 * (https://en.wikipedia.org/wiki/GeoJSON) String, like {"type":"Point",
 * "coordinates":[....]}
 *
 * @param geometryAsJsonString String containing a GeoJSON JSON payload
 * @throws IOException an error occurs parsing the payload
 */
public void setGeometryAsJson( String geometryAsJsonString )
    throws IOException
{
    if ( !Strings.isNullOrEmpty( geometryAsJsonString ) )
    {
        GeometryJSON geometryJSON = new GeometryJSON();

        Geometry geometry = geometryJSON.read( geometryAsJsonString );

        geometry.setSRID( 4326 );

        this.geometry = geometry;
    }
}
 
Example 13
Source File: TestFactory.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
/**
 * Returns a square geometry
 * @param lowerLeftXOffset x-coordinate of lower left corner
 * @param lowerLeftYOffset y-coordinate of lower left corner
 * @param edgeSize the edge size of the square
 * @return A square geometry with left corner at lowerLeftXOffset, lowerLeftYOffset
 */
public static Geometry makeSquareGeometry(Double lowerLeftXOffset, Double lowerLeftYOffset, Double edgeSize){
    GeometryFactory geometryFactory = new GeometryFactory();
    Coordinate[] corners = {
            new Coordinate(lowerLeftXOffset, lowerLeftYOffset),
            new Coordinate(lowerLeftXOffset, lowerLeftYOffset+edgeSize),
            new Coordinate(lowerLeftXOffset+edgeSize, lowerLeftYOffset+edgeSize),
            new Coordinate(lowerLeftXOffset+edgeSize, lowerLeftYOffset),
            new Coordinate(lowerLeftXOffset, lowerLeftYOffset)
    };
    Geometry square = geometryFactory.createPolygon(corners);
    square.setSRID(Subject.SRID);
    return square;
}
 
Example 14
Source File: TestFactory.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
/**
 * Make LineString given the coordinates
 * @param coordinates
 * @return
 */
public static Geometry makeLineStringGeometry(Coordinate[] coordinates) {
    GeometryFactory geometryFactory = new GeometryFactory();
    Geometry lineString =  geometryFactory.createLineString(coordinates);
    lineString.setSRID(Subject.SRID);
    return lineString;
}
 
Example 15
Source File: TestFactory.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
/**
 * makeLineStringGeometry
 * Returns a lineString at the offset provided
 * @param xOffset
 * @param yOffset
 * @param length length of the line
 * @return A LineString geometry from xOffset, yOffset to xOffset + length, yOffset + length
 */
public static Geometry makeLineStringGeometry(Double xOffset, Double yOffset, Double length) {
    GeometryFactory geometryFactory = new GeometryFactory();
    Coordinate[] coordinates = {new Coordinate(xOffset, yOffset),
            new Coordinate(xOffset + length, yOffset)};
    Geometry lineString =  geometryFactory.createLineString(coordinates);
    lineString.setSRID(Subject.SRID);
    return lineString;
}
 
Example 16
Source File: SqlUtils.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
static Geometry InputStream2Geometry(final InputStream inputStream) throws Exception {
	Geometry dbGeometry = null;
	if (inputStream != null) {
		// convert the stream to a byte[] array
		// so it can be passed to the WKBReader
		final byte[] buffer = new byte[255];
		int bytesRead = 0;
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			baos.write(buffer, 0, bytesRead);
		}

		final byte[] geometryAsBytes = baos.toByteArray();

		if (geometryAsBytes.length < 5) {
			throw new Exception("Invalid geometry inputStream - less than five bytes");
		}

		// first four bytes of the geometry are the SRID,
		// followed by the actual WKB. Determine the SRID
		// here
		final byte[] sridBytes = new byte[4];
		System.arraycopy(geometryAsBytes, 0, sridBytes, 0, 4);
		final boolean bigEndian = geometryAsBytes[4] == 0x00;

		int srid = 0;
		if (bigEndian) {
			for (final byte sridByte : sridBytes) {
				srid = (srid << 8) + (sridByte & 0xff);
			}
		} else {
			for (int i = 0; i < sridBytes.length; i++) {
				srid += (sridBytes[i] & 0xff) << 8 * i;
			}
		}

		// use the JTS WKBReader for WKB parsing
		final WKBReader wkbReader = new WKBReader();

		// copy the byte array, removing the first four
		// SRID bytes
		final byte[] wkb = new byte[geometryAsBytes.length - 4];
		System.arraycopy(geometryAsBytes, 4, wkb, 0, wkb.length);
		dbGeometry = wkbReader.read(wkb);
		dbGeometry.setSRID(srid);
	}

	return dbGeometry;
}
 
Example 17
Source File: GeoToolsFeatureModel.java    From geomajas-project-server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Geometry getGeometry(Object feature) throws LayerException {
	Geometry geometry = (Geometry) asFeature(feature).getDefaultGeometry();
	geometry.setSRID(srid);
	return (Geometry) geometry.clone();
}
 
Example 18
Source File: SubjectUtils.java    From TomboloDigitalConnector with MIT License 4 votes vote down vote up
private static Query queryFromSubjectSpecification(Session session, SubjectRecipe subjectRecipe) {
	SubjectType subjectType = SubjectTypeUtils.getSubjectTypeByProviderAndLabel(subjectRecipe.getProvider(), subjectRecipe.getSubjectType());

	String hqlQuery = "from Subject s where s.subjectType = :subjectType";

	// Add Attribute Match Rule if exists
	if (null != subjectRecipe.getMatchRule()){
		if (subjectRecipe.getMatchRule().attribute == SubjectAttributeMatchRule.MatchableAttribute.label) {
			hqlQuery += " and lower(label) like :pattern";
		} else if (subjectRecipe.getMatchRule().attribute == SubjectAttributeMatchRule.MatchableAttribute.name) {
			hqlQuery += " and lower(name) like :pattern";
		} else {
			throw new IllegalArgumentException(
					"SubjectAttributeMatchRule attribute is not a valid type (can be either name or label)");
		}
	}

	// Add Geo Match Rule if exists
	if (null != subjectRecipe.getGeoMatchRule()){
		List<SubjectRecipe.SubjectGeoMatchRule.GeoRelation> geoRel = new ArrayList<>();
		Collections.addAll(geoRel, SubjectRecipe.SubjectGeoMatchRule.GeoRelation.values());
		SubjectRecipe.SubjectGeoMatchRule.GeoRelation gr = subjectRecipe.getGeoMatchRule().geoRelation;
		if (geoRel.contains(subjectRecipe.getGeoMatchRule().geoRelation)){
			hqlQuery += " and " + subjectRecipe.getGeoMatchRule().geoRelation.name() + "(shape, :geom) = true";
		} else {
			throw new IllegalArgumentException(String.format(
					"SubjectGeoMatchRule geoRelation is not a valid type.\nSupported spatial joins: %s.",
					Stream.of(SubjectRecipe.SubjectGeoMatchRule.GeoRelation.values()).map(Enum::name)
							.collect(Collectors.toList()).toString()));
		}
	}

	// Create the basic query with obligatory paramaters
	Query query = session.createQuery(hqlQuery, Subject.class);

	for (Parameter parameter : query.getParameters()) {
		if (Objects.equals(parameter.getName(), "subjectType")) {
			query.setParameter("subjectType", subjectType);
		} else if (Objects.equals(parameter.getName(), "pattern")) {
			query.setParameter("pattern", subjectRecipe.getMatchRule().pattern.toLowerCase());
		} else if (Objects.equals(parameter.getName(), "geom")) {
			List<Subject> parents = getSubjectBySpecifications(subjectRecipe.getGeoMatchRule().subjects);

			Geometry union = null;
			for (Subject parent : parents){
				if (union == null)
					union = parent.getShape();
				else
					union = union.union(parent.getShape());
			}
			union.setSRID(Subject.SRID);
			query.setParameter("geom", union);
		}
	}

	return query;
}
 
Example 19
Source File: HibernateLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Enforces the correct srid on incoming features.
 * 
 * @param feature
 *            object to enforce srid on
 * @throws LayerException
 *             problem getting or setting srid
 */
private void enforceSrid(Object feature) throws LayerException {
	Geometry geom = getFeatureModel().getGeometry(feature);
	if (null != geom) {
		geom.setSRID(srid);
		getFeatureModel().setGeometry(feature, geom);
	}
}
 
Example 20
Source File: TestFactory.java    From TomboloDigitalConnector with MIT License 3 votes vote down vote up
/**
 * makeFakeGeometry
 * Returns a point at the offset provided
 * @param xOffset
 * @param yOffset
 * @return A point geometry at xOffset, yOffset
 */
public static Geometry makePointGeometry(Double xOffset, Double yOffset) {
    GeometryFactory geometryFactory = new GeometryFactory();
    Geometry point =  geometryFactory.createPoint(new Coordinate(xOffset, yOffset));
    point.setSRID(Subject.SRID);
    return point;
}