Search in sources :

Example 11 with SelectedArea

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

the class InOutComposer method getSelectedAreas.

public List<SelectedArea> getSelectedAreas() {
    List<SelectedArea> selectedAreas = new ArrayList<SelectedArea>();
    Vbox vboxArea = (Vbox) getFellowIfAny("vboxArea");
    for (Component c : vboxArea.getChildren()) {
        if ((c instanceof Checkbox) && ((Checkbox) c).isChecked()) {
            SelectedArea sa = null;
            String area = ((Checkbox) c).getValue();
            try {
                if (StringConstants.CURRENT.equals(area)) {
                    sa = new SelectedArea(null, getMapComposer().getViewArea());
                } else if (StringConstants.AUSTRALIA.equals(area)) {
                    sa = new SelectedArea(null, CommonData.getSettings().getProperty(CommonData.AUSTRALIA_WKT));
                } else if (StringConstants.WORLD.equals(area)) {
                    sa = new SelectedArea(null, CommonData.WORLD_WKT);
                } else {
                    List<MapLayer> layers = getMapComposer().getPolygonLayers();
                    for (MapLayer ml : layers) {
                        if (area.equals(ml.getName())) {
                            sa = new SelectedArea(ml, null);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("Unable to retrieve selected area", e);
            }
            if (sa != null) {
                selectedAreas.add(sa);
            }
        }
    }
    return selectedAreas;
}
Also used : Checkbox(org.zkoss.zul.Checkbox) SelectedArea(au.org.emii.portal.menu.SelectedArea) MapLayer(au.org.emii.portal.menu.MapLayer) Component(org.zkoss.zk.ui.Component) Vbox(org.zkoss.zul.Vbox) ParseException(org.json.simple.parser.ParseException)

Example 12 with SelectedArea

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

the class InOutComposer method onFinish.

@Override
public boolean onFinish() {
    Query query = getSelectedSpecies();
    query = query.newFacet(new Facet("occurrence_status_s", "absent", false), false);
    if (query == null) {
        return false;
    }
    List<SelectedArea> sa = getSelectedAreas();
    //check the number of selected areas
    int countSelected = sa.size();
    if (autoCompleteLayerSelection != null && cAreasFromLayer.isChecked() && autoCompleteLayerAreas == null) {
        countSelected += 2;
    }
    if (countSelected != 2) {
        getMapComposer().showMessage(countSelected + " areas are selected. Select only 2 areas.");
        return false;
    }
    try {
        StringBuilder results = new StringBuilder();
        double inArea = 0;
        Query in;
        Query out;
        double outArea = 0;
        String outName;
        String inName;
        Map<String, String[]> onlyIn = new HashMap<String, String[]>();
        Map<String, String[]> onlyOut = new HashMap<String, String[]>();
        Map<String, String[]> both = new HashMap<String, String[]>();
        String[] speciesListHeader = null;
        //get area of the layer
        if (autoCompleteLayerSelection != null && cAreasFromLayer.isChecked() && autoCompleteLayerAreas == null) {
            // in/out for a selected layer and the marine/terrestrial complement
            String fieldId = CommonData.getLayerFacetNameDefault(autoCompleteLayerSelection);
            JSONParser jp = new JSONParser();
            JSONObject jo = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/field/" + fieldId));
            inName = "In area (" + jo.get("name") + ")";
            JSONArray objects = (JSONArray) jo.get("objects");
            for (int i = 0; i < objects.size(); i++) {
                if (((JSONObject) objects.get(i)).containsKey("area_km")) {
                    inArea += (Double) ((JSONObject) objects.get(i)).get("area_km");
                }
            }
            in = query.newFacet(new Facet(fieldId, "*", true), false);
            //determine complement area
            JSONObject fld = CommonData.getLayer(fieldId);
            JSONObject layer = (JSONObject) fld.get("layer");
            boolean isMarine = Util.isSameDomain(new String[] { "marine" }, Util.getDomain(layer));
            boolean isTerrestrial = Util.isSameDomain(new String[] { "terrestrial" }, Util.getDomain(layer));
            String terrestrialQuery = CommonData.getSettings().getProperty("in_out_report.terrestrial.query", "cl2013:*");
            String terrestrialName = CommonData.getSettings().getProperty("in_out_report.terrestrial.name", "Other - ASGS Australian States and Territories");
            Double terrestrialArea = Double.parseDouble(CommonData.getSettings().getProperty("in_out_report.terrestrial.area", "7719806.774"));
            String marineQuery = CommonData.getSettings().getProperty("in_out_report.marine.query", "cl21:*");
            String marineName = CommonData.getSettings().getProperty("in_out_report.marine.name", "Other - IMCRA 4");
            Double marineArea = Double.parseDouble(CommonData.getSettings().getProperty("in_out_report.marine.area", "8669607.781"));
            if (isMarine && isTerrestrial) {
                outName = marineName + " AND " + terrestrialName;
                outArea = terrestrialArea + marineArea;
                out = query.newFacets(Arrays.asList(new Facet[] { new Facet(fieldId, "*", false), Facet.parseFacet("(" + terrestrialQuery + " OR " + marineQuery + ")") }), false);
            } else if (isMarine) {
                outName = marineName;
                outArea = marineArea;
                out = query.newFacets(Arrays.asList(new Facet[] { new Facet(fieldId, "*", false), Facet.parseFacet(marineQuery) }), false);
            } else if (isTerrestrial) {
                outName = terrestrialName;
                outArea = terrestrialArea;
                out = query.newFacets(Arrays.asList(new Facet[] { new Facet(fieldId, "*", false), Facet.parseFacet(terrestrialQuery) }), false);
            } else {
                //world
                outName = "rest of the world";
                outArea = 510000000.0;
                out = query.newFacet(new Facet(fieldId, "*", false), false);
            }
            outArea -= inArea;
        } else {
            inName = sa.get(0).getMapLayer().getDisplayName();
            outName = sa.get(1).getMapLayer().getDisplayName();
            in = QueryUtil.queryFromSelectedArea(query, sa.get(0), false, null);
            out = QueryUtil.queryFromSelectedArea(query, sa.get(1), false, null);
            try {
                inArea = Double.parseDouble(sa.get(0).getKm2Area().replace(",", ""));
                outArea = Double.parseDouble(sa.get(1).getKm2Area().replace(",", ""));
            } catch (Exception e) {
            }
            //build species lists for comparison
            List<String[]> inSpeciesList = new CSVReader(new StringReader(in.speciesList())).readAll();
            List<String[]> outSpeciesList = new CSVReader(new StringReader(out.speciesList())).readAll();
            //used to exclude header
            int row = 0;
            for (String[] line : inSpeciesList) {
                if (row == 0) {
                    speciesListHeader = line;
                    row++;
                } else if (line.length > 0) {
                    onlyIn.put(line[0], line);
                }
            }
            row = 0;
            for (String[] line : outSpeciesList) {
                if (row == 0) {
                    //header will be missing if no species in inArea
                    speciesListHeader = line;
                    row++;
                } else if (line.length > 0) {
                    if (!onlyIn.containsKey(line[0])) {
                        onlyOut.put(line[0], line);
                    } else {
                        onlyIn.remove(line[0]);
                        both.put(line[0], line);
                    }
                }
            }
        }
        results.append("Species,Area name,Sq km,Occurrences,Species\n");
        results.append(getSelectedSpeciesName()).append(",");
        results.append(inName).append(",").append(inArea).append(",").append(in.getOccurrenceCount()).append(",").append(in.getSpeciesCount()).append("\n");
        results.append(getSelectedSpeciesName()).append(",");
        results.append(outName).append(" (").append(outName).append("),").append(outArea).append(",").append(out.getOccurrenceCount()).append(",").append(out.getSpeciesCount()).append("\n");
        if (onlyIn.size() + onlyOut.size() + both.size() > 0) {
            results.append("\n");
            results.append("\nSpecies found only in ").append(inName).append(",").append(String.format("%d", onlyIn.size()));
            results.append("\nSpecies found only in ").append(outName).append(",").append(String.format("%d", onlyOut.size()));
            results.append("\nSpecies found in both areas,").append(String.format("%d", both.size()));
            results.append("\n\n").append(StringUtils.join(speciesListHeader, ",", 0, speciesListHeader.length - 3)).append(",").append(inName).append(",").append(outName);
            for (String[] line : both.values()) {
                results.append("\n");
                for (int i = 0; i < line.length - 3; i++) results.append("\"").append(line[i].replace("\"", "\"\",")).append("\",");
                results.append("found,found");
            }
            for (String[] line : onlyIn.values()) {
                results.append("\n");
                for (int i = 0; i < line.length - 3; i++) results.append("\"").append(line[i].replace("\"", "\"\",")).append("\",");
                results.append("found,not found");
            }
            for (String[] line : onlyOut.values()) {
                results.append("\n");
                for (int i = 0; i < line.length - 3; i++) results.append("\"").append(line[i].replace("\"", "\"\",")).append("\",");
                results.append("not found,found");
            }
        }
        //show results
        String metadata = "<html><body>" + "<div class='aooeoo'>" + "<div>Report for: " + getSelectedSpeciesName() + "<br />" + inName + "<br />" + outName + "</div><br />" + "<table >" + "<tr><td>Area name</td><td>Sq km</td><td>Occurrences</td><td>Species</td></tr>" + "<tr><td>" + inName + "</td><td>" + String.format("%.2f", inArea) + "</td><td>" + in.getOccurrenceCount() + "</td><td>" + in.getSpeciesCount() + "</td></tr>" + "<tr><td>" + outName + "</td><td>" + String.format("%.2f", outArea) + "</td><td>" + out.getOccurrenceCount() + "</td><td>" + out.getSpeciesCount() + "</td></tr>";
        if (onlyIn.size() + onlyOut.size() + both.size() > 0) {
            metadata += "<tr><td>&nbsp;</td></tr>" + "<tr><td>Species found only in " + inName + "</td><td>" + String.format("%d", onlyIn.size()) + "</td></tr>" + "<tr><td>Species found only in " + outName + "</td><td>" + String.format("%d", onlyOut.size()) + "</td></tr>" + "<tr><td>Species found in both areas</td><td>" + String.format("%d", both.size()) + "</td></tr>";
        }
        metadata += "</table></div>";
        Event ev = new Event(StringConstants.ONCLICK, null, "Compare Areas Report\n" + metadata);
        getMapComposer().openHTML(ev);
        //download metadata as text
        Filedownload.save(results.toString(), "text/plain", "Compare Areas Report.csv");
        this.detach();
        return true;
    } catch (Exception e) {
        LOGGER.error("failed In Out finish", e);
    }
    return false;
}
Also used : Query(au.org.ala.spatial.util.Query) CSVReader(au.com.bytecode.opencsv.CSVReader) SelectedArea(au.org.emii.portal.menu.SelectedArea) JSONArray(org.json.simple.JSONArray) ParseException(org.json.simple.parser.ParseException) JSONObject(org.json.simple.JSONObject) StringReader(java.io.StringReader) Event(org.zkoss.zk.ui.event.Event) JSONParser(org.json.simple.parser.JSONParser) Facet(au.org.ala.legend.Facet)

Example 13 with SelectedArea

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

the class AooEooComposer method onFinish.

@Override
public boolean onFinish() {
    SelectedArea sa = getSelectedArea();
    Query q = getSelectedSpecies();
    q = q.newFacet(new Facet("occurrence_status_s", "absent", false), false);
    Facet f = new Facet("occurrence_status_s", "absent", false);
    q = q.newFacet(f, false);
    Query newQ = QueryUtil.queryFromSelectedArea(q, sa, false, null);
    double gridSize = dResolution.doubleValue();
    // eoo, use actual points
    LegendObject legend = newQ.getLegend("lat_long");
    StringBuilder sb = new StringBuilder();
    int pointCount = processLegend(legend, sb);
    String aooWkt = aooWkt(legend, gridSize);
    // aoo = gridSize * gridSize * number of gridSize by gridSize cells with an occurrence * (approx sq degrees to sq km)
    double aoo = gridSize * gridSize * aooProcess(legend, gridSize) * 10000;
    double eoo = 0;
    WKTReader reader = new WKTReader();
    String metadata = null;
    try {
        Geometry g = reader.read(sb.toString());
        Geometry convexHull = g.convexHull();
        String wkt = convexHull.toText().replace(" (", "(").replace(", ", ",");
        eoo = SpatialUtil.calculateArea(wkt);
        //aoo area
        Geometry a = reader.read(aooWkt(legend, gridSize));
        Geometry aUnion = a.union();
        String aWkt = aUnion.toText().replace(" (", "(").replace(", ", ",");
        if (eoo > 0) {
            String name = "Extent of occurrence (area): " + q.getName();
            MapLayer ml = getMapComposer().addWKTLayer(wkt, name, name);
            name = "Area of occupancy (area): " + q.getName();
            MapLayer mla = getMapComposer().addWKTLayer(aWkt, name, name);
            metadata = "<html><body>" + "<div class='aooeoo'>" + "<div>The Sensitive Data Service may have changed the location of taxa that have a sensitive status." + " It is wise to first map the taxa and examine each record, then filter these records to create the " + "desired subset, then run the tool on the new filtered taxa layer.</div><br />" + "<table >" + "<tr><td>Number of records used for the calculations</td><td>" + newQ.getOccurrenceCount() + "</td></tr>" + "<tr><td>Species</td><td>" + q.getName() + "</td></tr>" + "<tr><td>Area of Occupancy (AOO: " + gridSize + " degree grid)</td><td>" + String.format("%.0f", aoo) + " sq km</td></tr>" + "<tr><td>Extent of Occurrence (EOO: Minimum convex hull)</td><td>" + (String.format("%.2f", eoo / 1000.0 / 1000.0)) + " sq km</td></tr></table></body></html>" + "</div>";
            ml.getMapLayerMetadata().setMoreInfo("Area of Occupancy and Extent of Occurrence\n" + metadata);
            name = "Extent of occurrence (points): " + q.getName();
            MapLayer ml2 = getMapComposer().mapSpecies(newQ, name, StringConstants.SPECIES, newQ.getOccurrenceCount(), LayerUtilitiesImpl.SPECIES, null, 0, MapComposer.DEFAULT_POINT_SIZE, MapComposer.DEFAULT_POINT_OPACITY, Util.nextColour(), false);
            ml2.getMapLayerMetadata().setMoreInfo("Area of Occupancy and Extent of Occurrence\n" + metadata);
        } else {
            //trigger eoo unavailable message
            pointCount = 2;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //show results
    String message = "The Sensitive Data Service may have changed the location of taxa that have a sensitive status. " + "It is wise to first map the taxa and examine each record, then filter these records to create the " + "desired subset, then run the tool on the new filtered taxa layer.\r\n" + "\r\nNumber of records used for the calculations: " + newQ.getOccurrenceCount() + "\r\nSpecies: " + q.getName() + "\r\nArea of Occupancy: " + String.format("%.0f", aoo) + " sq km" + "\r\nExtent of Occurrence: " + (pointCount < 3 ? "insufficient unique occurrence locations" : (String.format("%.2f", eoo / 1000.0 / 1000.0) + " sq km"));
    if (metadata != null) {
        Event ev = new Event(StringConstants.ONCLICK, null, "Area of Occupancy and Extent of Occurrence\n" + metadata);
        getMapComposer().openHTML(ev);
    } else {
        getMapComposer().showMessage(message);
    }
    //download metadata as text
    Filedownload.save(message, "text/plain", "Calculated AOO and EOO.txt");
    this.detach();
    return true;
}
Also used : Query(au.org.ala.spatial.util.Query) SelectedArea(au.org.emii.portal.menu.SelectedArea) MapLayer(au.org.emii.portal.menu.MapLayer) WKTReader(com.vividsolutions.jts.io.WKTReader) Geometry(com.vividsolutions.jts.geom.Geometry) LegendObject(au.org.ala.legend.LegendObject) Event(org.zkoss.zk.ui.event.Event) Facet(au.org.ala.legend.Facet)

Example 14 with SelectedArea

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

the class PhylogeneticDiversityComposer method onFinish.

@Override
public boolean onFinish() {
    List<SelectedArea> sa = getSelectedAreas();
    if (autoCompleteLayerSelection != null && cAreasFromLayer.isChecked()) {
        String fieldId = CommonData.getLayerFacetNameDefault(autoCompleteLayerSelection);
        String layer = CommonData.getFacetLayerName(fieldId);
        JSONObject field = CommonData.getLayer(layer);
        JSONObject lyr = (JSONObject) field.get("layer");
        String name = field.get(StringConstants.ID).toString();
        String uid = lyr.get(StringConstants.ID).toString();
        String type = lyr.get(StringConstants.TYPE).toString();
        String treeName = StringUtils.capitalize(field.get(StringConstants.NAME).toString());
        String treePath = lyr.get("displaypath").toString();
        String legendurl = CommonData.getGeoServer() + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=9&LAYER=" + name + "&styles=" + name + "_style";
        String metadata = CommonData.getLayersServer() + "/layers/view/more/" + uid;
        //is it already mapped with the same display name?
        boolean found = false;
        for (MapLayer ml : getMapComposer().getContextualLayers()) {
            if (ml.getDisplayName().equalsIgnoreCase(treeName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            getMapComposer().addWMSLayer(name, treeName, treePath, (float) 0.75, metadata, legendurl, StringConstants.ENVIRONMENTAL.equalsIgnoreCase(type) ? LayerUtilitiesImpl.GRID : LayerUtilitiesImpl.CONTEXTUAL, null, null, null);
            remoteLogger.logMapArea(treeName, "Layer - " + type, treePath, name, metadata);
        }
    }
    Map<String, Object> hm = new HashMap<String, Object>();
    hm.put("selectedareas", sa);
    List<Object> st = new ArrayList<Object>();
    StringBuilder sb = new StringBuilder();
    for (Object o : treesList.getSelectedItems()) {
        st.add(trees[((Listitem) o).getIndex()]);
        if (sb.length() > 0)
            sb.append(",");
        sb.append(((Map<String, String>) trees[((Listitem) o).getIndex()]).get(StringConstants.STUDY_ID));
    }
    hm.put("selectedtrees", st);
    Query q = getSelectedSpecies();
    if (q != null)
        q = q.newFacet(new Facet("occurrence_status_s", "absent", false), false);
    hm.put("query", q);
    PhylogeneticDiversityListResults window = (PhylogeneticDiversityListResults) Executions.createComponents("WEB-INF/zul/results/PhylogeneticDiversityResults.zul", getMapComposer(), hm);
    try {
        window.setParent(getMapComposer());
        window.doModal();
    } catch (Exception e) {
        LOGGER.error("error opening PhylogeneticDiversityResults.zul", e);
    }
    remoteLogger.logMapAnalysis("PhylogeneticDiversity", "PhylogeneticDiversity", sa.size() + " areas", getSelectedSpeciesName(), sb.toString(), "", "", "");
    detach();
    return true;
}
Also used : Query(au.org.ala.spatial.util.Query) PhylogeneticDiversityListResults(au.org.ala.spatial.composer.results.PhylogeneticDiversityListResults) HashMap(java.util.HashMap) SelectedArea(au.org.emii.portal.menu.SelectedArea) MapLayer(au.org.emii.portal.menu.MapLayer) ArrayList(java.util.ArrayList) ParseException(org.json.simple.parser.ParseException) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) Facet(au.org.ala.legend.Facet)

Example 15 with SelectedArea

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

the class GDMComposer method runGDMStep1.

public boolean runGDMStep1() {
    try {
        SelectedArea sa = getSelectedArea();
        query = QueryUtil.queryFromSelectedArea(getSelectedSpecies(), sa, false, getGeospatialKosher());
        query = query.newFacet(new Facet("occurrence_status_s", "absent", false), false);
        sbenvsel = getSelectedLayersWithDisplayNames();
        if (query.getSpeciesCount() < 2) {
            getMapComposer().showMessage("An list of species with multiple occurrences for each species is required by GDM.", this);
            return false;
        }
        HttpClient client = new HttpClient();
        PostMethod get = new PostMethod(CommonData.getSatServer() + "/ws/gdm/step1?" + "envlist=" + URLEncoder.encode(sbenvsel, StringConstants.UTF_8) + "&taxacount=" + query.getSpeciesCount() + "&speciesq=" + URLEncoder.encode(QueryUtil.queryFromSelectedArea(query, sa, false, getGeospatialKosher()).getQ(), StringConstants.UTF_8) + "&bs=" + URLEncoder.encode(query.getBS(), StringConstants.UTF_8));
        if (sa.getMapLayer() != null && sa.getMapLayer().getEnvelope() != null) {
            area = StringConstants.ENVELOPE + "(" + sa.getMapLayer().getEnvelope() + ")";
        } else {
            area = sa.getWkt();
        }
        if (getSelectedArea() != null) {
            get.addParameter(StringConstants.AREA, area);
        }
        get.addRequestHeader(StringConstants.ACCEPT, StringConstants.TEXT_PLAIN);
        LOGGER.debug("calling gdm ws step 1");
        client.executeMethod(get);
        step1Id = get.getResponseBodyAsString();
        //wait for step 1
        LOGGER.debug(step1Id);
        getFellow("runningMsg1").setVisible(true);
        statusMsg = ((Label) getFellow("runningMsg1")).getValue();
        startTime = System.currentTimeMillis();
        Events.echoEvent("step1Status", this, null);
        btnOk.setDisabled(true);
        return true;
    } catch (Exception e) {
        LOGGER.error("GDM error: ", e);
        getMapComposer().showMessage("Unknown error.", this);
    }
    return false;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) SelectedArea(au.org.emii.portal.menu.SelectedArea) HttpClient(org.apache.commons.httpclient.HttpClient) Facet(au.org.ala.legend.Facet)

Aggregations

SelectedArea (au.org.emii.portal.menu.SelectedArea)30 MapLayer (au.org.emii.portal.menu.MapLayer)14 Facet (au.org.ala.legend.Facet)12 HttpClient (org.apache.commons.httpclient.HttpClient)6 PostMethod (org.apache.commons.httpclient.methods.PostMethod)6 Query (au.org.ala.spatial.util.Query)5 JSONObject (org.json.simple.JSONObject)5 ArrayList (java.util.ArrayList)4 JSONParser (org.json.simple.parser.JSONParser)4 ParseException (org.json.simple.parser.ParseException)4 IOException (java.io.IOException)3 StringReader (java.io.StringReader)3 Event (org.zkoss.zk.ui.event.Event)3 CSVReader (au.com.bytecode.opencsv.CSVReader)2 Geometry (com.vividsolutions.jts.geom.Geometry)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 JSONArray (org.json.simple.JSONArray)2 Component (org.zkoss.zk.ui.Component)2