Search in sources :

Example 31 with Facet

use of au.org.ala.legend.Facet in project spatial-portal by AtlasOfLivingAustralia.

the class MapComposer method addObjectByPid.

/**
     * Adds a object as a layer to the map.
     *
     * @param pid
     * @param displayName
     * @param radiusKm for use when the pid refers to a point not a polygon
     * @return
     */
public MapLayer addObjectByPid(String pid, String displayName, double radiusKm) {
    JSONParser jp = new JSONParser();
    JSONObject obj = null;
    try {
        obj = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/object/" + pid));
    } catch (ParseException e) {
        LOGGER.error("failed to parse for object: " + pid);
    }
    //add feature to the map as a new layer
    String areaName = obj.get(StringConstants.NAME).toString();
    MapLayer mapLayer = null;
    boolean pointLayer = false;
    List<Double> dbb = null;
    try {
        dbb = Util.getBoundingBox(obj.get(StringConstants.BBOX).toString());
        //if the layer is a point create a radius
        if (dbb.get(0).floatValue() == dbb.get(2).floatValue() && dbb.get(1).floatValue() == dbb.get(3).floatValue()) {
            double radius = radiusKm * 1000.0;
            String wkt = Util.createCircleJs(dbb.get(0).floatValue(), dbb.get(1).floatValue(), radius);
            mapLayer = getMapComposer().addWKTLayer(wkt, displayName, displayName);
            pointLayer = true;
        }
    } catch (Exception e) {
    }
    if (mapLayer == null) {
        //not a point layer
        mapLayer = getMapComposer().addWMSLayer("PID:" + pid, displayName == null ? areaName : displayName, obj.get(StringConstants.WMSURL).toString(), 0.6f, null, null, LayerUtilitiesImpl.WKT, null, null);
        mapLayer.setAreaSqKm(obj.get(StringConstants.AREA_KM).toString());
    }
    if (mapLayer == null) {
        return null;
    }
    if (dbb != null) {
        mapLayer.getMapLayerMetadata().setBbox(dbb);
    }
    mapLayer.setPid(pid);
    mapLayer.setPolygonLayer(true);
    //if the layer is a point create a radius
    String fid = obj.get(StringConstants.FID).toString();
    MapLayerMetadata md = mapLayer.getMapLayerMetadata();
    try {
        md.setBbox(Util.getBoundingBox(obj.get(StringConstants.BBOX).toString()));
    } catch (Exception e) {
    }
    Facet facet = null;
    if (!pointLayer && CommonData.getLayer(fid) != null && CommonData.getFacetLayerNameDefault(fid) != null) {
        JSONObject field = CommonData.getLayer(fid);
        if (field.containsKey("indb") && StringConstants.TRUE.equalsIgnoreCase(field.get("indb").toString())) {
            String spid = field.get("spid").toString();
            md.setMoreInfo(CommonData.getLayersServer() + "/layers/view/more/" + spid);
            facet = Util.getFacetForObject(areaName, fid);
        }
    }
    if (facet != null) {
        List<Facet> facets = new ArrayList<Facet>();
        facets.add(facet);
        mapLayer.setFacets(facets);
        //do not set WKT for grids as shapefiles
        if (!((JSONObject) CommonData.getLayer(fid).get("layer")).get("path_orig").toString().contains("diva")) {
            mapLayer.setWktUrl(CommonData.getLayersServer() + "/shape/wkt/" + pid);
        }
    } else if (!pointLayer) {
        //not in biocache, so add as WKT
        mapLayer.setWKT(Util.readUrl(CommonData.getLayersServer() + "/shape/wkt/" + pid));
    }
    int colour = Util.nextColour();
    int r = (colour >> 16) & 0x000000ff;
    int g = (colour >> 8) & 0x000000ff;
    int b = (colour) & 0x000000ff;
    mapLayer.setRedVal(r);
    mapLayer.setGreenVal(g);
    mapLayer.setBlueVal(b);
    mapLayer.setDynamicStyle(true);
    getMapComposer().applyChange(mapLayer);
    getMapComposer().updateLayerControls();
    return mapLayer;
}
Also used : HasMapLayer(au.org.emii.portal.menu.HasMapLayer) MapLayer(au.org.emii.portal.menu.MapLayer) XmlArrayList(com.thoughtworks.xstream.persistence.XmlArrayList) ParseException(org.json.simple.parser.ParseException) MapLayerMetadata(au.org.emii.portal.menu.MapLayerMetadata) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Facet(au.org.ala.legend.Facet)

