use of com.vividsolutions.jts.io.WKTReader in project hale by halestudio.
the class MsSqlGeometries method convertToInstanceGeometry.
/**
* @see eu.esdihumboldt.hale.io.jdbc.GeometryAdvisor#convertToInstanceGeometry(java.lang.Object,
* eu.esdihumboldt.hale.common.schema.model.TypeDefinition,
* java.lang.Object, java.util.function.Supplier)
*/
@Override
public GeometryProperty<?> convertToInstanceGeometry(Object geom, TypeDefinition columnType, SQLServerConnection connection, Supplier<CRSDefinition> crsProvider) throws Exception {
Statement stmt = null;
ResultSet rs = null;
try {
// We need Column Data type
String columnDataType = columnType.getName().getLocalPart();
String geomAsHex = BaseEncoding.base16().lowerCase().encode((byte[]) geom);
String sqlGeom = //
"SELECT top 1 GeomConvert.geom.STSrid srid, GeomConvert.geom.STAsText() as geomAsText, GeomConvert.geom.STGeometryType() as geomType " + //
"FROM " + "(SELECT cast(cast(temp.wkb as varbinary(max)) as " + columnDataType + //
") as geom " + //
"FROM " + "( select " + "0x" + geomAsHex + //
" as wkb) as temp" + //
") " + //
"as GeomConvert";
stmt = connection.createStatement();
rs = stmt.executeQuery(sqlGeom);
Geometry jtsGeom = null;
int srId = 0;
if (rs.next()) {
srId = rs.getInt(1);
String geomAsText = rs.getString(2);
String geomType = rs.getString(3);
// WKTReader does not support CircularString, CurvePolygon,
// CompoundCurve
WKTReader wktReader = getSpecificWktReader(geomType);
try {
// conversion to JTS via WKT
jtsGeom = wktReader.read(geomAsText);
} catch (ParseException e) {
log.error("Could not load geometry from database", e);
}
}
CRSDefinition crsDef = null;
String authName = SRSUtil.getAuthorityName(srId, connection);
if (authName != null && authName.equals("EPSG")) {
// For geography/geometry data type, SQL server assumes lon/lat
// axis order, if we read using SQL function
String epsgCode = authName + ":" + SRSUtil.getSRS(srId, connection);
if (columnDataType.equals("geography"))
crsDef = new CodeDefinition(epsgCode, true);
else
crsDef = new CodeDefinition(epsgCode, null);
} else {
String wkt = SRSUtil.getSRSText(srId, connection);
if (wkt != null) {
crsDef = new WKTDefinition(wkt, null);
}
}
if (crsDef == null) {
log.warn("Could not find spatial reference system id " + srId + " in MS sql server");
crsDef = crsProvider.get();
if (crsDef == null) {
log.warn("Could not retrieve default spatial reference for " + srId + " in MS sql server");
}
// saving in cache
if (crsDef != null) {
String srsName = CRS.toSRS(crsDef.getCRS());
if (srsName != null) {
final int index = srsName.lastIndexOf(':');
String authorityName = null;
String authorizedId = null;
if (index > 0) {
authorityName = srsName.substring(0, index);
authorizedId = srsName.substring(index + 1).trim();
}
// we don't need wkt.
SRSUtil.addSRSinCache(srId, authorityName, authorizedId, null);
}
}
}
return new DefaultGeometryProperty<Geometry>(crsDef, jtsGeom);
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
//
}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
//
}
}
}
use of com.vividsolutions.jts.io.WKTReader in project sldeditor by robward-scisys.
the class WKTConversion method convertToGeometry.
/**
* Convert to com.vividsolutions.jts.geom geometry.
*
* @param wktString the wkt string
* @param crsCode the crs code
* @return the geometry
*/
public static Geometry convertToGeometry(String wktString, String crsCode) {
int srid = 0;
if (crsCode != null) {
CoordinateReferenceSystem crs = CoordManager.getInstance().getCRS(crsCode);
String sridString = CRS.toSRS(crs, true);
srid = Integer.valueOf(sridString).intValue();
}
com.vividsolutions.jts.geom.GeometryFactory geometryFactory = new com.vividsolutions.jts.geom.GeometryFactory(new PrecisionModel(), srid);
WKTReader parser = new WKTReader(geometryFactory);
if (wktString.startsWith(WKT_PREFIX)) {
wktString = wktString.substring(WKT_PREFIX.length());
}
Geometry shape = null;
try {
shape = parser.read(wktString);
} catch (com.vividsolutions.jts.io.ParseException e) {
ConsoleManager.getInstance().exception(WKTConversion.class, e);
}
return shape;
}
use of com.vividsolutions.jts.io.WKTReader in project ignite by apache.
the class H2IndexingAbstractGeoSelfTest method checkLocalQuery.
/**
* Check local query.
*
* @throws ParseException If failed.
*/
private void checkLocalQuery() throws ParseException {
IgniteCache<Integer, Enemy> c1 = grid(0).cache("enemy");
IgniteCache<Integer, EnemyCamp> c2 = grid(0).cache("camp");
final Geometry lethalArea = new WKTReader().read("POLYGON((30 30, 30 70, 70 70, 70 30, 30 30))");
Set<Integer> localCampsIDs = new HashSet<>();
for (Cache.Entry<Integer, EnemyCamp> e : c2.localEntries()) localCampsIDs.add(e.getKey());
int expectedEnemies = 0;
for (Cache.Entry<Integer, Enemy> e : c1.localEntries()) {
final Integer campID = e.getValue().campId;
if (localCampsIDs.contains(campID)) {
final EnemyCamp camp = c2.get(campID);
if (lethalArea.covers(camp.coords))
expectedEnemies++;
}
}
final SqlFieldsQuery query = new SqlFieldsQuery("select e._val, c._val from \"enemy\".Enemy e, " + "\"camp\".EnemyCamp c where e.campId = c._key and c.coords && ?").setArgs(lethalArea);
List<List<?>> result = c1.query(query.setLocal(true)).getAll();
assertEquals(expectedEnemies, result.size());
}
use of com.vividsolutions.jts.io.WKTReader in project spatial-portal by AtlasOfLivingAustralia.
the class ExportLayerComposer method exportAreaAs.
public void exportAreaAs(String type, String name, SelectedArea sa) {
String exportBaseDir = CommonData.getSettings().getProperty(StringConstants.ANALYSIS_OUTPUT_DIR) + File.separator + "export" + File.separator;
try {
String id = String.valueOf(System.currentTimeMillis());
File shpDir = new File(exportBaseDir + id + File.separator);
shpDir.mkdirs();
File shpfile;
String contentType = LayersUtil.LAYER_TYPE_ZIP;
String outfile = name.replaceAll(" ", "_");
if ("shp".equals(type)) {
shpfile = new File(exportBaseDir + id + File.separator + outfile + "_Shapefile.shp");
ShapefileUtils.saveShapefile(shpfile, sa.getWkt(), name);
outfile += "_SHP.zip";
} else if ("kml".equals(type)) {
StringBuilder sbKml = new StringBuilder();
sbKml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append("\r");
sbKml.append("<kml xmlns=\"http://earth.google.com/kml/2.2\">").append("\r");
sbKml.append("<Document>").append("\r");
sbKml.append(" <name>Spatial Portal Active Area</name>").append("\r");
sbKml.append(" <description><![CDATA[Active area saved from the ALA Spatial Portal: http://spatial.ala.org.au/]]></description>").append("\r");
sbKml.append(" <Style id=\"style1\">").append("\r");
sbKml.append(" <LineStyle>").append("\r");
sbKml.append(" <color>40000000</color>").append("\r");
sbKml.append(" <width>3</width>").append("\r");
sbKml.append(" </LineStyle>").append("\r");
sbKml.append(" <PolyStyle>").append("\r");
sbKml.append(" <color>73FF0000</color>").append("\r");
sbKml.append(" <fill>1</fill>").append("\r");
sbKml.append(" <outline>1</outline>").append("\r");
sbKml.append(" </PolyStyle>").append("\r");
sbKml.append(" </Style>").append("\r");
sbKml.append(" <Placemark>").append("\r");
sbKml.append(" <name>").append(name).append("</name>").append("\r");
sbKml.append(" <description><![CDATA[<div dir=\"ltr\">").append(name).append("<br></div>]]></description>").append("\r");
sbKml.append(" <styleUrl>#style1</styleUrl>").append("\r");
// Remove first line of kmlGeometry, <?xml...>
Geometry geom = new WKTReader().read(sa.getWkt());
Encoder encoder = new Encoder(new KMLConfiguration());
encoder.setIndenting(true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
encoder.encode(geom, KML.Geometry, baos);
String kmlGeometry = new String(baos.toByteArray());
sbKml.append(kmlGeometry.substring(kmlGeometry.indexOf("?>") + 2));
sbKml.append(" </Placemark>").append("\r");
sbKml.append("</Document>").append("\r");
sbKml.append("</kml>").append("\r");
shpfile = new File(exportBaseDir + id + File.separator + outfile + "_KML.kml");
BufferedWriter wout = new BufferedWriter(new FileWriter(shpfile));
wout.write(sbKml.toString());
wout.close();
outfile += "_KML.zip";
} else if (StringConstants.WKT.equals(type)) {
shpfile = new File(exportBaseDir + id + File.separator + outfile + "_WKT.txt");
BufferedWriter wout = new BufferedWriter(new FileWriter(shpfile));
wout.write(sa.getWkt());
wout.close();
outfile += "_WKT.zip";
}
// zip shpfile
Zipper.zipDirectory(exportBaseDir + id + File.separator, exportBaseDir + id + ".zip");
try {
byte[] bytes = FileUtils.readFileToByteArray(new File(exportBaseDir + id + ".zip"));
Filedownload.save(bytes, contentType, outfile);
} catch (Exception e) {
LOGGER.error("failed to download file : " + exportBaseDir + id + ".zip", e);
}
try {
remoteLogger.logMapAnalysis(name, "Export - " + StringUtils.capitalize(type) + " Area", sa.getWkt(), "", "", "", outfile, "download");
} catch (Exception e) {
LOGGER.error("remote logger error", e);
}
} catch (Exception e) {
LOGGER.error("Unable to export user area", e);
}
}
use of com.vividsolutions.jts.io.WKTReader in project spatial-portal by AtlasOfLivingAustralia.
the class BiocacheQuery method newWkt.
/**
* Restrict to an area.
* <p/>
* If an area already exists the additional area is applied.
*
* @param wkt
* @return new BiocacheQuery with the additional wkt area applied.
*/
@Override
public BiocacheQuery newWkt(String wkt, boolean forMapping) {
if (wkt == null || wkt.equals(CommonData.WORLD_WKT) || wkt.equals(this.wkt)) {
if (this.forMapping || !forMapping) {
return this;
} else {
return new BiocacheQuery(lsids, rawNames, wkt, extraParams, facets, forMapping, null, biocacheServer, biocacheWebServer, this.supportsDynamicFacets);
}
}
BiocacheQuery sq = null;
try {
String newWkt = wkt;
if (this.wkt != null) {
Geometry newGeom = new WKTReader().read(wkt);
Geometry thisGeom = new WKTReader().read(this.wkt);
Geometry intersectionGeom = thisGeom.intersection(newGeom);
newWkt = (new WKTWriter()).write(intersectionGeom).replace(" (", "(").replace(", ", ",").replace(") ", ")");
}
sq = new BiocacheQuery(lsids, rawNames, newWkt, extraParams, facets, forMapping, null, biocacheServer, biocacheWebServer, this.supportsDynamicFacets);
} catch (Exception e) {
LOGGER.error("error getting new WKT from an intersection", e);
}
return sq;
}
Aggregations