Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.eldslott.armory.utils.JsonUtils.java

public static String getString(JSONObject jsonObject, String name) {
    try {// w w w  .  ja  v a 2 s  .c  o m
        return String.valueOf(jsonObject.get(name));
    } catch (JSONException e) {
        Log.e(JsonUtils.class.toString(),
                "could not get from jsonObject for name '" + name + "': " + e.getMessage());
    } catch (Exception e) {
        Log.e(JsonUtils.class.toString(),
                "could not get from jsonObject for name '" + name + "': " + e.getMessage());
    }
    return null;
}

From source file:com.maya.portAuthority.googleMaps.Instructions.java

/**
 * Receives a JSONObject and returns a Direction
 * //from   w  w w  .j  av a 2s  . c o m
 * @param jsonObject
 * @return The Direction retrieved by the JSON Object
 */
public static List<Direction> parse(JSONObject jsonObject) throws Exception {
    List<Direction> directionsList = null; // returned direction
    Direction currentGDirection = null; // current direction
    List<Legs> legsList = null; // legs
    Legs currentLeg = null; // current leg
    List<Path> pathsList = null;// paths
    Path currentPath = null;// current path

    // JSON parts:
    JSONArray routes = null;
    JSONObject route = null;
    JSONObject bound = null;
    JSONArray legs = null;
    JSONObject leg = null;
    JSONArray steps = null;
    JSONObject step = null;
    String polyline = "";

    try {
        routes = jsonObject.getJSONArray("routes");
        LOGGER.info("routes found : " + routes.length());
        directionsList = new ArrayList<Direction>();
        // traverse routes
        for (int i = 0; i < routes.length(); i++) {
            route = (JSONObject) routes.get(i);
            legs = route.getJSONArray("legs");
            LOGGER.info("route[" + i + "]contains " + legs.length() + " legs");
            // traverse legs
            legsList = new ArrayList<Legs>();
            for (int j = 0; j < legs.length(); j++) {
                leg = (JSONObject) legs.get(j);
                steps = leg.getJSONArray("steps");
                LOGGER.info("route[" + i + "]:leg[" + j + "] contains " + steps.length() + " steps");
                // traverse all steps
                pathsList = new ArrayList<Path>();
                for (int k = 0; k < steps.length(); k++) {
                    step = (JSONObject) steps.get(k);
                    polyline = (String) ((JSONObject) (step).get("polyline")).get("points");
                    // Build the List of GDPoint that define the path
                    List<Point> list = decodePoly(polyline);
                    // Create the GDPath
                    currentPath = new Path(list);
                    currentPath.setDistance(((JSONObject) step.get("distance")).getInt("value"));
                    currentPath.setDuration(((JSONObject) step.get("duration")).getInt("value"));
                    currentPath.setHtmlText(step.getString("html_instructions"));
                    currentPath.setTravelMode(step.getString("travel_mode"));
                    LOGGER.info("routes[" + i + "]:legs[" + j + "]:Step[" + k + "] contains " + list.size()
                            + " points");
                    // Add it to the list of Path of the Direction
                    pathsList.add(currentPath);
                }
                //
                currentLeg = new Legs(pathsList);
                currentLeg.setDistance(((JSONObject) leg.get("distance")).getInt("value"));
                currentLeg.setmDuration(((JSONObject) leg.get("duration")).getInt("value"));
                currentLeg.setEndAddr(leg.getString("end_address"));
                currentLeg.setStartAddr(leg.getString("start_address"));
                legsList.add(currentLeg);

                LOGGER.info("Added a new Path and paths size is : " + pathsList.size());
            }
            // Build the GDirection using the paths found
            currentGDirection = new Direction(legsList);
            bound = (JSONObject) route.get("bounds");
            currentGDirection
                    .setNorthEastBound(new Location(((JSONObject) bound.get("northeast")).getDouble("lat"),
                            ((JSONObject) bound.get("northeast")).getDouble("lng")));
            currentGDirection
                    .setmSouthWestBound(new Location(((JSONObject) bound.get("southwest")).getDouble("lat"),
                            ((JSONObject) bound.get("southwest")).getDouble("lng")));
            currentGDirection.setCopyrights(route.getString("copyrights"));
            directionsList.add(currentGDirection);
        }

    } catch (JSONException e) {
        LOGGER.error("Parsing JSon from GoogleDirection Api failed, see stack trace below:", e);
        throw new Exception("Parsing JSon from GoogleDirection Api failed");
    } catch (Exception e) {
        LOGGER.error("Parsing JSon from GoogleDirection Api failed, see stack trace below:", e);
        throw new Exception("Parsing JSon from GoogleDirection Api failed");
    }
    return directionsList;
}

