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

The following examples show how to use com.vividsolutions.jts.geom.Geometry#isValid() . 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: ProcessingUtils.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Check GML Footprint validity
 */
public static boolean checkGMLFootprint (String footprint)
{
   try
   {
      Configuration configuration = new GMLConfiguration ();
      Parser parser = new Parser (configuration);

      Geometry geom =
            (Geometry) parser.parse (new InputSource (
                  new StringReader (footprint)));
      if (!geom.isEmpty() && !geom.isValid())
      {
         LOGGER.error("Wrong footprint");
         return false;
      }
   }
   catch (Exception e)
   {
      LOGGER.error("Error in extracted footprint: " + e.getMessage());
      return false;
   }
   return true;
}
 
Example 2
Source File: GMLShapeValidator.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   Check if the given shape is correct.
   @param shape
   @return
 */
private static Geometry checkShape(GMLShape shape) throws ValidationException {
    Geometry polygon = JTSTools.shapeToPolygon(shape);
    if (!polygon.isValid()) {
        throw new ValidationException(shape.getID(), "invalid shape");
    }
    if (!polygon.contains(polygon.getCentroid())) {
        throw new ValidationException(shape.getID(), "Shape doesn't contain centroid.");
    }
    return polygon;
}
 
Example 3
Source File: GeoWaveGeoIndexer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static SimpleFeature createFeature(final SimpleFeatureType featureType, final Statement statement) throws ParseException {
    final String subject = StatementSerializer.writeSubject(statement);
    final String predicate = StatementSerializer.writePredicate(statement);
    final String object = StatementSerializer.writeObject(statement);
    final String context = StatementSerializer.writeContext(statement);

    // create the feature
    final Object[] noValues = {};

    // create the hash
    final String statementId = Md5Hash.md5Base64(StatementSerializer.writeStatement(statement));
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(featureType, noValues, statementId);

    // write the statement data to the fields
    final Geometry geom = GeoParseUtils.getGeometry(statement, new GmlParser());
    if(geom == null || geom.isEmpty() || !geom.isValid()) {
        throw new ParseException("Could not create geometry for statement " + statement);
    }
    newFeature.setDefaultGeometry(geom);

    newFeature.setAttribute(SUBJECT_ATTRIBUTE, subject);
    newFeature.setAttribute(PREDICATE_ATTRIBUTE, predicate);
    newFeature.setAttribute(OBJECT_ATTRIBUTE, object);
    newFeature.setAttribute(CONTEXT_ATTRIBUTE, context);
    // GeoWave does not support querying based on a user generated feature ID
    // So, we create a separate ID attribute that it can query on.
    newFeature.setAttribute(GEO_ID_ATTRIBUTE, statementId);

    // preserve the ID that we created for this feature
    // (set the hint to FALSE to have GeoTools generate IDs)
    newFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

    return newFeature;
}
 
Example 4
Source File: GeoMesaGeoIndexer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static SimpleFeature createFeature(final SimpleFeatureType featureType, final Statement statement) throws ParseException {
    final String subject = StatementSerializer.writeSubject(statement);
    final String predicate = StatementSerializer.writePredicate(statement);
    final String object = StatementSerializer.writeObject(statement);
    final String context = StatementSerializer.writeContext(statement);

    // create the feature
    final Object[] noValues = {};

    // create the hash
    final String statementId = Md5Hash.md5Base64(StatementSerializer.writeStatement(statement));
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(featureType, noValues, statementId);

    // write the statement data to the fields
    final Geometry geom = GeoParseUtils.getGeometry(statement, new GmlParser());
    if(geom == null || geom.isEmpty() || !geom.isValid()) {
        throw new ParseException("Could not create geometry for statement " + statement);
    }
    newFeature.setDefaultGeometry(geom);

    newFeature.setAttribute(SUBJECT_ATTRIBUTE, subject);
    newFeature.setAttribute(PREDICATE_ATTRIBUTE, predicate);
    newFeature.setAttribute(OBJECT_ATTRIBUTE, object);
    newFeature.setAttribute(CONTEXT_ATTRIBUTE, context);

    // preserve the ID that we created for this feature
    // (set the hint to FALSE to have GeoTools generate IDs)
    newFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

    return newFeature;
}
 
Example 5
Source File: PreparedGeometryTeeOperation.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void runTeeOp(String opName, Geometry geometry, Object[] args)
{
	if (args.length < 1) return;
	if (! (args[0] instanceof Geometry)) return;
	Geometry g2 = (Geometry) args[0];
	
	if (! geometry.isValid())
		throw new IllegalStateException("Input geometry A is not valid");
	if (! g2.isValid())
		throw new IllegalStateException("Input geometry B is not valid");
			
	checkAllPrepOps(geometry, g2);
	checkAllPrepOps(g2, geometry);
}
 
Example 6
Source File: Test.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isExpectedResultGeometryValid()
{
  if (expectedResult instanceof GeometryResult) {
  	Geometry expectedGeom = ((GeometryResult) expectedResult).getGeometry();
  	return expectedGeom.isValid();
  }
  return true;
}
 
