Search in sources :

Example 36 with JsonArray

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

the class ImportAnalysisController method afterCompose.

@Override
public void afterCompose() {
    super.afterCompose();
    try {
        JSONObject jo = remoteLogger.getLogCSV();
        if (jo != null && jo.containsKey("abe") && !((JSONArray) jo.get("abe")).isEmpty()) {
            List<String[]> logEntries = new ArrayList<String[]>();
            for (Object o : (JSONArray) jo.get("abe")) {
                JSONObject j = (JSONObject) o;
                String[] r = new String[5];
                r[0] = j.containsKey(StringConstants.ID) ? j.get(StringConstants.ID).toString() : "";
                r[1] = j.containsKey("category2") ? j.get("category2").toString() : "";
                r[2] = j.containsKey("time") ? new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date(Long.parseLong(j.get("time").toString()))) : "";
                r[3] = "";
                r[4] = j.containsKey("service") && ((JSONObject) j.get("service")).containsKey("processid") ? ((JSONObject) j.get("service")).get("processid").toString() : "";
                if (r[4].length() > 0 && !"-1".equals(r[4]) && (StringConstants.CLASSIFICATION.equalsIgnoreCase(r[1]) || StringConstants.GDM.equalsIgnoreCase(r[1]) || StringConstants.PREDICTION.equalsIgnoreCase(r[1]) || StringConstants.SPECIES_TO_GRID.equalsIgnoreCase(r[1]))) {
                    try {
                        r[3] = StringConstants.TRUE;
                        refNum.setValue(r[4]);
                        pid = r[4];
                        if (!getJobStatus().contains(StringConstants.JOB_DOES_NOT_EXIST)) {
                            //not sure why, but sometimes data is missing even when the job exists
                            if (hasValidMetadata(r)) {
                                logEntries.add(r);
                            }
                        } else {
                            // older jobs don't exist, stop checking
                            break;
                        }
                    } catch (Exception e) {
                        r[4] = "unavailable";
                        r[3] = StringConstants.FALSE;
                    }
                }
            }
            if (!logEntries.isEmpty()) {
                divPriorAnalysis.setVisible(true);
                lbLog.setModel(new SimpleListModel(logEntries));
                setRenderer();
            }
        }
    } catch (Exception e) {
        LOGGER.error("getting log did not work", e);
    }
    refNum.setValue("");
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) ArrayList(java.util.ArrayList) JSONObject(org.json.simple.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 37 with JsonArray

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

the class TabulationComposer method afterCompose.

@Override
public void afterCompose() {
    super.afterCompose();
    this.selectedMethod = StringConstants.TABULATION;
    this.totalSteps = 1;
    this.updateWindowTitle();
    cbTabLayers1.setFocus(true);
    tabLayers = new HashMap<FieldDTO, List<FieldDTO>>();
    tabLayerDisplayNames = new HashMap<String, List<String>>();
    try {
        int i;
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(CommonData.getLayersServer() + "/tabulations.json");
        get.addRequestHeader(StringConstants.ACCEPT, StringConstants.APPLICATION_JSON);
        client.executeMethod(get);
        String tlayers = get.getResponseBodyAsString();
        JSONParser jp = new JSONParser();
        JSONObject joTop = (JSONObject) jp.parse(tlayers);
        JSONArray joarr = (JSONArray) joTop.get("tabulations");
        for (i = 0; i < joarr.size(); i++) {
            JSONObject jo = (JSONObject) joarr.get(i);
            FieldDTO f1 = new FieldDTO(jo.get("fid1").toString(), jo.get("name1").toString(), "");
            FieldDTO f2 = new FieldDTO(jo.get("fid2").toString(), jo.get("name2").toString(), "");
            load(f1, f2);
            load(f2, f1);
        }
        Set keySet = (Set) tabLayerDisplayNames.keySet();
        List keyList = new ArrayList(keySet);
        Collections.sort(keyList);
        LOGGER.debug("keyList1=" + keyList);
        for (int j = 0; j < keyList.size(); j++) {
            String temp = (String) keyList.get(j);
            LOGGER.debug("temp=" + temp);
            Comboitem ci = new Comboitem(temp);
            ci.setValue(temp);
            ci.setParent(cbTabLayers1);
        }
        cbTabLayers1.addEventListener("onChange", new EventListener() {

            public void onEvent(Event event) throws Exception {
                onChange$cbTabLayer1(event);
            }
        });
        cbTabLayers1.setSelectedIndex(0);
        onChange$cbTabLayer1(null);
        cbTabLayers2.setSelectedIndex(0);
        cbTabType.setSelectedIndex(0);
    } catch (Exception e) {
        LOGGER.debug("Unable to call tabulation service for a list of layers", e);
    }
}
Also used : JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Event(org.zkoss.zk.ui.event.Event) JSONParser(org.json.simple.parser.JSONParser) Comboitem(org.zkoss.zul.Comboitem) EventListener(org.zkoss.zk.ui.event.EventListener) FieldDTO(au.org.ala.spatial.dto.FieldDTO)

Example 38 with JsonArray

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

the class AreaReportPDF method createLayer.

MapLayer createLayer(String layerName, float opacity) {
    String uid;
    String type = "";
    String treeName = "";
    String treePath = "";
    String legendurl = "";
    String metadata = "";
    JSONArray layerlist = CommonData.getLayerListJSONArray();
    for (int j = 0; j < layerlist.size(); j++) {
        JSONObject field = (JSONObject) layerlist.get(j);
        JSONObject layer = (JSONObject) field.get("layer");
        String name = field.get(StringConstants.ID).toString();
        if (name.equals(layerName)) {
            String fieldId = field.get(StringConstants.ID).toString();
            uid = layer.get(StringConstants.ID).toString();
            type = layer.get(StringConstants.TYPE).toString();
            treeName = StringUtils.capitalize(field.get(StringConstants.NAME).toString());
            treePath = layer.get("displaypath").toString();
            legendurl = CommonData.getGeoServer() + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=9&LAYER=" + layerName + (fieldId.length() < 10 ? "&styles=" + fieldId + "_style" : "");
            metadata = CommonData.getLayersServer() + "/layers/view/more/" + uid;
            break;
        }
    }
    return addWMSLayer(layerName, treeName, treePath, opacity, metadata, legendurl, StringConstants.ENVIRONMENTAL.equalsIgnoreCase(type) ? LayerUtilitiesImpl.GRID : LayerUtilitiesImpl.CONTEXTUAL, null, null, null);
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray)

Example 39 with JsonArray

use of org.json.simple.JsonArray in project Loja_Agencia_De_Viagens by ArtCouSan.

the class BuscaVooVendaServlet method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String busca = request.getParameter("busca");
        VendaDAO dao = new VendaDAO();
        ArrayList<Voo> voo = dao.procurarVoo(busca);
        JSONArray jsonArray = new JSONArray();
        for (Voo voos : voo) {
            JSONObject json = new JSONObject();
            json.put("id_voo", voos.getId_voo());
            json.put("data_volta", voos.getData_volta());
            json.put("data_ida", voos.getData_ida());
            json.put("origem", voos.getOrigem());
            json.put("preco", voos.getPreco());
            json.put("quantidade_passagens", voos.getQuantidade_passagens());
            json.put("destino", voos.getDestino());
            jsonArray.add(json);
        }
        try (PrintWriter out = response.getWriter()) {
            out.println(jsonArray.toJSONString());
        }
    } catch (ClassNotFoundException | SQLException e) {
    }
}
Also used : JSONObject(org.json.simple.JSONObject) SQLException(java.sql.SQLException) Voo(br.senac.tads3.pi03b.gruposete.models.Voo) JSONArray(org.json.simple.JSONArray) VendaDAO(br.senac.tads3.pi03b.gruposete.dao.VendaDAO) PrintWriter(java.io.PrintWriter)

Example 40 with JsonArray

use of org.json.simple.JsonArray 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)

Aggregations

JSONArray (org.json.simple.JSONArray)267 JSONObject (org.json.simple.JSONObject)238 JSONParser (org.json.simple.parser.JSONParser)73 Test (org.junit.Test)40 ParseException (org.json.simple.parser.ParseException)23 ArrayList (java.util.ArrayList)21 HttpClient (org.apache.commons.httpclient.HttpClient)21 IOException (java.io.IOException)17 HashMap (java.util.HashMap)17 GetMethod (org.apache.commons.httpclient.methods.GetMethod)17 Transaction (org.xel.Transaction)12 File (java.io.File)11 List (java.util.List)10 HttpResponse (org.apache.http.HttpResponse)10 BlockchainTest (org.xel.BlockchainTest)10 APICall (org.xel.http.APICall)10 Block (org.xel.Block)9 MapLayer (au.org.emii.portal.menu.MapLayer)8 Map (java.util.Map)8 FileReader (java.io.FileReader)6