From source file:org.loklak.harvester.JsonFieldConverter.java

@SuppressWarnings("unchecked")
public JsonFieldConverter(JsonConversionSchemaEnum conversionSchema) throws IOException {
    final JSONObject convSchema = DAO.getConversionSchema(conversionSchema.getFilename());
    List<List<?>> convRules = (List<List<?>>) convSchema.get("rules");
    this.conversionRules = new HashMap<>();
    for (List<?> rule : convRules) {
        List<String> toInsert = new ArrayList<>();
        this.conversionRules.put((String) rule.get(0), toInsert);

        // the 2nd rule can be either a string
        if (rule.get(1) instanceof String) {
            toInsert.add((String) rule.get(1));
        } else {//  ww  w .j a  v  a2  s . co  m
            // or an array
            for (String afterField : (List<String>) rule.get(1)) {
                toInsert.add(afterField);
            }
        }
    }
}

From source file:org.loklak.harvester.JsonFieldConverter.java

private static Object getFieldValue(JSONObject object, String key) {
    if (key.contains(".")) {
        String[] deepFields = key.split(Pattern.quote("."));
        JSONObject currentLevel = object;
        for (int lvl = 0; lvl < deepFields.length; lvl++) {
            if (lvl == deepFields.length - 1) {
                return currentLevel.get(deepFields[lvl]);
            } else {
                if (currentLevel.get(deepFields[lvl]) == null) {
                    return null;
                }//from  w w  w .  j  ava  2 s  .c  om
                currentLevel = (JSONObject) currentLevel.get(deepFields[lvl]);
            }
        }
    } else {
        return object.get(key);
    }
    // unreachable code
    return null;
}

From source file:org.loklak.harvester.JsonFieldConverter.java

private static void putToField(JSONObject object, String key, Object value) {
    if (key.contains(".")) {
        String[] deepFields = key.split(Pattern.quote("."));
        JSONObject currentLevel = object;
        for (int lvl = 0; lvl < deepFields.length; lvl++) {
            if (lvl == deepFields.length - 1) {
                currentLevel.put(deepFields[lvl], value);
            } else {
                if (currentLevel.get(deepFields[lvl]) == null) {
                    currentLevel.put(deepFields[lvl], new HashMap<>());
                }/*ww  w.jav  a2  s.c om*/
                currentLevel = (JSONObject) currentLevel.get(deepFields[lvl]);
            }
        }
    } else {
        object.put(key, value);
    }
}

From source file:org.cvrgrid.waveform.backing.GlobusUploadBacking.java

/**
 * Private API that polls all the endpoints for a user.
 *//*from  w  w w .  j  ava2s.c o m*/
