Search in sources :

Example 46 with JsonArray

use of org.json.simple.JsonArray in project ats-framework by Axway.

the class JsonText method parseInternalJson.

/**
     * Inspects the JSON content and returns all matched entities into the 
     * provided input list
     * 
     * @param jsonResults the list with matched results
     * @param pathTokens the path to match
     */
private void parseInternalJson(List<JsonText> jsonResults, List<String> pathTokens) {
    List<String> _paths = new ArrayList<>(pathTokens);
    for (String path : pathTokens) {
        Matcher m = NAME_AND_INDEX_PATTERN.matcher(path);
        if (m.find()) {
            // path is pointing to array
            if (m.groupCount() < 2) {
                throw new JsonException("'" + _paths + "' does not specify an array in the valid way 'key_name[index_number]'");
            }
            // name in the path token
            String name = m.group(1);
            // index in the path token, for example "name[3]"
            int index = getIndex(path, m);
            _paths.remove(0);
            if (index == -1) {
                // we have an array but no index is specified -> "[]"
                Object internalObject = jsonObject.get(name);
                if (internalObject instanceof JSONArray) {
                    JSONArray internalJsonArray = (JSONArray) internalObject;
                    for (int i = 0; i < internalJsonArray.size(); i++) {
                        JsonText ooo = new JsonText(internalJsonArray.get(i));
                        if (_paths.size() == 0) {
                            // this is the path end, the last path token ends with "[]"
                            jsonResults.add(ooo);
                        } else {
                            // go deeper
                            ooo.parseInternalJson(jsonResults, _paths);
                        }
                    }
                    // we have cycled deeply into an array, do not go to the next path token
                    return;
                } else {
                    throw new RuntimeException("Not implemented");
                }
            } else if (!StringUtils.isNullOrEmpty(name)) {
                // pointing to JSON object
                if (index >= 0) {
                    _paths.add(0, "[" + String.valueOf(index) + "]");
                }
                new JsonText(jsonObject.get(name)).parseInternalJson(jsonResults, _paths);
                return;
            } else {
                // directly pointing to JSON array, for example "[3]"
                if (_paths.size() == 0) {
                    // this is the path end
                    if (index >= jsonArray.size()) {
                        throw new JsonException("Cannot remove item at positin " + (index + 1) + " as there are only " + jsonArray.size() + " items present");
                    } else {
                        jsonResults.add(new JsonText(jsonArray.get(index)));
                        return;
                    }
                } else {
                    // go deeper
                    new JsonText(jsonArray.get(index)).parseInternalJson(jsonResults, _paths);
                    return;
                }
            }
        } else {
            // path is pointing to object
            if (!jsonObject.containsKey(path)) {
                throw new JsonException("'" + _paths + "' is not a valid path");
            }
            if (jsonObject.get(path) == null) {
                // the value is null
                jsonResults.add(null);
                return;
            }
            JsonText jsonText = new JsonText(jsonObject.get(path));
            _paths.remove(0);
            if (_paths.size() > 0) {
                jsonText.parseInternalJson(jsonResults, _paths);
            } else {
                jsonResults.add(jsonText);
            }
            return;
        }
    }
}
Also used : JsonException(com.axway.ats.action.exceptions.JsonException) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject)

Example 47 with JsonArray

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

the class AreaMapPolygon method onSearchPoint.

/**
     * Searches the gazetter at a given point and then maps the polygon feature
     * found at the location (for the current top contextual layer).
     *
     * @param event
     */
public void onSearchPoint(Event event) {
    String searchPoint = (String) event.getData();
    String lon = searchPoint.split(",")[0];
    String lat = searchPoint.split(",")[1];
    LOGGER.debug("*************************************");
    LOGGER.debug("CommonData.getLayerList");
    LOGGER.debug("*************************************");
    JSONArray layerlist = CommonData.getLayerListJSONArray();
    MapComposer mc = getMapComposer();
    List<MapLayer> activeLayers = getPortalSession().getActiveLayers();
    Boolean searchComplete = false;
    for (int i = 0; i < activeLayers.size(); i++) {
        MapLayer ml = activeLayers.get(i);
        String activeLayerName = StringConstants.NONE;
        if (ml.getUri() != null) {
            activeLayerName = ml.getUri().replaceAll("^.*&style=", "").replaceAll("&.*", "").replaceAll("_style", "");
        }
        LOGGER.debug("ACTIVE LAYER: " + activeLayerName);
        if (ml.isDisplayed() && ml.isContextualLayer()) {
            for (int j = 0; j < layerlist.size() && !searchComplete; j++) {
                JSONObject field = (JSONObject) layerlist.get(j);
                JSONObject layer = (JSONObject) field.get("layer");
                if (layer.get(StringConstants.TYPE) != null && layer.get(StringConstants.TYPE).toString().length() > 0 && StringConstants.CONTEXTUAL.equalsIgnoreCase(layer.get(StringConstants.TYPE).toString()) && field.get(StringConstants.ID).toString().equalsIgnoreCase(activeLayerName)) {
                    LOGGER.debug(ml.getName());
                    Map<String, String> feature = GazetteerPointSearch.pointSearch(lon, lat, activeLayerName, CommonData.getGeoServer());
                    if (feature == null || !feature.containsKey(StringConstants.PID)) {
                        continue;
                    }
                    layerName = (mc.getMapLayer(txtLayerName.getValue()) == null) ? txtLayerName.getValue() : mc.getNextAreaLayerName(txtLayerName.getValue());
                    getMapComposer().addObjectByPid(feature.get(StringConstants.PID), layerName, 1);
                    //found the object on the layer
                    btnOk.setDisabled(false);
                    btnClear.setDisabled(false);
                    mc.updateLayerControls();
                    searchComplete = true;
                    displayGeom.setValue("layer: " + feature.get(StringConstants.LAYERNAME) + "\r\n" + "area: " + feature.get(StringConstants.VALUE));
                    return;
                }
            }
        }
    }
}
Also used : MapComposer(au.org.emii.portal.composer.MapComposer) JSONObject(org.json.simple.JSONObject) MapLayer(au.org.emii.portal.menu.MapLayer) JSONArray(org.json.simple.JSONArray)

Example 48 with JsonArray

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

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

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

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