Search in sources :

Example 41 with JSONParser

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

the class MapComposer method loadUrlParameters.

/**
     * Parsing of "q" and "fq" params
     *
     * @return
     */
private MapLayer loadUrlParameters() {
    MapLayer mapLayer = null;
    String params = null;
    try {
        String analysisLayerSelections = getCookieValue("analysis_layer_selections");
        if (analysisLayerSelections != null) {
            String[] s = URLDecoder.decode(analysisLayerSelections, StringConstants.UTF_8).split("\n");
            for (int i = 0; i < s.length; i++) {
                String[] ls = s[i].split(" // ");
                if (ls.length > 1) {
                    selectedLayers.add(new LayerSelection(ls[0], ls[1]));
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("error loading url parameters", e);
    }
    String tool = null;
    String toolParameters = null;
    try {
        params = Executions.getCurrent().getDesktop().getQueryString();
        LOGGER.debug("User params: " + params);
        List<Entry<String, String>> userParams = Util.getQueryParameters(params);
        StringBuilder sb = new StringBuilder();
        String qc = null;
        String bs = null;
        String ws = null;
        String wkt = null;
        int size = 4;
        float opacity = 0.6f;
        int colour = 0xff0000;
        String pointtype = "auto";
        String bb = null;
        Double lat = null;
        Double lon = null;
        Double radius = null;
        String colourBy = null;
        String savedsession = "";
        String s = null;
        boolean[] geospatialKosher = null;
        boolean supportDynamic = false;
        String qname = null;
        Boolean includeDistributions = true;
        for (int i = 0; i < userParams.size(); i++) {
            String key = userParams.get(i).getKey();
            String value = userParams.get(i).getValue();
            if ("wmscache".equals(key)) {
                useSpeciesWMSCache = value;
            }
            if ("tool".equals(key)) {
                tool = value;
            }
            if ("toolParameters".equals(key)) {
                toolParameters = value;
            }
            if ("species_lsid".equals(key)) {
                sb.append("lsid:").append(value);
            } else if ("q".equals(key)) {
                //relies on spitonparams (biocachequery)
                s = value;
                //remove brackets to make it work
                if (value.startsWith("(") && value.endsWith(")") && !value.contains(" ")) {
                    s = value.substring(1, value.length() - 2);
                }
            } else if ("qname".equals(key)) {
                qname = value;
            } else if ("fq".equals(key)) {
                //flag geospatialKosher filters separately
                boolean[] gk;
                if ((gk = BiocacheQuery.parseGeospatialKosher(value)) != null) {
                    geospatialKosher = gk;
                } else {
                    //use as-is
                    //spitonparams (biocachequery) splits these
                    sb.append("&").append(key).append("=").append(value);
                }
            } else if ("qc".equals(key)) {
                if (StringUtils.isNotEmpty(qc)) {
                    qc = "&qc=" + URLEncoder.encode(value, StringConstants.UTF_8);
                }
            } else if ("bs".equals(key)) {
                bs = value;
            } else if ("ws".equals(key)) {
                ws = value;
            } else if (StringConstants.WKT.equals(key)) {
                wkt = value;
            } else if ("psize".equals(key)) {
                size = Integer.parseInt(value);
            } else if ("popacity".equals(key)) {
                opacity = Float.parseFloat(value);
            } else if ("pcolour".equals(key)) {
                colour = Integer.parseInt(value, 16);
            } else if ("ptype".equals(key)) {
                pointtype = value;
            } else if (StringConstants.BBOX.equals(key)) {
                bb = value;
            } else if ("lat".equals(key)) {
                lat = Double.parseDouble(value);
            } else if ("lon".equals(key)) {
                lon = Double.parseDouble(value);
            } else if ("radius".equals(key)) {
                radius = Double.parseDouble(value);
            } else if ("ss".equals(key)) {
                savedsession = value.trim();
            } else if ("dynamic".equals(key)) {
                supportDynamic = Boolean.parseBoolean(value);
            } else if ("cm".equals(key)) {
                colourBy = value.trim();
            } else if ("includeDistributions".equals(key)) {
                try {
                    includeDistributions = Boolean.parseBoolean(value.trim());
                } catch (Exception e) {
                }
            }
        }
        if (lat != null && lon != null && radius != null) {
            //m to km
            wkt = Util.createCircleJs(lon, lat, radius * 1000);
        }
        if (StringUtils.isNotBlank(savedsession)) {
            loadUserSession(savedsession);
        } else {
            LOGGER.debug("No saved session to load");
        }
        LOGGER.debug("url query: " + sb.toString());
        if (sb.length() > 0 || (s != null && s.length() > 0)) {
            if (s != null) {
                s += sb.toString();
            } else {
                s = sb.toString();
            }
            BiocacheQuery q = new BiocacheQuery(null, wkt, s, null, true, geospatialKosher, bs, ws, supportDynamic);
            if (qc != null) {
                q.setQc(qc);
            }
            if (getMapLayerDisplayName(q.getSolrName()) == null) {
                if (bb == null) {
                    List<Double> bbox = q.getBBox();
                    String script = "map.zoomToExtent(new OpenLayers.Bounds(" + bbox.get(0) + "," + bbox.get(1) + "," + bbox.get(2) + "," + bbox.get(3) + ")" + ".transform(" + "  new OpenLayers.Projection('EPSG:4326')," + "  map.getProjectionObject()));";
                    openLayersJavascript.setAdditionalScript(script);
                }
                //mappable attributes
                int setGrid = -1;
                if (pointtype.equals(StringConstants.GRID)) {
                    setGrid = 1;
                } else if ("point".equals(pointtype)) {
                    setGrid = 0;
                }
                mapLayer = mapSpecies(q, qname != null ? qname : q.getSolrName(), StringConstants.SPECIES, q.getOccurrenceCount(), LayerUtilitiesImpl.SPECIES, null, setGrid, size, opacity, colour, colourBy, includeDistributions);
            }
        }
        mapMultiQueryLayers(geospatialKosher, bs, ws, supportDynamic);
    } catch (Exception e) {
        LOGGER.debug("Error loading url parameters: " + params, e);
    }
    //load any deep linked layers
    mapLayerFromParams();
    //load any deep linked objects
    mapObjectFromParams();
    if (tool != null) {
        //open this tool
        try {
            JSONParser jp = new JSONParser();
            Map map = new HashMap<String, Object>();
            if (toolParameters != null) {
                JSONObject jo = (JSONObject) jp.parse(toolParameters);
                for (Object key : jo.keySet()) {
                    map.put(key.toString(), jo.get(key));
                }
            }
            if ("phylogeneticdiversity".equals(tool)) {
                openModal("WEB-INF/zul/tool/PhylogeneticDiversity.zul", map, StringConstants.ADDTOOLWINDOW);
            } else if ("exportspeciesexternal".equals(tool)) {
                //assume bccvl is logged in at this stage
                openModal("WEB-INF/zul/output/ExportSpeciesExternal.zul", null, StringConstants.ADDTOOLWINDOW);
            }
        } catch (Exception e) {
            LOGGER.error("failed to open tool: " + tool, e);
        }
    }
    return mapLayer;
}
Also used : HasMapLayer(au.org.emii.portal.menu.HasMapLayer) MapLayer(au.org.emii.portal.menu.MapLayer) ParseException(org.json.simple.parser.ParseException) Entry(java.util.Map.Entry) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) LegendObject(au.org.ala.legend.LegendObject) RemoteMap(au.org.emii.portal.util.RemoteMap)

Example 42 with JSONParser

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

the class BiocacheQuery method retrieveCustomFacets.

/**
     * Retrieves a list of custom facets for the supplied query.
     *
     * @return
     */
private List<QueryField> retrieveCustomFacets() {
    List<QueryField> customFacets = new ArrayList<QueryField>();
    //custom fields can only be retrieved with specific query types
    String full = getFullQ(false);
    Matcher match = Pattern.compile("data_resource_uid:\"??dr[t][0-9]+\"??").matcher(full);
    if (!match.find()) {
        return customFacets;
    }
    //look up facets
    try {
        final String jsonUri = biocacheServer + "/upload/dynamicFacets?q=" + URLEncoder.encode(match.group(), "UTF-8");
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(jsonUri);
        get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.APPLICATION_JSON);
        client.executeMethod(get);
        String slist = get.getResponseBodyAsString();
        JSONParser jp = new JSONParser();
        JSONArray ja = (JSONArray) jp.parse(slist);
        for (Object arrayElement : ja) {
            JSONObject jsonObject = (JSONObject) arrayElement;
            String facetName = jsonObject.get(StringConstants.NAME).toString();
            String facetDisplayName = jsonObject.get("displayName").toString();
            //TODO: remove this when _RNG fields work in legend &cm= parameter
            if (!(facetDisplayName.contains("(Range)") && facetName.endsWith("_RNG"))) {
                LOGGER.debug("Adding custom index : " + arrayElement);
                customFacets.add(new QueryField(facetName, facetDisplayName, QueryField.GroupType.CUSTOM, QueryField.FieldType.STRING));
            }
        }
    } catch (Exception e) {
        LOGGER.error("error loading custom facets for: " + getFullQ(false), e);
    }
    return customFacets;
}
Also used : QueryField(au.org.ala.legend.QueryField) JSONObject(org.json.simple.JSONObject) Matcher(java.util.regex.Matcher) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) LegendObject(au.org.ala.legend.LegendObject)

