Search in sources :

Example 36 with JSONParser

use of org.json.simple.parser.JSONParser in project spatial-portal by AtlasOfLivingAustralia.

the class ScatterplotComposer method onFinish.

@Override
public boolean onFinish() {
    LOGGER.debug("Area: " + getSelectedArea());
    LOGGER.debug("Species: " + getSelectedSpecies());
    Query lsid = getSelectedSpecies();
    if (lsid == null) {
        getMapComposer().showMessage("There was a problem selecting the species.  Try to select the species again", this);
        return false;
    }
    lsid = lsid.newFacet(new Facet("occurrence_status_s", "absent", false), false);
    String name = getSelectedSpeciesName();
    String sbenvsel = getSelectedLayersWithDisplayNames();
    String[] layers = sbenvsel.split(":");
    if (layers.length > 2 || layers.length < 2) {
        getMapComposer().showMessage(sbenvsel.split(":").length + " layers selected.  Please select 2 environmental layers in step 4.");
        return false;
    }
    String[] layerNames = new String[2];
    String[] layerValues = new String[2];
    for (int i = 0; i < layers.length; i++) {
        String[] split = layers[i].split("\\|");
        layerValues[i] = split[0];
        layerNames[i] = split[1];
    }
    String pid = "";
    Query backgroundLsid = getSelectedSpeciesBk();
    if (backgroundLsid != null)
        backgroundLsid = backgroundLsid.newFacet(new Facet("occurrence_status_s", "absent", false), false);
    if (bgSearchSpeciesACComp.hasValidAnnotatedItemSelected()) {
        backgroundLsid = bgSearchSpeciesACComp.getQuery((Map) getMapComposer().getSession().getAttribute(StringConstants.USERPOINTS), false, getGeospatialKosher());
    }
    SelectedArea filterSa = getSelectedArea();
    if (filterSa == null) {
        LOGGER.error("scatterplot area is null");
        return false;
    }
    SelectedArea highlightSa = getSelectedAreaHighlight();
    boolean envGrid = chkShowEnvIntersection.isChecked();
    Query lsidQuery = QueryUtil.queryFromSelectedArea(lsid, filterSa, false, getGeospatialKosher());
    Query backgroundLsidQuery = null;
    if (backgroundLsid != null) {
        backgroundLsidQuery = QueryUtil.queryFromSelectedArea(backgroundLsid, filterSa, false, getGeospatialKosherBk());
    }
    ScatterplotDataDTO d = new ScatterplotDataDTO(lsidQuery, name, layerValues[0], layerNames[0], layerValues[1], layerNames[1], pid, null, true, highlightSa);
    try {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(CommonData.getSatServer() + "/ws/scatterplot/new");
        //add data parameters
        String layerunits = "";
        try {
            String envUnits1 = ((JSONObject) CommonData.getLayer(layerValues[0]).get("layer")).get("environmentalvalueunits").toString();
            String envUnits2 = ((JSONObject) CommonData.getLayer(layerValues[1]).get("layer")).get("environmentalvalueunits").toString();
            layerunits = envUnits1 + "," + envUnits2;
        } catch (Exception e) {
        }
        //colon delimited
        post.addParameter("layers", layerValues[0] + ":" + layerValues[1]);
        //CSV format
        post.addParameter("layernames", "\"" + layerNames[0].replace("\"", "\"\"").replace("\\", "\\\\") + "\",\"" + layerNames[1].replace("\"", "\"\"").replace("\\", "\\\\") + "\"");
        post.addParameter("layerunits", layerunits);
        post.addParameter("foregroundOccurrencesQs", lsidQuery.getQ());
        post.addParameter("foregroundOccurrencesBs", lsidQuery.getBS());
        post.addParameter("foregroundName", lsidQuery.getName());
        if (backgroundLsidQuery != null) {
            post.addParameter("backgroundOccurrencesQs", backgroundLsidQuery.getQ());
            post.addParameter("backgroundOccurrencesBs", backgroundLsidQuery.getBS());
            post.addParameter("backgroundName", backgroundLsidQuery.getName());
        }
        if (envGrid) {
            post.addParameter("gridDivisions", "20");
        }
        post.addParameter("filterWkt", filterSa.getWkt());
        //add style parameters (highlight area)
        if (highlightSa != null) {
            post.addParameter(StringConstants.HIGHLIGHT_WKT, highlightSa.getWkt());
        }
        post.addRequestHeader(StringConstants.ACCEPT, StringConstants.APPLICATION_JSON);
        client.executeMethod(post);
        String str = post.getResponseBodyAsString();
        JSONParser jp = new JSONParser();
        JSONObject jsonObject = (JSONObject) jp.parse(str);
        if (jsonObject != null && jsonObject.containsKey(StringConstants.ID)) {
            d.setId(jsonObject.get(StringConstants.ID).toString());
            d.setMissingCount(Integer.parseInt(jsonObject.get("missingCount").toString()));
        } else {
            LOGGER.error("error parsing scatterplot id from: " + str);
        }
    } catch (Exception e) {
        LOGGER.error("error getting a new scatterplot id", e);
    }
    getMapComposer().loadScatterplot(d, tToolName.getValue());
    this.detach();
    try {
        String extras = "";
        if (lsidQuery instanceof BiocacheQuery) {
            BiocacheQuery bq = (BiocacheQuery) lsidQuery;
            extras = bq.getWS() + "|" + bq.getBS() + "|" + bq.getFullQ(false) + "|" + extras;
            remoteLogger.logMapAnalysis(tToolName.getValue(), StringConstants.TOOL_SCATTERPLOT, filterSa.getWkt(), bq.getLsids(), layerValues[0] + ":" + layerValues[1], pid, extras, StringConstants.SUCCESSFUL);
        } else if (lsidQuery instanceof UserDataQuery) {
            remoteLogger.logMapAnalysis(tToolName.getValue(), StringConstants.TOOL_SCATTERPLOT, filterSa.getWkt(), lsidQuery.getQ(), "", pid, extras, StringConstants.SUCCESSFUL);
        } else {
            remoteLogger.logMapAnalysis(tToolName.getValue(), StringConstants.TOOL_SCATTERPLOT, filterSa.getWkt(), "", "", pid, extras, StringConstants.SUCCESSFUL);
        }
    } catch (Exception e) {
        LOGGER.error("logging error", e);
    }
    return true;
}
Also used : ScatterplotDataDTO(au.org.ala.spatial.dto.ScatterplotDataDTO) PostMethod(org.apache.commons.httpclient.methods.PostMethod) SelectedArea(au.org.emii.portal.menu.SelectedArea) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.commons.httpclient.HttpClient) JSONParser(org.json.simple.parser.JSONParser) Map(java.util.Map) Facet(au.org.ala.legend.Facet)

