Search in sources :

Example 21 with MapLayer

use of au.org.emii.portal.menu.MapLayer 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);
    }
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) MathTransform(org.opengis.referencing.operation.MathTransform) MapLayer(au.org.emii.portal.menu.MapLayer) WKTReader(com.vividsolutions.jts.io.WKTReader) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) FilterFactory(org.opengis.filter.FilterFactory) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) IOException(java.io.IOException) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Filter(org.opengis.filter.Filter) IsValidOp(com.vividsolutions.jts.operation.valid.IsValidOp) ParseException(com.vividsolutions.jts.io.ParseException) File(java.io.File)

Example 22 with MapLayer

use of au.org.emii.portal.menu.MapLayer in project spatial-portal by AtlasOfLivingAustralia.

the class EnvLayersCombobox method refresh.

public void refresh(String val) {
    //don't do autocomplete when < 1 characters
    if (val.length() < 0) {
        return;
    }
    String baseUrl = CommonData.getLayersServer() + "/fields/";
    try {
        Iterator it = getItems().iterator();
        JSONArray results;
        String lsurl = baseUrl;
        if (val.length() == 0) {
            results = CommonData.getLayerListJSONArray();
        } else {
            lsurl += "search/?q=" + URLEncoder.encode(val, StringConstants.UTF_8);
            LOGGER.debug("nsurl: " + lsurl);
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(lsurl);
            get.addRequestHeader(StringConstants.ACCEPT, StringConstants.JSON_JAVASCRIPT_ALL);
            client.executeMethod(get);
            String slist = get.getResponseBodyAsString();
            JSONParser jp = new JSONParser();
            results = (JSONArray) jp.parse(slist);
        }
        LOGGER.debug("got " + results.size() + " layers");
        Sessions.getCurrent().setAttribute("layerlist", results);
        if (!results.isEmpty()) {
            for (int i = 0; i < results.size(); i++) {
                JSONObject field = (JSONObject) results.get(i);
                JSONObject layer = (JSONObject) field.get("layer");
                if (!field.get(StringConstants.ENABLED).toString().equalsIgnoreCase("true") || !field.containsKey(StringConstants.NAME) || !layer.containsKey(StringConstants.TYPE) || !field.get(StringConstants.ADD_TO_MAP).toString().equalsIgnoreCase("true") || (!StringConstants.ENVIRONMENTAL.equalsIgnoreCase(layer.get(StringConstants.TYPE).toString()) && (includeLayers != null && !"AllLayers".equalsIgnoreCase(includeLayers) && !"MixLayers".equalsIgnoreCase(includeLayers)))) {
                    continue;
                }
                String displayName = field.get(StringConstants.NAME).toString();
                String type = layer.get(StringConstants.TYPE).toString();
                String name = field.get(StringConstants.ID).toString();
                Comboitem myci;
                if (it != null && it.hasNext()) {
                    myci = ((Comboitem) it.next());
                    myci.setLabel(displayName);
                } else {
                    it = null;
                    myci = new Comboitem(displayName);
                    myci.setParent(this);
                }
                String c2 = "";
                if (layer.containsKey(StringConstants.CLASSIFICATION2) && !StringConstants.NULL.equals(layer.get(StringConstants.CLASSIFICATION2))) {
                    c2 = layer.get(StringConstants.CLASSIFICATION2) + ": ";
                }
                String c1 = "";
                if (layer.containsKey(StringConstants.CLASSIFICATION1) && !StringConstants.NULL.equals(layer.get(StringConstants.CLASSIFICATION1))) {
                    c1 = layer.get(StringConstants.CLASSIFICATION1) + ": ";
                }
                myci.setDescription(c1 + c2 + type);
                myci.setValue(field);
            }
        }
        if (includeAnalysisLayers) {
            for (MapLayer ml : getMapComposer().getAnalysisLayers()) {
                String displayName = ml.getDisplayName();
                String type;
                String name;
                String classification1;
                String classification2;
                if (ml.getSubType() == LayerUtilitiesImpl.MAXENT) {
                    type = StringConstants.ENVIRONMENTAL;
                    classification1 = StringConstants.ANALYSIS;
                    classification2 = StringConstants.PREDICTION;
                    name = ml.getName();
                } else if (ml.getSubType() == LayerUtilitiesImpl.GDM) {
                    type = StringConstants.ENVIRONMENTAL;
                    classification1 = StringConstants.ANALYSIS;
                    classification2 = StringConstants.GDM;
                    name = ml.getName();
                } else if (ml.getSubType() == LayerUtilitiesImpl.ODENSITY) {
                    type = StringConstants.ENVIRONMENTAL;
                    classification1 = StringConstants.ANALYSIS;
                    classification2 = StringConstants.OCCURRENCE_DENSITY;
                    name = ml.getName();
                } else if (ml.getSubType() == LayerUtilitiesImpl.SRICHNESS) {
                    type = StringConstants.ENVIRONMENTAL;
                    classification1 = StringConstants.ANALYSIS;
                    classification2 = StringConstants.SPECIES_RICHNESS;
                    name = ml.getName();
                } else {
                    continue;
                }
                Comboitem myci;
                if (it != null && it.hasNext()) {
                    myci = ((Comboitem) it.next());
                    myci.setLabel(displayName);
                } else {
                    it = null;
                    myci = new Comboitem(displayName);
                    myci.setParent(this);
                }
                myci.setDescription(classification1 + ": " + classification2 + " " + type);
                myci.setDisabled(false);
                JSONObject jo = new JSONObject();
                jo.put(StringConstants.NAME, name);
                myci.setValue(jo);
            }
        }
        while (it != null && it.hasNext()) {
            it.next();
            it.remove();
        }
    } catch (Exception e) {
        LOGGER.error("Error searching for layers:", e);
    }
}
Also used : JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.commons.httpclient.HttpClient) MapLayer(au.org.emii.portal.menu.MapLayer) Iterator(java.util.Iterator) JSONArray(org.json.simple.JSONArray) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JSONParser(org.json.simple.parser.JSONParser) Comboitem(org.zkoss.zul.Comboitem)

