Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

private synchronized void sendRequest(final Request request) {
    callQueue.add(request);/*from  ww  w  . j av  a 2  s  .  c o m*/

    // If not in background, spin the spinner
    if (request.caller instanceof WaitSpinner) {
        ((WaitSpinner) request.caller).startWaitSpinner();
        request.waitFlag = true;
    }

    request.taskFuture = ThreadPool.get().enqueueAsync(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection conn = requestWith(request);

                conn.connect();
                Map<String, List<String>> headers = conn.getHeaderFields();
                List<String> clist = headers.get("Set-Cookie");
                if (clist != null) {
                    for (String cookie : clist) {
                        cookies.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                    }
                }

                InputStream is = conn.getInputStream();
                JSONObject d = parseResult(is);
                conn.disconnect();

                final Response response = new Response();
                response.serverCode = conn.getResponseCode();
                if (d != null) {
                    response.success = d.optBoolean("success");
                    response.error = d.optInt("error");
                    response.errorMessage = d.optString("message");
                    response.exceptionStack = d.optJSONArray("exception");
                    response.data = d.optJSONObject("data");
                }

                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleResponse(response, request);
                    }
                });
            } catch (Exception ex) {
                /*
                 *  This happens if there is a connection error.
                 */
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleIOError(request);
                    }
                });
            }
        }
    });
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeTest.java

@Test
public void testMergeSelf() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//from w  w w .  java 2s.  c  o  m
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // "git merge master"
    JSONObject merge = merge(gitHeadUri, Constants.MASTER);
    MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
    assertEquals(MergeStatus.ALREADY_UP_TO_DATE, mergeResult);
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeTest.java

@Test
public void testMergeConflict() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    JSONObject clone = clone(clonePath);
    String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//from  w  ww  . j  a  v  a 2s . c o  m
    String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE, null);
    assertNotNull(gitRemoteUri);

    // create branch 'a'
    branch(branchesLocation, "a");

    // checkout 'a'
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation);
    Git git = new Git(db1);
    assertBranchExist(git, "a");
    checkoutBranch(cloneLocation, "a");

    // modify while on 'a'
    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "change in a");

    gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // "git add ."
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // commit all
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit on a", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // assert clean
    assertStatus(StatusResult.CLEAN, gitStatusUri);

    // checkout 'master'
    checkoutBranch(cloneLocation, Constants.MASTER);

    // modify the same file on master
    modifyFile(testTxt, "change in master");

    gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // "git add ."
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // commit all
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit on master", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // assert clean
    assertStatus(StatusResult.CLEAN, gitStatusUri);

    // merge: "git merge a"
    JSONObject merge = merge(gitHeadUri, "a");
    MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
    assertEquals(MergeStatus.CONFLICTING, mergeResult);

    // check status
    assertStatus(new StatusResult().setConflictingNames("test.txt"), gitStatusUri);

    request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    String[] responseLines = response.getText().split("\n");
    assertEquals(5, responseLines.length);
    assertEquals("<<<<<<< HEAD", responseLines[0]);
    assertEquals("change in master", responseLines[1]);
    assertEquals("=======", responseLines[2]);
    assertEquals("change in a", responseLines[3]);
    // ignore the last line since it's different each time
    // assertEquals(">>>>>>> c5ddb0e22e7e829683bb3b336ca6cb24a1b5bb2e", responseLines[4]);

    // TODO: check commits, bug 340051
}

From source file:com.example.wcl.test_weiboshare.Status.java

public static Status parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//from ww  w .j  a  v  a2s.  co m

    Status status = new Status();
    status.created_at = jsonObject.optString("created_at");
    status.id = jsonObject.optString("id");
    status.mid = jsonObject.optString("mid");
    status.idstr = jsonObject.optString("idstr");
    status.text = jsonObject.optString("text");
    status.source = jsonObject.optString("source");
    status.favorited = jsonObject.optBoolean("favorited", false);
    status.truncated = jsonObject.optBoolean("truncated", false);

    // Have NOT supported
    status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
    status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
    status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
    status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
    status.original_pic = jsonObject.optString("original_pic");
    status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
    status.user = User.parse(jsonObject.optJSONObject("user"));
    status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
    status.reposts_count = jsonObject.optInt("reposts_count");
    status.comments_count = jsonObject.optInt("comments_count");
    status.attitudes_count = jsonObject.optInt("attitudes_count");
    status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
    status.visible = Visible.parse(jsonObject.optJSONObject("visible"));

    JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
    if (picUrlsArray != null && picUrlsArray.length() > 0) {
        int length = picUrlsArray.length();
        status.pic_urls = new ArrayList<String>(length);
        JSONObject tmpObject = null;
        for (int ix = 0; ix < length; ix++) {
            tmpObject = picUrlsArray.optJSONObject(ix);
            if (tmpObject != null) {
                status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
            }
        }
    }

    //status.ad = jsonObject.optString("ad", "");

    return status;
}