Example 43 with JSONParser

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

the class BiocacheQuery method getQidDetails.

private JSONObject getQidDetails(String qidTerm) {
    HttpClient client = new HttpClient();
    String url = biocacheServer + QID_DETAILS + qidTerm.replace("qid:", "");
    GetMethod get = new GetMethod(url);
    try {
        int result = client.executeMethod(get);
        String response = get.getResponseBodyAsString();
        if (result == 200) {
            JSONParser jp = new JSONParser();
            JSONObject jo = (JSONObject) jp.parse(response);
            return jo;
        } else {
            LOGGER.debug("error with url:" + url + " getting qid details for " + qidTerm + " > response_code:" + result + " response:" + response);
        }
    } catch (Exception e) {
        LOGGER.error("error getting biocache param details from " + url, e);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JSONParser(org.json.simple.parser.JSONParser)

Example 44 with JSONParser

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

the class BiocacheQuery method getAutoComplete.

/**
     * Returns the "autocomplete" values for the query based on the supplied facet field. Extensible so that we can add autocomplete
     * based on queries in other areas.
     * <p/>
     * NC 20131126 - added to support an autocomplete of raw taxon name for a fix associated with Fungi
     *
     * @param facet The facet to autocomplete on
     * @param value The prefix for the autocomplete
     * @param limit The maximum number of values to return
     * @return
     */
public String getAutoComplete(String facet, String value, int limit) {
    HttpClient client = new HttpClient();
    StringBuilder slist = new StringBuilder();
    if (value.length() >= 3 && StringUtils.isNotBlank(facet)) {
        try {
            String url = biocacheServer + QUERY_TITLE_URL + "q=" + getQ() + getQc() + "&facets=" + facet + "&fprefix=" + URLEncoder.encode(value, StringConstants.UTF_8) + "&pageSize=0&flimit=" + limit;
            GetMethod get = new GetMethod(url);
            get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.TEXT_PLAIN);
            int result = client.executeMethod(get);
            if (result == 200) {
                //success
                String rawJSON = get.getResponseBodyAsString();
                //parse
                JSONParser jp = new JSONParser();
                JSONObject jo = (JSONObject) jp.parse(rawJSON);
                JSONArray ja = (JSONArray) jo.get("facetResults");
                for (int i = 0; i < ja.size(); i++) {
                    JSONObject o = (JSONObject) ja.get(i);
                    if (o.get("fieldName").equals(facet)) {
                        //process the values in the list
                        JSONArray values = (JSONArray) o.get("fieldResult");
                        for (int j = 0; j < values.size(); j++) {
                            JSONObject vo = (JSONObject) values.get(j);
                            if (slist.length() > 0) {
                                slist.append("\n");
                            }
                            slist.append(vo.get("label")).append("//found ").append(vo.get(StringConstants.COUNT).toString());
                        }
                    }
                }
            } else {
                LOGGER.warn("There was an issue performing the autocomplete from the biocache: " + result);
            }
        } catch (Exception e) {
            LOGGER.error("failed to get autocomplete facet=" + facet + ", value=" + value, e);
        }
    }
    return slist.toString();
}
Also used : JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser)