Example 23 with MapLayer

use of au.org.emii.portal.menu.MapLayer in project spatial-portal by AtlasOfLivingAustralia.

the class EnvironmentalList method setupListEntries.

void setupListEntries() {
    listEntries = new ArrayList<ListEntryDTO>();
    JSONArray ja = CommonData.getLayerListJSONArray();
    for (int i = 0; i < ja.size(); i++) {
        JSONObject field = (JSONObject) ja.get(i);
        JSONObject layer = (JSONObject) field.get("layer");
        listEntries.add(new ListEntryDTO(field.get(StringConstants.ID).toString(), field.containsKey(StringConstants.NAME) ? field.get(StringConstants.NAME).toString() : field.get(StringConstants.ID).toString(), layer.containsKey(StringConstants.CLASSIFICATION1) ? layer.get(StringConstants.CLASSIFICATION1).toString() : "", layer.containsKey(StringConstants.CLASSIFICATION2) ? layer.get(StringConstants.CLASSIFICATION2).toString() : "", layer.containsKey(StringConstants.TYPE) ? layer.get(StringConstants.TYPE).toString() : "", layer.containsKey(StringConstants.DOMAIN) ? layer.get(StringConstants.DOMAIN).toString() : "", layer));
    }
    if (includeAnalysisLayers) {
        for (MapLayer ml : mapComposer.getAnalysisLayers()) {
            ListEntryDTO le = null;
            if (ml.getSubType() == LayerUtilitiesImpl.ALOC) {
                le = new ListEntryDTO(ml.getName(), ml.getDisplayName(), StringConstants.ANALYSIS, StringConstants.CLASSIFICATION, "Contextual", null, null);
            } else if (ml.getSubType() == LayerUtilitiesImpl.MAXENT) {
                le = new ListEntryDTO(ml.getName(), ml.getDisplayName(), StringConstants.ANALYSIS, StringConstants.PREDICTION, StringConstants.ENVIRONMENTAL, null, null);
            } else if (ml.getSubType() == LayerUtilitiesImpl.GDM) {
                le = new ListEntryDTO(ml.getName(), ml.getDisplayName(), StringConstants.ANALYSIS, StringConstants.GDM, StringConstants.ENVIRONMENTAL, null, null);
            } else if (ml.getSubType() == LayerUtilitiesImpl.ODENSITY) {
                le = new ListEntryDTO(ml.getName(), ml.getDisplayName(), StringConstants.ANALYSIS, StringConstants.OCCURRENCE_DENSITY, StringConstants.ENVIRONMENTAL, null, null);
            } else if (ml.getSubType() == LayerUtilitiesImpl.SRICHNESS) {
                le = new ListEntryDTO(ml.getName(), ml.getDisplayName(), StringConstants.ANALYSIS, StringConstants.SPECIES_RICHNESS, StringConstants.ENVIRONMENTAL, null, null);
            }
            if (le != null) {
                listEntries.add(le);
            }
        }
    }
    java.util.Collections.sort(listEntries, new Comparator<ListEntryDTO>() {

        @Override
        public int compare(ListEntryDTO e1, ListEntryDTO e2) {
            return (e1.getCatagory1() + " " + e1.getCatagory2() + " " + e1.getDisplayName()).compareTo(e2.getCatagory1() + " " + e2.getCatagory2() + " " + e2.getDisplayName());
        }
    });
}
Also used : ListEntryDTO(au.org.ala.spatial.dto.ListEntryDTO) JSONObject(org.json.simple.JSONObject) MapLayer(au.org.emii.portal.menu.MapLayer) JSONArray(org.json.simple.JSONArray)

