use of org.opengis.filter.FilterFactory in project spatial-portal by AtlasOfLivingAustralia.
the class AreaUploadShapefileWizardController method loadOnMap.
private void loadOnMap(Set<FeatureId> ids, String filename) {
try {
final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
Filter filter = ff.id(ids);
// set up the math transform used to process the data
SimpleFeatureType schema = features.getSchema();
CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem wgsCRS = DefaultGeographicCRS.WGS84;
// allow for some error due to different datums
boolean lenient = true;
if (dataCRS == null) {
// attempt to parse prj
try {
File prjFile = new File(filename.substring(0, filename.length() - 3) + "prj");
if (prjFile.exists()) {
String prj = FileUtils.readFileToString(prjFile);
if (prj.equals("PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0]]")) {
// support for arcgis online default shp exports
dataCRS = CRS.decode("EPSG:3857");
} else {
dataCRS = CRS.parseWKT(FileUtils.readFileToString(prjFile));
}
}
} catch (Exception e) {
LOGGER.error("failed to read prj for " + filename);
}
if (dataCRS == null) {
dataCRS = DefaultGeographicCRS.WGS84;
}
}
MathTransform transform = CRS.findMathTransform(dataCRS, wgsCRS, lenient);
SimpleFeatureCollection sff = source.getFeatures(filter);
SimpleFeatureIterator fif = sff.features();
StringBuilder sb = new StringBuilder();
StringBuilder sbGeometryCollection = new StringBuilder();
boolean isGeometryCollection = false;
List<Geometry> geoms = new ArrayList<Geometry>();
while (fif.hasNext()) {
SimpleFeature f = fif.next();
LOGGER.debug("Selected Feature: " + f.getID() + " -> " + f.getAttribute("ECOREGION"));
Geometry geom = (Geometry) f.getDefaultGeometry();
geom = JTS.transform(geom, transform);
String wktString = geom.toText();
wktString = wktString.replaceAll(", ", ",");
boolean valid = true;
boolean multipolygon = false;
boolean polygon = false;
boolean geometrycollection = false;
if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
wktString = wktString.substring((StringConstants.MULTIPOLYGON + " ").length(), wktString.length() - 1);
multipolygon = true;
} else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
wktString = wktString.substring((StringConstants.POLYGON + " ").length());
polygon = true;
} else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
geometrycollection = true;
isGeometryCollection = true;
} else {
valid = false;
}
if (valid) {
if (sb.length() > 0) {
sb.append(",");
sbGeometryCollection.append(",");
}
sb.append(wktString);
if (multipolygon) {
sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
if (!wktString.endsWith(")))")) {
sbGeometryCollection.append(")");
}
} else if (polygon) {
sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
} else if (geometrycollection) {
sbGeometryCollection.append(wktString);
}
}
}
String wkt;
if (!isGeometryCollection) {
if (!sb.toString().contains(")))")) {
sb.append(")");
}
wkt = StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "((");
} else {
sbGeometryCollection.append(")");
wkt = StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection.toString();
getMapComposer().showMessage("Shape is invalid: " + "GEOMETRYCOLLECTION not supported.");
}
GeometryFactory gf = new GeometryFactory();
gf.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
String msg = "";
boolean invalid = false;
try {
WKTReader wktReader = new WKTReader();
com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
// NC 20130319: Ensure that the WKT is valid according to the WKT standards.
IsValidOp op = new IsValidOp(g);
if (!op.isValid()) {
// this will fix some issues
g = g.buffer(0);
op = new IsValidOp(g);
}
if (!op.isValid()) {
invalid = true;
LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
msg = op.getValidationError().getMessage();
// TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
} else if (g.isRectangle()) {
// NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
// get the new WKT for the rectangle will possibly need to change the order.
com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
if (!wkt.equals(wkt2)) {
LOGGER.debug("NEW WKT for Rectangle: " + wkt);
msg = CommonData.lang("error_wkt_anticlockwise");
invalid = true;
}
}
if (!invalid) {
invalid = !op.isValid();
}
} catch (ParseException parseException) {
LOGGER.error("error testing validity of uploaded shape file wkt", parseException);
}
if (invalid) {
getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
} else {
MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layername, layername);
UserDataDTO ud = new UserDataDTO(layername);
ud.setFilename(media.getName());
ud.setUploadedTimeInMs(System.currentTimeMillis());
ud.setType("shapefile");
String metadata = "";
metadata += "User uploaded Shapefile \n";
metadata += "Name: " + ud.getName() + " <br />\n";
metadata += "Filename: " + ud.getFilename() + " <br />\n";
metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
metadata += "Selected polygons (fid): <br />\n";
metadata += "<ul>";
metadata += "</ul>";
mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
getMapComposer().replaceWKTwithWMS(mapLayer);
}
} catch (IOException e) {
LOGGER.debug("IO Error retrieving geometry", e);
} catch (Exception e) {
LOGGER.debug("Generic Error retrieving geometry", e);
}
}
use of org.opengis.filter.FilterFactory in project ddf by codice.
the class CatalogFrameworkImplTest method testUpdateWithStores.
// TODO (DDF-2436) -
@Ignore
@Test
public void testUpdateWithStores() throws Exception {
MockEventProcessor eventAdmin = new MockEventProcessor();
MockMemoryProvider provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(), true, new Date());
List<CatalogStore> storeList = new ArrayList<>();
List<FederatedSource> sourceList = new ArrayList<>();
MockCatalogStore store = new MockCatalogStore("catalogStoreId-1", true);
storeList.add(store);
sourceList.add(store);
CatalogFramework framework = createDummyCatalogFramework(provider, storeList, sourceList, eventAdmin);
FilterFactory filterFactory = new FilterFactoryImpl();
Filter filter = filterFactory.like(filterFactory.property(Metacard.METADATA), "*", "*", "?", "/", false);
List<Metacard> metacards = new ArrayList<>();
String id = UUID.randomUUID().toString();
MetacardImpl newCard = new MetacardImpl();
newCard.setId(id);
newCard.setAttribute("myKey", "myValue1");
metacards.add(newCard);
Map<String, Serializable> reqProps = new HashMap<>();
HashSet<String> destinations = new HashSet<>();
destinations.add("mockMemoryProvider");
destinations.add("catalogStoreId-1");
framework.create(new CreateRequestImpl(metacards, reqProps, destinations));
MetacardImpl updateCard = new MetacardImpl();
updateCard.setId(id);
updateCard.setAttribute("myKey", "myValue2");
List<Entry<Serializable, Metacard>> updates = new ArrayList<>();
updates.add(new SimpleEntry<>(id, updateCard));
destinations.remove("mockMemoryProvider");
framework.update(new UpdateRequestImpl(updates, Metacard.ID, new HashMap<>(), destinations));
assertThat(provider.hasReceivedUpdateByIdentifier(), is(false));
assertThat(store.hasReceivedUpdateByIdentifier(), is(true));
QueryResponse storeResponse = framework.query(new QueryRequestImpl(new QueryImpl(filter), destinations));
assertThat(storeResponse.getResults().size(), is(1));
assertThat(storeResponse.getResults().get(0).getMetacard().getAttribute("myKey").getValue(), equalTo("myValue2"));
destinations.clear();
QueryResponse providerResponse = framework.query(new QueryRequestImpl(new QueryImpl(filter), destinations));
assertThat(providerResponse.getResults().size(), is(1));
assertThat(providerResponse.getResults().get(0).getMetacard().getAttribute("myKey").getValue(), equalTo("myValue1"));
}
use of org.opengis.filter.FilterFactory in project ddf by codice.
the class CatalogFrameworkImplTest method testDeleteWithStores.
// TODO (DDF-2436) -
@Ignore
@Test
public void testDeleteWithStores() throws Exception {
MockEventProcessor eventAdmin = new MockEventProcessor();
MockMemoryProvider provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(), true, new Date());
List<CatalogStore> storeList = new ArrayList<>();
List<FederatedSource> sourceList = new ArrayList<>();
MockCatalogStore store = new MockCatalogStore("catalogStoreId-1", true);
storeList.add(store);
sourceList.add(store);
CatalogFramework framework = createDummyCatalogFramework(provider, storeList, sourceList, eventAdmin);
FilterFactory filterFactory = new FilterFactoryImpl();
Filter filter = filterFactory.like(filterFactory.property(Metacard.METADATA), "*", "*", "?", "/", false);
List<Metacard> metacards = new ArrayList<>();
String id = UUID.randomUUID().toString().replaceAll("-", "");
MetacardImpl newCard = new MetacardImpl();
newCard.setId(id);
newCard.setAttribute("myKey", "myValue1");
metacards.add(newCard);
Map<String, Serializable> reqProps = new HashMap<>();
HashSet<String> destinations = new HashSet<>();
destinations.add("mockMemoryProvider");
destinations.add("catalogStoreId-1");
framework.create(new CreateRequestImpl(metacards, reqProps, destinations));
DeleteRequest deleteRequest = new DeleteRequestImpl(Collections.singletonList(id), Metacard.ID, new HashMap<>(), destinations);
DeleteResponse response = framework.delete(deleteRequest);
assertThat(response.getDeletedMetacards().size(), is(1));
QueryResponse queryResponse = framework.query(new QueryRequestImpl(new QueryImpl(filter), true));
assertThat(queryResponse.getResults().size(), is(0));
}
use of org.opengis.filter.FilterFactory in project ddf by codice.
the class OpenSearchQueryTest method testOgcFilterEvaluateContextualLike.
@Test
@Ignore
public void testOgcFilterEvaluateContextualLike() throws Exception {
// String input = "abc_cat_dog_xyz";
String input = "<ns1:thing xmlns:ns1=\"http://ddf.codice.org/mynamespace\">cat</ns1:thing>";
// String searchTerm = "cat";
// List<Filter> filters = new ArrayList<Filter>();
FilterFactory filterFactory = new FilterFactoryImpl();
// Filter filter = filterFactory.like( filterFactory.property( "AnyText" ), searchTerm );
// Filter filter = filterFactory.equal( filterFactory.property( "thing" ),
// filterFactory.literal( searchTerm ), false );
// Filter filter = filterFactory.like( filterFactory.property( Query.ANY_TEXT ), searchTerm,
// "*", "?", "\\" );
// Filter filter = filterFactory.equal( filterFactory.property( Query.ANY_TEXT ),
// searchTerm, false );
// Filter filter = filterFactory.like( filterFactory.property( Query.ANY_TEXT ), searchTerm,
// "*", "?", "\\" );
Calendar.getInstance().getTime();
String startDate = "2011-10-8T05:48:27.891-07:00";
String endDate = "2011-10-10T06:18:27.581-07:00";
TemporalFilter temporalFilter = new TemporalFilter(startDate, endDate);
// WORKS Filter filter = filterFactory.between( filterFactory.literal( new Date() ),
// filterFactory.literal( temporalFilter.getStartDate() ), filterFactory.literal(
// temporalFilter.getEndDate() ) );
Filter filter = filterFactory.between(filterFactory.literal(new Date()), filterFactory.literal(temporalFilter.getStartDate()), filterFactory.literal(temporalFilter.getEndDate()));
FilterTransformer transform = new FilterTransformer();
transform.setIndentation(2);
LOGGER.debug(transform.transform(filter));
boolean result = filter.evaluate(input);
LOGGER.debug("result = {}", result);
// filters.add( filter );
}
use of org.opengis.filter.FilterFactory in project ddf by codice.
the class QueryImplTest method setUp.
/**
* Create the filter2 one time to use for all of the tests
*/
@BeforeClass
public static void setUp() {
FilterFactory filterFactory = new FilterFactoryImpl();
// Dummy filter copied from another test
filter1 = filterFactory.like(filterFactory.property(Metacard.METADATA), "million", DEFAULT_TEST_WILDCARD, DEFAULT_TEST_SINGLE_WILDCARD, "^", false);
filter2 = filterFactory.like(filterFactory.property(Metacard.METADATA), "zillion", DEFAULT_TEST_WILDCARD, DEFAULT_TEST_SINGLE_WILDCARD, "^", false);
}
Aggregations