Example usage for org.json.simple JSONArray get

List of usage examples for org.json.simple JSONArray get

Introduction

In this page you can find the example usage for org.json.simple JSONArray get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:eu.hansolo.accs.RestClient.java

private void updateLocations() {
    locationList.clear();//ww  w .  ja va2s.  com
    JSONArray locationsArray = getAllLocations();
    for (int i = 0; i < locationsArray.size(); i++) {
        JSONObject jsonLocation = (JSONObject) locationsArray.get(i);
        locationList.add(new Location(jsonLocation));
    }
}

From source file:geo.controller.GeoCodeServlet.java

private String convertCoordinates(double x, double y) {
    try {/*from w w w.  j a  v  a2s . c  o m*/
        URL oneMapCoordConvert = new URL(
                "http://www.onemap.sg/arcgis/rest/services/Utilities/Geometry/GeometryServer/project?"
                        + "f=json" + "&outSR=4326" + "&inSR=3414"
                        + "&geometries={\"geometryType\":\"esriGeometryPoint\",\"geometries\":[{\"x\":\"" + x
                        + "\",\"y\":\"" + y + "\",\"spatialReference\":{\"wkid\":\"3414\"}}]}");

        URLConnection yc = oneMapCoordConvert.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String json = reader.readLine();

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray jsonArray = (JSONArray) jsonObject.get("geometries");
        jsonObject = (JSONObject) jsonArray.get(0);

        return jsonObject.get("x").toString() + "," + jsonObject.get("y");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "";
}

From source file:net.bashtech.geobot.JSONUtil.java

public static String steam(String userID, String retValues) {
    String api_key = BotManager.getInstance().SteamAPIKey;

    try {/* w w  w.  j a va  2s  .c om*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager
                .getRemoteContent("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids="
                        + userID + "&key=" + api_key));

        JSONObject jsonObject = (JSONObject) obj;

        JSONObject response = (JSONObject) (jsonObject.get("response"));
        JSONArray players = (JSONArray) response.get("players");

        if (players.size() > 0) {
            JSONObject index0 = (JSONObject) players.get(0);
            String profileurl = (String) index0.get("profileurl");
            String gameextrainfo = (String) index0.get("gameextrainfo");
            String gameserverip = (String) index0.get("gameserverip");
            String gameid = (String) index0.get("gameid");

            if (retValues.equals("profile"))
                return JSONUtil.shortenUrlTinyURL(profileurl);
            else if (retValues.equals("game"))
                return (gameextrainfo != null ? gameextrainfo : "(unavailable)");
            else if (retValues.equals("server"))
                return (gameserverip != null ? gameserverip : "(unavailable)");
            else if (retValues.equals("store"))
                return (gameid != null ? "http://store.steampowered.com/app/" + gameid : "(unavailable)");
            else
                return "Profile: " + JSONUtil.shortenUrlTinyURL(profileurl)
                        + (gameextrainfo != null ? ", Game: " + gameextrainfo : "")
                        + (gameserverip != null ? ", Server: " + gameserverip : "");

        } else {
            return "Error querying API";
        }
    } catch (Exception ex) {
        System.out.println("Failed to query Steam API");
        return "Error querying API";
    }
}

From source file:com.wasteofplastic.acidisland.Update.java

/**
 * Query the API to find the latest approved file's details.
 * /*from w  w w. ja  v a2  s  . co  m*/
 * @return true if successful
 */
public boolean query() {
    URL url = null;

    try {
        // Create the URL to query using the project's ID
        url = new URL(API_HOST + API_QUERY + projectID);
    } catch (MalformedURLException e) {
        // There was an error creating the URL

        e.printStackTrace();
        return false;
    }

    try {
        // Open a connection and query the project
        URLConnection conn = url.openConnection();

        if (apiKey != null) {
            // Add the API key to the request if present
            conn.addRequestProperty("X-API-Key", apiKey);
        }

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ASkyBlockAcidIsland Update Checker");

        // Read the response of the query
        // The response will be in a JSON format, so only reading one line
        // is necessary.
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();

        // Parse the array of files from the query's response
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            // Get the version's title
            versionName = (String) latest.get(API_NAME_VALUE);

            // Get the version's link
            versionLink = (String) latest.get(API_LINK_VALUE);

            // Get the version's release type
            versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);

            // Get the version's file name
            versionFileName = (String) latest.get(API_FILE_NAME_VALUE);

            // Get the version's game version
            versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);

            return true;
        } else {
            System.out.println("There are no files for this project");
            return false;
        }
    } catch (IOException e) {
        // There was an error reading the query

        e.printStackTrace();
        return false;
    }
}