Example 24 with MapLayer

use of au.org.emii.portal.menu.MapLayer in project spatial-portal by AtlasOfLivingAustralia.

the class SelectedLayersCombobox method init.

public void init(List<LayerSelection> layerSelections, MapComposer mc, boolean includeAnalysisLayers) {
    this.includeAnalysisLayers = includeAnalysisLayers;
    while (getItemCount() > 0) {
        removeItemAt(0);
    }
    Comboitem ci = new Comboitem("Paste a layer set");
    ci.setParent(this);
    ci = new Comboitem("Import a layer set");
    ci.setParent(this);
    for (int i = 0; i < CommonData.getAnalysisLayerSets().size(); i++) {
        ci = new Comboitem(CommonData.getAnalysisLayerSets().get(i).toString());
        ci.setValue(CommonData.getAnalysisLayerSets().get(i));
        ci.setParent(this);
    }
    for (int i = 0; i < layerSelections.size(); i++) {
        ci = new Comboitem(layerSelections.get(i).toString());
        ci.setValue(layerSelections.get(i));
        ci.setParent(this);
    }
    //add on map layers, active and inactive
    for (MapLayer ml : mc.getGridLayers()) {
        //get layer name
        String name = null;
        String url = ml.getUri();
        int p1 = url.indexOf("&style=") + 7;
        int p2 = url.indexOf("_style", p1);
        if (p1 > 4) {
            if (p2 < 0) {
                p2 = url.length();
            }
            name = url.substring(p1, p2);
        }
        if (name != null) {
            ci = new Comboitem(ml.getDisplayName());
            ci.setValue(new LayerSelection(ml.getDisplayName(), name));
            ci.setParent(this);
        }
    }
    if (includeAnalysisLayers) {
        //add on map layers, active and inactive
        for (MapLayer ml : mc.getAnalysisLayers()) {
            String name = null;
            if (ml.getSubType() == LayerUtilitiesImpl.ALOC) {
                name = ml.getPid();
            } else if (ml.getSubType() == LayerUtilitiesImpl.MAXENT) {
                name = ml.getPid();
            } else if (ml.getSubType() == LayerUtilitiesImpl.GDM) {
                name = ml.getPid();
            } else if (ml.getSubType() == LayerUtilitiesImpl.ODENSITY) {
                name = ml.getPid();
            } else if (ml.getSubType() == LayerUtilitiesImpl.SRICHNESS) {
                name = ml.getPid();
            }
            if (name != null) {
                ci = new Comboitem(ml.getDisplayName());
                ci.setValue(new LayerSelection(ml.getDisplayName(), name));
                ci.setParent(this);
            }
        }
    }
}
Also used : LayerSelection(au.org.ala.spatial.util.LayerSelection) MapLayer(au.org.emii.portal.menu.MapLayer) Comboitem(org.zkoss.zul.Comboitem)

Example 25 with MapLayer

use of au.org.emii.portal.menu.MapLayer in project spatial-portal by AtlasOfLivingAustralia.

the class AreaRegionSelection method onClick$btnOk.

public void onClick$btnOk(Event event) {
    Comboitem ci = gazetteerAuto.getSelectedItem();
    if (!validate()) {
        return;
    }
    //exit if no match found
    if (ci == null) {
        return;
    }
    JSONObject jo = ci.getValue();
    MapLayer ml = getMapComposer().addObjectByPid(jo.get(StringConstants.PID).toString(), ci.getLabel(), dRadius.getValue());
    layerName = ml.getName();
    ok = true;
    this.detach();
}
Also used : JSONObject(org.json.simple.JSONObject) MapLayer(au.org.emii.portal.menu.MapLayer)

Aggregations

MapLayer (au.org.emii.portal.menu.MapLayer)131 HasMapLayer (au.org.emii.portal.menu.HasMapLayer)34 JSONObject (org.json.simple.JSONObject)24 MapComposer (au.org.emii.portal.composer.MapComposer)20 ParseException (org.json.simple.parser.ParseException)18 IOException (java.io.IOException)16 MapLayerMetadata (au.org.emii.portal.menu.MapLayerMetadata)15 SelectedArea (au.org.emii.portal.menu.SelectedArea)14 Facet (au.org.ala.legend.Facet)12 List (java.util.List)10 XmlArrayList (com.thoughtworks.xstream.persistence.XmlArrayList)9 JSONParser (org.json.simple.parser.JSONParser)9 JSONArray (org.json.simple.JSONArray)8 URL (java.net.URL)7 ArrayList (java.util.ArrayList)7 SuspendNotAllowedException (org.zkoss.zk.ui.SuspendNotAllowedException)7 LegendObject (au.org.ala.legend.LegendObject)6 Component (org.zkoss.zk.ui.Component)6 Geometry (com.vividsolutions.jts.geom.Geometry)5 ParseException (com.vividsolutions.jts.io.ParseException)5