From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {//w  w w. j  a v a2 s.c  om

        resp.setContentType("text/plain");

        InputStream stream = req.getInputStream();

        log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from "
                + req.getRemoteAddr());

        String amiId = req.getHeader("AMI-ID");
        log.info("Got AMI ID:" + amiId);
        String repository = req.getHeader("REPO");
        log.info("Got REPO:" + repository);
        if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) {
            log.severe("AMI ID and REPO HTTP Header required.");
            return;
        }

        // Gson gson = new Gson();
        // log.info("Parsed Gson " + gson.fromJson(new
        // InputStreamReader(stream), JsonObject.class));

        String jsonString = IOUtils.toString(stream);
        log.info("Got JSON String "
                + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1));
        JSONObject json = new JSONObject();
        try {
            json = new JSONObject(jsonString);
            log.fine("Parsed Json " + json);
            log.finer("Json has keys: " + json.names());
        } catch (JSONException e) {
            log.severe("No JSON sent or wrong format.");
            return;
        }

        JSONObject software = json.optJSONObject("software");
        if (software != null) {
            log.finer("Software JSON " + software);

            JSONArray softwareNames = software.names();
            log.finer("Key Array JSON " + softwareNames);
            for (int i = 0; i < softwareNames.length(); i++) {
                log.fine("software " + softwareNames.getString(i) + " with version "
                        + software.getJSONObject(softwareNames.getString(i)).getString("version"));

                Map<String, String> softAttributes = new HashMap<String, String>();
                JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names();
                for (int j = 0; j < softwareAttributes.length(); j++)
                    softAttributes.put(softwareAttributes.getString(j),
                            software.getJSONObject(softwareNames.getString(i))
                                    .getString(softwareAttributes.getString(j)));

                Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i),
                        software.getJSONObject(softwareNames.getString(i)).getString("version"),
                        softAttributes);
                if (soft != null) {
                    log.fine("Saved/restored software " + soft);
                    // soft.getAttributes().putAll(softAttributes);
                    // AmiManager.updateSoftware(soft);
                    // log.fine("Saved object " + soft);
                } else
                    log.severe("Not able to save software information for given Ami Id " + amiId + "!");

            }
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < softwareNames.length(); i++)
                names.add(softwareNames.getString(i));
            AmiManager.updateSoftwareNames(names);
            log.info("Saved " + softwareNames.length() + " software objects");

        }

        JSONObject languages = json.optJSONObject("languages");
        if (languages != null) {
            log.finer("Languages JSON " + languages);

            JSONArray languagesNames = languages.names();
            log.finer("Key Array JSON " + languagesNames);
            for (int i = 0; i < languagesNames.length(); i++) {
                log.fine("languages " + languagesNames.getString(i) + " with version "
                        + languages.getJSONObject(languagesNames.getString(i)).getString("version"));

                Map<String, String> langAttributes = new HashMap<String, String>();
                JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names();
                for (int j = 0; j < languageAttributes.length(); j++)
                    langAttributes.put(languageAttributes.getString(j),
                            languages.getJSONObject(languagesNames.getString(i))
                                    .getString(languageAttributes.getString(j)));

                Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i),
                        languages.getJSONObject(languagesNames.getString(i)).getString("version"),
                        langAttributes);
                if (lang != null) {
                    log.fine("Saved/restored programming language " + lang);
                    lang.getAttributes().putAll(langAttributes);
                    AmiManager.updateLanguage(lang);
                    log.fine("Saved object " + lang);
                } else
                    log.severe("Not able to save programming language information for given Ami Id " + amiId
                            + "!");

            }
            log.info("Saved " + languagesNames.length() + " programming language objects");
        }

        resp.getWriter().println(
                "Saving software packages and programming languages for " + amiId + " (" + repository + ").");

    } catch (JSONException e) {
        log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", e);
        e.printStackTrace();

    } catch (Exception ex) {
        log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", ex);
        ex.printStackTrace();
    }

    // log.info("returning to referer " + req.getHeader("referer"));
    // resp.sendRedirect(req.getHeader("referer") != null &&
    // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") :
    // "localhost:8088");
}

From source file:org.schedulesdirect.grabber.ScheduleTask.java