Example 32 with Facet

use of au.org.ala.legend.Facet in project spatial-portal by AtlasOfLivingAustralia.

the class LayerLegendScatterplotController method getFacetOut.

private Facet getFacetOut() {
    String fq = "*:*";
    String e1 = CommonData.getLayerFacetName(data.getLayer1());
    String e2 = CommonData.getLayerFacetName(data.getLayer2());
    //cannot facet when layers are not indexed
    if (!CommonData.getBiocacheLayerList().contains(e1) || !CommonData.getBiocacheLayerList().contains(e2)) {
        return null;
    }
    if (chkSelectMissingRecords.isChecked() && data.getPrevSelection() == null) {
        fq = e1 + ":[* TO *] AND " + e2 + ":[* TO *]";
    } else if (data.getPrevSelection() != null) {
        double x1 = data.getPrevSelection()[0];
        double x2 = data.getPrevSelection()[2];
        double y1 = data.getPrevSelection()[1];
        double y2 = data.getPrevSelection()[3];
        Facet f1 = new Facet(e1, y1, y2, true);
        Facet f2 = new Facet(e2, x1, x2, true);
        if (chkSelectMissingRecords.isChecked()) {
            fq = "-(" + f1.toString() + " AND " + f2.toString() + ") AND " + e1 + ":[* TO *] AND " + e2 + ":[* TO *]";
        } else {
            fq = "-(" + f1.toString() + " AND " + f2.toString() + ")";
        }
    }
    return Facet.parseFacet(fq);
}
Also used : Facet(au.org.ala.legend.Facet)

Example 33 with Facet

use of au.org.ala.legend.Facet in project spatial-portal by AtlasOfLivingAustralia.

the class LayerLegendScatterplotController method onChange$tbxChartSelection.

public void onChange$tbxChartSelection(Event event) {
    try {
        //input order is [x, y, width, height]
        // + optional bounding box coordinates [x1,y1,x2,y2]
        LOGGER.debug(event.getData());
        String[] coordsStr = ((String) event.getData()).replace("px", "").split(",");
        double[] coordsDbl = new double[coordsStr.length];
        for (int i = 0; i < coordsStr.length; i++) {
            coordsDbl[i] = Double.parseDouble(coordsStr[i]);
        }
        String params = "?minx=" + coordsDbl[0] + "&miny=" + coordsDbl[1] + "&maxx=" + coordsDbl[2] + "&maxy=" + coordsDbl[3];
        data.setImagePath(CommonData.getSatServer() + "/ws/scatterplot/" + data.getId() + params);
        ObjectMapper om = new ObjectMapper();
        JSONArray ja = om.readValue(new URL(data.getImagePath()), JSONArray.class);
        data.setPrevSelection(new double[4]);
        data.getPrevSelection()[0] = Double.parseDouble(ja.get(0).toString());
        data.getPrevSelection()[1] = Double.parseDouble(ja.get(1).toString());
        data.getPrevSelection()[2] = Double.parseDouble(ja.get(2).toString());
        data.getPrevSelection()[3] = Double.parseDouble(ja.get(3).toString());
        Facet f = getFacetIn();
        if (f != null) {
            mapLayer.setHighlight(f.toString());
        } else {
            mapLayer.setHighlight(null);
        }
        getMapComposer().applyChange(mapLayer);
        tbxChartSelection.setText("");
        tbxDomain.setValue(String.format("%s: %g - %g", data.getLayer1Name(), data.getPrevSelection()[1], data.getPrevSelection()[3]));
        tbxRange.setValue(String.format("%s: %g - %g", data.getLayer2Name(), data.getPrevSelection()[0], data.getPrevSelection()[2]));
        data.setImagePath(CommonData.getSatServer() + "/ws/scatterplot/" + data.getId() + ".png" + params);
        registerScatterPlotSelection();
        redraw();
    } catch (Exception e) {
        LOGGER.error("failed to build scatterplot legend", e);
        clearSelection();
        getMapComposer().applyChange(mapLayer);
    }
}
Also used : JSONArray(org.json.simple.JSONArray) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) URL(java.net.URL) Facet(au.org.ala.legend.Facet)

Example 34 with Facet

use of au.org.ala.legend.Facet in project spatial-portal by AtlasOfLivingAustralia.