From source file:net.bashtech.geobot.JSONUtil.java

public static String BOIItemInfo(String searchTerm) {
    String modified = searchTerm.toLowerCase().replace(" a ", "").replace(" ", "").replace("/", "")
            .replace("'", "").replace("the", "").replace("&lt;", "<").replace("1", "one").replace("2", "two")
            .replace("3", "three").replace("20", "twenty").replace("-", "").replace(".", "").replace("!", "")
            .replace("=", "").replace("equals", "");
    int found = -1;
    try {/*w  w w.  j  ava 2s  . c  o m*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager.getRemoteContent("http://coebot.tv/boiitemsarray.json"));
        JSONArray topArray = (JSONArray) obj;
        for (int i = 0; i < topArray.size(); i++) {
            JSONObject tempobj = (JSONObject) topArray.get(i);
            String orig = (String) tempobj.get("title");
            if (modified
                    .equalsIgnoreCase(orig.toLowerCase().replace(" a ", "").replace(" ", "").replace("/", "")
                            .replace("'", "").replace("the", "").replace("&lt;", "<").replace("1", "one")
                            .replace("2", "two").replace("3", "three").replace("20", "twenty").replace("-", "")
                            .replace(".", "").replace("!", "").replace("=", "").replace("equals", ""))) {
                found = i;
                break;
            }
        }
        if (found > -1) {
            JSONObject item = (JSONObject) topArray.get(found);
            JSONArray info = (JSONArray) item.get("info");
            String retString = "";
            for (int i = 0; i < info.size(); i++) {
                if (retString.length() + ((String) info.get(i)).length() < 245)
                    retString += info.get(i) + "; ";
                else
                    break;
            }
            retString = retString.trim();
            retString = retString.substring(0, retString.length() - 1);
            return retString;
        } else {

            return "Item Not Found";
        }

    } catch (Exception e) {
        e.printStackTrace();
        return "Error";
    }
}

From source file:com.unilever.audit.services2.SyncUp.java

@POST
@Path("Data")
@Produces("application/json")
@Consumes("text/plain")
public SyncUpReply SyncUp(String json) {

    SyncUpReply syncReply = new SyncUpReply();
    String id = null;/* w  ww  .  ja v  a  2s . c om*/
    try {
        JSONObject result = (JSONObject) new JSONParser().parse(json);
        JSONArray visitArray = (JSONArray) result.get("visit");
        id = ((JSONObject) visitArray.get(0)).get("merchandiserId").toString();
        System.out.println("--------------" + visitArray);
        /*****************save Json***********************/
        Visitsjson visitsjson = new Visitsjson();
        visitsjson.setSyncdate(new Date());
        visitsjson.setMerchandiserid(new BigInteger(id));
        visitsjson.setJson(json);
        visitsjsonFacadeREST.create(visitsjson);

        for (Iterator<JSONObject> it = visitArray.iterator(); it.hasNext();) {
            try {
                // save every visit with its results by calling one method that works in a single transaction
                JSONObject visitData = it.next();
                context.getBusinessObject(SyncUp.class).saveVisit(visitData);
                syncReply.getVisits().add(visitData.get("visitId").toString());
                syncReply.setMsg("successfully added");
            } catch (Exception e) // if any error/exception occured this will not affect the other visits
            {
                e.printStackTrace();
                syncLog.setAuditLog(0, Integer.parseInt(id), new Date(), Utils.getRootCause(e).getMessage(),
                        "syncUp");
                // log the exception
            }
        }
        if (syncReply.getVisits().size() > 0) {
            Merchandisers m = em.getReference(Merchandisers.class, new BigDecimal(id));
            m.setLast_sync_up(new Date());
            merchandisersFacadeREST.edit(new BigDecimal(id), m);
        }
    } catch (Exception ex) {
        // TODO: log this in DB
        Logger.getLogger(SyncUp.class.getName()).log(Level.SEVERE, null, ex);
        syncLog.setAuditLog(0, Integer.parseInt(id), new Date(), Utils.getRootCause(ex).getMessage(), "syncUp");
    }
    return syncReply;
}

From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java

@Test
public void writingReportShouldCreateJsonFile() throws Exception {
    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());

    Date date = new Date();

    Method method = action.getClass().getDeclaredMethod("writeReport", Date.class, String.class, Boolean.TYPE);
    method.setAccessible(true);/*from   ww w .  j av  a  2s .c o m*/

    method.invoke(action, date, "test-1234", true);

    File logFile = new File(testFolder.getRoot(), "deployment.log");
    assertTrue(logFile.exists());

    List<String> jsonContent = Files.readAllLines(logFile.toPath(), Charset.defaultCharset());
    assertEquals(1, jsonContent.size());

    JSONParser jsonParser = new JSONParser();
    JSONObject log = (JSONObject) jsonParser.parse(jsonContent.get(0));
    JSONArray deployments = (JSONArray) log.get("deployments");
    JSONObject deployment = (JSONObject) deployments.get(0);

    assertEquals(String.valueOf(date.getTime()), deployment.get("date").toString());
    assertEquals("SYSTEM", deployment.get("username").toString());
    assertEquals("true", deployment.get("status").toString());
    assertEquals("test-1234", deployment.get("pipelineId"));
}

