Search in sources :

Example 51 with JsonArray

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

the class CommonData method getDataTypes.

/**
     * Extracts the biocache data types from the webservice so that they can be used to dynamically load the facets
     *
     * @return
     */
private static Map<String, QueryField.FieldType> getDataTypes() throws Exception {
    Map<String, QueryField.FieldType> map = new HashMap<String, QueryField.FieldType>();
    //get the JSON from the WS
    JSONParser jp = new JSONParser();
    JSONArray values = (JSONArray) jp.parse(Util.readUrl(CommonData.getBiocacheServer() + "/index/fields"));
    for (Object mvalues : values) {
        String name = ((JSONObject) mvalues).get(StringConstants.NAME).toString();
        String dtype = "string";
        if (((JSONObject) mvalues).containsKey("dataType"))
            dtype = ((JSONObject) mvalues).get("dataType").toString();
        if ("string".equals(dtype) || "textgen".equals(dtype)) {
            map.put(name, QueryField.FieldType.STRING);
        } else if ("int".equals(dtype) || "tint".equals(dtype) || "tdate".equals(dtype)) {
            map.put(name, QueryField.FieldType.INT);
        } else if ("double".equals(dtype) || "tdouble".equals(dtype)) {
            map.put(name, QueryField.FieldType.DOUBLE);
        } else {
            map.put(name, QueryField.FieldType.STRING);
        }
    }
    return map;
}
Also used : QueryField(au.org.ala.legend.QueryField) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject)

Example 52 with JsonArray

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

the class CommonData method initJournalmap.