the class LayerLegendGeneralComposer method onClick$createInGroup.

public void onClick$createInGroup(Event e) {
    StringBuilder sb = new StringBuilder();
    String layer = ((JSONObject) mapLayer.getClassificationObjects().get(0)).get("fid").toString();
    //build facet
    for (Object n : selectedList) {
        if (sb.length() > 0) {
            sb.append(" OR ");
        }
        sb.append(layer).append(":\"").append(n).append("\"");
    }
    //get pids
    String pids = "";
    String anyPid = "";
    Integer groupCount = mapLayer.getClassificationGroupCount();
    JSONArray groupObjects = mapLayer.getClassificationObjects();
    for (Object name : selectedList) {
        for (int i = 0; i < groupCount; i++) {
            if (name.equals(((JSONObject) groupObjects.get(i)).get("name"))) {
                if (!pids.isEmpty()) {
                    pids += "~";
                }
                anyPid = ((JSONObject) groupObjects.get(i)).get("pid").toString();
                pids += anyPid;
                break;
            }
        }
    }
    JSONParser jp = new JSONParser();
    JSONObject obj = null;
    Double[] bbox = new Double[4];
    boolean firstPid = true;
    Map<Integer, String> urlParts = new HashMap<Integer, String>();
    try {
        obj = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/object/" + anyPid));
        for (String p : pids.split("~")) {
            JSONObject jo = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/object/" + p));
            String bbString = jo.get(StringConstants.BBOX).toString();
            bbString = bbString.replace(StringConstants.POLYGON + "((", "").replace("))", "").replace(",", " ");
            String[] split = bbString.split(" ");
            String u = jo.get(StringConstants.WMSURL).toString();
            if (!u.contains("viewparams")) {
                //grid as contextual
                //extract colour map entries
                String s = u.split("ColorMap%3E")[1];
                int pos = 0;
                for (String c : s.split("%3CColorMapEntry")) {
                    int start = c.indexOf("quantity") + 14;
                    if (start > 14) {
                        Integer qty = Integer.parseInt(c.substring(start, c.indexOf("%", start)));
                        //do no overwrite existing quantities if this is the first or last entry
                        if (pos == 1 || pos == 2 || !urlParts.containsKey(qty))
                            urlParts.put(qty, c.replace("%3C%2F", ""));
                    }
                }
            }
            if (firstPid || Double.parseDouble(split[0]) < bbox[0])
                bbox[0] = Double.parseDouble(split[0]);
            if (firstPid || Double.parseDouble(split[1]) < bbox[1])
                bbox[1] = Double.parseDouble(split[1]);
            if (firstPid || Double.parseDouble(split[4]) > bbox[2])
                bbox[2] = Double.parseDouble(split[4]);
            if (firstPid || Double.parseDouble(split[5]) > bbox[3])
                bbox[3] = Double.parseDouble(split[5]);
            firstPid = false;
        }
    } catch (ParseException er) {
        LOGGER.error("failed to parse for object: " + anyPid);
    }
    String bboxString = "POLYGON((" + bbox[0] + " " + bbox[1] + "," + bbox[0] + " " + bbox[3] + "," + bbox[2] + " " + bbox[3] + "," + bbox[2] + " " + bbox[1] + "," + bbox[0] + " " + bbox[1] + "))";
    String url = obj.get(StringConstants.WMSURL).toString();
    if (!url.contains("s:" + anyPid)) {
        //grid as contextual layer
        String[] split = url.split("ColorMap%3E");
        String colours = "";
        List<Integer> sorted = new ArrayList<Integer>(urlParts.keySet());
        Collections.sort(sorted);
        for (int i = 0; i < sorted.size(); i++) {
            colours += "%3CColorMapEntry" + urlParts.get(sorted.get(i));
        }
        colours += "%3C%2F";
        url = split[0] + "ColorMap%3E" + colours + "ColorMap%3E" + split[2];
    } else {
        url = url.replace("s:" + anyPid, "s:" + pids);
    }
    String name = selectedList.size() + " areas: " + mapLayer.getDisplayName();
    MapLayer ml = getMapComposer().addWMSLayer(getMapComposer().getNextAreaLayerName(name), name, url, 0.6f, /*metadata url*/
    null, null, LayerUtilitiesImpl.WKT, null, null);
    String lname = ml.getName();
    //add colour!
    int colour = Util.nextColour();
    int r = (colour >> 16) & 0x000000ff;
    int g = (colour >> 8) & 0x000000ff;
    int b = (colour) & 0x000000ff;
    ml.setRedVal(r);
    ml.setGreenVal(g);
    ml.setBlueVal(b);
    ml.setDynamicStyle(true);
    ml.setPolygonLayer(true);
    Facet facet = Facet.parseFacet(sb.toString());
    //only get field data if it is an intersected layer (to exclude layers containing points)
    JSONObject field = CommonData.getLayer((String) obj.get(StringConstants.FID));
    List<Facet> facets = new ArrayList<Facet>();
    facets.add(facet);
    ml.setFacets(facets);
    ml.setWKT(bboxString);
    MapLayerMetadata md = ml.getMapLayerMetadata();
    md.setBbox(Arrays.asList(bbox));
    try {
        md.setMoreInfo(CommonData.getLayersServer() + "/layers/view/more/" + field.get("spid").toString());
    } catch (Exception er) {
        LOGGER.error("error setting map layer moreInfo: " + (field != null ? field.toString() : "layerObj is null"), er);
    }
    getMapComposer().applyChange(ml);
    getMapComposer().updateLayerControls();
    getMapComposer().reloadMapLayerNowAndIndexes(ml);
}
Also used : MapLayer(au.org.emii.portal.menu.MapLayer) JSONArray(org.json.simple.JSONArray) ParseException(org.json.simple.parser.ParseException) MapLayerMetadata(au.org.emii.portal.menu.MapLayerMetadata) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) LegendObject(au.org.ala.legend.LegendObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Facet(au.org.ala.legend.Facet)

Example 35 with Facet

use of au.org.ala.legend.Facet in project spatial-portal by AtlasOfLivingAustralia.

the class PointGenerationComposer method onFinish.

@Override
public boolean onFinish() {
    SelectedArea sa = getSelectedArea();
    double[][] bbox = null;
    if (sa.getMapLayer() != null && sa.getMapLayer().getMapLayerMetadata() != null) {
        List<Double> bb = sa.getMapLayer().getMapLayerMetadata().getBbox();
        bbox = new double[2][2];
        bbox[0][0] = bb.get(0);
        bbox[0][1] = bb.get(1);
        bbox[1][0] = bb.get(2);
        bbox[1][1] = bb.get(3);
    } else {
        List<Double> bb = Util.getBoundingBox(sa.getWkt());
        bbox = new double[][] { { bb.get(0), bb.get(1) }, { bb.get(2), bb.get(3) } };
    }
    //with bounding box, cut points
    try {
        String wkt = (sa.getMapLayer() != null ? sa.getMapLayer().getWKT() : sa.getWkt());
        StringBuilder sb = new StringBuilder();
        sb.append("longitude,latitude");
        int count = 0;
        int width = (int) Math.ceil((bbox[1][0] - bbox[0][0]) / resolution.getValue());
        int height = (int) Math.ceil((bbox[1][1] - bbox[0][1]) / resolution.getValue());
        double startx = Math.floor(bbox[0][0] / resolution.getValue()) * resolution.getValue();
        double starty = Math.floor(bbox[0][1] / resolution.getValue()) * resolution.getValue();
        if (wkt == null) {
            if (sa.getFacets() != null) {
                double[][] points = new double[(width + 1) * (height + 1)][2];
                int pos = 0;
                for (int i = 0; i <= width; i++) {
                    for (int j = 0; j <= height; j++) {
                        double lng = startx + i * resolution.getValue();
                        double lat = starty + j * resolution.getValue();
                        points[pos][0] = lng;
                        points[pos][1] = lat;
                        pos = pos + 1;
                    }
                }
                List<String> fields = new ArrayList<String>();
                for (Facet f : sa.getFacets()) {
                    fields.add(f.getFields()[0]);
                }
                List<String[]> result = Sampling.sampling(fields, points);
                for (int i = 0; i < result.size(); i++) {
                    Facet f = sa.getFacets().get(i);
                    String[] intersection = result.get(i);
                    for (int j = 0; j < intersection.length; j++) {
                        if (f.isValid("\"" + intersection[j] + "\"")) {
                            sb.append("\n");
                            sb.append(points[j][0]).append(",").append(points[j][1]);
                            count++;
                        }
                    }
                }
            } else {
                LOGGER.error("invalid area selected for point generation");
                getMapComposer().showMessage("Unsupported area selected for point generation. Choose a different area.");
                return false;
            }
        } else {
            //write temporary shapefile
            File tmp = File.createTempFile("tmp", ".shp");
            ShapefileUtils.saveShapefile(tmp, wkt, "tmp");
            FileDataStore store = FileDataStoreFinder.getDataStore(tmp);
            FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
            FeatureCollection featureCollection = featureSource.getFeatures();
            GeometryFactory gf = new GeometryFactory();
            List<Geometry> geometry = new ArrayList<Geometry>();
            FeatureIterator it = featureCollection.features();
            while (it.hasNext()) {
                SimpleFeature feature = (SimpleFeature) it.next();
                geometry.add((Geometry) feature.getDefaultGeometry());
            }
            try {
                it.close();
            } catch (Exception e) {
            }
            for (int i = 0; i <= width; i++) {
                for (int j = 0; j <= height; j++) {
                    double lng = startx + i * resolution.getValue();
                    double lat = starty + j * resolution.getValue();
                    Coordinate c = new Coordinate(lng, lat);
                    Geometry point = gf.createPoint(c);
                    for (Geometry geom : geometry) {
                        if (geom.contains(point)) {
                            sb.append("\n");
                            sb.append(lng).append(",").append(lat);
                            count++;
                        }
                    }
                }
            }
            //close tmp file
            try {
                store.dispose();
            } catch (Exception e) {
            }
            //delete tmp files
            try {
                FileUtils.deleteQuietly(tmp);
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".shx")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".fix")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".dbf")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".prj")));
            } catch (Exception e) {
            }
        }
        if (count <= 0) {
            getMapComposer().showMessage("No points generated. Try again with a smaller resolution or larger area.");
        } else if (count > Integer.parseInt(CommonData.getSettings().getProperty("max_record_count_upload"))) {
            getMapComposer().showMessage(count + " points generated. Maximum is " + CommonData.getSettings().getProperty("generated_points_max") + ".\n" + "Try again with a larger resolution or smaller area.");
        } else {
            String name = tToolName.getValue();
            try {
                UploadSpeciesController.loadUserPoints(new UserDataDTO(name), new StringReader(sb.toString()), true, name, "points in " + getSelectedAreaDisplayName() + " on " + resolution.getValue() + " degree resolution grid.", getMapComposer(), null);
                detach();
                return true;
            } catch (Exception e) {
                LOGGER.error("failed to upload points");
            }
        }
    } catch (Exception e) {
    }
    return false;
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) SelectedArea(au.org.emii.portal.menu.SelectedArea) ArrayList(java.util.ArrayList) FeatureIterator(org.geotools.feature.FeatureIterator) StringReader(java.io.StringReader) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) FileDataStore(org.geotools.data.FileDataStore) Facet(au.org.ala.legend.Facet) FeatureSource(org.geotools.data.FeatureSource) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(com.vividsolutions.jts.geom.Geometry) FeatureCollection(org.geotools.feature.FeatureCollection) Coordinate(com.vividsolutions.jts.geom.Coordinate) File(java.io.File)