Example 37 with JSONParser

use of org.json.simple.parser.JSONParser 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 38 with JSONParser

use of org.json.simple.parser.JSONParser in project spatial-portal by AtlasOfLivingAustralia.

the class PhylogeneticDiversityComposer method fillPDTreeList.

private void fillPDTreeList() {
    JSONArray ja = null;
    String url = CommonData.getSettings().getProperty(CommonData.PHYLOLIST_URL) + "/phylo/getExpertTrees";
    JSONParser jp = new JSONParser();
    try {
        ja = (JSONArray) jp.parse(Util.readUrl(url));
    } catch (ParseException e) {
        LOGGER.error("failed to parse getExpertTrees");
    }
    if (ja == null || ja.size() == 0) {
        Events.echoEvent("onClose", this, null);
        getMapComposer().showMessage("Phylogenetic diversity tool is currently unavailable.");
        return;
    }
    trees = new Object[ja.size()];
    header = new ArrayList<String>();
    //restrict header to what is in the zul
    for (Component c : getFellow(StringConstants.TREES_HEADER).getChildren()) {
        header.add(c.getId().substring(3));
    }
    int row = 0;
    for (int i = 0; i < ja.size(); i++) {
        JSONObject j = (JSONObject) ja.get(i);
        Map<String, String> pdrow = new HashMap<String, String>();
        for (Object o : j.keySet()) {
            String key = (String) o;
            if (j.containsKey(key) && j.get(key) != null) {
                pdrow.put(key, j.get(key).toString());
            } else {
                pdrow.put(key, null);
            }
        }
        trees[row] = pdrow;
        row++;
    }
    treesList.setModel(new ListModelArray(trees, false));
    treesList.setItemRenderer(new ListitemRenderer() {

        public void render(Listitem li, Object data, int itemIdx) {
            Map<String, String> map = (Map<String, String>) data;
            for (int i = 0; i < header.size(); i++) {
                String value = map.get(header.get(i));
                if (value == null) {
                    value = "";
                }
                if ("treeViewUrl".equalsIgnoreCase(header.get(i))) {
                    Html img = new Html("<i class='icon-info-sign'></i>");
                    img.setAttribute("link", value.isEmpty() ? CommonData.getSettings().getProperty(CommonData.PHYLOLIST_URL) : value);
                    Listcell lc = new Listcell();
                    lc.setParent(li);
                    img.setParent(lc);
                    img.addEventListener(StringConstants.ONCLICK, new EventListener() {

                        @Override
                        public void onEvent(Event event) throws Exception {
                            //re-toggle the checked flag
                            Listitem li = (Listitem) event.getTarget().getParent().getParent();
                            li.getListbox().toggleItemSelection(li);
                            String metadata = (String) event.getTarget().getAttribute("link");
                            getMapComposer().activateLink(metadata, "Metadata", false);
                        }
                    });
                } else {
                    Listcell lc = new Listcell(value);
                    lc.setParent(li);
                }
            }
        }
    });
    treesList.setMultiple(true);
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject) Event(org.zkoss.zk.ui.event.Event) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) EventListener(org.zkoss.zk.ui.event.EventListener) Component(org.zkoss.zk.ui.Component) HashMap(java.util.HashMap) Map(java.util.Map)

