use of com.vividsolutions.jts.operation.valid.IsValidOp in project spatial-portal by AtlasOfLivingAustralia.
the class Util method fixWkt.
public static String fixWkt(String wkt) {
if (wkt == null || !(wkt.startsWith("POLYGON") || wkt.startsWith("MULTIPOLYGON"))) {
return wkt;
}
String newWkt = wkt;
try {
WKTReader wktReader = new WKTReader();
com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
// NC 20130319: Ensure that the WKT is valid according to the WKT standards.
// if outside -180 to 180, cut and fit
Envelope env = g.getEnvelopeInternal();
if (env.getMinX() < -180 || env.getMaxX() > 180) {
int minx = -180;
while (minx > env.getMinX()) {
minx -= 360;
}
int maxx = 180;
while (maxx < env.getMaxX()) {
maxx += 360;
}
// divide, translate and rejoin
Geometry newGeometry = null;
for (int i = minx; i < maxx; i += 360) {
Geometry cutter = wktReader.read("POLYGON((" + i + " -90," + i + " 90," + (i + 360) + " 90," + (i + 360) + " -90," + i + " -90))");
Geometry part = cutter.intersection(g);
// offset cutter
if (i != -180) {
AffineTransformation at = AffineTransformation.translationInstance(-180 - i, 0);
part.apply(at);
}
if (part.getArea() > 0) {
if (newGeometry == null) {
newGeometry = part;
} else {
newGeometry = newGeometry.union(part);
}
}
}
newWkt = newGeometry.toText();
}
IsValidOp op = new IsValidOp(g);
if (!op.isValid()) {
// this will fix some issues
g = g.buffer(0);
op = new IsValidOp(g);
}
if (!op.isValid()) {
// give up?
} else if (g.isRectangle()) {
// NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
// get the new WKT for the rectangle will possibly need to change the order.
com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
newWkt = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
}
} catch (ParseException parseException) {
LOGGER.error("error fixing WKT", parseException);
}
return newWkt;
}
use of com.vividsolutions.jts.operation.valid.IsValidOp in project spatial-portal by AtlasOfLivingAustralia.
the class AreaUploadShapefileWizardController method loadOnMap.
private void loadOnMap(Set<FeatureId> ids, String filename) {
try {
final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
Filter filter = ff.id(ids);
// set up the math transform used to process the data
SimpleFeatureType schema = features.getSchema();
CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem wgsCRS = DefaultGeographicCRS.WGS84;
// allow for some error due to different datums
boolean lenient = true;
if (dataCRS == null) {
// attempt to parse prj
try {
File prjFile = new File(filename.substring(0, filename.length() - 3) + "prj");
if (prjFile.exists()) {
String prj = FileUtils.readFileToString(prjFile);
if (prj.equals("PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0]]")) {
// support for arcgis online default shp exports
dataCRS = CRS.decode("EPSG:3857");
} else {
dataCRS = CRS.parseWKT(FileUtils.readFileToString(prjFile));
}
}
} catch (Exception e) {
LOGGER.error("failed to read prj for " + filename);
}
if (dataCRS == null) {
dataCRS = DefaultGeographicCRS.WGS84;
}
}
MathTransform transform = CRS.findMathTransform(dataCRS, wgsCRS, lenient);
SimpleFeatureCollection sff = source.getFeatures(filter);
SimpleFeatureIterator fif = sff.features();
StringBuilder sb = new StringBuilder();
StringBuilder sbGeometryCollection = new StringBuilder();
boolean isGeometryCollection = false;
List<Geometry> geoms = new ArrayList<Geometry>();
while (fif.hasNext()) {
SimpleFeature f = fif.next();
LOGGER.debug("Selected Feature: " + f.getID() + " -> " + f.getAttribute("ECOREGION"));
Geometry geom = (Geometry) f.getDefaultGeometry();
geom = JTS.transform(geom, transform);
String wktString = geom.toText();
wktString = wktString.replaceAll(", ", ",");
boolean valid = true;
boolean multipolygon = false;
boolean polygon = false;
boolean geometrycollection = false;
if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
wktString = wktString.substring((StringConstants.MULTIPOLYGON + " ").length(), wktString.length() - 1);
multipolygon = true;
} else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
wktString = wktString.substring((StringConstants.POLYGON + " ").length());
polygon = true;
} else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
geometrycollection = true;
isGeometryCollection = true;
} else {
valid = false;
}
if (valid) {
if (sb.length() > 0) {
sb.append(",");
sbGeometryCollection.append(",");
}
sb.append(wktString);
if (multipolygon) {
sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
if (!wktString.endsWith(")))")) {
sbGeometryCollection.append(")");
}
} else if (polygon) {
sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
} else if (geometrycollection) {
sbGeometryCollection.append(wktString);
}
}
}
String wkt;
if (!isGeometryCollection) {
if (!sb.toString().contains(")))")) {
sb.append(")");
}
wkt = StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "((");
} else {
sbGeometryCollection.append(")");
wkt = StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection.toString();
getMapComposer().showMessage("Shape is invalid: " + "GEOMETRYCOLLECTION not supported.");
}
GeometryFactory gf = new GeometryFactory();
gf.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
String msg = "";
boolean invalid = false;
try {
WKTReader wktReader = new WKTReader();
com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
// NC 20130319: Ensure that the WKT is valid according to the WKT standards.
IsValidOp op = new IsValidOp(g);
if (!op.isValid()) {
// this will fix some issues
g = g.buffer(0);
op = new IsValidOp(g);
}
if (!op.isValid()) {
invalid = true;
LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
msg = op.getValidationError().getMessage();
// TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
} else if (g.isRectangle()) {
// NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
// get the new WKT for the rectangle will possibly need to change the order.
com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
if (!wkt.equals(wkt2)) {
LOGGER.debug("NEW WKT for Rectangle: " + wkt);
msg = CommonData.lang("error_wkt_anticlockwise");
invalid = true;
}
}
if (!invalid) {
invalid = !op.isValid();
}
} catch (ParseException parseException) {
LOGGER.error("error testing validity of uploaded shape file wkt", parseException);
}
if (invalid) {
getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
} else {
MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layername, layername);
UserDataDTO ud = new UserDataDTO(layername);
ud.setFilename(media.getName());
ud.setUploadedTimeInMs(System.currentTimeMillis());
ud.setType("shapefile");
String metadata = "";
metadata += "User uploaded Shapefile \n";
metadata += "Name: " + ud.getName() + " <br />\n";
metadata += "Filename: " + ud.getFilename() + " <br />\n";
metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
metadata += "Selected polygons (fid): <br />\n";
metadata += "<ul>";
metadata += "</ul>";
mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
getMapComposer().replaceWKTwithWMS(mapLayer);
}
} catch (IOException e) {
LOGGER.debug("IO Error retrieving geometry", e);
} catch (Exception e) {
LOGGER.debug("Generic Error retrieving geometry", e);
}
}
use of com.vividsolutions.jts.operation.valid.IsValidOp in project spatial-portal by AtlasOfLivingAustralia.
the class AreaPolygon method validWKT.
public boolean validWKT(String wkt) {
if (wkt.replaceAll(" ", "").isEmpty()) {
invalidWKT.setValue("WKT is Invalid");
return false;
} else {
invalidWKT.setValue("");
}
try {
WKTReader wktReader = new WKTReader();
com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
// NC 20130319: Ensure that the WKT is valid according to the WKT standards.
IsValidOp op = new IsValidOp(g);
if (!op.isValid()) {
// this will fix some issues
g = g.buffer(0);
op = new IsValidOp(g);
}
if (!op.isValid()) {
invalidWKT.setValue(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
LOGGER.warn("WKT is invalid." + op.getValidationError().getMessage());
// TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
} else if (g.isRectangle()) {
// NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
// get the new WKT for the rectangle will possibly need to change the order.
com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
if (!wkt.equals(wkt2)) {
LOGGER.debug("NEW WKT for Rectangle: " + wkt);
invalidWKT.setValue(CommonData.lang("error_wkt_rectangle_wrong_order"));
displayGeom.setValue(wkt2);
return false;
}
}
return op.isValid();
} catch (ParseException parseException) {
invalidWKT.setValue(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + parseException.getMessage());
return false;
}
}
use of com.vividsolutions.jts.operation.valid.IsValidOp in project spatial-portal by AtlasOfLivingAustralia.
the class AreaUploadShapefile method onUpload$btnFileUpload.
public void onUpload$btnFileUpload(Event event) {
UploadEvent ue = null;
if ("onUpload".equals(event.getName())) {
ue = (UploadEvent) event;
} else if ("onForward".equals(event.getName())) {
ue = (UploadEvent) ((ForwardEvent) event).getOrigin();
}
if (ue == null) {
LOGGER.debug("unable to upload file");
return;
} else {
LOGGER.debug("fileUploaded()");
}
try {
Media m = ue.getMedia();
LOGGER.debug("m.getName(): " + m.getName());
LOGGER.debug("getContentType: " + m.getContentType());
LOGGER.debug("getFormat: " + m.getFormat());
UserDataDTO ud = new UserDataDTO(txtLayerName.getValue());
ud.setFilename(m.getName());
byte[] kmldata = getKml(m);
if (kmldata.length > 0) {
loadUserLayerKML(m.getName(), kmldata, ud);
} else if (m.getName().toLowerCase().endsWith("zip")) {
Map args = new HashMap();
args.put(StringConstants.LAYERNAME, txtLayerName.getValue());
args.put(StringConstants.MEDIA, m);
String windowname = "areashapewizard";
if (getFellowIfAny(windowname) != null) {
getFellowIfAny(windowname).detach();
}
Window window = (Window) Executions.createComponents("WEB-INF/zul/add/area/AreaUploadShapefileWizard.zul", this.getParent(), args);
try {
window.setParent(this.getParent());
window.doModal();
} catch (SuspendNotAllowedException e) {
// we are really closing the window without opening/displaying to the user
}
} else if (m.getName().toLowerCase().endsWith("zip_removeme")) {
Map input = Zipper.unzipFile(m.getName(), m.getStreamData(), "/data/ala/runtime/output/layers/");
String type = "";
String file = "";
if (input.containsKey(StringConstants.TYPE)) {
type = (String) input.get(StringConstants.TYPE);
}
if (input.containsKey(StringConstants.FILE)) {
file = (String) input.get(StringConstants.FILE);
}
if ("shp".equalsIgnoreCase(type)) {
LOGGER.debug("Uploaded file is a shapefile. Loading...");
Map shape = ShapefileUtils.loadShapefile(new File(file));
if (shape != null) {
String wkt = (String) shape.get(StringConstants.WKT);
LOGGER.debug("Got shapefile wkt...validating");
String msg = "";
boolean invalid = false;
try {
WKTReader wktReader = new WKTReader();
com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
// NC 20130319: Ensure that the WKT is valid according to the WKT standards.
IsValidOp op = new IsValidOp(g);
if (!op.isValid()) {
// this will fix some issues
g = g.buffer(0);
op = new IsValidOp(g);
}
if (!op.isValid()) {
invalid = true;
LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
msg = op.getValidationError().getMessage();
// TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
} else if (g.isRectangle()) {
// NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
// get the new WKT for the rectangle will possibly need to change the order.
com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
String wkt2 = "POLYGON((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
if (!wkt.equals(wkt2)) {
LOGGER.debug("NEW WKT for Rectangle: " + wkt);
msg = CommonData.lang("error_wkt_anticlockwise");
invalid = true;
}
}
if (!invalid) {
invalid = !op.isValid();
}
} catch (ParseException parseException) {
LOGGER.error("error testing validity of uploaded shape file wkt", parseException);
}
if (invalid) {
ok = false;
getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
} else {
layerName = getMapComposer().getNextAreaLayerName(txtLayerName.getValue());
MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layerName, txtLayerName.getValue());
ud.setUploadedTimeInMs(System.currentTimeMillis());
ud.setType("shapefile");
String metadata = "";
metadata += "User uploaded Shapefile \n";
metadata += "Name: " + ud.getName() + " <br />\n";
metadata += "Filename: " + ud.getFilename() + " <br />\n";
metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
ok = true;
}
}
} else {
LOGGER.debug("Unknown file type. ");
getMapComposer().showMessage(CommonData.lang("error_unknown_file_type"));
}
} else {
LOGGER.debug("Unknown file type. ");
getMapComposer().showMessage(CommonData.lang("error_unknown_file_type"));
}
} catch (Exception ex) {
getMapComposer().showMessage(CommonData.lang("error_upload_failed"));
LOGGER.error("unable to load user area file: ", ex);
}
}
use of com.vividsolutions.jts.operation.valid.IsValidOp in project spatial-portal by AtlasOfLivingAustralia.
the class AreaUploadShapefile method loadUserLayerKML.
public void loadUserLayerKML(String name, byte[] kmldata, UserDataDTO ud) {
try {
String id = String.valueOf(System.currentTimeMillis());
String kmlpath = "/data/ala/runtime/output/layers/" + id + "/";
File kmlfilepath = new File(kmlpath);
kmlfilepath.mkdirs();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(kmlfilepath.getAbsolutePath() + "/" + name)));
String kmlstr = new String(kmldata);
out.write(kmlstr);
out.close();
MapComposer mc = getMapComposer();
layerName = (mc.getMapLayer(txtLayerName.getValue()) == null) ? txtLayerName.getValue() : mc.getNextAreaLayerName(txtLayerName.getValue());
String wkt = getKMLPolygonAsWKT(kmlstr);
if (wkt != null && wkt.length() == 0) {
getMapComposer().showMessage("Failed to find the area in this KML file. \r\n\r\n" + "KML file must have a single placemark within no more than 1 folder.");
return;
} else if (wkt == null) {
getMapComposer().showMessage("Failed to parse this KML file. \r\n\r\n" + "Try importing a Shapefile or WKT instead.");
return;
}
boolean invalid = false;
String msg = "";
try {
WKTReader wktReader = new WKTReader();
com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
// NC 20130319: Ensure that the WKT is valid according to the WKT standards.
IsValidOp op = new IsValidOp(g);
if (!op.isValid()) {
// this will fix some issues
g = g.buffer(0);
op = new IsValidOp(g);
}
if (!op.isValid()) {
invalid = true;
LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
msg = op.getValidationError().getMessage();
// TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
} else if (g.isRectangle()) {
// NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
// get the new WKT for the rectangle will possibly need to change the order.
com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
if (!wkt.equals(wkt2)) {
LOGGER.debug("NEW WKT for Rectangle: " + wkt);
msg = CommonData.lang("error_wkt_anticlockwise");
invalid = true;
}
}
if (!invalid) {
invalid = !op.isValid();
}
} catch (ParseException parseException) {
LOGGER.error(CommonData.lang(StringConstants.ERROR_WKT_INVALID), parseException);
}
if (invalid) {
ok = false;
getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
} else {
MapLayer mapLayer = mc.addWKTLayer(wkt, layerName, txtLayerName.getValue());
ud.setUploadedTimeInMs(Long.parseLong(id));
ud.setType("kml");
String metadata = "";
metadata += "User uploaded KML area \n";
metadata += "Name: " + ud.getName() + " <br />\n";
metadata += "Filename: " + ud.getFilename() + " <br />\n";
metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
if (mapLayer == null) {
LOGGER.debug("The layer " + name + " couldnt be created");
mc.showMessage(mc.getLanguagePack().getLang("ext_layer_creation_failure"));
} else {
ok = true;
mc.addUserDefinedLayerToMenu(mapLayer, true);
}
}
} catch (IOException e) {
getMapComposer().showMessage(CommonData.lang("error_upload_failed"));
LOGGER.debug("unable to load user kml: ", e);
}
}
Aggregations