Example 45 with JSONParser

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

the class BiocacheQuery method getGuid.

/**
     * Performs a scientific name or common name lookup and returns the guid if it exists in the BIE
     * <p/>
     * TODO Move getGuid and getClassification to BIE Utilities...
     *
     * @param name
     * @return
     */
public static String getGuid(String name) {
    if ("true".equalsIgnoreCase(CommonData.getSettings().getProperty("new.bie"))) {
        String url = CommonData.getBieServer() + "/ws/species/lookup/bulk";
        try {
            HttpClient client = new HttpClient();
            PostMethod get = new PostMethod(url);
            get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.APPLICATION_JSON);
            get.setRequestEntity(new StringRequestEntity("{\"names\":[\"" + name.replace("\"", "\\\"") + "\"]}"));
            client.executeMethod(get);
            String body = get.getResponseBodyAsString();
            JSONParser jp = new JSONParser();
            JSONArray ja = (JSONArray) jp.parse(body);
            if (ja != null && !ja.isEmpty()) {
                JSONObject jo = (JSONObject) ja.get(0);
                if (jo != null && jo.containsKey("acceptedIdentifier") && jo.get("acceptedIdentifier") != null) {
                    return jo.get("acceptedIdentifier").toString();
                } else if (jo != null && jo.containsKey("acceptedIdentifierGuid") && jo.get("acceptedIdentifierGuid") != null) {
                    return jo.get("acceptedIdentifierGuid").toString();
                } else if (jo != null && jo.containsKey("acceptedConceptID") && jo.get("acceptedConceptID") != null) {
                    return jo.get("acceptedConceptID").toString();
                } else if (jo != null && jo.containsKey("guid") && jo.get("guid") != null) {
                    return jo.get("guid").toString();
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("error getting guid at: " + url, e);
            return null;
        }
    } else {
        String url = CommonData.getBieServer() + "/ws/guid/" + name.replaceAll(" ", "%20");
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.APPLICATION_JSON);
            client.executeMethod(get);
            String body = get.getResponseBodyAsString();
            JSONParser jp = new JSONParser();
            JSONArray ja = (JSONArray) jp.parse(body);
            if (ja != null && !ja.isEmpty()) {
                JSONObject jo = (JSONObject) ja.get(0);
                if (jo != null && jo.containsKey("acceptedIdentifier") && jo.get("acceptedIdentifier") != null) {
                    return jo.get("acceptedIdentifier").toString();
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("error getting guid at: " + url, e);
            return null;
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) JSONObject(org.json.simple.JSONObject) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) JSONArray(org.json.simple.JSONArray) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JSONParser(org.json.simple.parser.JSONParser)

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