Example 39 with JSONParser

use of org.json.simple.parser.JSONParser in project spatial-portal by AtlasOfLivingAustralia.

the class ContextualLayerListComposer method addToMap.

private void addToMap(Map htCat1, Map htCat2, String cat1, String cat2, DefaultTreeNode treeNode) {
    String nCat1 = cat1;
    if (cat1.trim().isEmpty() || "?".equals(cat1.trim()) || StringConstants.NULL.equals(cat1.trim())) {
        nCat1 = "Other";
    }
    if (cat2.trim().isEmpty() || "?".equals(cat2.trim()) || StringConstants.NULL.equals(cat2.trim())) {
        List alCat1 = (List) htCat1.get(cat1);
        if (alCat1 == null) {
            alCat1 = new ArrayList();
        }
        alCat1.add(treeNode);
        htCat1.put(nCat1, alCat1);
    } else {
        // first check if cat1 already exists
        // if yes, grab the cat2 list and add add to its AL
        // else, create a new one and add it to cat1.list
        String cat2Full = nCat1 + ">" + cat2;
        List alCat2 = (List) htCat2.get(cat2Full);
        if (alCat2 == null) {
            alCat2 = new ArrayList();
        }
        alCat2.add(treeNode);
        if (!htCat2.containsKey(cat2Full)) {
            htCat2.put(cat2Full, alCat2);
        }
        List alCat1 = (List) htCat1.get(cat1);
        if (alCat1 == null) {
            alCat1 = new ArrayList();
        }
        String subtype = ((JSONObject) ((JSONObject) treeNode.getData()).get("layer")).get(StringConstants.TYPE).toString();
        JSONParser jp = new JSONParser();
        JSONObject joCat2 = null;
        try {
            joCat2 = (JSONObject) jp.parse("{\"name\":\"" + cat2Full + "\",\"layer\":{\"type\":\"node\"},\"subtype\":" + ((StringConstants.ENVIRONMENTAL.equalsIgnoreCase(subtype)) ? LayerUtilitiesImpl.GRID : LayerUtilitiesImpl.CONTEXTUAL) + "}");
        } catch (ParseException e) {
            LOGGER.error("parse error");
        }
        DefaultTreeNode stnCat2 = new DefaultTreeNode(joCat2, alCat2);
        boolean found = false;
        for (int i = 0; i < alCat1.size(); i++) {
            if (stnCat2.toString().equals(alCat1.get(i).toString())) {
                found = true;
                ((DefaultTreeNode) alCat1.get(i)).add(treeNode);
                break;
            }
        }
        if (!found) {
            alCat1.add(stnCat2);
        }
        if (!htCat1.containsKey(nCat1)) {
            htCat1.put(nCat1, alCat1);
        }
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 40 with JSONParser

use of org.json.simple.parser.JSONParser in project spatial-portal by AtlasOfLivingAustralia.

the class LayerLegendGeneralComposer method setupForClassificationLayers.

private void setupForClassificationLayers() {
    if (mapLayer.isPolygonLayer())
        return;
    String activeLayerName = StringConstants.NONE;
    JSONObject field = null;
    JSONObject layer = null;
    if (mapLayer != null && mapLayer.getUri() != null) {
        if (mapLayer.getBaseUri() != null) {
            activeLayerName = mapLayer.getBaseUri().replaceAll("^.*&style=", "").replaceAll("&.*", "").replaceAll("_style", "");
        } else {
            activeLayerName = mapLayer.getUri().replaceAll("^.*&style=", "").replaceAll("&.*", "").replaceAll("_style", "");
        }
        field = CommonData.getLayer(activeLayerName);
        if (field == null)
            return;
        layer = (JSONObject) field.get("layer");
    }
    LOGGER.debug("ACTIVE LAYER: " + activeLayerName);
    if (mapLayer != null && mapLayer.getSubType() == LayerUtilitiesImpl.ALOC) {
        divClassificationPicker.setVisible(true);
        //reset content
        Integer groupCount = mapLayer.getClassificationGroupCount();
        if (groupCount == null) {
            mapLayer.setClassificationGroupCount(getClassificationGroupCount(mapLayer.getName().replace("aloc_", "")));
            groupCount = 0;
        }
        for (int i = cbClassificationGroup.getItemCount() - 1; i >= 0; i--) {
            cbClassificationGroup.removeItemAt(i);
        }
        Comboitem ci = new Comboitem(StringConstants.NONE);
        ci.setParent(cbClassificationGroup);
        for (int i = 1; i <= groupCount; i++) {
            new Comboitem("Group " + i).setParent(cbClassificationGroup);
        }
        //is there a current selection?
        Integer groupSelection = mapLayer.getClassificationSelection();
        if (groupSelection == null) {
            groupSelection = 0;
            mapLayer.setClassificationSelection(groupSelection);
        }
        cbClassificationGroup.setSelectedIndex(groupSelection);
        getFellow("btnCreateArea").setVisible(false);
        cbClassificationGroup.setVisible(true);
        lbClassificationGroup.setVisible(false);
        hboxClassificationGroup.setVisible(false);
    } else if (layer != null && layer.containsKey("type") && layer.get("type").toString().equalsIgnoreCase("contextual")) {
        divClassificationPicker.setVisible(true);
        if (mapLayer.getClassificationGroupCount() == null || mapLayer.getClassificationGroupCount() == 0) {
            //build
            String fieldId = field.get(StringConstants.ID).toString();
            JSONParser jp = new JSONParser();
            JSONObject objJson = null;
            try {
                objJson = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/field/" + fieldId));
            } catch (ParseException e) {
                LOGGER.error("failed to parse for: " + fieldId);
            }
            JSONArray objects = (JSONArray) objJson.get("objects");
            //sort
            List<JSONObject> list = objects.subList(0, objects.size());
            Collections.sort(list, new Comparator<JSONObject>() {

                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    String s1 = (o1 == null || !o1.containsKey("name")) ? "" : o1.get("name").toString();
                    String s2 = (o2 == null || !o2.containsKey("name")) ? "" : o2.get("name").toString();
                    return s1.compareTo(s2);
                }
            });
            JSONArray obj = new JSONArray();
            obj.addAll(list);
            mapLayer.setClassificationGroupCount(obj.size());
            mapLayer.setClassificationObjects(obj);
        }
        //reset content
        Integer groupCount = mapLayer.getClassificationGroupCount();
        JSONArray groupObjects = mapLayer.getClassificationObjects();
        lbClassificationGroup.setItemRenderer(new ListitemRenderer<JSONObject>() {

            @Override
            public void render(Listitem item, JSONObject data, int index) throws Exception {
                Checkbox cb = new Checkbox();
                final int idx = index;
                cb.addEventListener("onCheck", new EventListener<Event>() {

                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (mapLayer != null) {
                            lbClassificationGroup.setMultiple(true);
                            String v = ((Listcell) event.getTarget().getParent().getParent().getChildren().get(1)).getLabel();
                            if (((CheckEvent) event).isChecked()) {
                                selectedList.add(v);
                            } else {
                                selectedList.remove(v);
                            }
                            lblSelectedCount.setValue(selectedList.size() + " checked");
                            getFellow("clearSelection").setVisible(selectedList.size() > 0);
                            getFellow("createInGroup").setVisible(selectedList.size() > 0);
                            if (getFellowIfAny("createOutGroup") != null)
                                getFellow("createOutGroup").setVisible(selectedList.size() > 0);
                            highlightSelect(idx);
                        }
                    }
                });
                determineCheckboxState(cb, data.get("name").toString());
                Listcell lc;
                lc = new Listcell();
                cb.setParent(lc);
                lc.setParent(item);
                lc = new Listcell(data.get("name").toString());
                lc.setParent(item);
                lc = new Listcell();
                Image img = new Image();
                img.setTooltip("Create as an area layer");
                img.setClass("icon-plus-sign");
                img.setParent(lc);
                lc.setParent(item);
                final JSONObject j = data;
                img.addEventListener("onClick", new EventListener<Event>() {

                    @Override
                    public void onEvent(Event event) throws Exception {
                        createAreaEcho(j.get("pid").toString());
                    }
                });
                lc = new Listcell();
                img = new Image();
                img.setTooltip("Zoom to area");
                img.setClass("icon-zoom-in");
                img.setParent(lc);
                lc.setParent(item);
                img.addEventListener("onClick", new EventListener<Event>() {

                    @Override
                    public void onEvent(Event event) throws Exception {
                        List<Double> b = Util.getBoundingBox(j.get("bbox").toString());
                        BoundingBox bbox = new BoundingBox();
                        bbox.setMinLongitude(b.get(0).floatValue());
                        bbox.setMinLatitude(b.get(1).floatValue());
                        bbox.setMaxLongitude(b.get(2).floatValue());
                        bbox.setMaxLatitude(b.get(3).floatValue());
                        getMapComposer().getOpenLayersJavascript().execute(getMapComposer().getOpenLayersJavascript().zoomToBoundingBox(bbox, false));
                    }
                });
            }
        });
        lbClassificationGroup.addEventListener("onSelect", new EventListener<Event>() {

            @Override
            public void onEvent(Event event) throws Exception {
                if (mapLayer != null) {
                    highlightSelect(lbClassificationGroup.getSelectedIndex());
                }
            }
        });
        List<JSONObject> model = new ArrayList<JSONObject>();
        for (int i = 0; i < groupCount; i++) {
            model.add((JSONObject) groupObjects.get(i));
        }
        lbClassificationGroup.setModel(new SimpleListModel(model));
        //is there a current selection?
        Integer groupSelection = mapLayer.getClassificationSelection();
        if (groupSelection == null) {
            groupSelection = 0;
            mapLayer.setClassificationSelection(groupSelection);
        }
        getFellow("btnCreateArea").setVisible(true);
        getFellow("btnCreateArea").setVisible(false);
        cbClassificationGroup.setVisible(false);
        lbClassificationGroup.setVisible(true);
        hboxClassificationGroup.setVisible(true);
    } else {
        getFellow("btnCreateArea").setVisible(false);
        divClassificationPicker.setVisible(false);
    }
}
Also used : JSONArray(org.json.simple.JSONArray) Image(org.zkoss.zul.Image) ParseException(org.json.simple.parser.ParseException) JSONObject(org.json.simple.JSONObject) Checkbox(org.zkoss.zul.Checkbox) BoundingBox(au.org.emii.portal.value.BoundingBox) CheckEvent(org.zkoss.zk.ui.event.CheckEvent) Event(org.zkoss.zk.ui.event.Event) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ParseException(org.json.simple.parser.ParseException) EventListener(org.zkoss.zk.ui.event.EventListener)

Aggregations

JSONParser (org.json.simple.parser.JSONParser)200 JSONObject (org.json.simple.JSONObject)168 JSONArray (org.json.simple.JSONArray)73 ParseException (org.json.simple.parser.ParseException)49 HttpClient (org.apache.commons.httpclient.HttpClient)44 GetMethod (org.apache.commons.httpclient.methods.GetMethod)34 Test (org.junit.Test)28 HashMap (java.util.HashMap)23 Map (java.util.Map)19 IOException (java.io.IOException)18 File (java.io.File)16 Before (org.junit.Before)15 URL (java.net.URL)14 ArrayList (java.util.ArrayList)13 InputStreamReader (java.io.InputStreamReader)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)11 MapLayer (au.org.emii.portal.menu.MapLayer)9 Point (com.vividsolutions.jts.geom.Point)9 FileReader (java.io.FileReader)9 InputStream (java.io.InputStream)7