Search in sources :

Example 1 with Query

use of au.org.ala.spatial.util.Query in project spatial-portal by AtlasOfLivingAustralia.

the class ExportSpeciesExternalComposer method onFinish.

@Override
public boolean onFinish() {
    List<Query> list = getAllSelectedSpecies();
    List<Map> maps = new ArrayList<>();
    for (Query q : list) {
        Map m = new HashMap();
        m.put("name", q.getName());
        m.put("query", "qid:" + ((BiocacheQuery) q).getQid());
        m.put("url", q.getBS());
        maps.add(m);
    }
    Map container = new HashMap();
    container.put("data", maps);
    String json = JSONObject.toJSONString(container);
    getMapComposer().getOpenLayersJavascript().execute("postToExternal('" + CommonData.getSettings().getProperty("bccvl.post.url") + "', " + json + ");");
    login(null);
    loggingIn = false;
    return true;
}
Also used : BiocacheQuery(au.org.ala.spatial.util.BiocacheQuery) Query(au.org.ala.spatial.util.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BiocacheQuery(au.org.ala.spatial.util.BiocacheQuery) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with Query

use of au.org.ala.spatial.util.Query in project spatial-portal by AtlasOfLivingAustralia.

the class LayerLegendScatterplotController method registerScatterPlotSelection.

private void registerScatterPlotSelection() {
    try {
        if (data.getLayer1() != null && data.getLayer1().length() > 0 && data.getLayer2() != null && data.getLayer2().length() > 0) {
            Facet f = getFacetIn();
            int count = 0;
            if (f != null) {
                Query q = data.getQuery().newFacet(f, false);
                count = q.getOccurrenceCount();
            }
            updateCount(String.valueOf(count));
        }
    } catch (Exception e) {
        LOGGER.error("error updating scatterplot selection", e);
        clearSelection();
        getMapComposer().applyChange(mapLayer);
    }
}
Also used : Query(au.org.ala.spatial.util.Query) Facet(au.org.ala.legend.Facet)

Example 3 with Query

use of au.org.ala.spatial.util.Query 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 4 with Query

use of au.org.ala.spatial.util.Query 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 5 with Query

use of au.org.ala.spatial.util.Query 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)

Aggregations

Query (au.org.ala.spatial.util.Query)12 Facet (au.org.ala.legend.Facet)5 SelectedArea (au.org.emii.portal.menu.SelectedArea)5 BiocacheQuery (au.org.ala.spatial.util.BiocacheQuery)4 MapLayer (au.org.emii.portal.menu.MapLayer)4 CSVReader (au.com.bytecode.opencsv.CSVReader)3 StringReader (java.io.StringReader)3 ArrayList (java.util.ArrayList)3 JSONObject (org.json.simple.JSONObject)3 ScatterplotDataDTO (au.org.ala.spatial.dto.ScatterplotDataDTO)2 MapComposer (au.org.emii.portal.composer.MapComposer)2 HashMap (java.util.HashMap)2 JSONArray (org.json.simple.JSONArray)2 JSONParser (org.json.simple.parser.JSONParser)2 ParseException (org.json.simple.parser.ParseException)2 Event (org.zkoss.zk.ui.event.Event)2 LegendObject (au.org.ala.legend.LegendObject)1 SamplingAnalysisDownloadController (au.org.ala.spatial.composer.output.SamplingAnalysisDownloadController)1 PhylogeneticDiversityListResults (au.org.ala.spatial.composer.results.PhylogeneticDiversityListResults)1 Geometry (com.vividsolutions.jts.geom.Geometry)1