protected Map<String, Collection<String>> getStaleStationIds() {
    Map<String, Collection<String>> staleIds = new HashMap<>();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULE_MD5S,
            clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl());
    JSONArray data = new JSONArray();
    for (int i = 0; i < this.req.length(); ++i) {
        JSONObject o = new JSONObject();
        o.put("stationID", this.req.getString(i));
        data.put(o);//from www.ja v  a2  s .  c  o  m
    }
    try {
        JSONObject result = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(result)) {
            Iterator<?> idItr = result.keys();
            while (idItr.hasNext()) {
                String stationId = idItr.next().toString();
                boolean schedFileExists = Files
                        .exists(vfs.getPath("schedules", String.format("%s.txt", stationId)));
                Path cachedMd5File = vfs.getPath("md5s", String.format("%s.txt", stationId));
                JSONObject cachedMd5s = Files.exists(cachedMd5File)
                        ? Config.get().getObjectMapper()
                                .readValue(new String(Files.readAllBytes(cachedMd5File),
                                        ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class)
                        : new JSONObject();
                JSONObject stationInfo = result.getJSONObject(stationId);
                Iterator<?> dateItr = stationInfo.keys();
                while (dateItr.hasNext()) {
                    String date = dateItr.next().toString();
                    JSONObject dateInfo = stationInfo.getJSONObject(date);
                    if (!schedFileExists || isScheduleStale(dateInfo, cachedMd5s.optJSONObject(date))) {
                        Collection<String> dates = staleIds.get(stationId);
                        if (dates == null) {
                            dates = new ArrayList<String>();
                            staleIds.put(stationId, dates);
                        }
                        dates.add(date);
                        if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Station %s/%s queued for refresh!", stationId, date));
                    } else if (LOG.isDebugEnabled())
                        LOG.debug(String.format("Station %s is unchanged on the server; skipping it!",
                                stationId));
                }
                Files.write(cachedMd5File, stationInfo.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                        StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                        StandardOpenOption.CREATE);
            }
        }
    } catch (Throwable t) {
        Grabber.failedTask = true;
        LOG.error("Error processing cache; returning partial stale list!", t);
    }
    return staleIds;
}

From source file:com.danlvse.weebo.model.Favorite.java

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//  w ww . j a va2s.c  o m

    Favorite favorite = new Favorite();
    favorite.status = Feed.parse(jsonObject.optJSONObject("status"));
    favorite.favorited_time = jsonObject.optString("favorited_time");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonArray.length() > 0) {
        int length = jsonArray.length();
        favorite.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            favorite.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return favorite;
}

From source file:com.marianhello.cordova.bgloc.Config.java

public static Config fromJSONArray(JSONArray data) throws JSONException {
    JSONObject jObject = data.getJSONObject(0);
    Config config = new Config();
    config.setStationaryRadius((float) jObject.optDouble("stationaryRadius", config.getStationaryRadius()));
    config.setDistanceFilter(jObject.optInt("distanceFilter", config.getDistanceFilter()));
    config.setDesiredAccuracy(jObject.optInt("desiredAccuracy", config.getDesiredAccuracy()));
    config.setDebugging(jObject.optBoolean("debug", config.isDebugging()));
    config.setNotificationTitle(jObject.optString("notificationTitle", config.getNotificationTitle()));
    config.setNotificationText(jObject.optString("notificationText", config.getNotificationText()));
    config.setStopOnTerminate(jObject.optBoolean("stopOnTerminate", config.getStopOnTerminate()));
    config.setStartOnBoot(jObject.optBoolean("startOnBoot", config.getStartOnBoot()));
    config.setServiceProvider(jObject.optInt("locationService", config.getServiceProvider().asInt()));
    config.setInterval(jObject.optInt("interval", config.getInterval()));
    config.setFastestInterval(jObject.optInt("fastestInterval", config.getFastestInterval()));
    config.setActivitiesInterval(jObject.optInt("activitiesInterval", config.getActivitiesInterval()));
    config.setNotificationIconColor(/*from  ww w.j  av  a 2s .c o  m*/
            jObject.optString("notificationIconColor", config.getNotificationIconColor()));
    config.setLargeNotificationIcon(
            jObject.optString("notificationIconLarge", config.getLargeNotificationIcon()));
    config.setSmallNotificationIcon(
            jObject.optString("notificationIconSmall", config.getSmallNotificationIcon()));
    config.setStartForeground(jObject.optBoolean("startForeground", config.getStartForeground()));
    config.setUrl(jObject.optString("url", config.getUrl()));
    config.setMethod(jObject.optString("method", config.getMethod()));
    config.setHeaders(jObject.optJSONObject("headers"));
    config.setParams(jObject.optJSONObject("params"));
    return config;
}

From source file:org.jraf.android.cinetoday.mobile.api.codec.theater.TheaterCodec.java

public void fill(Theater theater, JSONObject jsonTheater) throws ParseException {
    try {/* w w  w .ja  va  2  s .c  o m*/
        theater.id = jsonTheater.getString("code");
        theater.name = jsonTheater.getString("name");
        theater.address = jsonTheater.getString("address") + "\n" + jsonTheater.getString("postalCode") + " "
                + jsonTheater.getString("city");

        JSONObject jsonPoster = jsonTheater.optJSONObject("poster");
        if (jsonPoster != null) {
            theater.pictureUri = jsonPoster.getString("href");
        }
    } catch (JSONException e) {
        throw new ParseException(e);
    }
}

From source file:net.digitalphantom.app.weatherapp.data.Channel.java

@Override
public void populate(JSONObject data) {

    units = new Units();
    units.populate(data.optJSONObject("units"));

    item = new Item();
    item.populate(data.optJSONObject("item"));

    JSONObject locationData = data.optJSONObject("location");

    String region = locationData.optString("region");
    String country = locationData.optString("country");

    location = String.format("%s, %s", locationData.optString("city"),
            (region.length() != 0 ? region : country));
}