private void computeGeodeticBBox(float geoWidth, float geoHeight, float centerX, float centerY, float dpi, String srsCode) {
try {
CoordinateReferenceSystem crs;
if (srsCode.equalsIgnoreCase("EPSG:900913")) {
crs = CRS.parseWKT(GOOGLE_WKT);
} else {
crs = CRS.decode(srsCode, true);
GeodeticCalculator calc = new GeodeticCalculator(crs);
DirectPosition2D directPosition2D = new DirectPosition2D(centerX, centerY);
directPosition2D.setCoordinateReferenceSystem(crs);
calc.setStartingPosition(directPosition2D);
calc.setDirection(-90, geoWidth / 2.0f);
minGeoX = (float) calc.getDestinationPosition().getOrdinate(0);
calc.setDirection(90, geoWidth / 2.0f);
maxGeoX = (float) calc.getDestinationPosition().getOrdinate(0);
calc.setDirection(180, geoHeight / 2.0f);
minGeoY = (float) calc.getDestinationPosition().getOrdinate(1);
calc.setDirection(0, geoHeight / 2.0f);
maxGeoY = (float) calc.getDestinationPosition().getOrdinate(1);
pixelPerGeoUnit = (paperWidth * dpi) / 72.0f / (maxGeoX - minGeoX);
} catch (Exception e) {
throw new RuntimeException(e);
Example 2
// docs end display
* Export features to a new shapefile using the map projection in which they are currently
* displayed
// docs start export
private void exportToShapefile() throws Exception {
SimpleFeatureType schema = featureSource.getSchema();
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save reprojected shapefile");
chooser.setSaveFile(sourceFile);
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
return;
File file = chooser.getSelectedFile();
if (file.equals(sourceFile)) {
JOptionPane.showMessageDialog(null, "Cannot replace " + file);
return;
// set up the math transform used to process the data
CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem worldCRS = map.getCoordinateReferenceSystem();
// allow for some error due to different datums
boolean lenient = true;
MathTransform transform = CRS.findMathTransform(dataCRS, worldCRS, lenient);
// grab all features
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
// And create a new Shapefile with a slight modified schema
DataStoreFactorySpi factory = new ShapefileDataStoreFactory();
Map<String, Serializable> create = new HashMap<String, Serializable>();
create.put("url", file.toURI().toURL());
create.put("create spatial index", Boolean.TRUE);
DataStore dataStore = factory.createNewDataStore(create);
SimpleFeatureType featureType = SimpleFeatureTypeBuilder.retype(schema, worldCRS);
dataStore.createSchema(featureType);
// carefully open an iterator and writer to process the results
Transaction transaction = new DefaultTransaction("Reproject");
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(featureType.getTypeName(), transaction);
SimpleFeatureIterator iterator = featureCollection.features();
try {
while (iterator.hasNext()) {
// copy the contents of each feature and transform the geometry
SimpleFeature feature = iterator.next();
SimpleFeature copy = writer.next();
copy.setAttributes(feature.getAttributes());
Geometry geometry = (Geometry) feature.getDefaultGeometry();
Geometry geometry2 = JTS.transform(geometry, transform);
copy.setDefaultGeometry(geometry2);
writer.write();
transaction.commit();
JOptionPane.showMessageDialog(null, "Export to shapefile complete");
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
JOptionPane.showMessageDialog(null, "Export to shapefile failed");
} finally {
writer.close();
iterator.close();
transaction.close();
Example 3
/**
* loadWMS purpose.
* Converts a DOM tree into a WMS object.
* @param wmsElement
* a DOM tree to convert into a WMS object.
* @throws ConfigurationException
* When an error occurs.
* @see GlobalData#getBaseUrl()
protected void loadWMS(Element wmsElement) throws ConfigurationException {
wms = new WMSDTO();
wms.setService(loadService(wmsElement));
final String spaceSeparatedListOfCrsCodes = ReaderUtils.getChildText(wmsElement, "capabilitiesCrsList");
if (spaceSeparatedListOfCrsCodes != null) {
final String[] codes = spaceSeparatedListOfCrsCodes.split(",");
Set capabilitiesCrsCodes = new HashSet();
for (int i = 0; i < codes.length; i++) {
String code = codes[i].toUpperCase().trim();
try {
CRS.decode(code);
capabilitiesCrsCodes.add(code);
} catch (Exception e) {
LOGGER.warning("Invalid CRS code found in capabilitiesCrsList: '" + code + "' is not a known CRS identifier");
wms.setCapabilitiesCrs(capabilitiesCrsCodes);
wms.setSvgRenderer(ReaderUtils.getChildText(wmsElement, "svgRenderer"));
wms.setSvgAntiAlias(!"false".equals(ReaderUtils.getChildText(wmsElement, "svgAntiAlias")));
if (ReaderUtils.getChildText(wmsElement, "globalWatermarking") != null) {
wms.setGlobalWatermarking(!"false".equals(ReaderUtils.getChildText(wmsElement, "globalWatermarking")));
wms.setGlobalWatermarkingURL(ReaderUtils.getChildText(wmsElement, "globalWatermarkingURL"));
if (ReaderUtils.getChildText(wmsElement, "globalWatermarkingTransparency") != null) {
wms.setWatermarkTransparency(Integer.parseInt(ReaderUtils.getChildText(wmsElement, "globalWatermarkingTransparency")));
if (ReaderUtils.getChildText(wmsElement, "globalWatermarkingPosition") != null) {
wms.setWatermarkPosition(Integer.parseInt(ReaderUtils.getChildText(wmsElement, "globalWatermarkingPosition")));
} else {
// lower right corner
wms.setWatermarkPosition(8);
try {
wms.setAllowInterpolation(ReaderUtils.getChildText(wmsElement, "allowInterpolation", true));
} catch (Exception e) {
wms.setAllowInterpolation("Nearest");
loadBaseMapLayers(wmsElement);
Example 4
/**
* If subclasses override they *must* call super.setUp() first.
@Override
protected void oneTimeSetUp() throws Exception {
// do we need to reset the referencing subsystem and reorient it with lon/lat order?
if (System.getProperty("org.geotools.referencing.forceXY") == null || !"http".equals(Hints.getSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING))) {
System.setProperty("org.geotools.referencing.forceXY", "true");
Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http");
CRS.reset("all");
// set up test data
testData = buildTestData();
testData.setUp();
// is loaded before GoeServer has a chance to setup logging for good)
try {
Logging.ALL.setLoggerFactory(Log4JLoggerFactory.getInstance());
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Could not configure log4j logging redirection", e);
System.setProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, "true");
GeoServerResourceLoader loader = new GeoServerResourceLoader(testData.getDataDirectoryRoot());
LoggingUtils.configureGeoServerLogging(loader, getClass().getResourceAsStream(getLogConfiguration()), false, true, null);
//HACK: once we port tests to the new data directory, remove this
GeoServerLoader.setLegacy(useLegacyDataDirectory());
// if we have data, create a mock servlet context and start up the spring configuration
if (testData.isTestDataAvailable()) {
MockServletContext servletContext = new MockServletContext();
servletContext.setInitParameter("GEOSERVER_DATA_DIR", testData.getDataDirectoryRoot().getPath());
servletContext.setInitParameter("serviceStrategy", "PARTIAL-BUFFER2");
//set up a fake WEB-INF directory
if (testData.getDataDirectoryRoot().canWrite()) {
File webinf = new File(testData.getDataDirectoryRoot(), "WEB-INF");
webinf.mkdir();
servletContext.setRealPath("WEB-INF", webinf.getAbsolutePath());
applicationContext = new GeoServerTestApplicationContext(getSpringContextLocations(), servletContext);
applicationContext.setUseLegacyGeoServerLoader(useLegacyDataDirectory());
applicationContext.refresh();
// set the parameter after a refresh because it appears a refresh
// wipes
// out all parameters
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
}
Example 5
/**
* Returns a {@link CoordinateReferenceSystem} object based on its identifier
* caching the result.
* The <tt>srsName</tt> parameter should have one of the forms:
* <li>EPSG:XXXX
* <li>http://www.opengis.net/gml/srs/epsg.xml#XXXX
* <li>urn:x-ogc:def:crs:EPSG:XXXX
* </ul>
* OR be something parsable by {@link CRS#decode(String)}.
* @param srsName The coordinate reference system identifier.
* @throws IOException In the event the srsName can not be parsed or leads
* to an exception in the underlying call to CRS.decode.
public CoordinateReferenceSystem getCRS(String srsName) throws IOException {
if (srsName == null)
return null;
CoordinateReferenceSystem crs = crsCache.get(srsName);
if (crs == null) {
synchronized (crsCache) {
crs = crsCache.get(srsName);
if (crs == null) {
try {
crs = CRS.decode(srsName);
crsCache.put(srsName, crs);
} catch (Exception e) {
throw (IOException) new IOException().initCause(e);
return crs;
}
Example 6
public void encode(Element element, Object value, PrintHandler output, Map hints) throws IOException, OperationNotSupportedException {
if (!canEncode(element, value, hints)) {
throw new OperationNotSupportedException("Cannot encode " + value);
if (value instanceof ReferencedEnvelope) {
ReferencedEnvelope bbox = (ReferencedEnvelope) value;
AttributesImpl ai = new AttributesImpl();
// no GID
if (bbox != null && bbox.getCoordinateReferenceSystem() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
String srsName = CRS.toSRS(bbox.getCoordinateReferenceSystem());
ai.addAttribute("", "srsName", "", "anyURI", srsName);
} else {
ai = null;
if (bbox == null || bbox.isNull() || bbox.isEmpty()) {
return;
// we handle the case for a null element, see canEncode for details
if (element != null) {
output.startElement(GMLSchema.NAMESPACE, element.getName(), ai);
} else {
output.startElement(GMLSchema.NAMESPACE, "Box", ai);
// Coordinate[] coords = g.getCoordinates();
Envelope e = bbox;
encodeCoords(elements[1], e, output);
if (element != null) {
output.endElement(GMLSchema.NAMESPACE, element.getName());
} else {
output.endElement(GMLSchema.NAMESPACE, "Box");
} else {
Geometry g = (Geometry) value;
AttributesImpl ai = new AttributesImpl();
// no GID
if (g != null && g.getUserData() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
ai.addAttribute("", "srsName", "", "anyURI", g.getUserData().toString());
} else {
// if (g.getSRID() != 0) {
// // deprecated version
// ai.addAttribute("", "srsName", "", "anyURI",
// "" + g.getSRID());
// } else {
ai = null;
// }
if ((g == null) || (g.getNumPoints() == 0) || (g.getCoordinates().length == 0)) {
return;
//we handle the case for a null element, see canEncode for details
if (element != null) {
output.startElement(GMLSchema.NAMESPACE, element.getName(), ai);
} else {
output.startElement(GMLSchema.NAMESPACE, "Box", ai);
// Coordinate[] coords = g.getCoordinates();
Envelope e = g.getEnvelopeInternal();
encodeCoords(elements[1], e, output);
if (element != null) {
output.endElement(GMLSchema.NAMESPACE, element.getName());
} else {
output.endElement(GMLSchema.NAMESPACE, "Box");
}
Example 7
public void encode(Element element, Object value, PrintHandler output, Map hints) throws IOException, OperationNotSupportedException {
if (!canEncode(element, value, hints)) {
throw new OperationNotSupportedException("Cannot encode " + value);
if (value instanceof ReferencedEnvelope) {
ReferencedEnvelope bbox = (ReferencedEnvelope) value;
AttributesImpl ai = new AttributesImpl();
// no GID
if (bbox != null && bbox.getCoordinateReferenceSystem() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
String srsName = CRS.toSRS(bbox.getCoordinateReferenceSystem());
ai.addAttribute("", "srsName", "", "anyURI", srsName);
} else {
ai = null;
if (bbox == null || bbox.isNull() || bbox.isEmpty()) {
return;
// we handle the case for a null element, see canEncode for details
if (element != null) {
output.startElement(GMLSchema.NAMESPACE, element.getName(), ai);
} else {
output.startElement(GMLSchema.NAMESPACE, "Box", ai);
// Coordinate[] coords = g.getCoordinates();
Envelope e = bbox;
encodeCoords(elements[1], e, output);
if (element != null) {
output.endElement(GMLSchema.NAMESPACE, element.getName());
} else {
output.endElement(GMLSchema.NAMESPACE, "Box");
} else {
Geometry g = (Geometry) value;
AttributesImpl ai = new AttributesImpl();
// no GID
if (g != null && g.getUserData() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
ai.addAttribute("", "srsName", "", "anyURI", g.getUserData().toString());
} else {
// if (g.getSRID() != 0) {
// // deprecated version
// ai.addAttribute("", "srsName", "", "anyURI",
// "" + g.getSRID());
// } else {
ai = null;
// }
if ((g == null) || (g.getNumPoints() == 0) || (g.getCoordinates().length == 0)) {
return;
//we handle the case for a null element, see canEncode for details
if (element != null) {
output.startElement(GMLSchema.NAMESPACE, element.getName(), ai);
} else {
output.startElement(GMLSchema.NAMESPACE, "Box", ai);
// Coordinate[] coords = g.getCoordinates();
Envelope e = g.getEnvelopeInternal();
encodeCoords(elements[1], e, output);
if (element != null) {
output.endElement(GMLSchema.NAMESPACE, element.getName());
} else {
output.endElement(GMLSchema.NAMESPACE, "Box");
}
Example 8
public void encode(Element element, Object value, PrintHandler output, Map hints) throws IOException, OperationNotSupportedException {
if (!canEncode(element, value, hints)) {
throw new OperationNotSupportedException("Cannot encode " + value);
if (value instanceof ReferencedEnvelope) {
ReferencedEnvelope bbox = (ReferencedEnvelope) value;
AttributesImpl ai = new AttributesImpl();
// no GID
if (bbox != null && bbox.getCoordinateReferenceSystem() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
String srsName = CRS.toSRS(bbox.getCoordinateReferenceSystem());
ai.addAttribute("", "srsName", "", "anyURI", srsName);
} else {
ai = null;
if (bbox == null || bbox.isNull() || bbox.isEmpty()) {
return;
// we handle the case for a null element, see canEncode for details
if (element != null) {
output.startElement(GMLSchema.NAMESPACE, element.getName(), ai);
} else {
output.startElement(GMLSchema.NAMESPACE, "Box", ai);
// Coordinate[] coords = g.getCoordinates();
Envelope e = bbox;
encodeCoords(elements[1], e, output);
if (element != null) {
output.endElement(GMLSchema.NAMESPACE, element.getName());
} else {
output.endElement(GMLSchema.NAMESPACE, "Box");
} else {
Geometry g = (Geometry) value;
AttributesImpl ai = new AttributesImpl();
// no GID
if (g != null && g.getUserData() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
ai.addAttribute("", "srsName", "", "anyURI", g.getUserData().toString());
} else {
// if (g.getSRID() != 0) {
// // deprecated version
// ai.addAttribute("", "srsName", "", "anyURI",
// "" + g.getSRID());
// } else {
ai = null;
// }
if ((g == null) || (g.getNumPoints() == 0) || (g.getCoordinates().length == 0)) {
return;
//we handle the case for a null element, see canEncode for details
if (element != null) {
output.startElement(GMLSchema.NAMESPACE, element.getName(), ai);
} else {
output.startElement(GMLSchema.NAMESPACE, "Box", ai);
// Coordinate[] coords = g.getCoordinates();
Envelope e = g.getEnvelopeInternal();
encodeCoords(elements[1], e, output);
if (element != null) {
output.endElement(GMLSchema.NAMESPACE, element.getName());
} else {
output.endElement(GMLSchema.NAMESPACE, "Box");
}
Example 9
private static AttributesImpl getSrsNameAttribute(Geometry g) {
AttributesImpl ai = new AttributesImpl();
// no GID
if (g.getUserData() != null) {
// TODO Fix this when parsing is better ... should be a coord reference system
if (g.getUserData() instanceof String) {
ai.addAttribute("", "srsName", "", "anyURI", (String) g.getUserData());
} else if (g.getUserData() instanceof CoordinateReferenceSystem) {
CoordinateReferenceSystem crs = (CoordinateReferenceSystem) g.getUserData();
try {
Integer code = CRS.lookupEpsgCode(crs, false);
if (code != null) {
ai.addAttribute("", "srsName", "", "anyURI", "EPSG:" + code);
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not encode the srsName for geometry, no EPSG code found", ex);
} else {
// if (g.getSRID() != 0) {
// // deprecated version
// ai.addAttribute("", "srsName", "", "anyURI", "" + g.getSRID());
// } else {
ai = null;
// }
return ai;
}
Example 10
/**
* Returns a {@link CoordinateReferenceSystem} object based on its identifier
* caching the result.
* The <tt>srsName</tt> parameter should have one of the forms:
* <li>EPSG:XXXX
* <li>http://www.opengis.net/gml/srs/epsg.xml#XXXX
* <li>urn:x-ogc:def:crs:EPSG:XXXX
* </ul>
* OR be something parsable by {@link CRS#decode(String)}.
* @param srsName The coordinate reference system identifier.
* @throws IOException In the event the srsName can not be parsed or leads
* to an exception in the underlying call to CRS.decode.
public CoordinateReferenceSystem getCRS(String srsName) throws IOException {
if (srsName == null)
return null;
CoordinateReferenceSystem crs = crsCache.get(srsName);
if (crs == null) {
synchronized (crsCache) {
crs = crsCache.get(srsName);
if (crs == null) {
try {
crs = CRS.decode(srsName);
crsCache.put(srsName, crs);
} catch (Exception e) {
throw (IOException) new IOException().initCause(e);
return crs;
}
Example 11
private static MosaicConfigurationBean loadMosaicProperties(final URL sourceURL, final Set<String> ignorePropertiesSet) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Trying to load properties file from URL:" + sourceURL);
// ret value
final MosaicConfigurationBean retValue = new MosaicConfigurationBean();
final CatalogConfigurationBean catalogConfigurationBean = new CatalogConfigurationBean();
retValue.setCatalogConfigurationBean(catalogConfigurationBean);
final boolean ignoreSome = ignorePropertiesSet != null && !ignorePropertiesSet.isEmpty();
// load the properties file
URL propsURL = sourceURL;
if (!sourceURL.toExternalForm().endsWith(".properties")) {
propsURL = DataUtilities.changeUrlExt(sourceURL, "properties");
if (propsURL.getProtocol().equals("file")) {
final File sourceFile = DataUtilities.urlToFile(propsURL);
if (!sourceFile.exists()) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("properties file doesn't exist");
return null;
final Properties properties = CoverageUtilities.loadPropertiesFromURL(propsURL);
if (properties == null) {
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Unable to load mosaic properties file");
return null;
String[] pairs = null;
String pair[] = null;
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.ENVELOPE2D)) {
String bboxString = properties.getProperty(Prop.ENVELOPE2D, null);
if (bboxString != null) {
bboxString = bboxString.trim();
try {
ReferencedEnvelope bbox = parseEnvelope(bboxString);
if (bbox != null)
retValue.setEnvelope(bbox);
else if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Cannot parse imposed bbox.");
} catch (Exception e) {
if (LOGGER.isLoggable(Level.INFO))
LOGGER.log(Level.INFO, "Cannot parse imposed bbox.", e);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.AUXILIARY_FILE)) {
retValue.setAuxiliaryFilePath(properties.getProperty(Prop.AUXILIARY_FILE));
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.AUXILIARY_DATASTORE_FILE)) {
retValue.setAuxiliaryDatastorePath(properties.getProperty(Prop.AUXILIARY_DATASTORE_FILE));
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.CHECK_AUXILIARY_METADATA)) {
final boolean checkAuxiliaryMetadata = Boolean.valueOf(properties.getProperty(Prop.CHECK_AUXILIARY_METADATA, "false").trim());
retValue.setCheckAuxiliaryMetadata(checkAuxiliaryMetadata);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.LEVELS)) {
int levelsNumber = Integer.parseInt(properties.getProperty(Prop.LEVELS_NUM, "1").trim());
retValue.setLevelsNum(levelsNumber);
if (!properties.containsKey(Prop.LEVELS)) {
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Required key Levels not found.");
return null;
final String levels = properties.getProperty(Prop.LEVELS).trim();
pairs = levels.split(" ");
if (pairs.length != levelsNumber) {
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("Levels number is different from the provided number of levels resoltion.");
return null;
final double[][] resolutions = new double[levelsNumber][2];
for (int i = 0; i < levelsNumber; i++) {
pair = pairs[i].split(",");
if (pair == null || pair.length != 2) {
if (LOGGER.isLoggable(Level.INFO))
LOGGER.info("OverviewLevel number is different from the provided number of levels resoltion.");
return null;
resolutions[i][0] = Double.parseDouble(pair[0]);
resolutions[i][1] = Double.parseDouble(pair[1]);
retValue.setLevels(resolutions);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.TYPENAME)) {
String typeName = properties.getProperty(Prop.TYPENAME, null);
catalogConfigurationBean.setTypeName(typeName);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.SUGGESTED_SPI)) {
if (properties.containsKey(Prop.SUGGESTED_SPI)) {
final String suggestedSPI = properties.getProperty(Prop.SUGGESTED_SPI).trim();
catalogConfigurationBean.setSuggestedSPI(suggestedSPI);
if (properties.containsKey(Prop.TIME_ATTRIBUTE)) {
final String timeAttribute = properties.getProperty("TimeAttribute").trim();
retValue.setTimeAttribute(timeAttribute);
if (properties.containsKey(Prop.ELEVATION_ATTRIBUTE)) {
final String elevationAttribute = properties.getProperty(Prop.ELEVATION_ATTRIBUTE).trim();
retValue.setElevationAttribute(elevationAttribute);
if (properties.containsKey(Prop.CRS_ATTRIBUTE)) {
final String crsAttribute = properties.getProperty(Prop.CRS_ATTRIBUTE).trim();
retValue.setCRSAttribute(crsAttribute);
if (properties.containsKey(Prop.ADDITIONAL_DOMAIN_ATTRIBUTES)) {
final String additionalDomainAttributes = properties.getProperty(Prop.ADDITIONAL_DOMAIN_ATTRIBUTES).trim();
retValue.setAdditionalDomainAttributes(additionalDomainAttributes);
if (properties.containsKey(Prop.CACHING)) {
String caching = properties.getProperty(Prop.CACHING).trim();
try {
catalogConfigurationBean.setCaching(Boolean.valueOf(caching));
} catch (Throwable e) {
catalogConfigurationBean.setCaching(Boolean.valueOf(Utils.DEFAULT_CACHING_BEHAVIOR));
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.NAME)) {
if (!properties.containsKey(Prop.NAME)) {
if (LOGGER.isLoggable(Level.SEVERE))
LOGGER.severe("Required key Name not found.");
return null;
String coverageName = properties.getProperty(Prop.NAME).trim();
retValue.setName(coverageName);
// we do not find it.
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.EXP_RGB)) {
final boolean expandMe = Boolean.valueOf(properties.getProperty(Prop.EXP_RGB, "false").trim());
retValue.setExpandToRGB(expandMe);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.WRAP_STORE)) {
final boolean wrapStore = Boolean.valueOf(properties.getProperty(Prop.WRAP_STORE, "false").trim());
catalogConfigurationBean.setWrapStore(wrapStore);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.HETEROGENEOUS)) {
final boolean heterogeneous = Boolean.valueOf(properties.getProperty(Prop.HETEROGENEOUS, "false").trim());
catalogConfigurationBean.setHeterogeneous(heterogeneous);
if (!catalogConfigurationBean.isHeterogeneous() && (!ignoreSome || !ignorePropertiesSet.contains(Prop.HETEROGENEOUS_CRS))) {
final boolean heterogeneous = Boolean.valueOf(properties.getProperty(Prop.HETEROGENEOUS_CRS, "false").trim());
catalogConfigurationBean.setHeterogeneous(heterogeneous);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.ABSOLUTE_PATH)) {
final boolean absolutePath = Boolean.valueOf(properties.getProperty(Prop.ABSOLUTE_PATH, Boolean.toString(Utils.DEFAULT_PATH_BEHAVIOR)).trim());
catalogConfigurationBean.setAbsolutePath(absolutePath);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.FOOTPRINT_MANAGEMENT)) {
final boolean footprintManagement = Boolean.valueOf(properties.getProperty(Prop.FOOTPRINT_MANAGEMENT, "false").trim());
retValue.setFootprintManagement(footprintManagement);
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.LOCATION_ATTRIBUTE)) {
catalogConfigurationBean.setLocationAttribute(properties.getProperty(Prop.LOCATION_ATTRIBUTE, Utils.DEFAULT_LOCATION_ATTRIBUTE).trim());
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.COVERAGE_NAME_COLLECTOR_SPI)) {
String coverageNameCollectorSpi = properties.getProperty(Prop.COVERAGE_NAME_COLLECTOR_SPI);
if (coverageNameCollectorSpi != null && ((coverageNameCollectorSpi = coverageNameCollectorSpi.trim()) != null)) {
retValue.setCoverageNameCollectorSpi(coverageNameCollectorSpi);
// target CRS
if (!ignoreSome || !ignorePropertiesSet.contains(Prop.MOSAIC_CRS)) {
String crsCode = properties.getProperty(Prop.MOSAIC_CRS);
if (crsCode != null && !crsCode.isEmpty()) {
try {
retValue.setCrs(decodeSrs(crsCode));
} catch (FactoryException e) {
LOGGER.log(Level.FINE, "Unable to decode CRS of mosaic properties file. Configured CRS " + "code was: " + crsCode, e);
// Also initialize the indexer here, since it will be needed later on.
File mosaicParentFolder = DataUtilities.urlToFile(sourceURL).getParentFile();
Indexer indexer = loadIndexer(mosaicParentFolder);
if (indexer != null) {
retValue.setIndexer(indexer);
String granuleCollectorFactorySPI = IndexerUtils.getParameter(Prop.GRANULE_COLLECTOR_FACTORY, indexer);
if (granuleCollectorFactorySPI == null || granuleCollectorFactorySPI.length() <= 0) {
boolean isHeterogeneousCRS = Boolean.parseBoolean(IndexerUtils.getParameter(Prop.HETEROGENEOUS_CRS, indexer));
if (isHeterogeneousCRS) {
//in this case we know we need the reprojecting collector anyway, let's use it
IndexerUtils.setParam(indexer, Prop.GRANULE_COLLECTOR_FACTORY, ReprojectingSubmosaicProducerFactory.class.getName());
// return value
return retValue;
}
Example 12
/**
* Writes a set of feature diffs to the stream.
* @param diffs a map of {@link PropertyDescriptor} to {@link AttributeDiffs} that specify the
* difference between two features
* @throws XMLStreamException
public void writeFeatureDiffResponse(Map<PropertyDescriptor, AttributeDiff> diffs) throws XMLStreamException {
Set<Entry<PropertyDescriptor, AttributeDiff>> entries = diffs.entrySet();
Iterator<Entry<PropertyDescriptor, AttributeDiff>> iter = entries.iterator();
while (iter.hasNext()) {
Entry<PropertyDescriptor, AttributeDiff> entry = iter.next();
out.writeStartElement("diff");
PropertyType attrType = entry.getKey().getType();
if (attrType instanceof GeometryType) {
writeElement("geometry", "true");
GeometryType gt = (GeometryType) attrType;
CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
if (crs != null) {
String crsCode = null;
try {
crsCode = CRS.lookupIdentifier(Citations.EPSG, crs, false);
} catch (FactoryException e) {
crsCode = null;
if (crsCode != null) {
writeElement("crs", "EPSG:" + crsCode);
writeElement("attributename", entry.getKey().getName().toString());
writeElement("changetype", entry.getValue().getType().toString());
if (entry.getValue().getOldValue() != null && entry.getValue().getOldValue().isPresent()) {
writeElement("oldvalue", entry.getValue().getOldValue().get().toString());
if (entry.getValue().getNewValue() != null && entry.getValue().getNewValue().isPresent() && !entry.getValue().getType().equals(TYPE.NO_CHANGE)) {
writeElement("newvalue", entry.getValue().getNewValue().get().toString());
out.writeEndElement();
}
Example 13
/**
* @param src
* @param dstGridGeometry
* @throws IllegalArgumentException
private void initTransformations() throws IllegalArgumentException {
// === Take one for all all the transformation we need to pass from
// model, sample, src, target and viceversa.
g2wd = (AffineTransform) dstGridGeometry.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
try {
w2gd = g2wd.createInverse();
} catch (NoninvertibleTransformException e) {
throw new IllegalArgumentException("Can't compute source W2G", e);
g2ws = (AffineTransform) src.getGridGeometry().getGridToCRS2D(PixelOrientation.UPPER_LEFT);
try {
w2gs = g2ws.createInverse();
} catch (NoninvertibleTransformException e) {
throw new IllegalArgumentException("Can't compute source W2G", e);
try {
CoordinateReferenceSystem sourceCRS = src.getCoordinateReferenceSystem2D();
CoordinateReferenceSystem targetCRS = dstGridGeometry.getCoordinateReferenceSystem2D();
if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
src2dstCRSTransform = CRS.findMathTransform(sourceCRS, targetCRS, true);
dst2srcCRSTransform = src2dstCRSTransform.inverse();
if (!src2dstCRSTransform.isIdentity()) {
needReprojection = true;
return;
// === if we got here we don't need to reproject, let's concatenate the transforms
// we don't reproject, let's simplify
needReprojection = false;
concatenatedForwardTransform = (AffineTransform) w2gd.clone();
concatenatedForwardTransform.concatenate(g2ws);
concatenatedBackwardTransform = concatenatedForwardTransform.createInverse();
if (XAffineTransform.isIdentity(concatenatedForwardTransform, 1E-6)) {
// TODO improve this check
// identity
concatenatedForwardTransform = new AffineTransform();
// identity
concatenatedBackwardTransform = new AffineTransform();
} catch (Exception e) {
throw new IllegalArgumentException("Can't create a transform between CRS", e);
}
Example 14
/**
* Writes a set of feature diffs to the stream.
* @param diffs a map of {@link PropertyDescriptor} to {@link AttributeDiffs} that specify the
* difference between two features
* @throws XMLStreamException
public void writeFeatureDiffResponse(Map<PropertyDescriptor, AttributeDiff> diffs) throws XMLStreamException {
Set<Entry<PropertyDescriptor, AttributeDiff>> entries = diffs.entrySet();
Iterator<Entry<PropertyDescriptor, AttributeDiff>> iter = entries.iterator();
while (iter.hasNext()) {
Entry<PropertyDescriptor, AttributeDiff> entry = iter.next();
out.writeStartElement("diff");
PropertyType attrType = entry.getKey().getType();
if (attrType instanceof GeometryType) {
writeElement("geometry", "true");
GeometryType gt = (GeometryType) attrType;
CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
if (crs != null) {
String crsCode = null;
try {
crsCode = CRS.lookupIdentifier(Citations.EPSG, crs, false);
} catch (FactoryException e) {
crsCode = null;
if (crsCode != null) {
writeElement("crs", "EPSG:" + crsCode);
writeElement("attributename", entry.getKey().getName().toString());
writeElement("changetype", entry.getValue().getType().toString());
if (entry.getValue().getOldValue() != null && entry.getValue().getOldValue().isPresent()) {
writeElement("oldvalue", entry.getValue().getOldValue().get().toString());
if (entry.getValue().getNewValue() != null && entry.getValue().getNewValue().isPresent() && !entry.getValue().getType().equals(TYPE.NO_CHANGE)) {
writeElement("newvalue", entry.getValue().getNewValue().get().toString());
out.writeEndElement();
}
Example 15
public void load(File blockShapefile, Geometry boundary) throws IOException, FactoryException {
System.out.println("loading " + blockShapefile.getName());
PreparedPolygon preparedBoundary = null;
if (boundary != null)
preparedBoundary = new PreparedPolygon((Polygonal) boundary);
Map map = new HashMap();
map.put("url", blockShapefile.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
SimpleFeatureType schema = featureSource.getSchema();
CoordinateReferenceSystem shpCRS = schema.getCoordinateReferenceSystem();
MathTransform transform = CRS.findMathTransform(shpCRS, wgsCRS, true);
SimpleFeatureCollection collection = featureSource.getFeatures();
SimpleFeatureIterator iterator = collection.features();
Integer skippedFeatures = 0;
Integer clipedFeatures = 0;
try {
while (iterator.hasNext()) {
try {
SimpleFeature feature = iterator.next();
String geoId = (String) feature.getAttribute("GEOID10");
Long areaLand = (Long) feature.getAttribute("ALAND10");
Long areaWater = (Long) feature.getAttribute("AWATER10");
Double percentLand = (double) (areaLand / (areaLand + areaWater));
Geometry geom = JTS.transform((Geometry) feature.getDefaultGeometry(), transform);
Point centroid = geom.getCentroid();
if (preparedBoundary == null || (preparedBoundary.contains(centroid)))
lodesBlocks.put(geoId, new IndicatorItem(geoId, geom, percentLand));
clipedFeatures++;
} catch (Exception e) {
skippedFeatures++;
System.out.println(e.toString());
continue;
} finally {
iterator.close();
dataStore.dispose();
System.out.println("Features imported: " + lodesBlocks.size() + "(" + skippedFeatures + " skipped, " + clipedFeatures + " outside survey area)");
}
Example 16
@Override
public void createIndividuals() {
LOG.info("Loading population from raster file {}", sourceFilename);
try {
File rasterFile = new File(sourceFilename);
// determine file format and CRS, then load raster
AbstractGridFormat format = GridFormatFinder.findFormat(rasterFile);
AbstractGridCoverage2DReader reader = format.getReader(rasterFile);
GridCoverage2D coverage = reader.read(null);
this.coverageCRS = coverage.getCoordinateReferenceSystem();
GridGeometry2D gridGeometry = coverage.getGridGeometry();
GridEnvelope2D gridEnvelope = gridGeometry.getGridRange2D();
gridGeometry.getGridToCRS();
// because we may want to produce an empty raster rather than loading one, alongside the coverage we
// store the row/col dimensions and the referenced envelope in the original coordinate reference system.
this.cols = gridEnvelope.width;
this.rows = gridEnvelope.height;
this.createIndividuals0();
} catch (Exception ex) {
throw new IllegalStateException("Error loading population from raster file: ", ex);
LOG.info("Done loading raster from file.");
}
Example 17
@Override
public void createIndividuals() {
LOG.info("Loading population from raster file {}", sourceFilename);
try {
File rasterFile = new File(sourceFilename);
// determine file format and CRS, then load raster
AbstractGridFormat format = GridFormatFinder.findFormat(rasterFile);
AbstractGridCoverage2DReader reader = format.getReader(rasterFile);
GridCoverage2D coverage = reader.read(null);
this.coverageCRS = coverage.getCoordinateReferenceSystem();
GridGeometry2D gridGeometry = coverage.getGridGeometry();
GridEnvelope2D gridEnvelope = gridGeometry.getGridRange2D();
gridGeometry.getGridToCRS();
// because we may want to produce an empty raster rather than loading one, alongside the coverage we
// store the row/col dimensions and the referenced envelope in the original coordinate reference system.
this.cols = gridEnvelope.width;
this.rows = gridEnvelope.height;
this.createIndividuals0();
} catch (Exception ex) {
throw new IllegalStateException("Error loading population from raster file: ", ex);
LOG.info("Done loading raster from file.");
}
Example 18
public static PointSet fromShapefile(File file, String originIDField, List<String> propertyFields) throws IOException, NoSuchAuthorityCodeException, FactoryException, EmptyPolygonException, UnsupportedGeometryException {
if (!file.exists())
throw new RuntimeException("Shapefile does not exist.");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
// Set up fields based on first feature in collection
// This assumes that all features have the same set of properties, which I think is always the case for shapefiles
SimpleFeatureIterator it = featureCollection.features();
SimpleFeature protoFt = it.next();
if (propertyFields == null) {
propertyFields = new ArrayList<String>();
// No property fields specified, so use all property fields
for (Property p : protoFt.getProperties()) {
propertyFields.add(p.getName().toString());
// If ID field is specified, don't use it as a property
if (originIDField != null && propertyFields.contains(originIDField)) {
propertyFields.remove(originIDField);
// Reset iterator
it = featureCollection.features();
PointSet ret = new PointSet(featureCollection.size());
int i = 0;
while (it.hasNext()) {
SimpleFeature feature = it.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
PointFeature ft = new PointFeature();
ft.setGeom(geom);
// Set feature's ID to the specified ID field, or to index if none is specified
if (originIDField == null) {
ft.setId(Integer.toString(i));
} else {
ft.setId(feature.getProperty(originIDField).getValue().toString());
for (Property prop : feature.getProperties()) {
String propName = prop.getName().toString();
if (propertyFields.contains(propName)) {
Object binding = prop.getType().getBinding();
//attempt to coerce the prop's value into an integer
int val;
if (binding.equals(Integer.class)) {
val = (Integer) prop.getValue();
} else if (binding.equals(Long.class)) {
val = ((Long) prop.getValue()).intValue();
} else if (binding.equals(String.class)) {
try {
val = Integer.parseInt((String) prop.getValue());
} catch (NumberFormatException ex) {
continue;
} else {
LOG.debug("Property {} of feature {} could not be interpreted as int, skipping", prop.getName().toString(), ft.getId());
continue;
ft.addAttribute(propName, val);
} else {
LOG.debug("Property {} not requested; igoring", propName);
ret.addFeature(ft, i);
ArrayList<String> IDlist = new ArrayList<String>();
for (String id : ret.ids) {
IDlist.add(id);
LOG.debug("Created PointSet from shapefile with IDs {}", IDlist);
return ret;
}
Example 19
public static PointSet fromShapefile(File file, String originIDField, List<String> propertyFields) throws IOException, NoSuchAuthorityCodeException, FactoryException, EmptyPolygonException, UnsupportedGeometryException {
if (!file.exists())
throw new RuntimeException("Shapefile does not exist.");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
// Set up fields based on first feature in collection
// This assumes that all features have the same set of properties, which I think is always the case for shapefiles
SimpleFeatureIterator it = featureCollection.features();
SimpleFeature protoFt = it.next();
if (propertyFields == null) {
propertyFields = new ArrayList<String>();
// No property fields specified, so use all property fields
for (Property p : protoFt.getProperties()) {
propertyFields.add(p.getName().toString());
// If ID field is specified, don't use it as a property
if (originIDField != null && propertyFields.contains(originIDField)) {
propertyFields.remove(originIDField);
// Reset iterator
it = featureCollection.features();
PointSet ret = new PointSet(featureCollection.size());
int i = 0;
while (it.hasNext()) {
SimpleFeature feature = it.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
PointFeature ft = new PointFeature();
ft.setGeom(geom);
// Set feature's ID to the specified ID field, or to index if none is specified
if (originIDField == null) {
ft.setId(Integer.toString(i));
} else {
ft.setId(feature.getProperty(originIDField).getValue().toString());
for (Property prop : feature.getProperties()) {
String propName = prop.getName().toString();
if (propertyFields.contains(propName)) {
Object binding = prop.getType().getBinding();
//attempt to coerce the prop's value into an integer
int val;
if (binding.equals(Integer.class)) {
val = (Integer) prop.getValue();
} else if (binding.equals(Long.class)) {
val = ((Long) prop.getValue()).intValue();
} else if (binding.equals(String.class)) {
try {
val = Integer.parseInt((String) prop.getValue());
} catch (NumberFormatException ex) {
continue;
} else {
LOG.debug("Property {} of feature {} could not be interpreted as int, skipping", prop.getName().toString(), ft.getId());
continue;
ft.addAttribute(propName, val);
} else {
LOG.debug("Property {} not requested; igoring", propName);
ret.addFeature(ft, i);
ArrayList<String> IDlist = new ArrayList<String>();
for (String id : ret.ids) {
IDlist.add(id);
LOG.debug("Created PointSet from shapefile with IDs {}", IDlist);
return ret;
}
Example 20
public void updateFormModel(Map<String, Object> parameterMap) throws ValidationException, ConversionException {
Property[] properties = reprojectionContainer.getProperties();
for (Property property : properties) {
String propertyName = property.getName();
Object newValue = parameterMap.get(propertyName);
if (newValue != null) {
property.setValue(newValue);
if (orthoMode) {
Object elevationModelName = parameterMap.get("elevationModelName");
if (elevationModelName instanceof String) {
try {
demSelector.setDemName((String) elevationModelName);
} catch (ParamValidateException e) {
throw new ValidationException(e.getMessage(), e);
} catch (ParamParseException e) {
throw new ConversionException(e.getMessage(), e);
Object crsAsWKT = parameterMap.get("crs");
if (crsAsWKT instanceof String) {
try {
CoordinateReferenceSystem crs;
crs = CRS.parseWKT((String) crsAsWKT);
if (crs instanceof ProjectedCRS) {
ProjectedCRS projectedCRS = (ProjectedCRS) crs;
Projection conversionFromBase = projectedCRS.getConversionFromBase();
OperationMethod operationMethod = conversionFromBase.getMethod();
ParameterValueGroup parameterValues = conversionFromBase.getParameterValues();
GeodeticDatum geodeticDatum = projectedCRS.getDatum();
customCrsUI.setCustom(geodeticDatum, operationMethod, parameterValues);
} else {
throw new ConversionException("Failed to convert CRS from WKT.");
} catch (FactoryException e) {
throw new ConversionException("Failed to convert CRS from WKT.", e);
if (parameterMap.containsKey("referencePixelX")) {
PropertyContainer propertySet = PropertyContainer.createMapBacked(parameterMap);
outputGeometryModel = new OutputGeometryFormModel(propertySet);
reprojectionContainer.setValue(Model.PRESERVE_RESOLUTION, false);
} else {
outputGeometryModel = null;
reprojectionContainer.setValue(Model.PRESERVE_RESOLUTION, true);
updateCRS();
}
Example 21
public static final Point fromLatLon(double lat, double lon) {
Point result = null;
try {
CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:" + DEFAULT_GEOM);
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + TARGET_GEOM);
// Logger.info(targetCRS.toWKT());
MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, false);
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), DEFAULT_GEOM);
Point point = geometryFactory.createPoint(new Coordinate(lat, lon));
result = (Point) JTS.transform(point, transform);
result.setSRID(TARGET_GEOM);
} catch (FactoryException e) {
Logger.error("Could not get CRS for EPSG_3857", e);
} catch (TransformException e) {
Logger.error("Could not transform (" + lat + ", " + lon + ") into EPSG_3857");
return result;
}
Example 22
// -----------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------
* Set the FeatureType for this Data Adapter.
* @param featureType
* - new feature type
private void setFeatureType(final SimpleFeatureType featureType) {
persistedFeatureType = featureType;
if (GeoWaveGTDataStore.DEFAULT_CRS.equals(featureType.getCoordinateReferenceSystem())) {
reprojectedFeatureType = persistedFeatureType;
} else {
reprojectedFeatureType = SimpleFeatureTypeBuilder.retype(featureType, GeoWaveGTDataStore.DEFAULT_CRS);
if (featureType.getCoordinateReferenceSystem() != null) {
try {
transform = CRS.findMathTransform(featureType.getCoordinateReferenceSystem(), GeoWaveGTDataStore.DEFAULT_CRS, true);
} catch (final FactoryException e) {
LOGGER.warn("Unable to create coordinate reference system transform", e);
resetTimeDescriptors();
statsManager = new StatsManager(this, persistedFeatureType, reprojectedFeatureType, transform);
secondaryIndexManager = new SecondaryIndexManager(this, persistedFeatureType, statsManager);
}
Example 23
/**
* DOCUMENT ME!
* @return DOCUMENT ME!
* @throws DriverException
* @throws XMLException
public org.gvsig.persistence.generated.Project getXMLEntity() {
org.gvsig.persistence.generated.Project ret = new org.gvsig.persistence.generated.Project();
ret.setVersion(VERSION);
ret.setName(name);
ret.setComments(getComments());
ret.setOwner(owner);
ret.setCreationDate(creationDate);
ret.setModificationDate(modificationDate);
ret.setAbsolutePath(isAbsolutePath);
ret.setSelectionColor(StringUtilities.color2String(selectionColor));
ret.setDefaultCrs(CRS.toSRS(crs));
for (int i = 0; i < extents.size(); i++) {
ret.getExtents().add(extents.get(i).getXMLEntity());
for (int i = 0; i < documents.size(); i++) {
DocumentType xmlchild = documents.get(i).getXMLEntity();
ret.getDocuments().add(xmlchild);
return ret;
}
Example 24
/**
* Checks if GeoPosition are in a metric system and if not convert them if
* necessary.
* @param pos List of {@link GeoPosition}
* @return List of {@link GeoPosition}
public List<GeoPosition> checkEPSG(List<GeoPosition> pos) {
// list is empty
if (pos.size() == 0) {
return pos;
int epsg = pos.get(0).getEpsgCode();
// Worldmercator
int FALLBACK_EPSG = 3395;
// WGS84
FALLBACK_EPSG = 4326;
try {
CoordinateSystem cs = CRS.decode("EPSG:" + epsg).getCoordinateSystem();
for (int i = 0; epsg != FALLBACK_EPSG && i < cs.getDimension(); i++) {
CoordinateSystemAxis axis = cs.getAxis(i);
try {
Unit<Length> unit = axis.getUnit().asType(Length.class);
if (!//$NON-NLS-1$
unit.toString().equals(//$NON-NLS-1$
"m")) {
// not metric
epsg = FALLBACK_EPSG;
} catch (ClassCastException e) {
epsg = FALLBACK_EPSG;
} catch (Exception e) {
e.printStackTrace();
// convert all coordinates
try {
GeotoolsConverter g = (GeotoolsConverter) GeotoolsConverter.getInstance();
pos = g.convertAll(pos, epsg);
} catch (IllegalGeoPositionException e1) {
e1.printStackTrace();
return pos;
}
Example 25
private void useCombinedSVMmodels(Collection<OsmPrimitive> sel, boolean useClassFeatures) {
System.out.println("The system will combine " + filesAndWeights.size() + " SVM models.");
MathTransform transform = null;
GeometryFactory geometryFactory = new GeometryFactory();
CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem targetCRS = DefaultGeocentricCRS.CARTESIAN;
try {
transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
} catch (FactoryException ex) {
Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex);
OSMWay selectedInstance;
List<OsmPrimitive> osmPrimitiveSelection = new ArrayList<>(sel);
OsmPrimitive s;
//get a simple selection
if (!osmPrimitiveSelection.isEmpty()) {
s = osmPrimitiveSelection.get(0);
} else {
return;
selectedInstance = new OSMWay();
for (Way selectedWay : s.getDataSet().getSelectedWays()) {
List<Node> selectedWayNodes = selectedWay.getNodes();
for (Node node : selectedWayNodes) {
node.getCoor();
if (node.isLatLonKnown()) {
double lat = node.getCoor().lat();
double lon = node.getCoor().lon();
Coordinate sourceCoordinate = new Coordinate(lon, lat);
Coordinate targetGeometry = null;
try {
targetGeometry = JTS.transform(sourceCoordinate, null, transform);
} catch (MismatchedDimensionExceptionTransformException | ex) {
Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
selectedInstance.addNodeGeometry(geom);
Geometry fullGeom = geometryFactory.buildGeometry(selectedInstance.getNodeGeometries());
if ((selectedInstance.getNodeGeometries().size() > 3) && selectedInstance.getNodeGeometries().get(0).equals(selectedInstance.getNodeGeometries().get(selectedInstance.getNodeGeometries().size() - 1))) {
//checks if the beginning and ending node are the same and the number of nodes are more than 3.
//the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
LinearRing linear = geometryFactory.createLinearRing(fullGeom.getCoordinates());
Polygon poly = new Polygon(linear, null, geometryFactory);
selectedInstance.setGeometry(poly);
System.out.println("\n\npolygon");
} else if (selectedInstance.getNodeGeometries().size() > 1) {
//it is an open geometry with more than one nodes, make it linestring
System.out.println("\n\nlinestring");
LineString lineString = geometryFactory.createLineString(fullGeom.getCoordinates());
selectedInstance.setGeometry(lineString);
} else {
//we assume all the rest geometries are points
System.out.println("\n\npoint");
Point point = geometryFactory.createPoint(fullGeom.getCoordinate());
selectedInstance.setGeometry(point);
Map<String, String> selectedTags = s.getInterestingTags();
selectedInstance.setAllTags(selectedTags);
//construct vector
if (selectedInstance != null) {
int id;
OSMClassification classifier = new OSMClassification();
classifier.calculateClasses(selectedInstance, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
if (useClassFeatures) {
ClassFeatures classFeatures = new ClassFeatures();
classFeatures.createClassFeatures(selectedInstance, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
id = 1422;
} else {
id = 1;
GeometryFeatures geometryFeatures = new GeometryFeatures(id);
geometryFeatures.createGeometryFeatures(selectedInstance);
id = geometryFeatures.getLastID();
TextualFeatures textualFeatures = new TextualFeatures(id, textualList, languageDetector);
textualFeatures.createTextualFeatures(selectedInstance);
List<FeatureNode> featureNodeList = selectedInstance.getFeatureNodeList();
FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
int i = 0;
for (FeatureNode featureNode : featureNodeList) {
featureNodeArray[i] = featureNode;
FeatureNode[] testInstance2 = featureNodeArray;
//compute prediction list for every model
int[] ranks = new int[10];
for (int l = 0; l < 10; l++) {
//init from 10 to 1
ranks[l] = 10 - l;
Map<String, Double> scoreMap = new HashMap<>();
Map<File, Double> alignedFilesAndWeights = getAlignedModels(filesAndWeights);
for (File modelFile : alignedFilesAndWeights.keySet()) {
try {
modelSVM = Model.load(modelFile);
} catch (IOException ex) {
Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
modelSVMLabelSize = modelSVM.getLabels().length;
modelSVMLabels = modelSVM.getLabels();
Map<Integer, Integer> mapLabelsToIDs = new HashMap<>();
for (int h = 0; h < modelSVMLabelSize; h++) {
mapLabelsToIDs.put(modelSVMLabels[h], h);
double[] scores = new double[modelSVMLabelSize];
Linear.predictValues(modelSVM, testInstance2, scores);
Map<Double, Integer> scoresValues = new HashMap<>();
for (int h = 0; h < scores.length; h++) {
scoresValues.put(scores[h], h);
Arrays.sort(scores);
int predicted1 = modelSVMLabels[scoresValues.get(scores[scores.length - 1])];
int predicted2 = modelSVMLabels[scoresValues.get(scores[scores.length - 2])];
int predicted3 = modelSVMLabels[scoresValues.get(scores[scores.length - 3])];
int predicted4 = modelSVMLabels[scoresValues.get(scores[scores.length - 4])];
int predicted5 = modelSVMLabels[scoresValues.get(scores[scores.length - 5])];
int predicted6 = modelSVMLabels[scoresValues.get(scores[scores.length - 6])];
int predicted7 = modelSVMLabels[scoresValues.get(scores[scores.length - 7])];
int predicted8 = modelSVMLabels[scoresValues.get(scores[scores.length - 8])];
int predicted9 = modelSVMLabels[scoresValues.get(scores[scores.length - 9])];
int predicted10 = modelSVMLabels[scoresValues.get(scores[scores.length - 10])];
String[] predictedTags = new String[10];
for (Map.Entry<String, Integer> entry : mapperWithIDs.entrySet()) {
if (entry.getValue().equals(predicted1)) {
predictedTags[0] = entry.getKey();
} else if (entry.getValue().equals(predicted2)) {
predictedTags[1] = entry.getKey();
} else if (entry.getValue().equals(predicted3)) {
predictedTags[2] = entry.getKey();
} else if (entry.getValue().equals(predicted4)) {
predictedTags[3] = entry.getKey();
} else if (entry.getValue().equals(predicted5)) {
predictedTags[4] = entry.getKey();
} else if (entry.getValue().equals(predicted6)) {
predictedTags[5] = entry.getKey();
} else if (entry.getValue().equals(predicted7)) {
predictedTags[6] = entry.getKey();
} else if (entry.getValue().equals(predicted8)) {
predictedTags[7] = entry.getKey();
} else if (entry.getValue().equals(predicted9)) {
predictedTags[8] = entry.getKey();
} else if (entry.getValue().equals(predicted10)) {
predictedTags[9] = entry.getKey();
//clearing model, to add the new computed classes in jlist
model.clear();
for (Map.Entry<String, String> tag : mappings.entrySet()) {
for (int k = 0; k < 10; k++) {
if (tag.getValue().equals(predictedTags[k])) {
predictedTags[k] = tag.getKey();
model.addElement(tag.getKey());
System.out.println("combined, predicted classes: " + Arrays.toString(predictedTags));
for (int r = 0; r < ranks.length; r++) {
String predictedTag = predictedTags[r];
Double currentWeight = alignedFilesAndWeights.get(modelFile);
double finalRank = ranks[r] * currentWeight;
if (scoreMap.containsKey(predictedTag)) {
Double scoreToAdd = scoreMap.get(predictedTag);
scoreMap.put(predictedTag, finalRank + scoreToAdd);
} else {
scoreMap.put(predictedTag, finalRank);
//add final weight - predicted tag
//files iter
model.clear();
List<Double> scoresList = new ArrayList<>(scoreMap.values());
Collections.sort(scoresList, Collections.reverseOrder());
for (Double sco : scoresList) {
if (model.size() > 9) {
break;
for (Map.Entry<String, Double> scoreEntry : scoreMap.entrySet()) {
if (scoreEntry.getValue().equals(sco)) {
model.addElement(scoreEntry.getKey());
}
Example 26
@SuppressWarnings("nls")
@Override
public void widgetSelected(SelectionEvent event) {
Widget widget = event.widget;
final Shell activeShell = event.display.getActiveShell();
if (widget.equals(btnSource)) {
FileDialog fileDialog = new FileDialog(activeShell, SWT.SINGLE);
fileDialog.setFilterNames(new String[] { "Text file (*.txt, *.csv, *.tab, *.asc, *.dat, *.wkt)" });
fileDialog.setFilterExtensions(new String[] { "*.txt;*.csv;*.tab;*.asc;*.dat;*.wkt" });
String selectedFile = fileDialog.open();
if (selectedFile != null) {
cboSource.add(selectedFile);
cboSource.setText(selectedFile);
} else if (widget.equals(chkHeader)) {
loadTables();
} else if (widget.equals(optTab) || widget.equals(optColon) || widget.equals(optComma) || widget.equals(optSpace)) {
delimiter = widget.getData().toString();
loadTables();
} else if (widget.equals(optEtc)) {
txtDelimiter.setEnabled(optEtc.getSelection());
txtDelimiter.setFocus();
delimiter = txtDelimiter.getText();
loadTables();
} else if (widget.equals(btnSourceCrs)) {
CRSChooserDialog dialog = new CRSChooserDialog(activeShell, null);
if (dialog.open() == Window.OK) {
CoordinateReferenceSystem crs = dialog.getResult();
try {
if (crs != null) {
txtSourceCrs.setText(CRS.lookupIdentifier(crs, true));
} catch (FactoryException e) {
txtSourceCrs.setText(EMPTY);
txtSourceCrs.setData(crs);
} else if (widget.equals(btnTargetCrs)) {
CRSChooserDialog dialog = new CRSChooserDialog(activeShell, null);
if (dialog.open() == Window.OK) {
CoordinateReferenceSystem crs = dialog.getResult();
try {
if (crs != null) {
txtTargetCrs.setText(CRS.lookupIdentifier(crs, true));
} catch (FactoryException e) {
txtTargetCrs.setText(EMPTY);
txtTargetCrs.setData(crs);
}
Example 27
@Test
public void testImportDb() throws Exception {
Catalog catalog = getCatalog();
assertNull(catalog.getLayerByName("gs:point"));
ImportController ctrl = new ImportController(getGeoServer(), applicationContext);
try (H2TestData data = new H2TestData()) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/geoserver");
request.setRequestURI("/geoserver/hello");
request.setMethod("post");
JSONObj result = data.createConnectionParameters();
result = ctrl.importDb("gs", result, request);
Long id = Long.parseLong(result.str("id"));
result = pollImport(ctrl, "gs", id, "pending", request);
assertNotNull(result);
assertTrue(result.integer("tasksTotal") > 0);
List<String> names = Arrays.asList(new String[] { "ft1", "ft2", "ft3" });
JSONArr tasks = new JSONArr();
for (JSONObj o : result.array("tasks").objects()) {
if (names.contains(o.get("name")) && o.get("status").equals("READY")) {
tasks.add(new JSONObj().put("task", o.get("task").toString()));
assertEquals("table", o.get("type"));
JSONObj response = new JSONObj();
response.put("tasks", tasks);
result = ctrl.update("gs", id, response, request);
result = pollImport(ctrl, "gs", id, "complete", request);
assertNotNull(result);
int complete = 0;
int ready = 0;
int no_crs = 0;
int failed = 0;
tasks = new JSONArr();
for (JSONObj o : result.array("tasks").objects()) {
if (o.get("status").equals("READY")) {
ready++;
if (o.get("status").equals("NO_CRS")) {
no_crs++;
String srs = "EPSG:4326";
tasks.add(new JSONObj().put("task", o.get("task").toString()).put("proj", IO.proj(new JSONObj(), CRS.decode(srs), srs)));
if (o.get("status").equals("COMPLETE")) {
complete++;
if (o.get("status").equals("ERROR") || o.get("status").equals("NO_BOUNDS")) {
failed++;
assertEquals(0, ready);
assertEquals(1, complete);
assertEquals(2, no_crs);
assertEquals(0, failed);
response = new JSONObj();
response.put("tasks", tasks);
result = ctrl.update("gs", id, response, request);
//Wait for the import to complete
result = pollImport(ctrl, "gs", id, "complete", request);
assertNotNull(result);
for (JSONObj o : result.array("tasks").objects()) {
assertEquals("COMPLETE", o.get("status"));
//Try to reimport the same store - should fail and return existing store
result = data.createConnectionParameters();
result = ctrl.importDb("gs", result, request);
assertNotNull(result.get("store"));
assertNull(result.get("id"));
}
Example 28
public static MathTransform getTransform(Coordinate refLatLon) {
try {
final CRSAuthorityFactory crsAuthorityFactory = CRS.getAuthorityFactory(false);
final GeographicCRS geoCRS = crsAuthorityFactory.createGeographicCRS("EPSG:4326");
final CoordinateReferenceSystem dataCRS = crsAuthorityFactory.createCoordinateReferenceSystem("EPSG:" + getEPSGCodefromUTS(//EPSG:32618
refLatLon));
final MathTransform transform = CRS.findMathTransform(geoCRS, dataCRS);
GeoUtils.recentMathTransform = transform;
return transform;
} catch (final NoSuchIdentifierException e) {
e.printStackTrace();
} catch (final FactoryException e) {
e.printStackTrace();
return null;
}
Example 29
static CoordinateReferenceSystem parseCRS(String mapProjection, final Product[] sourceProducts) {
try {
if (mapProjection != null && !mapProjection.isEmpty())
return CRS.parseWKT(mapProjection);
} catch (Exception e) {
try {
if (mapProjection.matches("[0-9]*")) {
mapProjection = "EPSG:" + mapProjection;
if (mapProjection.matches("AUTO:[0-9]*")) {
final GeoPos centerGeoPos;
if (sourceProducts == null || sourceProducts[0] == null)
centerGeoPos = new GeoPos(0, 0);
centerGeoPos = ProductUtils.getCenterGeoPos(sourceProducts[0]);
mapProjection = String.format("%s,%s,%s", mapProjection, centerGeoPos.lon, centerGeoPos.lat);
return CRS.decode(mapProjection, true);
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
Example 30
/**
* Reprojects a {@link JGTProcessingRegion region}.
* @param sourceCRS
* the original {@link CoordinateReferenceSystem crs} of the
* region.
* @param targetCRS
* the target {@link CoordinateReferenceSystem crs} of the
* region.
* @param lenient
* defines whether to apply a lenient transformation or not.
* @return a new {@link JGTProcessingRegion region}.
* @throws Exception
* exception that may be thrown when applying the
* transformation.
public JGTProcessingRegion reproject(CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS, boolean lenient) throws Exception {
MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, lenient);
Envelope envelope = getEnvelope();
Envelope targetEnvelope = JTS.transform(envelope, transform);
return new JGTProcessingRegion(targetEnvelope.getMinX(), targetEnvelope.getMaxX(), targetEnvelope.getMinY(), targetEnvelope.getMaxY(), getRows(), getCols());
}
Example 31
/**
* Parse the given projection.
* @param projection The projection string.
* @param longitudeFirst longitudeFirst
public static CoordinateReferenceSystem parseProjection(final String projection, final Boolean longitudeFirst) {
String epsgCode = projection;
try {
if (longitudeFirst == null) {
return CRS.decode(epsgCode);
} else {
return CRS.decode(epsgCode, longitudeFirst);
} catch (NoSuchAuthorityCodeException e) {
throw new RuntimeException(epsgCode + " was not recognized as a crs code", e);
} catch (FactoryException e) {
throw new RuntimeException("Error occurred while parsing: " + epsgCode, e);
}
Example 32
public static double[] transform(String from, String to, double[] xy) {
try {
if (from == null || to == null) {
return xy;
if (from.compareToIgnoreCase("EPSG:4326") == 0) {
// E6 support
if (xy[0] > 181 || xy[0] < -181) {
xy[0] /= 1000000;
if (xy[1] > 91 || xy[1] < -91) {
xy[1] /= 1000000;
if (from.equals(to)) {
return xy;
CoordinateReferenceSystem from_crs = CRS.decode(from);
// The 'true' means:
// "I'm going to use the order (longitude, latitude)"
CoordinateReferenceSystem to_crs = CRS.decode(to, true);
// The 'false' means:
// "There will be an exception if Geotools doesn't know how to do it"
MathTransform transform1 = CRS.findMathTransform(from_crs, to_crs, false);
DirectPosition2D from_point = new DirectPosition2D(xy[0], xy[1]);
DirectPosition2D to_point = new DirectPosition2D(0, 0);
transform1.transform(from_point, to_point);
return new double[] { to_point.x, to_point.y };
} catch (Exception exc) {
exc.printStackTrace();
return null;
}
Example 33
@Test
public void testImageGeneration() throws Exception {
SimpleGeoServiceImpl openGeoreports = new SimpleGeoServiceImpl();
MapServiceConfiguration mapServiceConfiguration = new MapServiceConfiguration();
Map<String, MapService> mapServices = new HashMap<String, MapService>();
MapService mapService = new MapService();
String mapServiceName = "sample-service";
mapService.setName(mapServiceName);
ArrayList<MapLayer> mapLayers = new ArrayList<MapLayer>();
MapLayer mapLayer = new MapLayer();
Map<String, String> params = new HashMap<String, String>();
params.put("url", "file:build/classes/com/vellut/opengeoreports/server/data/bc_border.shp");
mapLayer.setDataStore(DataStoreFinder.getDataStore(params));
mapLayer.setName("bc_border");
mapLayer.setStyle(createLineStyle());
mapLayers.add(mapLayer);
mapService.setMapLayers(mapLayers);
//TODO set a background default in initialization callback
mapService.setBackground(Color.WHITE);
mapService.setCrs(CRS.decode("EPSG:4326"));
mapServices.put(mapService.getName(), mapService);
mapServiceConfiguration.setMapServices(mapServices);
openGeoreports.setMapServiceConfiguration(mapServiceConfiguration);
byte[] mapImage = openGeoreports.getMapImage(mapServiceName, new MapSize(500, 500), "png");
assertNotNull(mapImage);
assertTrue(mapImage.length > 0);
}
Example 34
public static CrsGeoCoding getModisTileGeocoding(String tile) {
ModisTileCoordinates modisTileCoordinates = ModisTileCoordinates.getInstance();
int tileIndex = modisTileCoordinates.findTileIndex(tile);
if (tileIndex == -1) {
throw new OperatorException("Found no tileIndex for tileName=''" + tile + "");
final double easting = modisTileCoordinates.getUpperLeftX(tileIndex);
final double northing = modisTileCoordinates.getUpperLeftY(tileIndex);
final String crsString = AlbedoInversionConstants.MODIS_SIN_PROJECTION_CRS_STRING;
final int imageWidth = AlbedoInversionConstants.MODIS_TILE_WIDTH;
final int imageHeight = AlbedoInversionConstants.MODIS_TILE_HEIGHT;
final double pixelSizeX = AlbedoInversionConstants.MODIS_SIN_PROJECTION_PIXEL_SIZE_X;
final double pixelSizeY = AlbedoInversionConstants.MODIS_SIN_PROJECTION_PIXEL_SIZE_Y;
CrsGeoCoding geoCoding;
try {
final CoordinateReferenceSystem crs = CRS.parseWKT(crsString);
geoCoding = new CrsGeoCoding(crs, imageWidth, imageHeight, easting, northing, pixelSizeX, pixelSizeY);
} catch (Exception e) {
throw new OperatorException("Cannot attach geocoding for tileName= ''" + tile + " : ", e);
return geoCoding;
}
Example 35
@Test
public void testGeoHashGridWithProjectedEnvelope() throws Exception {
features = TestUtil.createAggregationFeatures(ImmutableList.of(ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key", GeoHash.encodeHash(new LatLong(-89.9, -179.9), 1), "doc_count", 10)))));
ReferencedEnvelope envelope = new ReferencedEnvelope(-19926188.85, 19926188.85, -30240971.96, 30240971.96, CRS.decode("EPSG:3857"));
geohashGrid.initalize(envelope, features);
assertEquals(new ReferencedEnvelope(-180, 180, -90, 90, DefaultGeographicCRS.WGS84), geohashGrid.getBoundingBox());
}
Example 36
/**
* Project geometry.
* @param originalGeom
* the original geom
* @param srcCRSCode
* the src crs code
* @param trgCRSCode
* the trg crs code
* @return the geometry
* @throws NoSuchAuthorityCodeException
* the no such authority code exception
* @throws FactoryException
* the factory exception
* @throws MismatchedDimensionException
* the mismatched dimension exception
* @throws TransformException
* the transform exception
public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode, String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException, TransformException {
Geometry projectedGeometry = null;
final MathTransform transform = CRS.findMathTransform(CRS.decode(srcCRSCode, true), CRS.decode(trgCRSCode, true), true);
// converting geometries into a linear system
try {
projectedGeometry = JTS.transform(originalGeom, transform);
} catch (Exception e) {
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), 4326);
WKTReader reader = new WKTReader(geometryFactory);
try {
Polygon worldCutPolygon = (Polygon) reader.read("POLYGON((-180 -89.9, -180 89.9, 180 89.9, 180 -89.9, -180 -89.9))");
projectedGeometry = JTS.transform(originalGeom.intersection(worldCutPolygon), transform);
} catch (Exception ex) {
throw new RuntimeException(ex);
return projectedGeometry;
}
Example 37
public static synchronized CoordinateReferenceSystem getCrs(String epsg) {
try {
if (crs.get(epsg) != null)
return crs.get(epsg);
if (epsg.equals(EPSG_900913)) {
String wkt = IOUtils.toString(FeatureUtil.class.getResourceAsStream("/epsg/EPSG_900913.txt"));
crs.put(epsg, CRS.parseWKT(wkt));
} else if (epsg.equals(EPSG_102100)) {
String wkt = IOUtils.toString(FeatureUtil.class.getResourceAsStream("/epsg/EPSG_102100.txt"));
crs.put(epsg, CRS.parseWKT(wkt));
} else
crs.put(epsg, CRS.decode(epsg));
return crs.get(epsg);
} catch (FactoryException e) {
throw new RuntimeException("could not load " + epsg, e);
} catch (IOException e) {
throw new RuntimeException(e);
}
Example 38
public void writeGeoJson(Writer writer, String targetCrsName) {
load();
try {
CoordinateReferenceSystem targetCrs = CRS.decode(targetCrsName);
MathTransform transform = CRS.findMathTransform(crs, targetCrs);
FeatureJSON f = new FeatureJSON();
f.writeCRS(targetCrs, writer);
features.stream().forEach( feature -> {
try {
SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
tb.setCRS(targetCrs);
SimpleFeatureBuilder b = new SimpleFeatureBuilder(feature.getFeatureType());
b.add(JTS.transform((Geometry) feature.getDefaultGeometry(), transform));
f.writeFeature(b.buildFeature(feature.getID()), writer);
} catch (Exception e) {
throw new RuntimeException(e);
} catch (IOExceptionFactoryException | e) {
throw new RuntimeException(e);
}
Example 39
/**
* Set the list of mapped positions.
* @throws MismatchedSizeException if the list doesn't have the expected number of points.
* @throws MismatchedDimensionException if some points doesn't have the
* {@linkplain #getDimension expected number of dimensions}.
* @throws MismatchedReferenceSystemException if CRS is not the same for all points.
public void setMappedPositions(final List /*<MappedPosition>*/
positions) throws MismatchedSizeException, MismatchedDimensionException, MismatchedReferenceSystemException {
final CoordinateReferenceSystem source, target;
source = ensureValid(getPoints(positions, false), "sourcePoints");
target = ensureValid(getPoints(positions, true), "targetPoints");
* Now stores the informations. Note that we set the source and target CRS
* only after 'ensureValid' succeed for both CRS.
this.positions.clear();
this.positions.addAll(positions);
this.sourceCRS = source;
this.targetCRS = target;
this.transform = null;
}
Example 40
private MathTransform createTransform() throws Exception {
GeometryDescriptor geometryType = featureSource.getSchema().getGeometryDescriptor();
CoordinateReferenceSystem sourceCrs = geometryType.getCoordinateReferenceSystem();
if (sourceCrs == null) {
// if it's not WGS84, we'll soon find out as we check the geometry against the
// country bounds
sourceCrs = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem geoCRS = DefaultGeographicCRS.WGS84;
// allow for some error due to different datums
boolean lenient = true;
return CRS.findMathTransform(sourceCrs, geoCRS, lenient);
}
Example 41
/**
* Reproject the given coordinates into WGS84 coordinates based on a known source datum or SRS.
* Darwin Core allows not only geodetic datums but also full spatial reference systems as values for "datum".
* The method will always return lat lons even if the processing failed. In that case only issues are set and the
* parsing result set to fail - but with a valid payload.
* @param lat the original latitude
* @param lon the original longitude
* @param datum the original geodetic datum the coordinates are in
* @return the reprojected coordinates or the original ones in case transformation failed
public static OccurrenceParseResult<LatLng> reproject(double lat, double lon, String datum) {
Preconditions.checkArgument(lat >= -90d && lat <= 90d);
Preconditions.checkArgument(lon >= -180d && lon <= 180d);
Set<OccurrenceIssue> issues = EnumSet.noneOf(OccurrenceIssue.class);
if (Strings.isNullOrEmpty(datum)) {
issues.add(OccurrenceIssue.GEODETIC_DATUM_ASSUMED_WGS84);
return OccurrenceParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new LatLng(lat, lon), issues);
try {
CoordinateReferenceSystem crs = parseCRS(datum);
if (crs == null) {
issues.add(OccurrenceIssue.GEODETIC_DATUM_INVALID);
issues.add(OccurrenceIssue.GEODETIC_DATUM_ASSUMED_WGS84);
} else {
MathTransform transform = CRS.findMathTransform(crs, DefaultGeographicCRS.WGS84, true);
// different CRS may swap the x/y axis for lat lon, so check first:
double[] srcPt;
double[] dstPt = new double[3];
if (CRS.getAxisOrder(crs) == CRS.AxisOrder.NORTH_EAST) {
// lat lon
srcPt = new double[] { lat, lon, 0 };
} else {
// lon lat
LOG.debug("Use lon/lat ordering for reprojection with datum={} and lat/lon={}/{}", datum, lat, lon);
srcPt = new double[] { lon, lat, 0 };
transform.transform(srcPt, 0, dstPt, 0, 1);
double lat2 = dstPt[1];
double lon2 = dstPt[0];
// verify the datum shift is reasonable
if (Math.abs(lat - lat2) > SUSPICIOUS_SHIFT || Math.abs(lon - lon2) > SUSPICIOUS_SHIFT) {
issues.add(OccurrenceIssue.COORDINATE_REPROJECTION_SUSPICIOUS);
LOG.debug("Found suspicious shift for datum={} and lat/lon={}/{} so returning failure and keeping orig coord", datum, lat, lon);
return OccurrenceParseResult.fail(new LatLng(lat, lon), issues);
// flag the record if coords actually changed
if (lat != lat2 || lon != lon2) {
issues.add(OccurrenceIssue.COORDINATE_REPROJECTED);
return OccurrenceParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new LatLng(lat2, lon2), issues);
} catch (Exception e) {
issues.add(OccurrenceIssue.COORDINATE_REPROJECTION_FAILED);
LOG.debug("Coordinate reprojection failed with datum={} and lat/lon={}/{}: {}", datum, lat, lon, e.getMessage());
return OccurrenceParseResult.fail(new LatLng(lat, lon), issues);
}
Example 42
/**
* Removes TemplateModelEvents from the queue and put
* @param events
* @return
* @throws ActionException
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
final Queue<EventObject> ret = new LinkedList<EventObject>();
while (events.size() > 0) {
final EventObject ev;
try {
if ((ev = events.remove()) != null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("RasterizeAction.execute(): working on incoming event: " + ev.getSource());
String rasterAttribName = conf.getRasterAttribName();
String rasterCqlFilter = "";
if (conf.getRasterCqlFilter() != null)
rasterCqlFilter = conf.getRasterCqlFilter();
double noData = conf.getRasterNoData();
// System.out.println("NODATA"+noData);
int rasterpixelheight = conf.getRasterpixelheight();
int rasterpixelwidth = conf.getRasterpixelwidth();
double rasterx0 = conf.getRasterx0();
double rasterx1 = conf.getRasterx1();
double rastery0 = conf.getRastery0();
double rastery1 = conf.getRastery1();
int height = conf.getRetileH();
int width = conf.getRetileW();
String layername = conf.getLayername();
if (layername == null)
throw new ActionException(this, "the layer name cannot be empty");
if (rasterpixelheight == 0.0d || rasterpixelwidth == 0.0d)
throw new ActionException(this, "the raster pixel size is wrong");
FileSystemEvent fileEvent = (FileSystemEvent) ev;
File file = fileEvent.getSource();
FileDataStore store = null;
// in this case the features field is not null but it is filled externally
if (features == null) {
store = FileDataStoreFinder.getDataStore(file);
if (store == null)
throw new ActionException(this, "the layer " + file.getCanonicalPath() + " cannot be found. Skip execution.");
FeatureSource featureSource = store.getFeatureSource();
SimpleFeatureType schema = (SimpleFeatureType) featureSource.getSchema();
Query query = new Query(schema.getTypeName(), Filter.INCLUDE);
query.setCoordinateSystem(CRS.decode("EPSG:4326", true));
features = (SimpleFeatureCollection) featureSource.getFeatures(query);
// features = (SimpleFeatureCollection) featureSource.getFeatures();
//CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem crs = features.getSchema().getCoordinateReferenceSystem();
ReferencedEnvelope bounds = new ReferencedEnvelope(rasterx0, rasterx1, rastery0, rastery1, crs);
Dimension gridDim = new Dimension(rasterpixelwidth, rasterpixelheight);
String covName = layername;
ProgressListener monitor = null;
GridCoverage2D cov = VectorToRasterProcess.process(features, rasterAttribName, gridDim, bounds, covName, monitor);
LOGGER.debug("CRS :" + cov.getCoordinateReferenceSystem().toWKT());
// System.out.println(cov.toString());
// Map<String, Object> attribute = new HashMap<String, Object>();
// attribute.put("rasterAttribName", rasterAttribName);
// if (rasterCqlFilter!=null) attribute.put("rasterCqlFilter", rasterCqlFilter);
File tmpTiff = null;
if (conf.getFilename() != null)
tmpTiff = new File(conf.getWorkingDirectory(), conf.getFilename());
tmpTiff = new File(conf.getWorkingDirectory(), "testcov.tif");
GeoTiffWriter writer = null;
try {
writer = new GeoTiffWriter(tmpTiff);
if (height > 0 && width > 0) {
GeoTiffWriteParams params = new GeoTiffWriteParams();
params.setTilingMode(TIFFImageWriteParam.MODE_EXPLICIT);
params.setTiling(conf.getRetileH(), conf.getRetileW());
ParameterValue<GeoToolsWriteParams> value = GeoTiffFormat.GEOTOOLS_WRITE_PARAMS.createValue();
value.setValue(params);
writer.write(cov, new GeneralParameterValue[] { value });
} else
writer.write(cov, null);
} catch (IOException e) {
LOGGER.error("An exception was raised executing the RasterizeAction", e);
throw new ActionException(this, "An exception was raised executing the RasterizeAction");
} finally {
// if (writer!=null) writer.dispose();
FileSystemEvent fileSystemInsertEvent = new FileSystemEvent(tmpTiff, FileSystemEventType.FILE_ADDED);
ret.add(fileSystemInsertEvent);
if (store != null)
store.dispose();
// add the event to the return
} else {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("RasterizeAction.execute(): Encountered a NULL event: SKIPPING...");
continue;
} catch (Throwable ioe) {
ioe.printStackTrace();
final String message = "RasterizeAction.execute(): Unable to produce the output: " + ioe.getLocalizedMessage();
if (LOGGER.isErrorEnabled())
LOGGER.error(message);
throw new ActionException(this, message);
return ret;
}
Example 43
@Override
public void write(List<? extends BaseData> items) throws Exception {
for (BaseData item : items) {
if (item instanceof Place) {
Place place = (Place) item;
MapSpec mapSpec = new MapSpec();
mapSpec.setDpi(300);
TMSLayer tmsLayer = new TMSLayer();
tmsLayer.setLayer("eMonocot");
tmsLayer.setBaseURL("http://e-monocot.org/tiles/");
tmsLayer.setMaxExtent(new double[] { -20037508.3392, -20037508.3392, 20037508.3392, 20037508.3392 });
tmsLayer.setResolutions(new double[] { 156543.0339, 78271.51695, 39135.758475, 19567.8792375, 9783.93961875, 4891.969809375, 2445.9849046875 });
tmsLayer.setFormat("png");
mapSpec.getLayers().add(tmsLayer);
WMSLayer wmsLayer = new WMSLayer();
wmsLayer.setLayers(new String[] { "emonocot:place" });
wmsLayer.setBaseURL("http://e-monocot.org/geoserver/wms");
wmsLayer.setMaxExtent(new double[] { -20037508.3392, -20037508.3392, 20037508.3392, 20037508.3392 });
wmsLayer.setResolutions(new double[] { 156543.0339, 78271.51695, 39135.758475, 19567.8792375, 9783.93961875, 4891.969809375, 2445.9849046875 });
wmsLayer.setFormat("image/png");
wmsLayer.setStyles(new String[] { "eMonocot" });
wmsLayer.getCustomParams().put("featureid", place.getMapFeatureId().toString());
mapSpec.getLayers().add(wmsLayer);
Page page = new Page();
CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:4326");
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:3857");
MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
Point bottomLeft = (Point) JTS.transform(geometryFactory.createPoint(new Coordinate(place.getEnvelope().getMinY(), place.getEnvelope().getMinX())), transform);
Point topRight = (Point) JTS.transform(geometryFactory.createPoint(new Coordinate(place.getEnvelope().getMaxY(), place.getEnvelope().getMaxX())), transform);
page.setBbox(new double[] { bottomLeft.getCoordinate().x, bottomLeft.getCoordinate().y, topRight.getCoordinate().x, topRight.getCoordinate().y });
mapSpec.getPages().add(page);
String json = objectMapper.writeValueAsString(mapSpec);
mapPrinter.setYamlConfigFile(config.getFile());
PJsonObject jsonSpec = MapPrinter.parseSpec(json);
File outputFile = new File(outputDirectory.getFile(), place.getId() + ".png");
mapPrinter.print(jsonSpec, new FileOutputStream(outputFile), referer);
} else if (item instanceof Taxon) {
}
Example 44
/**
* *****************************
* @param workspace the wk to use
* @param layerName the layerName to retrieve
* @param styleName the style name to set or if null will be setted the
* default one
* @return the builded InfoPreview
* @throws ResourceNotFoundFault
private InfoPreview buildSHPInfoPreviewFromExistingWK(String workspace, String layerName, String styleName) throws ResourceNotFoundFault, IllegalArgumentException {
String userWorkspace = workspace;
if (userWorkspace == null) {
userWorkspace = this.getWorkspace(workspace);
RESTLayer layer = restReader.getLayer(userWorkspace, layerName);
RESTFeatureType featureType = restReader.getFeatureType(layer);
InfoPreview infoPreview = null;
try {
logger.info("Parameters: userWorkspace: " + userWorkspace + " - layerName: " + layerName + " - featureType: " + featureType + " - layer: " + layer + " - RESTURL: " + RESTURL);
// Map<String, String> parametersMap = Maps.newHashMap();
// parametersMap.put("url", layerName);
// featureType = DataStoreFinder.getDataStore(parametersMap).getFeatureSource(layerName);
// System.out.println("" + CRS.getGeographicBoundingBox());
Integer code = this.getEPSGCodeFromString(featureType.getCRS());
String epsgCode = null;
if (code != null) {
epsgCode = "EPSG:" + code.toString();
infoPreview = new InfoPreview(RESTURL, userWorkspace, layerName, featureType.getMinX(), featureType.getMinY(), featureType.getMaxX(), featureType.getMaxY(), epsgCode, GPSharedUtils.isEmpty(styleName) ? layer.getDefaultStyle() : styleName, Boolean.TRUE, Lists.<LayerPublishAction>newArrayList(LayerPublishAction.values()));
} catch (Exception e) {
final String error = "The layer " + layerName + " is published in the " + userWorkspace + " workspace, but the server cannot provide info. " + e;
logger.error(error);
throw new IllegalArgumentException(error, e.getCause());
return infoPreview;
}
Example 45
private static boolean setFeature(File baseDir, File granule, SimpleFeature feature, String geometryName, String locationKey) {
String granuleBaseName = FilenameUtils.getBaseName(granule.getAbsolutePath());
// get attributes and copy them over
try {
AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(granule);
if (format == null || (format instanceof UnknownFormat)) {
throw new IllegalArgumentException("Unable to find a reader for the provided file: " + granule.getAbsolutePath());
// can throw UnsupportedOperationsException
final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format.getReader(granule, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
ReferencedEnvelope bb = new ReferencedEnvelope(originalEnvelope);
WKTReader wktReader = new WKTReader();
Geometry the_geom = wktReader.read("POLYGON((" + bb.getMinX() + " " + bb.getMinY() + "," + bb.getMinX() + " " + bb.getMaxY() + "," + bb.getMaxX() + " " + bb.getMaxY() + "," + bb.getMaxX() + " " + bb.getMinY() + "," + bb.getMinX() + " " + bb.getMinY() + "))");
Integer SRID = CRS.lookupEpsgCode(bb.getCoordinateReferenceSystem(), true);
* TODO ETJ suggestion: String crsId =
* CRS.lookupIdentifier(bb.getCoordinateReferenceSystem(), true);
if (SRID == null) {
throw new IllegalArgumentException("Unable to get the EPSG code for the granule: " + granule);
the_geom.setSRID(SRID);
feature.setAttribute(geometryName, the_geom);
// TODO absolute
feature.setAttribute(locationKey, granule.getName());
// granule.getName().replaceAll("\\", "\\\\"));
final File indexer = new File(baseDir, org.geotools.gce.imagemosaic.Utils.INDEXER_PROPERTIES);
final Properties indexerProps = ImageMosaicProperties.getPropertyFile(indexer);
* @see {@link #org.geotools.gce.imagemosaic.properties.RegExPropertiesCollector.collect(File)}
final String granuleName = FilenameUtils.getBaseName(granule.getName());
if (indexerProps.getProperty("TimeAttribute") != null) {
// Since timeattrib may be ranged, we may have 2 attribs to update
String timePropNames[] = indexerProps.getProperty("TimeAttribute").split(";");
for (String timePropName : timePropNames) {
updateFeatureTimeAttrib(feature, baseDir, timePropName, indexerProps, granuleName);
if (indexerProps.getProperty("ElevationAttribute") != null) {
// TODO move out of the cycle
final File elevationRegex = new File(baseDir, "elevationregex.properties");
final Properties elevProps = ImageMosaicProperties.getPropertyFile(elevationRegex);
final Pattern elevPattern = Pattern.compile(elevProps.getProperty("regex"));
// TODO move out of the cycle
final Matcher matcher = elevPattern.matcher(granuleName);
if (matcher.find()) {
feature.setAttribute(indexerProps.getProperty("ElevationAttribute"), Double.valueOf(matcher.group()));
if (indexerProps.getProperty("RuntimeAttribute") != null) {
// TODO move out of the cycle
final File runtimeRegex = new File(baseDir, "runtimeregex.properties");
final Properties runtimeProps = ImageMosaicProperties.getPropertyFile(runtimeRegex);
final Pattern runtimePattern = Pattern.compile(runtimeProps.getProperty("regex"));
// TODO move out of the cycle
final Matcher matcher = runtimePattern.matcher(granuleName);
if (matcher.find()) {
feature.setAttribute(indexerProps.getProperty("RuntimeAttribute"), Integer.valueOf(matcher.group()));
return true;
} catch (Throwable e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
return false;
}
Example 46
/**
* Route plan using osrm server.
* @param param
* @param host_port
* @param http
* @return
* @throws IOException
* @throws ParseException
* @throws JAXBException
* @throws InterruptedException
public AbstractResponseParametersType routePlan(DetermineRouteRequestType param, String host_port, String http, Locale locale) throws IOException, JAXBException, ParseException, InterruptedException {
DetermineRouteResponseType res = new DetermineRouteResponseType();
// MANDATORY:
// Describes the overall characteristics of the route
RouteSummaryType routeSummary = new RouteSummaryType();
// OPTIONAL:
// Contains a reference to the route stored at the Route
// Determination Service server.
// Can be used in subsequent request to the Route Service to request
// additional information about the route, or to request an
// alternate route.
RouteHandleType routeHandle = new RouteHandleType();
// Constains a list of turn-by-turn route instructions and advisories,
// formatted for presentation.
// May contain the geometry and bounding box if specified in the
// request.
// May contain description. FOr example this can be used to connect the
// instruction with a map.
RouteInstructionsListType routeInstructionsList = new RouteInstructionsListType();
try {
lastNode = null;
RouteGeometryType routeGeometry = new RouteGeometryType();
WayPointListType wayPointList = param.getRoutePlan().getWayPointList();
String url = "/viaroute";
CoordinateReferenceSystem sourceCRS = CRS.decode(EPSG_4326);
CoordinateReferenceSystem targetCRS = GeoUtil.getSRS(wayPointList.getStartPoint());
com.vividsolutions.jts.geom.Point point = GeoUtil.getPoint(wayPointList.getStartPoint(), sourceCRS);
url += "?loc=" + point.getY() + "," + point.getX();
for (WayPointType wayPoint : wayPointList.getViaPoint()) {
point = GeoUtil.getPoint(wayPoint, sourceCRS);
url += "&loc=" + point.getY() + "," + point.getX();
point = GeoUtil.getPoint(wayPointList.getEndPoint(), sourceCRS);
url += "&loc=" + point.getY() + "," + point.getX();
LOG.debug(url);
LineStringType lst = new LineStringType();
lst.setSrsName(targetCRS.getName().getCode());
routeGeometry.setLineString(lst);
res.setRouteGeometry(routeGeometry);
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(getOSRMStream(host_port, url));
jp.nextToken();
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != null) {
String fieldname = jp.getCurrentName();
if (fieldname == null)
else if (jp.getCurrentName().equals("total_distance")) {
DistanceType duration = new DistanceType();
duration.setUom(DistanceUnitType.M);
duration.setValue(new BigDecimal(jp.getText()));
routeSummary.setTotalDistance(duration);
} else if (jp.getCurrentName().equals("total_time")) {
Duration duration = dataTypeFactory.newDuration(true, 0, 0, 0, 0, 0, jp.getIntValue());
routeSummary.setTotalTime(duration);
} else if (jp.getCurrentName().equals("route_geometry")) {
decodeRouteGeometry(lst.getPosOrPointPropertyOrPointRep(), targetCRS, sourceCRS, jp);
} else if (jp.getCurrentName().equals("route_instructions")) {
processInstructions(locale, routeSummary, routeInstructionsList, jp, lst);
jp.nextToken();
// ensure resources get cleaned up timely and properly
jp.close();
res.setRouteHandle(routeHandle);
if (param.getRouteInstructionsRequest() != null) {
res.setRouteInstructionsList(routeInstructionsList);
res.getRouteInstructionsList().setFormat("text/plain");
res.getRouteInstructionsList().setLang(locale.getLanguage());
res.setRouteSummary(routeSummary);
} catch (Throwable t) {
LOG.error("Error generating route response: " + t, t);
t.printStackTrace();
return res;
}
Example 47
private ReferencedEnvelope createEnvelope() {
ReferencedEnvelope env = null;
try {
env = new ReferencedEnvelope(WORLD_BOTTOM, WORLD_TOP, WORLD_LEFT, WORLD_RIGHT, CRS.decode("EPSG:4326"));
} catch (FactoryException e) {
LOGGER.error("Cannot create georeferenced Envelope: " + e.getMessage(), e);
return env;
}
Example 48
/*
* (non-Javadoc)
* @see
* au.org.aurin.wif.svc.ProjectService#convertUnionToUAZ(java.lang.String,
* java.util.List)
@Override
public Boolean convertUnionToUAZ(final String id, List<String> optionalColumns, final String roleId) throws WifInvalidInputException, UAZAlreadyCreatedException, WifInvalidConfigException, IncompleteSuitabilityLUConfigException, NoSuchAuthorityCodeException, DataStoreUnavailableException, FactoryException, GeoServerConfigException, DataStoreCreationException {
String msg = "Expanding union to UAZ failed";
LOGGER.info("converting the project Union table to UAZ with projectID={}", id);
WifProject project = getProjectConfiguration(id);
if (project.getSetupCompleted()) {
LOGGER.error("cannot execute the request, the project with the ID " + id + " project has already created an uaz");
throw new UAZAlreadyCreatedException("cannot execute the request, the project with the ID " + id + " project has already created an uaz");
// TODO better not supported yet
// LOGGER.debug("Using {} optional columns ", optionalColumns.size());
// for (String column : optionalColumns) {
// LOGGER.debug("Using optional column ={}", column);
optionalColumns = null;
LOGGER.debug("setting up suitability configuration,having the specified columns to the union table");
final SuitabilityConfig suitabilityConfig = project.getSuitabilityConfig();
if (suitabilityConfig == null) {
msg = msg + " SuitabilityConfig is not valid!";
LOGGER.error(msg);
throw new WifInvalidConfigException(msg);
LOGGER.debug("Using the following suitabilityConfig {} ", suitabilityConfig.toString());
suitabilityConfig.setup(optionalColumns, project);
final int size = suitabilityConfig.getScoreColumns().size();
if (size == 0) {
msg = msg + " There are no score columns configured, analysis will not be shown! Check that there are suitability landuses configured";
LOGGER.error(msg);
throw new IncompleteSuitabilityLUConfigException(msg);
LOGGER.debug("Setup created {} scoreColumns", size);
final String tableName = suitabilityConfig.getUnifiedAreaZone();
final ArrayList<String> columnList = new ArrayList<String>(suitabilityConfig.getScoreColumns());
// columnList.addAll(optionalColumns)
if (project.getAreaLabel() == null) {
msg = msg + " area column for reporting hasn't been set!";
LOGGER.error(msg);
throw new WifInvalidConfigException(msg);
try {
LOGGER.debug("Expanding UAZ with {} columns", columnList.size());
if (geodataFinder.expandUAZcolumns(tableName, columnList)) {
LOGGER.info("requesting to create a geoserver layer for SRS: {}", project.getSrs());
final CoordinateReferenceSystem crs = CRS.decode(project.getSrs());
project = this.createWMSLayer(project, roleId, project.getSuitabilityConfig().getUnifiedAreaZone(), crs);
// creating metadata in aurin
// TODO enable in the next iteration oof what if
// try {
// postgisToDataStoreExporter.persistInAurin(project, roleId);
// } catch (MiddlewarePersistentException e) {
// LOGGER.warn("sharing with aurin is not enabled!");
// ali- also call postgisToDataStoreExporter.exportUAZ
project.setSetupCompleted(true);
project.setSuitabilityConfig(suitabilityConfig);
wifProjectDao.updateProject(project);
return true;
} else {
return false;
} catch (final NoSuchAuthorityCodeException e) {
msg = msg + " could not update the spatial database of the project, geoserver doesn't recognise the SRS";
LOGGER.error(msg);
throw new GeoServerConfigException(msg, e);
}
Example 49
public static Geometry reproject(Geometry geom, int toSrid) throws NoSuchAuthorityCodeException, FactoryException, UnsupportedGeometryTypeException, MismatchedDimensionException, TransformException {
DefaultCoordinateOperationFactory trFactory = new DefaultCoordinateOperationFactory();
CoordinateReferenceSystem sourceCS = CRS.decode("EPSG:" + geom.getSRID());
CoordinateReferenceSystem targetCS = CRS.decode("EPSG:" + toSrid);
CoordinateOperation tr = trFactory.createOperation(sourceCS, targetCS);
MathTransform mtrans = tr.getMathTransform();
Geometry newGeom = null;
GeometryFactory geomFactory = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), toSrid);
switch(getGeometryType(geom)) {
case POINT:
Point point = (Point) geom;
DirectPosition2D point2d = new DirectPosition2D(point.getX(), point.getY());
mtrans.transform(point2d, point2d);
newGeom = geomFactory.createPoint(new Coordinate(point2d.getX(), point2d.getY()));
break;
case LINESTRING:
newGeom = reprojectLineString(geomFactory, mtrans, (LineString) geom);
break;
case POLYGON:
Polygon polygon = (Polygon) geom;
LinearRing shell = lineStringToLinearRing(reprojectLineString(geomFactory, mtrans, polygon.getExteriorRing()));
int numHoles = polygon.getNumInteriorRing();
LinearRing[] holes = new LinearRing[numHoles];
for (int i = 0; i < numHoles; i++) {
holes[i] = lineStringToLinearRing(reprojectLineString(geomFactory, mtrans, polygon.getInteriorRingN(i)));
newGeom = geomFactory.createPolygon(shell, holes);
break;
return newGeom;
}
Example 50
private GraphObjectMap utmToLatLon(final String zone, final String hemisphere, final String east, final String north) {
final GraphObjectMap obj = new GraphObjectMap();
// clean zone string (remove all non-digits)
final String cleanedZone = zone.replaceAll("[\\D]+", "");
final StringBuilder epsg = new StringBuilder("EPSG:32");
switch(hemisphere) {
case "N":
epsg.append("6");
break;
case "S":
epsg.append("7");
break;
// append "0" to zone number of single-digit
if (cleanedZone.length() == 1) {
epsg.append("0");
// append zone number
epsg.append(cleanedZone);
try {
final CoordinateReferenceSystem src = CRS.decode(epsg.toString());
final CoordinateReferenceSystem dst = CRS.decode("EPSG:4326");
final MathTransform transform = CRS.findMathTransform(src, dst, true);
final DirectPosition sourcePt = new DirectPosition2D(getDoubleOrNull(east), getDoubleOrNull(north));
final DirectPosition targetPt = transform.transform(sourcePt, null);
obj.put(latitudeProperty, targetPt.getOrdinate(0));
obj.put(longitudeProperty, targetPt.getOrdinate(1));
} catch (Throwable t) {
logger.warn("", t);
return obj;
}
Example 51
private void populateSimpleFeatures(String geometryHNodeId, String geometry2HNodeId, ArrayList<Row> rows, List<SimpleFeature> features, Class binding) {
for (Row row : rows) {
try {
Geometry JTSGeometry = null;
String posList = null;
if (geometry2HNodeId == "") {
posList = row.getNode(geometryHNodeId).getValue().asString();
// Future work on WKB columns:
// WKBReader wkbreader = new WKBReader();
// byte[] wkbPosList = WKBReader.hexToBytes(posList);
// JTSGeometry = wkbreader.read(wkbPosList);
} else // lat and lng case
String lon = row.getNode(geometryHNodeId).getValue().asString();
String lat = row.getNode(geometry2HNodeId).getValue().asString();
if (lon.trim().length() == 0 || lat.trim().length() == 0)
continue;
posList = "POINT(" + lon + " " + lat + ")";
if (// no spatial data
posList == null)
continue;
else if (// assuming the lon, lat case ... we might need to handle additional cases
!posList.contains("(")) {
posList = "POINT(" + posList.replace(",", " ") + ")";
posList = posList.toUpperCase();
WKTReader reader = new WKTReader();
JTSGeometry = reader.read(posList);
if (JTSGeometry == null)
continue;
String srid = "";
if (SRIDHNodeId != "")
srid = row.getNode(SRIDHNodeId).getValue().asString();
// default to WGS84
srid = "4326";
if (!srid.contains(":"))
srid = "EPSG:" + srid;
CoordinateReferenceSystem sourceCRS = null;
try {
sourceCRS = CRS.decode(srid, true);
} catch (NoSuchAuthorityCodeException e) {
logger.error("No such authority code!", e);
} catch (FactoryException e) {
logger.error("Error parsing SRID!", e);
SimpleFeatureTypeBuilder simpleFeatureTypeBuilder = new SimpleFeatureTypeBuilder();
simpleFeatureTypeBuilder.setName("SimpleFeature");
simpleFeatureTypeBuilder.setCRS(sourceCRS);
simpleFeatureTypeBuilder.add("GEOM", binding);
simpleFeatureTypeBuilder.addAll(featureSchema);
SimpleFeatureType simpleFeatureTypeWithCRS = simpleFeatureTypeBuilder.buildFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(simpleFeatureTypeWithCRS);
featureBuilder.add(JTSGeometry);
for (String hNodeId : geomHNodeIdList) {
Node node = row.getNode(hNodeId);
if (node.hasNestedTable())
featureBuilder.add("Nested table");
else {
String colValue = node.getValue().asString();
featureBuilder.add(colValue);
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
} catch (Exception e) {
logger.error("Error creating geometry! Skipping it.", e);
continue;
}
Example 52
private void populateSimpleFeatures(String geometryHNodeId, String geometry2HNodeId, ArrayList<Row> rows, List<SimpleFeature> features, @SuppressWarnings("rawtypes") Class binding) {
for (Row row : rows) {
try {
Geometry JTSGeometry;
String posList;
if (geometry2HNodeId == "") {
posList = row.getNode(geometryHNodeId).getValue().asString();
// Future work on WKB columns:
// WKBReader wkbreader = new WKBReader();
// byte[] wkbPosList = WKBReader.hexToBytes(posList);
// JTSGeometry = wkbreader.read(wkbPosList);
} else // lat and lng case
String lon = row.getNode(geometryHNodeId).getValue().asString();
String lat = row.getNode(geometry2HNodeId).getValue().asString();
if (lon.trim().length() == 0 || lat.trim().length() == 0)
continue;
posList = "POINT(" + lon + " " + lat + ")";
if (// no spatial data
posList == null)
continue;
else if (// assuming the lon, lat case ... we might need to handle additional cases
!posList.contains("(")) {
posList = "POINT(" + posList.replace(",", " ") + ")";
posList = posList.toUpperCase();
WKTReader reader = new WKTReader();
JTSGeometry = reader.read(posList);
if (JTSGeometry == null)
continue;
String srid;
if (SRIDHNodeId != "")
srid = row.getNode(SRIDHNodeId).getValue().asString();
// default to WGS84
srid = "4326";
if (!srid.contains(":"))
srid = "EPSG:" + srid;
CoordinateReferenceSystem sourceCRS = null;
try {
sourceCRS = CRS.decode(srid, true);
} catch (NoSuchAuthorityCodeException e) {
logger.error("No such authority code!", e);
} catch (FactoryException e) {
logger.error("Error parsing SRID!", e);
SimpleFeatureTypeBuilder simpleFeatureTypeBuilder = new SimpleFeatureTypeBuilder();
simpleFeatureTypeBuilder.setName("SimpleFeature");
simpleFeatureTypeBuilder.setCRS(sourceCRS);
simpleFeatureTypeBuilder.add("GEOM", binding);
simpleFeatureTypeBuilder.addAll(featureSchema);
SimpleFeatureType simpleFeatureTypeWithCRS = simpleFeatureTypeBuilder.buildFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(simpleFeatureTypeWithCRS);
featureBuilder.add(JTSGeometry);
for (String hNodeId : geomHNodeIdList) {
Node node = row.getNode(hNodeId);
if (node.hasNestedTable())
featureBuilder.add("Nested table");
else {
String colValue = node.getValue().asString();
featureBuilder.add(colValue);
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
} catch (Exception e) {
logger.error("Error creating geometry! Skipping it.", e);
continue;
}
Example 53
/**
* This method is used to set the tie point and the scale parameters for the GeoTiff file we are writing or the
* ModelTransformation in case a more general {@link AffineTransform} is needed to represent the raster space to
* model space transform.
* This method works regardles of the nature fo the crs without making any assumptions on the order or the direction
* of the axes, but checking them from the supplied CRS.
* @see {@link http://lists.maptools.org/pipermail/geotiff/2006-January/000213.html}
* @see {@http://lists.maptools.org/pipermail/geotiff/2006-January/000212.html
* @param crs
* The {@link CoordinateReferenceSystem} of the {@link GridCoverage2D} to encode.
* @param metadata
* where to set the georeferencing information.
* @param range
* that describes the raster space for this geotiff.
* @param rasterToModel
* describes the {@link AffineTransform} between raster space and model space.
* @param retainAxesOrder
* <code>true</code> in case we want to retain the axes order, <code>false</code> otherwise for lon-lat
* enforcing.
* @throws IOException
* in case something bad happens during the write operation.
private static void setGeoReference(final CoordinateReferenceSystem crs, final GeoTiffIIOMetadataEncoder metadata, final AffineTransform rasterToModel, GridEnvelope2D range, boolean retainAxesOrder) throws IOException {
// We have to set an affine transformation which is going to be 2D
// since we support baseline GeoTiff.
final AffineTransform modifiedRasterToModel = new AffineTransform(rasterToModel);
// move the internal grid to world to corner from center
modifiedRasterToModel.concatenate(CoverageUtilities.CENTER_TO_CORNER);
int minx = range.getLow(0);
int miny = range.getLow(1);
if (minx != 0 || miny != 0) {
// //
// Preconcatenate a transform to have raster space beginning at
// (0,0) as this is not captured by the TIFF spec
// //
modifiedRasterToModel.concatenate(AffineTransform.getTranslateInstance(minx, miny));
// Setting raster type to pixel corner since that is the default for geotiff
// and makes most software happy
metadata.addGeoShortParam(GeoTiffConstants.GTRasterTypeGeoKey, GeoTiffConstants.RasterPixelIsArea);
// AXES Swap Management
// we need to understand how the axes of this gridcoverage are
// specified, trying to understand the direction of the first axis in
// order to correctly use transformations.
boolean swapAxes = XAffineTransform.getSwapXY(modifiedRasterToModel) == -1 || CRS.getAxisOrder(crs).equals(AxisOrder.NORTH_EAST);
swapAxes &= !retainAxesOrder;
if (swapAxes) {
modifiedRasterToModel.preConcatenate(CoverageUtilities.AXES_SWAP);
metadata.setModelTransformation(modifiedRasterToModel);
}
Example 54
/**
* Retrieves the transformation that is necessary to transform the
* data from the shape file to WGS84.
* @param shapeCRS the projection of the shape file
* @return the transformation ({@code null} if no transformation required)
* @throws NoSuchAuthorityCodeException if the given projection of the shape file is not supported
* @throws FactoryException if the given projection of the shape file is not supported
private MathTransform createTransformation(String shapeCRS) throws NoSuchAuthorityCodeException, FactoryException {
if ("WGS84".equals(shapeCRS)) {
return null;
if ("Mercator".equals(shapeCRS)) {
shapeCRS = "EPSG:3857";
CoordinateReferenceSystem crsInShapefile = CRS.decode(shapeCRS);
CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
// allow for some error due to different datums
boolean lenient = true;
return CRS.findMathTransform(crsInShapefile, targetCRS, lenient);
}
Example 55
/**
* @return A {@link List} of {@link String} with the names of all different
* CRS used in the map.
public List<String> getUsedCrs() {
if (cacheUsedCrs != null || (System.currentTimeMillis() - cacheUsedCrsLastCheckedTime) > 1000) {
cacheUsedCrsLastCheckedTime = System.currentTimeMillis();
CoordinateReferenceSystem mapCrs = getLayer0Crs();
// Returns a List of all DIFFERENT CRS used in the map
if (mapCrs != null) {
cacheUsedCrs = new ArrayList<String>();
// Name/Descriptor of the Map's CRS
// The Map's CRS is always the first one in the list
cacheUsedCrs.add(GeotoolsGUIUtil.getTitleForCRS(mapCrs));
* Now iterate over the layer's CRSs and check A) If they
* semantically differ from the Map's one, and B) check that no
* CRS-Name is in the list twice.
for (DpRef dpr : getLayers()) {
DpLayer dpl = (DpLayer) dpr.getTarget();
CoordinateReferenceSystem layerCrs = dpl.getCrs();
if (layerCrs != null) {
if (!CRS.equalsIgnoreMetadata(mapCrs, layerCrs)) {
String layerCrsName = GeotoolsGUIUtil.getTitleForCRS(layerCrs);
if (layerCrsName != null && !cacheUsedCrs.contains(layerCrsName)) {
cacheUsedCrs.add(layerCrsName);
} else
cacheUsedCrs = null;
return cacheUsedCrs;
}
Example 56
@Test
public void testWktParser() throws Exception {
String geometryWkt = "POINT( 48.44 -123.37)";
GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
WKTParser parser = new WKTParser(builder);
// This fixed the NPE in parser.parse() - seems GeoTools has bug with
// keeping the CRS hint set ...
parser.setFactory(new PrimitiveFactoryImpl(DefaultGeographicCRS.WGS84));
Geometry geometry = parser.parse(geometryWkt);
CoordinateReferenceSystem crs = geometry.getCoordinateReferenceSystem();
assertNotNull(crs);
String geometryWkt2 = "POINT( 48.44 -123.37)";
builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
WKTParser parser2 = new WKTParser(builder);
Geometry geometry2 = parser2.parse(geometryWkt2);
assertTrue(geometry2.intersects(geometry));
double[] coords = geometry.getCentroid().getCoordinate();
LOGGER.debug("coords[0] = {}, coords[1] = {}", coords[0], coords[1]);
}
Example 57
private Dimension getImageDimension() throws FactoryException, TransformException {
minx -= 0.01;
miny -= 0.01;
maxx += 0.01;
maxy += 0.01;
CoordinateReferenceSystem crs = CRS.decode("EPSG:4326", true);
Coordinate c1 = new Coordinate(minx, miny);
Coordinate c2 = new Coordinate(maxx, miny);
double widthDist = JTS.orthodromicDistance(c1, c2, crs);
c1 = new Coordinate(minx, miny);
c2 = new Coordinate(minx, maxy);
double heightDist = JTS.orthodromicDistance(c1, c2, crs);
return new Dimension((int) (widthDist * IMAGE_SCALE), (int) (heightDist * IMAGE_SCALE));
}
Example 58
public MathTransform2D getMap2CartesianTransform() throws FactoryException {
if (mapToCartesianTransform == null) {
if (mapDisplayContextCrs instanceof ProjectedCRS) {
ProjectedCRS pCrs = (ProjectedCRS) mapDisplayContextCrs;
MathTransform transform = CRS.findMathTransform(pCrs.getBaseCRS(), pCrs);
assert transform instanceof MathTransform2D;
mapToCartesianTransform = (MathTransform2D) transform;
return mapToCartesianTransform;
return null;
} else {
return mapToCartesianTransform;
}
Example 59
/**
* @return returns <tt>true</tt>, if height is allowed, or we could not say:"it is not allowed" because of parsing errors...
private boolean shouldHeightPanelBeAddedForEPSG(final EPSGCode epsgCode) {
if (epsgCode == null) {
return true;
// try to create gt-CRS from code and check for height axis
// 1 try to create CRS object
String epsgString = "EPSG:";
final TableElement epsgCodeTableElem = epsgCode.getTableElement();
if (epsgCodeTableElem != null && epsgCodeTableElem instanceof Column) {
final int row = ((Column) epsgCodeTableElem).getFirstLineWithData();
final int column = ((Column) epsgCodeTableElem).getNumber();
final String cellValue = TableController.getInstance().getValueAt(row, column);
epsgString = epsgString.concat(cellValue);
} else if (epsgCode.getValue() > 0) {
epsgString = epsgString.concat(Integer.toString(epsgCode.getValue()));
try {
logger.debug(String.format("Trying to decode CRS from EPSG string : '%s'", epsgString));
final CoordinateReferenceSystem crs = CRS.decode(epsgString);
// 2 check for axis Z -> if present -> yes
logger.debug(String.format("CRS decoded to '%s' with %s dimensions.", crs.getName(), crs.getCoordinateSystem().getDimension()));
if (crs.getCoordinateSystem().getDimension() == 3) {
return true;
}// TODO what about user feedback?
catch (final NoSuchAuthorityCodeException e) {
logger.error(String.format("Exception thrown: %s", e.getMessage()), e);
} catch (final FactoryException e) {
logger.error(String.format("Exception thrown: %s", e.getMessage()), e);
return false;
}
Example 60
@Override
protected void addGeoCoding(Product product) throws IOException {
final int w = product.getSceneRasterWidth();
final int h = product.getSceneRasterHeight();
try {
final Array x = findVariable("xc").read();
final Array y = findVariable("yc").read();
final Array lat = findVariable("lat").read(new int[] { w / 2, h / 2 }, new int[] { 1, 1 });
final double easting = x.getDouble(0) * KM;
final double northing = y.getDouble(0) * KM;
final double sizeX = (x.getDouble(w - 1) * KM - easting) / (w - 1);
final double sizeY = (northing - y.getDouble(h - 1) * KM) / (h - 1);
final String code;
if (lat.getDouble(0) > 0.0) {
code = "EPSG:3411";
} else {
code = "EPSG:3412";
final CoordinateReferenceSystem crs = CRS.decode(code);
final GeoCoding gc = new CrsGeoCoding(crs, w, h, easting, northing, sizeX, sizeY, 0.5, 0.5);
product.setGeoCoding(gc);
} catch (InvalidRangeExceptionFactoryException | TransformException | e) {
throw new IllegalStateException(e);
}
Example 61
/**
* @throws RuntimeException
* if an error occurs while writing the stream to disk or
* unzipping the written file
* @see org.n52.wps.io.IParser#parse(java.io.InputStream)
@Override
public GTVectorDataBinding parse(InputStream stream, String mimeType, String schema) {
try {
String fileName = "tempfile" + UUID.randomUUID() + ".zip";
String tmpDirPath = System.getProperty("java.io.tmpdir");
File tempFile = new File(tmpDirPath + File.separatorChar + fileName);
// mark tempFile for final delete
finalizeFiles.add(tempFile);
try {
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte buf[] = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
outputStream.close();
stream.close();
} catch (FileNotFoundException e) {
System.gc();
LOGGER.error(e.getMessage(), e);
throw new RuntimeException(e);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
System.gc();
throw new RuntimeException(e);
// mark for final delete
finalizeFiles.add(tempFile);
stream.close();
List<File> wktFiles = IOUtils.unzip(tempFile, "wkt");
// mark for final delete
finalizeFiles.addAll(wktFiles);
if (wktFiles == null || wktFiles.size() == 0) {
throw new RuntimeException("Cannot find a shapefile inside the zipped file.");
//set namespace namespace
List<Geometry> geometries = new ArrayList<Geometry>();
//please not that only 1 geometry is returned. If multiple geometries are included, perhaps use the read(String wktstring) method
for (int i = 0; i < wktFiles.size(); i++) {
File wktFile = wktFiles.get(i);
Reader fileReader = new FileReader(wktFile);
WKTReader2 wktReader = new WKTReader2();
com.vividsolutions.jts.geom.Geometry geometry = wktReader.read(fileReader);
geometries.add(geometry);
CoordinateReferenceSystem coordinateReferenceSystem = CRS.decode("EPSG:4326");
SimpleFeatureCollection inputFeatureCollection = createFeatureCollection(geometries, coordinateReferenceSystem);
return new GTVectorDataBinding(inputFeatureCollection);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException("An error has occurred while accessing provided data", e);
} catch (ParseException e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException("An error has occurred while accessing provided data", e);
} catch (NoSuchAuthorityCodeException e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException("An error has occurred while accessing provided data", e);
} catch (FactoryException e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException("An error has occurred while accessing provided data", e);
}
Example 62
/**
* Query a geotools source for features using the criterion as a filter.
* @param source
* @param criterion
* @param attributeNames
* @param crs
* @return
* @throws IOException
* @throws GeomajasException
protected Query createQuery(String typeName, List<AttributeDescriptor> schema, Criterion criterion, int maxFeatures, int startIndex, List<String> attributeNames, String crs) throws IOException {
CriterionToFilterConverter converter = criterionToFilterFactory.createConverter();
Filter filter = converter.convert(criterion, schema);
Query query = null;
if (attributeNames == null) {
query = new Query(typeName, filter, maxFeatures > 0 ? maxFeatures : Integer.MAX_VALUE, Query.ALL_NAMES, null);
} else {
query = new Query(typeName, filter, maxFeatures > 0 ? maxFeatures : Integer.MAX_VALUE, attributeNames.toArray(new String[attributeNames.size()]), null);
if (startIndex > 0) {
query.setStartIndex(startIndex);
if (null != crs) {
try {
// always use the urn version as otherwise servers disagree on axis order
if (crs.equalsIgnoreCase("EPSG:4326")) {
crs = "urn:x-ogc:def:crs:EPSG:4326";
query.setCoordinateSystem(CRS.decode(crs));
} catch (// assume non-fatal
NoSuchAuthorityCodeException // assume non-fatal
log.warn("Problem getting CRS for id " + crs + ": " + e.getMessage());
} catch (FactoryException e) {
log.warn("Problem getting CRS for id " + crs + ": " + e.getMessage());
return query;
}
Example 63
public static void main(String[] args) throws Exception {
if (args.length < 5) {
System.out.println("usage: cmd [--(discrete|shapefile)] indicator_shp indicator_fld diss_shp diss_fld output_fn");
return;
int argOfs = 0;
boolean discrete = args[0].equals("--discrete");
boolean shapefile = args[0].equals("--shapefile");
if (discrete || shapefile) {
argOfs = 1;
String indicator_shp = args[argOfs + 0];
String indFldExpression = args[argOfs + 1];
String diss_shp = args[argOfs + 2];
String dissFldExpression = args[argOfs + 3];
String output_fn = args[argOfs + 4];
//==== get indicator shapefile
FeatureSource<?, ?> indicatorSource = getFeatureSource(indicator_shp);
//==== get diss source
FeatureSource<?, ?> dissSource = getFeatureSource(diss_shp);
//==== make sure both shapefiles have the same CRS
CoordinateReferenceSystem crs1 = indicatorSource.getSchema().getCoordinateReferenceSystem();
CoordinateReferenceSystem crs2 = dissSource.getSchema().getCoordinateReferenceSystem();
if (!crs1.equals(crs2)) {
throw new Exception("Coordinate systems don't match. " + crs1 + "\n\n" + crs2);
//==== loop through indicator shapefile, finding overlapping diss items
HashMap<Feature, ArrayList<Feature>> dissToInd = collectIndByDiss(indicatorSource, dissSource);
if (dissToInd.size() == 0) {
System.out.println("no overlaps found.");
return;
// register each diss with the inds, along with the ind's share of the diss's magnitude
HashMap<Feature, ArrayList<DissShare>> indDissShares = collectDissSharesByInd(dissFldExpression, dissToInd);
// dole out the ind's magnitude in proportion to the diss's mag share, accumulating under the diss
HashMap<Feature, Double> dissMags = distributeIndToDisses(indFldExpression, indDissShares);
// go through the dissMag list and emit points at centroids
if (shapefile) {
writeToShapefile(output_fn, dissMags);
} else {
writeToCSV(discrete, output_fn, dissMags);
System.out.print("done.\n");
}
Example 64
/**
* render selected georesource
* @param destination
* @param resource
* @param monitor
* @throws AWEException
private void renderGeoResource(final Graphics2D destination, final IGeoResource resource, IProgressMonitor monitor) throws RenderException, ModelException {
if (monitor == null) {
monitor = new NullProgressMonitor();
// TODO: Get size from info (???)
monitor.beginTask("render network sites and sectors: " + resource.getIdentifier(), IProgressMonitor.UNKNOWN);
try {
setStyle(destination);
// find a resource to render
model = resource.resolve(IGISModel.class, monitor);
if (!model.canRender()) {
return;
final IColoringInterceptorFactory colorerFactory = ColoringInterceptorsCache.getCache().getFactory(model);
if (colorerFactory != null) {
colorer = colorerFactory.createInterceptor(model);
if (selection != null && !selection.getModel().getAllGIS().contains(model)) {
selection = null;
// get rendering bounds and zoom
setCrsTransforms(resource.getInfo(null).getCRS());
final Envelope bounds_transformed = getTransformedBounds();
final Envelope data_bounds = model.getBounds();
Long count;
if (bounds_transformed == null) {
commonStyle.setScale(Scale.MEDIUM);
} else if (data_bounds != null && data_bounds.getHeight() > 0 && data_bounds.getWidth() > 0) {
count = getRenderableElementCount(model);
setScaling(bounds_transformed, data_bounds, monitor, count);
renderElements(destination, bounds_transformed, data_bounds, monitor);
} catch (final IOException e) {
LOGGER.error("Could not relosve resource.", e);
throw new RenderException(e);
} catch (final TransformException e) {
LOGGER.error("Could not transform bounds.", e);
throw new RenderException(e);
} catch (final FactoryException e) {
LOGGER.error("Could not set CRS transforms.", e);
throw new RenderException(e);
}
Example 65
/**
* Creates GEOMETRY_COLUMN registrations and spatial indexes for all
* geometry columns
@Override
public void postCreateTable(String schemaName, SimpleFeatureType featureType, Connection cx) throws SQLException {
schemaName = schemaName != null ? schemaName : "public";
String tableName = featureType.getName().getLocalPart();
Statement st = null;
try {
st = cx.createStatement();
// register all geometry columns in the database
for (AttributeDescriptor att : featureType.getAttributeDescriptors()) {
if (att instanceof GeometryDescriptor) {
GeometryDescriptor gd = (GeometryDescriptor) att;
// lookup or reverse engineer the srid
int srid = -1;
if (gd.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID) != null) {
srid = (Integer) gd.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID);
} else if (gd.getCoordinateReferenceSystem() != null) {
try {
Integer result = CRS.lookupEpsgCode(gd.getCoordinateReferenceSystem(), true);
if (result != null)
srid = result;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Error looking up the " + "epsg code for metadata " + "insertion, assuming -1", e);
// assume 2 dimensions, but ease future customisation
int dimensions = 2;
// grab the geometry type
String geomType = null;
if (geomType == null)
geomType = "GEOMETRY";
String sql = null;
// register the geometry type, first remove and eventual
// leftover, then write out the real one
sql = "DELETE FROM GEOMETRY_COLUMNS" + //
" WHERE f_table_catalog=''" + " AND f_table_schema = '" + schemaName + //
"'" + " AND f_table_name = '" + tableName + //
"'" + " AND f_geometry_column = '" + gd.getLocalName() + "'";
LOGGER.fine(sql);
st.execute(sql);
sql = //
"INSERT INTO GEOMETRY_COLUMNS VALUES (''," + "'" + schemaName + //
"'," + "'" + tableName + //
"'," + "'" + gd.getLocalName() + //
"'," + dimensions + //
"," + srid + //
"," + "'" + geomType + "')";
LOGGER.fine(sql);
st.execute(sql);
// add srid checks
if (srid > -1) {
sql = //
"ALTER TABLE " + "\"" + schemaName + //
"\"" + //
"." + "\"" + tableName + //
"\"" + //
" ADD CONSTRAINT \"enforce_srid_" + gd.getLocalName() + //
"\"" + //
" CHECK (ST_SRID(" + "\"" + gd.getLocalName() + //
"\"" + ") = " + srid + ")";
LOGGER.fine(sql);
st.execute(sql);
// add dimension checks
sql = //
"ALTER TABLE " + "\"" + schemaName + //
"\"" + //
"." + "\"" + tableName + //
"\"" + //
" ADD CONSTRAINT \"enforce_dims_" + gd.getLocalName() + //
"\"" + " CHECK (st_ndims(\"" + gd.getLocalName() + //
"\")" + " = 2)";
LOGGER.fine(sql);
st.execute(sql);
// add geometry type checks
if (!geomType.equals("GEOMETRY")) {
sql = //
"ALTER TABLE " + "\"" + schemaName + //
"\"" + //
"." + "\"" + tableName + //
"\"" + //
" ADD CONSTRAINT \"enforce_geotype_" + gd.getLocalName() + //
"\"" + //
" CHECK (geometrytype(" + "\"" + gd.getLocalName() + //
"\"" + ") = '" + geomType + "'::text " + "OR \"" + gd.getLocalName() + //
"\"" + " IS NULL)";
LOGGER.fine(sql);
st.execute(sql);
// add the spatial index
sql = //
"CREATE INDEX \"spatial_" + tableName + "_" + gd.getLocalName().toLowerCase() + //
"\"" + //
" ON " + "\"" + schemaName + //
"\"" + //
"." + "\"" + tableName + //
"\"" + //
" USING GIST (" + "\"" + gd.getLocalName() + //
"\"" + ")";
LOGGER.fine(sql);
st.execute(sql);
if (!cx.getAutoCommit()) {
cx.commit();
} finally {
dataStore.closeSafe(st);
}
Example 66
/**
* Transform geometry
* @param geometry
* Geometry to transform
* @param targetSRID
* TargetEPSG code
* @param sourceCRS
* Source CRS
* @param targetCRS
* Target CRS
* @return Transformed geometry
* @throws OwsExceptionReport
private Geometry transform(final Geometry geometry, final int targetSRID, final CoordinateReferenceSystem sourceCRS, final CoordinateReferenceSystem targetCRS) throws OwsExceptionReport {
if (sourceCRS.equals(targetCRS)) {
return geometry;
Geometry switchedCoordiantes = switchCoordinateAxisIfNeeded(geometry, targetSRID);
try {
MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
Geometry transformed = JTS.transform(switchedCoordiantes, transform);
transformed.setSRID(targetSRID);
return transformed;
} catch (FactoryException fe) {
throw new NoApplicableCodeException().causedBy(fe).withMessage("The EPSG code '%s' is not supported!", switchedCoordiantes.getSRID());
} catch (MismatchedDimensionException mde) {
throw new NoApplicableCodeException().causedBy(mde).withMessage("The EPSG code '%s' is not supported!", switchedCoordiantes.getSRID());
} catch (TransformException te) {
throw new NoApplicableCodeException().causedBy(te).withMessage("The EPSG code '%s' is not supported!", switchedCoordiantes.getSRID());
}
Example 67
/**
* Main entry point of the utility for extracting triples from geospatially-enabled DBMSs
public static void main(String[] args) throws Exception {
if (args.length >= 0) {
Properties properties = new Properties();
//Specify properties file for conversion of elements from a database
//Argument like "./bin/PostGIS_options.conf"
properties.load(new FileInputStream(args[0]));
System.setProperty("org.geotools.referencing.forceXY", "false");
String tmpDir = properties.getProperty("tmpDir");
String outputFile = properties.getProperty("outputFile");
String outFormat = properties.getProperty("format");
System.out.println("Output format is: " + outFormat);
dtr = new RdbToRdf(tmpDir);
int dbType = Integer.valueOf(properties.getProperty("dbType"));
String dbName = properties.getProperty("dbName");
String dbUserName = properties.getProperty("dbUserName");
String dbPassword = properties.getProperty("dbPassword");
String dbHost = properties.getProperty("dbHost");
int dbPort = Integer.parseInt(properties.getProperty("dbPort"));
//Determine connection type to the specified DBMS
DbConnector databaseConnector = null;
switch(dbType) {
case //Currently NOT supported
DbConstants.MSACCESS:
databaseConnector = new MsAccessDbConnector(dbHost, dbPort, dbName, dbUserName, dbPassword);
break;
case DbConstants.MYSQL:
databaseConnector = new MySqlDbConnector(dbHost, dbPort, dbName, dbUserName, dbPassword);
break;
case DbConstants.ORACLE:
databaseConnector = new OracleDbConnector(dbHost, dbPort, dbName, dbUserName, dbPassword);
break;
case DbConstants.POSTGRESQL:
databaseConnector = new PostgresqlDbConnector(dbHost, dbPort, dbName, dbUserName, dbPassword);
break;
case DbConstants.DB2:
databaseConnector = new DB2DbConnector(dbHost, dbPort, dbName, dbUserName, dbPassword);
break;
String resourceName = properties.getProperty("resourceName");
ignoreStr = properties.getProperty("ignore");
targetStore = properties.getProperty("targetStore");
//Table and attribute properties
String tableName = properties.getProperty("tableName");
String condition = properties.getProperty("condition");
String labelColumnName = properties.getProperty("labelColumnName");
String geometryColumnName = properties.getProperty("geometryColumnName");
String nameColumnName = properties.getProperty("nameColumnName");
String classColumnName = properties.getProperty("classColumnName");
// Namespace parameters
String namespacePrefix = properties.getProperty("nsPrefix");
if (UtilsLib.isNullOrEmpty(namespacePrefix)) {
namespacePrefix = "georesource";
String namespace = properties.getProperty("nsURI");
if (UtilsLib.isNullOrEmpty(namespace)) {
namespace = "http://geoknow.eu/resource/";
String ontologyNSPrefix = properties.getProperty("ontologyNSPrefix");
if (UtilsLib.isNullOrEmpty(ontologyNSPrefix)) {
ontologyNSPrefix = "geontology";
String ontologyNamespace = properties.getProperty("ontologyNS");
if (UtilsLib.isNullOrEmpty(ontologyNamespace)) {
ontologyNamespace = "http://www.opengis.net/ont/geosparql#";
dtr.model.setNsPrefix(ontologyNSPrefix, ontologyNamespace);
dtr.model.setNsPrefix(namespacePrefix, namespace);
dtr.nsgeontology = ontologyNamespace;
dtr.nsgeoresource = namespace;
// Reference systems parameters
dtr.gmlSourceRS = properties.getProperty("gmlSourceRS");
dtr.gmlTargetRS = properties.getProperty("gmlTargetRS");
dtr.sourceRS = properties.getProperty("sourceRS");
dtr.targetRS = properties.getProperty("targetRS");
//Check if a coordinate transform is required for geometries
if (dtr.sourceRS != null)
try {
// allow for some error due to different datums
boolean lenient = true;
Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
CoordinateReferenceSystem sourceCRS = factory.createCoordinateReferenceSystem(dtr.sourceRS);
CoordinateReferenceSystem targetCRS = factory.createCoordinateReferenceSystem(dtr.targetRS);
transform = CRS.findMathTransform(sourceCRS, targetCRS, lenient);
//Needed for parsing original geometry in WTK representation
int srid = Integer.parseInt(dtr.sourceRS.substring(dtr.sourceRS.indexOf(':') + 1, dtr.sourceRS.length()));
GeometryFactory geomFactory = new GeometryFactory(new PrecisionModel(), srid);
reader = new WKTReader(geomFactory);
System.out.println("Transformation will take place from " + dtr.sourceRS + " to " + dtr.targetRS + " reference system.");
} catch (Exception e) {
System.out.println("No transformation will take place. Input data is expected in WGS84 reference system.");
// Other parameters
dtr.defaultLang = properties.getProperty("defaultLang");
if (UtilsLib.isNullOrEmpty(dtr.defaultLang)) {
dtr.defaultLang = "en";
dtr.executeParser(databaseConnector, tableName, resourceName, condition, outputFile, outFormat, labelColumnName, geometryColumnName, nameColumnName, classColumnName);
//Remove all temporary files as soon as processing is finished
UtilsLib.removeDirectory(tmpDir);
} else {
System.out.println("Incorrect arguments number. Properties file required.");
}
Example 68
public Geometry transformGeometry(Geometry geometry, String sourceCRS, String targetCRS) throws SpatialIndexException {
//provisional workarounds
if ("osgb:BNG".equalsIgnoreCase(sourceCRS.trim()))
sourceCRS = "EPSG:27700";
if ("osgb:BNG".equalsIgnoreCase(targetCRS.trim()))
targetCRS = "EPSG:27700";
MathTransform transform = (MathTransform) transformations.get(sourceCRS + "_" + targetCRS);
if (transform == null) {
try {
try {
transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode);
} catch (OperationNotFoundException e) {
LOG.info(e);
LOG.info("Switching to lenient mode... beware of precision loss !");
useLenientMode = true;
transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode);
transformations.put(sourceCRS + "_" + targetCRS, transform);
LOG.debug("Instantiated transformation from '" + sourceCRS + "' to '" + targetCRS + "'");
} catch (NoSuchAuthorityCodeException e) {
LOG.error(e);
} catch (FactoryException e) {
LOG.error(e);
if (transform == null) {
throw new SpatialIndexException("Unable to get a transformation from '" + sourceCRS + "' to '" + targetCRS + "'");
coordinateTransformer.setMathTransform(transform);
try {
return coordinateTransformer.transform(geometry);
} catch (TransformException e) {
throw new SpatialIndexException(e);
}
Example 69
public Geometry transformGeometry(Geometry geometry, String sourceCRS, String targetCRS) throws SpatialIndexException {
//provisional workarounds
if ("osgb:BNG".equalsIgnoreCase(sourceCRS.trim()))
sourceCRS = "EPSG:27700";
if ("osgb:BNG".equalsIgnoreCase(targetCRS.trim()))
targetCRS = "EPSG:27700";
MathTransform transform = transformations.get(sourceCRS + "_" + targetCRS);
if (transform == null) {
try {
try {
transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode);
} catch (OperationNotFoundException e) {
LOG.info(e);
LOG.info("Switching to lenient mode... beware of precision loss !");
useLenientMode = true;
transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode);
transformations.put(sourceCRS + "_" + targetCRS, transform);
LOG.debug("Instantiated transformation from '" + sourceCRS + "' to '" + targetCRS + "'");
} catch (NoSuchAuthorityCodeException e) {
LOG.error(e);
} catch (FactoryException e) {
LOG.error(e);
if (transform == null) {
throw new SpatialIndexException("Unable to get a transformation from '" + sourceCRS + "' to '" + targetCRS + "'");
coordinateTransformer.setMathTransform(transform);
try {
return coordinateTransformer.transform(geometry);
} catch (TransformException e) {
throw new SpatialIndexException(e);
}
Example 70
public Geometry transformGeometry(Geometry geometry, String sourceCRS, String targetCRS) throws SpatialIndexException {
//provisional workarounds
if ("osgb:BNG".equalsIgnoreCase(sourceCRS.trim()))
sourceCRS = "EPSG:27700";
if ("osgb:BNG".equalsIgnoreCase(targetCRS.trim()))
targetCRS = "EPSG:27700";
MathTransform transform = transformations.get(sourceCRS + "_" + targetCRS);
if (transform == null) {
try {
try {
transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode);
} catch (OperationNotFoundException e) {
LOG.info(e);
LOG.info("Switching to lenient mode... beware of precision loss !");
useLenientMode = true;
transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode);
transformations.put(sourceCRS + "_" + targetCRS, transform);
LOG.debug("Instantiated transformation from '" + sourceCRS + "' to '" + targetCRS + "'");
} catch (NoSuchAuthorityCodeException e) {
LOG.error(e);
} catch (FactoryException e) {
LOG.error(e);
if (transform == null) {
throw new SpatialIndexException("Unable to get a transformation from '" + sourceCRS + "' to '" + targetCRS + "'");
coordinateTransformer.setMathTransform(transform);
try {
return coordinateTransformer.transform(geometry);
} catch (TransformException e) {
throw new SpatialIndexException(e);
}
Example 71
@Test
public void testWktParser() throws Exception {
String geometryWkt = "POINT( 48.44 -123.37)";
GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
WKTParser parser = new WKTParser(builder);
// This fixed the NPE in parser.parse() - seems GeoTools has bug with
// keeping the CRS hint set ...
parser.setFactory(new PrimitiveFactoryImpl(DefaultGeographicCRS.WGS84));
Geometry geometry = parser.parse(geometryWkt);
CoordinateReferenceSystem crs = geometry.getCoordinateReferenceSystem();
assertNotNull(crs);
String geometryWkt2 = "POINT( 48.44 -123.37)";
builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
WKTParser parser2 = new WKTParser(builder);
Geometry geometry2 = parser2.parse(geometryWkt2);
assertTrue(geometry2.intersects(geometry));
double[] coords = geometry.getCentroid().getCoordinate();
LOGGER.debug("coords[0] = " + coords[0] + ", coords[1] = " + coords[1]);
}
Example 72
/**
* Create math transform to go from WGS84 to the input EPSG SRID system
* @param espg_srid
* @return
public static MathTransform fromWGS84(String espg_srid) {
try {
CoordinateReferenceSystem crs = crsFac.createCoordinateReferenceSystem(espg_srid);
return CRS.findMathTransform(wgs84crs, crs, true);
} catch (Throwable e) {
throw new RuntimeException(e);
}
Example 73
public static MathTransform createMathTransform(CrsId srs, CrsId target) {
try {
CoordinateReferenceSystem sourceCRS = create(srs);
CoordinateReferenceSystem targetCRS = create(target);
return CRS.findMathTransform(sourceCRS, targetCRS);
} catch (FactoryException e) {
throw new RuntimeException(e);