Commit 48f49b1b authored by Matija Obreza's avatar Matija Obreza
Browse files

Source code formatted

parent 2423754f
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......@@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory;
* Helper for CSV header management.
*/
public abstract class HeaderUtils {
/** The Constant LOG. */
private final static Logger LOG = LoggerFactory.getLogger(HeaderUtils.class);
......@@ -42,8 +42,8 @@ public abstract class HeaderUtils {
* @throws IOException when one unacceptable header is found
*/
public static void throwIfHeaderFound(final String[] headers, final String[] notAllowedHeaders) throws IOException {
for (String header : notAllowedHeaders) {
int pos = ArrayUtils.indexOf(headers, header);
for (final String header : notAllowedHeaders) {
final int pos = ArrayUtils.indexOf(headers, header);
if (pos >= 0) {
throw new IOException("Header " + header + " found in input file. Refusing to run.");
}
......@@ -58,8 +58,8 @@ public abstract class HeaderUtils {
* @throws IOException when one unacceptable header is found
*/
public static void throwIfHeaderNotFound(final String[] headers, final String[] requiredHeaders) throws IOException {
for (String header : requiredHeaders) {
int pos = ArrayUtils.indexOf(headers, header);
for (final String header : requiredHeaders) {
final int pos = ArrayUtils.indexOf(headers, header);
if (pos < 0) {
throw new IOException("Header " + header + " not found in input file. Refusing to run.");
}
......@@ -73,9 +73,9 @@ public abstract class HeaderUtils {
* @return a new List with header indexes
*/
public static List<Integer> mapHeaderPositions(final String[] headers) {
List<Integer> outputMapping = new ArrayList<>();
final List<Integer> outputMapping = new ArrayList<>();
int col = 0;
for (String header : headers) {
for (final String header : headers) {
LOG.debug("Mapping input column={} to index={}", header, col);
outputMapping.add(col++);
}
......@@ -90,11 +90,11 @@ public abstract class HeaderUtils {
* @return Map of positions of supported headers
*/
public static Map<String, Integer> makeSourceMapping(final String[] headers, final String[] supportedHeaders) {
Map<String, Integer> sourceMapping = new HashMap<>();
final Map<String, Integer> sourceMapping = new HashMap<>();
Arrays.stream(supportedHeaders).forEach(header -> {
LOG.debug("Looking for header {} in {}", header, Arrays.asList(headers));
int pos = ArrayUtils.indexOf(headers, header);
final int pos = ArrayUtils.indexOf(headers, header);
if (pos >= 0) {
LOG.debug("Header {} is in position {}", header, pos);
sourceMapping.put(header, pos);
......@@ -114,10 +114,10 @@ public abstract class HeaderUtils {
* @param outputMapping mapping of output columns
* @return the output CSV line filled with data from input CSV line
*/
public static String[] toOutputLine(String[] nextLine, final List<String> outputHeaders, final List<Integer> outputMapping) {
public static String[] toOutputLine(final String[] nextLine, final List<String> outputHeaders, final List<Integer> outputMapping) {
final String[] outputLine = new String[outputHeaders.size()];
for (int outputCol = 0; outputCol < outputMapping.size(); outputCol++) {
Integer mapped = outputMapping.get(outputCol);
final Integer mapped = outputMapping.get(outputCol);
if (mapped != null)
outputLine[outputCol] = nextLine[mapped];
}
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......@@ -34,7 +34,7 @@ public interface LandOrSeaService {
/**
* Classifies location as one of Land, Coastal or Water
*
*
* @param longitude the longitude
* @param latitude the latitude
* @param allowedDistanceFromLand the allowed distance from land
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......@@ -25,18 +25,18 @@ public class LonLatCacheKey implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -3626533849742141104L;
/** The longitude. */
private float longitude;
private final float longitude;
/** The latitude. */
private float latitude;
private final float latitude;
/** The orig cty. */
private String origCty;
/** The allowed distance margin. */
private int allowedDistanceMargin;
private final int allowedDistanceMargin;
/**
* Instantiates a new lon lat cache key.
......@@ -45,7 +45,7 @@ public class LonLatCacheKey implements Serializable {
* @param latitude the latitude
* @param allowedDistanceMargin the allowed distance margin
*/
public LonLatCacheKey(float longitude, float latitude, int allowedDistanceMargin) {
public LonLatCacheKey(final float longitude, final float latitude, final int allowedDistanceMargin) {
this.longitude = longitude;
this.latitude = latitude;
this.allowedDistanceMargin = allowedDistanceMargin;
......@@ -59,39 +59,41 @@ public class LonLatCacheKey implements Serializable {
* @param origCty the orig cty
* @param allowedDistanceMargin the allowed distance margin
*/
public LonLatCacheKey(float longitude, float latitude, String origCty, int allowedDistanceMargin) {
public LonLatCacheKey(final float longitude, final float latitude, final String origCty, final int allowedDistanceMargin) {
this.longitude = longitude;
this.latitude = latitude;
this.origCty = origCty;
this.allowedDistanceMargin = allowedDistanceMargin;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + allowedDistanceMargin;
result = prime * result + Float.floatToIntBits(latitude);
result = prime * result + Float.floatToIntBits(longitude);
result = prime * result + ((origCty == null) ? 0 : origCty.hashCode());
result = (prime * result) + allowedDistanceMargin;
result = (prime * result) + Float.floatToIntBits(latitude);
result = (prime * result) + Float.floatToIntBits(longitude);
result = (prime * result) + ((origCty == null) ? 0 : origCty.hashCode());
return result;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LonLatCacheKey other = (LonLatCacheKey) obj;
final LonLatCacheKey other = (LonLatCacheKey) obj;
if (allowedDistanceMargin != other.allowedDistanceMargin)
return false;
if (Float.floatToIntBits(latitude) != Float.floatToIntBits(other.latitude))
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......@@ -41,10 +41,10 @@ import com.vividsolutions.jts.geom.Polygon;
* The Class ShapefileUtils.
*/
public class ShapefileUtils {
/** The Constant RING_POINTS. */
private static final int RING_POINTS = 12;
/** The Constant geometryFactory. */
private static final GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
......@@ -56,20 +56,19 @@ public class ShapefileUtils {
* @throws MalformedURLException the malformed url exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public static DataStore openShapeFile(String shapeFilePath) throws MalformedURLException, IOException {
public static DataStore openShapeFile(final String shapeFilePath) throws MalformedURLException, IOException {
File file = new File("data", shapeFilePath);
Map<String, Object> map = new HashMap<String, Object>();
final File file = new File("data", shapeFilePath);
final Map<String, Object> map = new HashMap<>();
map.put("url", file.toURI().toURL());
System.err.println(file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
final DataStore dataStore = DataStoreFinder.getDataStore(map);
return dataStore;
}
/**
* Uses ideas from
* https://geoaware.wordpress.com/2013/10/16/geodetic-buffers-with-geotools/
* Uses ideas from https://geoaware.wordpress.com/2013/10/16/geodetic-buffers-with-geotools/
*
* @param longitude the longitude
* @param latitude the latitude
......@@ -79,17 +78,17 @@ public class ShapefileUtils {
* @throws TransformException the transform exception
* @throws FactoryException the factory exception
*/
public static Geometry getPointBuffer(double longitude, double latitude, double distanceMeters)
public static Geometry getPointBuffer(final double longitude, final double latitude, final double distanceMeters)
throws MismatchedDimensionException, TransformException, FactoryException {
Coordinate[] coords1 = new Coordinate[RING_POINTS + 1];
final Coordinate[] coords1 = new Coordinate[RING_POINTS + 1];
GeodeticCalculator gc = new GeodeticCalculator(DefaultGeographicCRS.WGS84);
final GeodeticCalculator gc = new GeodeticCalculator(DefaultGeographicCRS.WGS84);
gc.setStartingGeographicPoint(longitude, latitude);
for (int i = 0; i < RING_POINTS; i++) {
gc.setDirection(i * 360.0 / RING_POINTS, distanceMeters);
Point2D destGeoPoint = gc.getDestinationGeographicPoint();
gc.setDirection((i * 360.0) / RING_POINTS, distanceMeters);
final Point2D destGeoPoint = gc.getDestinationGeographicPoint();
coords1[i] = new Coordinate(destGeoPoint.getX(), destGeoPoint.getY(), 0);
// System.err.println("a=" + (i * 360.0 / RING_POINTS) + " p=" + p +
// " d=" + gc.getOrthodromicDistance());
......@@ -97,7 +96,7 @@ public class ShapefileUtils {
// Points of LinearRing form a closed linestring
coords1[RING_POINTS] = coords1[0];
Polygon x = geometryFactory.createPolygon(geometryFactory.createLinearRing(coords1));
final Polygon x = geometryFactory.createPolygon(geometryFactory.createLinearRing(coords1));
// System.err.println(x);
return x;
}
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......@@ -72,13 +72,13 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
private LoadingCache<LonLatCacheKey, String> countryCache;
/** The debug. */
private boolean debug = false;
private final boolean debug = false;
static {
try {
// Initialize stuff
} catch (Throwable e) {
} catch (final Throwable e) {
// big problem
throw new RuntimeException(e);
}
......@@ -93,28 +93,29 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
public void afterPropertiesSet() throws MalformedURLException, IOException {
// http://www.gadm.org/version2
// Use "six dissolved layers"
DataStore dataStoreAdm0 = ShapefileUtils.openShapeFile("TM_WORLD_BORDERS-0.3.shp");
DataStore dataStoreAdm0X = ShapefileUtils.openShapeFile("gadm28_adm1.shp");
final DataStore dataStoreAdm0 = ShapefileUtils.openShapeFile("TM_WORLD_BORDERS-0.3.shp");
final DataStore dataStoreAdm0X = ShapefileUtils.openShapeFile("gadm28_adm1.shp");
sourceAdmin0 = dataStoreAdm0.getFeatureSource(dataStoreAdm0.getTypeNames()[0]);
sourceAdmin0X = dataStoreAdm0X.getFeatureSource(dataStoreAdm0X.getTypeNames()[0]);
countryCache = CacheBuilder.newBuilder().maximumSize(5000).recordStats().expireAfterWrite(20, TimeUnit.SECONDS).build(new CacheLoader<LonLatCacheKey, String>() {
@Override
public String load(LonLatCacheKey key) throws Exception {
// LOG.debug("Loading");
return _getCountry(key.getLongitude(), key.getLatitude(), key.getOrigCty(), key.getAllowedDistanceMargin());
}
});
countryCache = CacheBuilder.newBuilder().maximumSize(5000).recordStats().expireAfterWrite(20, TimeUnit.SECONDS).build(
new CacheLoader<LonLatCacheKey, String>() {
@Override
public String load(final LonLatCacheKey key) throws Exception {
// LOG.debug("Loading");
return _getCountry(key.getLongitude(), key.getLatitude(), key.getOrigCty(), key.getAllowedDistanceMargin());
}
});
}
/*
* (non-Javadoc)
*
* @see org.genesys.geotools.LandOrSeaService#isOnLand(float, float, int)
*/
@Override
public String getCountries(float longitude, float latitude, String origCty, int allowedDistanceMargin) throws Exception {
public String getCountries(final float longitude, final float latitude, final String origCty, final int allowedDistanceMargin)
throws Exception {
// 1 geographical mile is 1855.3248 metres for WGS84
// 1855.3248m * 60 = 111319.488m
......@@ -126,7 +127,7 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
try {
return countryCache.get(new LonLatCacheKey(longitude, latitude, origCty, allowedDistanceMargin));
} catch (ExecutionException e) {
} catch (final ExecutionException e) {
throw new Exception(e.getCause());
}
}
......@@ -141,33 +142,35 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
* @return the string
* @throws Exception the exception
*/
private String _getCountry(float longitude, float latitude, String origCtyISO, int allowedDistanceMargin) throws Exception {
private String _getCountry(final float longitude, final float latitude, final String origCtyISO, final int allowedDistanceMargin)
throws Exception {
// LOG.debug(longitude + ", " + latitude + " " + origCtyISO);
StopWatch stopWatch = new StopWatch();
final StopWatch stopWatch = new StopWatch();
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
String geometryPropertyName = sourceAdmin0.getSchema().getGeometryDescriptor().getLocalName();
final Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
final String geometryPropertyName = sourceAdmin0.getSchema().getGeometryDescriptor().getLocalName();
// CoordinateReferenceSystem targetCRS =
// sourceAdmin0.getSchema().getGeometryDescriptor()
// .getCoordinateReferenceSystem();
ReferencedEnvelope bbox = new ReferencedEnvelope(longitude - 30, longitude + 30, latitude - 30, latitude + 30, DefaultGeographicCRS.WGS84);
final ReferencedEnvelope bbox = new ReferencedEnvelope(longitude - 30, longitude + 30, latitude - 30, latitude + 30,
DefaultGeographicCRS.WGS84);
Filter filterExact =
final Filter filterExact =
// ff.and(
// ff.equal(ff.property("ISO3"), ff.literal(origCtyISO), false),
ff.and(ff.bbox(ff.property(geometryPropertyName), bbox), ff.contains(ff.property(geometryPropertyName), ff.literal(point)));
StringBuffer sb = new StringBuffer();
final StringBuffer sb = new StringBuffer();
stopWatch.start();
// LOG.debug(1);
FeatureCollection<SimpleFeatureType, SimpleFeature> matchingFeatures = sourceAdmin0.getFeatures(filterExact);
final FeatureCollection<SimpleFeatureType, SimpleFeature> matchingFeatures = sourceAdmin0.getFeatures(filterExact);
try (FeatureIterator<SimpleFeature> features = matchingFeatures.features()) {
if (features.hasNext()) {
// LOG.debug(3);
SimpleFeature feature = features.next();
final SimpleFeature feature = features.next();
// System.out.print(feature.getID());
// System.out.print(": ");
// System.out.println(feature.getDefaultGeometryProperty().getValue());
......@@ -183,7 +186,7 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
LOG.debug("Processing time split: " + processingTime);
}
if (sb.length() == 0 || !sb.toString().contains(origCtyISO)) {
if ((sb.length() == 0) || !sb.toString().contains(origCtyISO)) {
// if (sb.length() > 0) sb.append(", ");
// sb.append("???");
// Filter filterBuffered =
......@@ -191,20 +194,20 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
// ff.literal(ShapefileUtils.getPointBuffer(point,
// allowedDistanceMargin)));
// LOG.debug(4);
FeatureCollection<SimpleFeatureType, SimpleFeature> matchingFeatures2 = sourceAdmin0X.getFeatures(filterExact);
final FeatureCollection<SimpleFeatureType, SimpleFeature> matchingFeatures2 = sourceAdmin0X.getFeatures(filterExact);
// LOG.debug(4.1);
try (FeatureIterator<SimpleFeature> features = matchingFeatures2.features()) {
if (features.hasNext()) {
// LOG.debug(7);
SimpleFeature feature = features.next();
final SimpleFeature feature = features.next();
// System.out.print(feature.getID());
// System.out.print(": ");
//
// System.out.println(feature.getDefaultGeometryProperty().getValue());
Object isoAttr = feature.getAttribute("ISO");
final Object isoAttr = feature.getAttribute("ISO");
String countryIsoCode = isoAttr == null ? "" : isoAttr.toString();
final String countryIsoCode = isoAttr == null ? "" : isoAttr.toString();
if (!sb.toString().contains(countryIsoCode)) {
if (sb.length() > 0)
sb.append(", ");
......@@ -215,7 +218,7 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
}
stopWatch.stop();
processingTime = stopWatch.getTime();
if (LOG.isInfoEnabled() || processingTime > 3000) {
if (LOG.isInfoEnabled() || (processingTime > 3000)) {
LOG.info("Total processing time: {} for\t{}\t\t", processingTime, origCtyISO, longitude, latitude);
}
......@@ -227,9 +230,10 @@ public class CountryOfOriginServiceImpl implements CountryOfOriginService {
* Prints the cache.
*/
public void printCache() {
CacheStats stats = countryCache.stats();
final CacheStats stats = countryCache.stats();
if (LOG.isInfoEnabled()) {
LOG.info("Hit count=" + stats.hitCount() + " rate=" + stats.hitRate() + " Miss count=" + stats.missCount() + " rate=" + stats.missRate());
LOG.info("Hit count=" + stats.hitCount() + " rate=" + stats.hitRate() + " Miss count=" + stats.missCount() + " rate=" + stats
.missRate());
}
}
}
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
......@@ -24,13 +24,6 @@ import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.genesys.geotools.service.LandOrSeaService;
import org.genesys.geotools.service.LonLatCacheKey;
import org.genesys.geotools.service.ShapefileUtils;
......@@ -48,6 +41,13 @@ import org.opengis.filter.FilterFactory2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
/**
* Polygons used here are derived from OSM data, © OpenStreetMap contributors.
*/
......@@ -55,25 +55,25 @@ public class LandOrSeaServiceImpl implements LandOrSeaService {
/** LOG */
private final static Logger LOG = LoggerFactory.getLogger(LandOrSeaServiceImpl.class);
/** The Constant ff. */
private static final FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
/** The Constant geometryFactory. */
private static final GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
/** The source land. */
private FeatureSource<SimpleFeatureType, SimpleFeature> sourceLand;
/** The source water. */
private FeatureSource<SimpleFeatureType, SimpleFeature> sourceWater;
/** The water cache. */
private LoadingCache<LonLatCacheKey, Boolean> waterCache;
/** The classifier cache. */
private LoadingCache<LonLatCacheKey, String> classifierCache;
/**
* After properties set.
*
......@@ -83,32 +83,32 @@ public class LandOrSeaServiceImpl implements LandOrSeaService {
public void afterPropertiesSet() throws MalformedURLException, IOException {
// http://openstreetmapdata.com/data/land-polygons
// Use "split large polygons"
DataStore dataStoreLand = openShapeFile("land_polygons.shp");
final DataStore dataStoreLand = openShapeFile("land_polygons.shp");
// http://openstreetmapdata.com/data/water-polygons