private Status getEndpoints(JSONTransferAPIClient client, String query, String endpointType) {

    try {

        JSONTransferAPIClient.Result r = client.getResult(query);
        Map<String, GlobusEndpointList> globusEndpointLists = this.getGlobusEndpointLists();
        GlobusEndpointList globusEndpointList = globusEndpointLists.get(endpointType);
        logger.info("Endpoint Listing " + query + " for " + client.getUsername() + ": ");
        Iterator<?> keys = r.document.keys();
        while (keys.hasNext()) {
            String next = (String) keys.next();
            if (next.equalsIgnoreCase("data_type")) {

                globusEndpointList.setDataType(r.document.getString(next));

            } else if (next.equalsIgnoreCase("length")) {

                globusEndpointList.setLength(new Integer(r.document.getString(next)));

            } else if (next.equalsIgnoreCase("limit")) {

                globusEndpointList.setLimit(r.document.getString(next));

            } else if (next.equalsIgnoreCase("offset")) {

                globusEndpointList.setOffset(r.document.getString(next));

            } else if (next.equalsIgnoreCase("total")) {

                globusEndpointList.setTotal(r.document.getString(next));

            } else if (next.equalsIgnoreCase("data")) {
                JSONArray data = r.document.getJSONArray(next);
                int size = data.length();
                ArrayList<GlobusEndpoint> globusEndpoints = new ArrayList<GlobusEndpoint>();
                for (int j = 0; j < size; j++) {
                    GlobusEndpoint globusEndpoint = new GlobusEndpoint();
                    JSONObject globusEndpointInfo = data.getJSONObject(j);
                    Iterator<?> keys2 = globusEndpointInfo.keys();
                    while (keys2.hasNext()) {
                        String next2 = (String) keys2.next();
                        if (next2.equalsIgnoreCase("data_type")) {

                            globusEndpoint.setDataType(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("username")) {

                            globusEndpoint.setUserName(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("globus_connect_setup_key")) {

                            globusEndpoint.setGlobusConnectSetupKey(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("name")) {

                            globusEndpoint.setName(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("activated")) {

                            globusEndpoint.setActivated(globusEndpointInfo.getBoolean(next2));

                        } else if (next2.equalsIgnoreCase("is_globus_connect")) {

                            globusEndpoint.setIsGlobusConnect(globusEndpointInfo.getBoolean(next2));

                        } else if (next2.equalsIgnoreCase("ls_link")) {

                            JSONObject linkInfo = globusEndpointInfo.getJSONObject(next2);
                            GlobusLink lsLink = new GlobusLink();
                            Iterator<?> keys3 = linkInfo.keys();
                            while (keys3.hasNext()) {

                                String next3 = (String) keys3.next();
                                if (next3.equalsIgnoreCase("data_type")) {

                                    lsLink.setDataType(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("href")) {

                                    lsLink.setHref(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("resource")) {

                                    lsLink.setResource(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("relationship")) {

                                    lsLink.setRelationship(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("title")) {

                                    lsLink.setTitle(linkInfo.getString(next3));

                                }

                            }
                            globusEndpoint.setLsLink(lsLink);

                        } else if (next2.equalsIgnoreCase("canonical_name")) {

                            globusEndpoint.setCanonicalName(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("myproxy_server")) {

                            globusEndpoint.setMyProxyServer(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("expire_time")) {

                            //globusEndpoint.setExpireTime(new Date(globusEndpointInfo.getString(next2)));

                        } else if (next2.equalsIgnoreCase("public")) {

                            globusEndpoint.setGlobusPublic(globusEndpointInfo.getBoolean(next2));

                        } else if (next2.equalsIgnoreCase("description")) {

                            globusEndpoint.setDescription(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("data")) {

                            JSONArray serverData = globusEndpointInfo.getJSONArray(next2);
                            int serverDataSize = serverData.length();
                            ArrayList<GlobusServer> globusServers = new ArrayList<GlobusServer>();
                            for (int k = 0; k < serverDataSize; k++) {
                                GlobusServer globusServer = new GlobusServer();
                                JSONObject globusServerInfo = serverData.getJSONObject(k);
                                Iterator<?> keys4 = globusServerInfo.keys();
                                while (keys4.hasNext()) {
                                    String next4 = (String) keys4.next();
                                    if (next4.equalsIgnoreCase("data_type")) {

                                        globusServer.setDataType(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("id")) {

                                        globusServer.setId(globusServerInfo.getInt(next4));

                                    } else if (next4.equalsIgnoreCase("hostname")) {

                                        globusServer.setHostname(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("uri")) {

                                        globusServer.setUri(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("scheme")) {

                                        globusServer.setScheme(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("port")) {

                                        if (globusServerInfo.get("port").toString().equalsIgnoreCase("null")) {

                                            globusServer.setPort(0);

                                        } else {

                                            globusServer.setPort(globusServerInfo.getInt(next4));

                                        }

                                    } else if (next4.equalsIgnoreCase("subject")) {

                                        globusServer.setSubject(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("is_connected")) {

                                        globusServer.setIsConnected(globusServerInfo.getBoolean(next4));

                                    }

                                }
                                globusServers.add(globusServer);
                            }
                            globusEndpoint.setGlobusServers(globusServers);
                        }

                    }
                    globusEndpoints.add(globusEndpoint);
                }
                globusEndpointList.setGlobusEndpoints(globusEndpoints);
            }

        }

        globusEndpointLists.put(endpointType, globusEndpointList);
        this.setGlobusEndpointLists(globusEndpointLists);
        return Status.OK;

    } catch (Exception e) {

        logger.error("Got an exception..\n");
        logger.error(e.getMessage());
        logger.error(e.getStackTrace().toString());
        e.printStackTrace();
        return Status.FAIL;

    }

}

From source file:org.araqne.confdb.file.Importer.java

private Map<String, Object> parse(JSONObject jsonObject) throws IOException {
    Map<String, Object> m = new HashMap<String, Object>();
    String[] names = JSONObject.getNames(jsonObject);
    if (names == null)
        return m;

    for (String key : names) {
        try {/* w w  w. jav a2s .  c  om*/
            Object value = jsonObject.get(key);
            if (value == JSONObject.NULL)
                value = null;
            else if (value instanceof JSONArray)
                value = parse((JSONArray) value);
            else if (value instanceof JSONObject)
                value = parse((JSONObject) value);

            m.put(key, value);
        } catch (JSONException e) {
            logger.error("araqne confdb: cannot parse json", e);
            throw new IOException(e);
        }
    }

    return m;
}

From source file:com.ecofactor.qa.automation.newapp.ThermostatControlEETest.java

/**
 * Sets the point reason api./*w  w  w  .j  a va2s .  c  o  m*/
 * @param userName the user name
 * @param password the password
 * @param thermostatId the thermostat id
 */
@Test(groups = { Groups.SANITY1, Groups.BROWSER,
        Groups.ANDROID }, dataProvider = "defaultSavingsEnegry", dataProviderClass = CommonsDataProvider.class, priority = 8)
public void setPointReasonAPI(final String userName, final String password, Integer thermostatId) {

    loadPage(userName, password, true);
    thPageOps.openTstatController();
    Assert.assertTrue(thCtrlOpsPage.isPageLoaded(), "Tstat Control Page is not Opened");
    Assert.assertTrue(thCtrlUIPage.isSavingsEnergyLinkDisplayed(), "Savings Energy Link is not displayed");

    WebDriver driver = null;
    try {
        loginPage.setLoggedIn(false);

        LogUtil.setLogString(LogSection.START, "New Browser verfication starts", true);
        driver = createWebDriver();
        loginPage.setDriver(driver);
        thPageOps.setDriver(driver);
        thPageUI.setDriver(driver);
        thCtrlUIPage.setDriver(driver);
        loadPage(userName, password, true);
        thPageOps.openTstatController();
        Assert.assertTrue(thCtrlOpsPage.isPageLoaded(), "Tstat Control Page is not Opened");
        loginPage.setDriver(null);
        thCtrlOpsPage.setDriver(driver);
        String content = thCtrlOpsPage.getEEapi(
                "https://my-apps-qa.ecofactor.com/ws/v1.0/thermostat/" + thermostatId + "/state", null, 200);
        LogUtil.setLogString("Json result :" + content, true);
        JSONObject jsonObj = new JSONObject(content);
        String setPointReason = jsonObj.get("setpoint_reason").toString();
        LogUtil.setLogString("SetPoint reason :" + setPointReason, true);
        driver.navigate().back();
        Assert.assertTrue(setPointReason.equalsIgnoreCase("ee"), "Setpoint Reason is not EE");
        thPageOps.setDriver(null);
        thCtrlOpsPage.setDriver(null);
        thCtrlUIPage.setDriver(null);
        thPageUI.setDriver(null);
        LogUtil.setLogString(LogSection.END, "New Browser verification ends", true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        loginPage.setDriver(null);
        thPageOps.setDriver(null);
        thCtrlOpsPage.setDriver(null);
        thCtrlUIPage.setDriver(null);
        thPageUI.setDriver(null);
        if (driver != null) {
            LogUtil.setLogString("Quit driver for new browser", true);
            driver.quit();
        }
    }
    WaitUtil.mediumWait();
    thCtrlOpsPage.closeThermostatControl();
    Assert.assertTrue(thPageUI.isUnderSavingsEnergy(), "Savings Energy is not displayed");
}

From source file:org.crawler.LinkExtractor.java

void processFile(File jsonFile) throws Exception {

    System.out.println("Processing JSON file " + jsonFile.getName());

    FileReader fr = new FileReader(jsonFile);
    BufferedReader br = new BufferedReader(fr);
    String line;/*ww  w .j av a 2 s  .com*/
    StringBuffer buff = new StringBuffer();

    while ((line = br.readLine()) != null) {
        buff.append(line + "\n");
    }

    JSONObject jsonObject = new JSONObject(buff.toString());
    JSONArray items = (JSONArray) jsonObject.get("items");
    JSONObject item;
    Question question = null;

    for (int i = 0; i < items.length(); i++) {
        question = null;

        try {
            item = items.getJSONObject(i);
            question = new Question(item); // the current question
            int qid = question.getID();
            // Skip if the linked questions for this one
            // has already been crawled                
            if (crawledLinks.get(qid) != null) {
                System.out.println("Skipping crawling of question: " + qid);
                continue;
            }

            String links = extractLinkedIds(question);
            numRequests++;
            if (numRequests == 10000) {
                System.out.println("Breaking after 10000 requests");
            }

            String linkMsg = qid + "\t" + links;
            fout.write(linkMsg + "\n");

            System.out.println(linkMsg);
            Thread.sleep(delay);
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }

    fout.flush();

    br.close();
    fr.close();
}

From source file:org.crawler.LinkExtractor.java

public String extractLinkedIds(Question thisQuestion) throws Exception {
    StringBuffer links = new StringBuffer();
    final String key = "SljJ5BMNJM*UKmsOMwMx4w(("; //"R7HIsOi63KTX52j*7XK6mg((";
    final String userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0";

    String urlPrefix = "https://api.stackexchange.com/2.2/questions/";
    //String urlSuffix = "/linked?pagesize=100&site=stackoverflow&filter=!LURkzC_(wGQOeHiFvabvfS&key=SkjoA6hPLw50*v8PEShiUw((";
    String urlSuffix = "/linked?pagesize=100&site=stackoverflow&filter=!LURkzC_(wGQOeHiFvabvfS&key=" + key;

    String url = urlPrefix + String.valueOf(thisQuestion.getID()) + urlSuffix;

    String json = null;//w w w.  j  ava 2  s.  com

    json = Jsoup.connect(url).userAgent(userAgent).timeout(20000). // timeout 20s
            ignoreContentType(true).execute().body();

    // Now parse the JSON returned to obtain a list of ids
    if (json.length() == 0)
        return "";

    // parse this JSON to see if there's more to be fetched
    JSONObject jsonObject = new JSONObject(json);
    JSONArray items = (JSONArray) jsonObject.get("items");

    for (int i = 0; i < items.length(); i++) {
        try {
            JSONObject item = items.getJSONObject(i);
            links.append(item.get("question_id").toString()).append(",");
            String backoff = (String) item.get("backoff");
            if (backoff != null) {
                int backoffDelay = Integer.parseInt(backoff);
                Thread.sleep((backoffDelay + 1) * 1000);
            }
            String quotaLeft = (String) item.get("quota_remaining");
            int quotaRemVal = -1;
            if (quotaLeft != null) {
                try {
                    quotaRemVal = Integer.parseInt(quotaLeft);
                } catch (NumberFormatException nex) {
                }
            }
            System.out.println("#requests left: " + quotaRemVal + ", #requests sent: " + numRequests);
            if (quotaRemVal <= 1)
                break;
        } catch (JSONException jex) {
            System.err.println("JSON parse exception" + jex);
        }
    }

    if (links.length() > 0)
        links.deleteCharAt(links.length() - 1); // remove trailing comma
    return links.toString();
}