From source file:geo.controller.GeoCodeServlet.java

private String geoCodeTransactions(String token, Transaction t) {

    try {// w  ww  .j ava  2 s .  com
        URL oneMapGeoCode = new URL("http://www.onemap.sg/API/services.svc/basicSearch?token=" + token
                + "&returnGeom=1&searchVal=" + t.postalCode);

        URLConnection yc = oneMapGeoCode.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String json = reader.readLine();

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray jsonArray = (JSONArray) jsonObject.get("SearchResults");
        jsonObject = (JSONObject) jsonArray.get(1);
        double xCoordinate = Double.parseDouble(jsonObject.get("X").toString());
        double yCoordinate = Double.parseDouble(jsonObject.get("Y").toString());

        //converts SVY21 (OneMap) to WSG84 (Google Map)
        return convertCoordinates(xCoordinate, yCoordinate);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "";
}

From source file:com.zb.app.biz.service.WeixinTest.java

public String getFakeid(String openid) {
    if (isLogin) {
        GetMethod get = new GetMethod("https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token="
                + token + "&lang=zh_CN&pagesize=10&pageidx=0&type=0");
        get.setRequestHeader("Cookie", this.cookiestr);
        get.setRequestHeader("Host", "mp.weixin.qq.com");
        get.setRequestHeader("Referer",
                "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token=" + token
                        + "&lang=zh_CN");
        get.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        try {/*from w w  w .  j av a2  s  .c  o  m*/
            int code = httpClient.executeMethod(get);
            System.out.println(code);
            if (HttpStatus.SC_OK == code) {
                System.out.println("Fake Success");
                String str = get.getResponseBodyAsString();
                System.out.println(str.length());
                // String userjson = StringUtils.substringBetween(str,
                // "<script id=\"json-friendList\" type=\"json/text\">", "</script>");
                String userjson = StringUtils.substringBetween(str, "\"contacts\":", "})");
                System.out.println(userjson);
                JSONParser parser = new JSONParser();
                try {
                    JSONArray array = (JSONArray) parser.parse(userjson);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = (JSONObject) array.get(i);
                        String fakeid = obj.get("id").toString();
                        if (compareFakeid(fakeid, openid)) {
                            return fakeid;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        login();
        return getFakeid(openid);
    }
    return null;
}

From source file:geo.controller.GeoCodeServlet.java

private String geoCodeMRT(String token, MRTStation m) {
    String json = "";

    try {// www .  j ava2s  . com
        URL oneMapGeoCode = new URL("http://www.onemap.sg/API/services.svc/basicSearch?token=" + token
                + "&returnGeom=1&searchVal=" + URLEncoder.encode((m.stationName + " MRT").trim(), "UTF-8"));

        URLConnection yc = oneMapGeoCode.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        json = reader.readLine();

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray jsonArray = (JSONArray) jsonObject.get("SearchResults");
        jsonObject = (JSONObject) jsonArray.get(1);
        double xCoordinate = Double.parseDouble(jsonObject.get("X").toString());
        double yCoordinate = Double.parseDouble(jsonObject.get("Y").toString());

        //converts SVY21 (OneMap) to WSG84 (Google Map)
        return convertCoordinates(xCoordinate, yCoordinate);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    System.out.println(json);

    return "";
}