private static void initJournalmap() {
    if (journalMapArticles != null && journalMapArticles.size() > 0) {
        return;
    }
    journalMapArticles = new ArrayList<JSONObject>();
    journalMapLocations = new ArrayList<JournalMapLocation>();
    try {
        String journalmapUrl = CommonData.getSettings().getProperty("journalmap.url", null);
        String journalmapKey = CommonData.getSettings().getProperty("journalmap.api_key", null);
        //try disk cache
        File jaFile = new File("/data/webportal/journalmapArticles.json");
        if (jaFile.exists()) {
            JSONParser jp = new JSONParser();
            JSONArray ja = (JSONArray) jp.parse(FileUtils.readFileToString(jaFile));
            for (int i = 0; i < ja.size(); i++) {
                journalMapArticles.add((JSONObject) ja.get(i));
            }
        } else if (journalmapKey != null && !journalmapKey.isEmpty()) {
            int page = 1;
            int maxpage = 0;
            List<String> publicationsIds = new ArrayList<String>();
            while (page == 1 || page <= maxpage) {
                HttpClient client = new HttpClient();
                String url = journalmapUrl + "api/publications.json?version=1.0&key=" + journalmapKey + "&page=" + page;
                page = page + 1;
                LOGGER.debug("journalmap url: " + url);
                GetMethod get = new GetMethod(url);
                int result = client.executeMethod(get);
                //update maxpage
                maxpage = Integer.parseInt(get.getResponseHeader("X-Pages").getValue());
                //cache
                JSONParser jp = new JSONParser();
                JSONArray jcollection = (JSONArray) jp.parse(get.getResponseBodyAsString());
                for (int i = 0; i < jcollection.size(); i++) {
                    if (((JSONObject) jcollection.get(i)).containsKey("id")) {
                        publicationsIds.add(((JSONObject) jcollection.get(i)).get("id").toString());
                        LOGGER.debug("found publication: " + ((JSONObject) jcollection.get(i)).get("id").toString() + ", article_count: " + ((JSONObject) jcollection.get(i)).get("articles_count").toString());
                    }
                }
            }
            for (String publicationsId : publicationsIds) {
                //allow for collection failure
                try {
                    page = 1;
                    maxpage = 0;
                    while (page == 1 || page <= maxpage) {
                        HttpClient client = new HttpClient();
                        String url = journalmapUrl + "api/articles.json?version=1.0&key=" + journalmapKey + "&page=" + page + "&publication_id=" + publicationsId;
                        page = page + 1;
                        LOGGER.debug("journalmap url: " + url);
                        GetMethod get = new GetMethod(url);
                        int result = client.executeMethod(get);
                        //update maxpage
                        maxpage = Integer.parseInt(get.getResponseHeader("X-Pages").getValue());
                        //cache
                        JSONParser jp = new JSONParser();
                        JSONArray jarticles = (JSONArray) jp.parse(get.getResponseBodyAsString());
                        for (int j = 0; j < jarticles.size(); j++) {
                            JSONObject o = (JSONObject) jarticles.get(j);
                            if (o.containsKey("locations")) {
                                journalMapArticles.add(o);
                            }
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("journalmap - failure to get articles from publicationsId: " + publicationsId);
                }
            }
            //save to disk cache
            FileWriter fw = new FileWriter(jaFile);
            JSONValue.writeJSONString(journalMapArticles, fw);
            fw.flush();
            fw.close();
        }
    } catch (Exception e) {
        LOGGER.error("error initialising journalmap data", e);
    }
    //construct locations list
    for (int i = 0; i < journalMapArticles.size(); i++) {
        JSONArray locations = (JSONArray) journalMapArticles.get(i).get("locations");
        for (int j = 0; j < locations.size(); j++) {
            JSONObject l = (JSONObject) locations.get(j);
            double longitude = Double.parseDouble(l.get("longitude").toString());
            double latitude = Double.parseDouble(l.get("latitude").toString());
            journalMapLocations.add(new JournalMapLocation(longitude, latitude, i));
        }
    }
}
Also used : JSONArray(org.json.simple.JSONArray) Point(com.vividsolutions.jts.geom.Point) 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 53 with JsonArray

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

the class BiocacheQuery method retrieveCustomFields.

private List<String> retrieveCustomFields() {
    List<String> customFields = new ArrayList<String>();
    //look up facets
    final String jsonUri = biocacheServer + "/upload/dynamicFacets?q=" + getFullQ(true) + "&qc=" + getQc();
    try {
        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();
            if (!facetName.endsWith("_RNG")) {
                customFields.add(facetName);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error loading custom facets for: " + jsonUri, e);
    }
    return customFields;
}
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) JSONObject(org.json.simple.JSONObject) LegendObject(au.org.ala.legend.LegendObject)

Example 54 with JsonArray

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

the class BiocacheQuery method endemicSpeciesList.

public String endemicSpeciesList() {
    if (endemicSpeciesList != null) {
        return endemicSpeciesList;
    }
    if (CommonData.getSettings().containsKey("endemic.sp.method") && CommonData.getSettings().getProperty("endemic.sp.method").equals("true")) {
        String speciesList = speciesList();
        //can get species list counts as "kosher:true" or "kosher:*" only
        Map speciesCounts;
        if (getGeospatialKosher()[1]) {
            //[1] is 'include kosher:false'
            speciesCounts = CommonData.getSpeciesListCounts(false);
        } else {
            speciesCounts = CommonData.getSpeciesListCountsKosher(false);
        }
        StringBuilder sb = new StringBuilder();
        int speciesCol = 0;
        int countCol = 11;
        try {
            CSVReader csv = new CSVReader(new StringReader(speciesList));
            String[] row;
            int currentPos = 0;
            int nextPos = speciesList.indexOf('\n', currentPos + 1);
            //header
            sb.append(speciesList.substring(currentPos, nextPos));
            //header
            csv.readNext();
            while ((row = csv.readNext()) != null) {
                //add if species is not present elsewhere
                Long c = (Long) speciesCounts.get(row[speciesCol]);
                if (c != null && c <= Long.parseLong(row[countCol])) {
                    if (nextPos > speciesList.length()) {
                        nextPos = speciesList.length();
                    }
                    sb.append(speciesList.substring(currentPos, nextPos));
                } else if (c == null) {
                    LOGGER.error("failed to find species_guid: " + row[speciesCol] + " in CommonData.getSpeciesListCounts()");
                }
                currentPos = nextPos;
                nextPos = speciesList.indexOf('\n', currentPos + 1);
            }
        } catch (Exception e) {
            LOGGER.error("failed generating endemic species list", e);
        }
        endemicSpeciesList = sb.toString();
    } else {
        forMapping = true;
        if (paramId == null)
            makeParamId();
        HttpClient client = new HttpClient();
        String url = biocacheServer + ENDEMIC_LIST + paramId + "?facets=names_and_lsid";
        LOGGER.debug(url);
        GetMethod get = new GetMethod(url);
        try {
            client.executeMethod(get);
            JSONParser jp = new JSONParser();
            JSONArray ja = (JSONArray) jp.parse(get.getResponseBodyAsString());
            //extract endemic matches from the species list
            String speciesList = speciesList();
            StringBuilder sb = new StringBuilder();
            int idx = speciesList.indexOf('\n');
            if (idx > 0) {
                sb.append(speciesList.substring(0, idx));
            }
            for (int j = 0; j < ja.size(); j++) {
                JSONObject jo = (JSONObject) ja.get(j);
                if (jo.containsKey("label")) {
                    idx = speciesList.indexOf("\n" + jo.get("label") + ",");
                    if (idx > 0) {
                        int lineEnd = speciesList.indexOf('\n', idx + 1);
                        if (lineEnd < 0)
                            lineEnd = speciesList.length();
                        sb.append(speciesList.substring(idx, lineEnd));
                    }
                }
            }
            endemicSpeciesList = sb.toString();
        } catch (Exception e) {
            LOGGER.error("error getting endemic species result", e);
        }
    }
    return endemicSpeciesList;
}
Also used : CSVReader(au.com.bytecode.opencsv.CSVReader) JSONArray(org.json.simple.JSONArray) 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 55 with JsonArray

use of org.json.simple.JsonArray in project Glowstone by GlowstoneMC.

the class StatusRequestHandler method handle.

@Override
@SuppressWarnings("unchecked")
public void handle(GlowSession session, StatusRequestMessage message) {
    // create and call the event
    GlowServer server = session.getServer();
    int online = server.getOnlinePlayers().size();
    InetAddress address = session.getAddress().getAddress();
    StatusEvent event = new StatusEvent(address, server.getMotd(), online, server.getMaxPlayers());
    event.players = new ArrayList<>(server.getOnlinePlayers());
    event.icon = server.getServerIcon();
    event.serverType = server.getServerType();
    event.clientModsAllowed = server.getAllowClientMods();
    EventFactory.callEvent(event);
    // build the json
    JSONObject json = new JSONObject();
    JSONObject version = new JSONObject();
    version.put("name", GlowServer.GAME_VERSION);
    int protocolVersion = GlowServer.PROTOCOL_VERSION;
    version.put("protocol", protocolVersion);
    json.put("version", version);
    JSONObject players = new JSONObject();
    players.put("max", event.getMaxPlayers());
    players.put("online", online);
    if (!event.players.isEmpty()) {
        event.players = event.players.subList(0, Math.min(event.players.size(), server.getPlayerSampleCount()));
        Collections.shuffle(event.players);
        JSONArray playersSample = new JSONArray();
        for (Player player : event.players) {
            JSONObject p = new JSONObject();
            p.put("name", player.getName());
            p.put("id", player.getUniqueId().toString());
            playersSample.add(p);
        }
        players.put("sample", playersSample);
    }
    json.put("players", players);
    JSONObject description = new JSONObject();
    description.put("text", event.getMotd());
    json.put("description", description);
    if (event.icon.getData() != null) {
        json.put("favicon", event.icon.getData());
    }
    // Mod list must be included but can be empty
    // TODO: support adding GS-ported Forge server-side mods?
    JSONArray modList = new JSONArray();
    JSONObject modinfo = new JSONObject();
    modinfo.put("type", event.serverType);
    modinfo.put("modList", modList);
    if (!event.clientModsAllowed) {
        modinfo.put("clientModsAllowed", false);
    }
    json.put("modinfo", modinfo);
    // send it off
    session.send(new StatusResponseMessage(json));
}
Also used : Player(org.bukkit.entity.Player) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) StatusResponseMessage(net.glowstone.net.message.status.StatusResponseMessage) GlowServer(net.glowstone.GlowServer) InetAddress(java.net.InetAddress)

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