Example 7
Source File: GeometryValidator.java    From geowe-core with GNU General Public License v3.0 4 votes vote down vote up
private void validate(final Geometry geom, final List<ValidationResult> validationErrors) {
	
	if (geom.isEmpty()) {
		return;
	}

	if (geom instanceof GeometryCollection) {
		final GeometryCollection gc = (GeometryCollection) geom;
		for (int numGeom = 0; numGeom < gc.getNumGeometries(); numGeom++) {
			validate(gc.getGeometryN(numGeom), validationErrors);
		}
	}

	final ValidationResult result = new ValidationResult();
	result.setWkt(geom.toText());
	final List<String> messages = new ArrayList<String>();
	
	if (!geom.isValid()) {
		messages.add("Error en topología básica");
	}

	if (!geom.isSimple()) {
		messages.add("No es una geometría simple");
	}

	if (repeatedPointTester.hasRepeatedPoint(geom)) {
		messages.add("Se encuentran vértices repetidos");
	}

	if (geom instanceof Polygon) {
		final Polygon polygon = (Polygon) geom;
		if (CGAlgorithms.isCCW(polygon.getExteriorRing().getCoordinates())) {
			messages.add("Error en orientación del polígono");
		} else {

			for (int numRing = 0; numRing < polygon.getNumInteriorRing(); numRing++) {
				if (!CGAlgorithms.isCCW(polygon.getInteriorRingN(numRing).getCoordinates())) {
					messages.add("Error en orientación del polígono en anillos interiores");
					break;
				}
			}
		}

		if (!validateMinPolygonArea(geom)) {
			messages.add("Error en validación mínima de area de un polígono");
		}
	}

	if (!validateMinSegmentLength(geom)) {
		messages.add("Error en validación mínima de longitud de segmento. Coordenadas");
		result.setErrorsPoints(errorCoordinates);
	}


	if(!messages.isEmpty()) {
		result.setMessages(messages);
		validationErrors.add(result);
	}		
}
 
Example 8
Source File: GamaShapeFile.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
protected void readShapes(final IScope scope) {
	scope.getGui().getStatus(scope).beginSubStatus("Reading file " + getName(scope));
	ShapefileDataStore store = null;
	final File file = getFile(scope);
	final IList list = getBuffer();
	int size = 0;
	try {
		store = getDataStore(file.toURI().toURL());
		final ContentFeatureSource source = store.getFeatureSource();
		final Envelope3D env = Envelope3D.of(source.getBounds());
		size = source.getCount(Query.ALL);
		int index = 0;
		computeProjection(scope, env);
		try (FeatureReader reader = store.getFeatureReader()) {
			while (reader.hasNext()) {
				index++;
				if (index % 20 == 0) {
					scope.getGui().getStatus(scope).setSubStatusCompletion(index / (double) size);
				}
				final Feature feature = reader.next();
				Geometry g = (Geometry) feature.getDefaultGeometryProperty().getValue();
				if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) {
					if (!with3D && !g.isValid()) {
						g = GeometryUtils.cleanGeometry(g);
					}
					g = gis.transform(g);
					if (!with3D) {
						g.apply(ZERO_Z);
						g.geometryChanged();
					}
					g = multiPolygonManagement(g);
					GamaGisGeometry gt = new GamaGisGeometry(g, feature);
					if (gt.getInnerGeometry() != null)
						list.add(gt);
					
				} else if (g == null) {
					// See Issue 725
					GAMA.reportError(scope,
							GamaRuntimeException
									.warning("GamaShapeFile.fillBuffer; geometry could not be added  as it is "
											+ "nil: " + feature.getIdentifier(), scope),
							false);
				}
			}
		}
	} catch (final IOException e) {
		throw GamaRuntimeException.create(e, scope);
	} finally {
		if (store != null) {
			store.dispose();
		}
		scope.getGui().getStatus(scope).endSubStatus("Reading file " + getName(scope));
	}
	if (size > list.size()) {
		GAMA.reportError(scope, GamaRuntimeException.warning("Problem with file " + getFile(scope) + ": only "
				+ list.size() + " of the " + size + " geometries could be added", scope), false);
	}
}
 
Example 9
Source File: GeometrySnapRounder.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static Geometry ensureValid(Geometry geom) {
  if (geom.isValid()) return geom;
  return cleanPolygonal(geom);
}
 
Example 10
Source File: MiscellaneousTest2.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testZeroAreaPolygon() throws Exception {
  Geometry g = reader.read(
        "POLYGON((0 0, 0 0, 0 0, 0 0, 0 0))");
  g.isValid();
  assertTrue(true); //No exception thrown [Jon Aquino]
}
 
Example 11
Source File: MiscellaneousTest2.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testLineStringIsValid() throws Exception {
  Geometry g = reader.read(
        "LINESTRING(0 0, 0 0)");
  g.isValid();
  assertTrue(true); //No exception thrown [Jon Aquino]
}