Aggregations

Facet (au.org.ala.legend.Facet)35 MapLayer (au.org.emii.portal.menu.MapLayer)12 SelectedArea (au.org.emii.portal.menu.SelectedArea)12 JSONObject (org.json.simple.JSONObject)8 ArrayList (java.util.ArrayList)7 JSONParser (org.json.simple.parser.JSONParser)6 ParseException (org.json.simple.parser.ParseException)6 Query (au.org.ala.spatial.util.Query)5 LegendObject (au.org.ala.legend.LegendObject)3 MapLayerMetadata (au.org.emii.portal.menu.MapLayerMetadata)3 Geometry (com.vividsolutions.jts.geom.Geometry)3 IOException (java.io.IOException)3 StringReader (java.io.StringReader)3 HttpClient (org.apache.commons.httpclient.HttpClient)3 PostMethod (org.apache.commons.httpclient.methods.PostMethod)3 JSONArray (org.json.simple.JSONArray)3 CSVReader (au.com.bytecode.opencsv.CSVReader)2 ScatterplotDataDTO (au.org.ala.spatial.dto.ScatterplotDataDTO)2 BiocacheQuery (au.org.ala.spatial.util.BiocacheQuery)2 XmlArrayList (com.thoughtworks.xstream.persistence.XmlArrayList)2