Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:org.dasein.cloud.tier3.APIHandler.java

private void get(@Nonnull APIResponse apiResponse, @Nullable String paginationId, final int page,
        final @Nonnull String resource, final @Nullable String id, final @Nullable NameValuePair... parameters)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + APIHandler.class.getName() + ".get(" + paginationId + "," + page + ","
                + resource + "," + id + "," + Arrays.toString(parameters) + ")");
    }/*  w w w.  j  a va  2 s . c  o m*/
    try {
        NameValuePair[] params;

        if (parameters != null && paginationId != null) {
            if (parameters.length < 1) {
                params = new NameValuePair[] { new BasicNameValuePair("requestPaginationId", paginationId),
                        new BasicNameValuePair("requestPage", String.valueOf(page)) };
            } else {
                params = new NameValuePair[parameters.length + 2];

                int i = 0;

                for (; i < parameters.length; i++) {
                    params[i] = parameters[i];
                }
                params[i++] = new BasicNameValuePair("requestPaginationId", paginationId);
                params[i] = new BasicNameValuePair("requestPage", String.valueOf(page));
            }
        } else {
            params = parameters;
        }
        String target = getEndpoint(resource, id, params);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [GET (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpGet get = new HttpGet(target);

                get.addHeader("Accept", "application/json");
                get.addHeader("Content-Type", "application/json");
                get.addHeader("Cookie", provider.logon());

                if (wire.isDebugEnabled()) {
                    wire.debug(get.getRequestLine().toString());
                    for (Header header : get.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "GET " + resource);
                    response = client.execute(get);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    apiResponse.receive();
                    return;
                }
                if (status.getStatusCode() != OK) {
                    logger.error("Expected OK for GET request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();
                    String body;

                    if (entity == null) {
                        throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    apiResponse.receive(new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), body));
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudException("No entity was returned from an HTTP GET");
                    }
                    boolean complete;

                    Header h = response.getFirstHeader("x-es-pagination");
                    final String pid;

                    if (h != null) {
                        pid = h.getValue();

                        if (pid != null) {
                            Header last = response.getFirstHeader("x-es-last-page");

                            complete = last != null && last.getValue().equalsIgnoreCase("true");
                        } else {
                            complete = true;
                        }
                    } else {
                        pid = null;
                        complete = true;
                    }
                    if (entity.getContentType() == null
                            || entity.getContentType().getValue().contains("json")) {
                        String body;

                        try {
                            body = EntityUtils.toString(entity);
                        } catch (IOException e) {
                            throw new Tier3Exception(e);
                        }
                        if (wire.isDebugEnabled()) {
                            wire.debug(body);
                        }
                        wire.debug("");

                        try {
                            apiResponse.receive(status.getStatusCode(), new JSONObject(body), complete);
                        } catch (JSONException e) {
                            throw new CloudException(e);
                        }
                    } else {
                        try {
                            apiResponse.receive(status.getStatusCode(), entity.getContent());
                        } catch (IOException e) {
                            throw new CloudException(e);
                        }
                    }
                    if (!complete) {
                        APIResponse r = new APIResponse();

                        apiResponse.setNext(r);
                        get(r, pid, page + 1, resource, id, parameters);
                    }
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [GET (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + APIHandler.class.getName() + ".get()");
        }
    }
}

From source file:org.dasein.cloud.tier3.APIHandler.java

public @Nonnull APIResponse put(@Nonnull String resource, @Nonnull String id, @Nonnull String json)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace(/*w  w w  .j  ava  2 s  .  c om*/
                "ENTER - " + APIHandler.class.getName() + ".put(" + resource + "," + id + "," + json + ")");
    }
    try {
        String target = getEndpoint(resource, id);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpPut put = new HttpPut(target);

                put.addHeader("Accept", "application/json");
                put.addHeader("Content-type", "application/json");
                put.addHeader("Cookie", provider.logon());

                try {
                    put.setEntity(new StringEntity(json, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    logger.error("Unsupported encoding UTF-8: " + e.getMessage());
                    throw new InternalException(e);
                }

                if (wire.isDebugEnabled()) {
                    wire.debug(put.getRequestLine().toString());
                    for (Header header : put.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                    wire.debug(json);
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "PUT " + resource);
                    response = client.execute(put);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND || status.getStatusCode() == NO_CONTENT) {
                    APIResponse r = new APIResponse();

                    r.receive();
                    return r;
                }
                if (status.getStatusCode() != ACCEPTED) {
                    logger.error(
                            "Expected ACCEPTED or CREATED for POST request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), json);
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudException("No response to the PUT");
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    APIResponse r = new APIResponse();

                    try {
                        r.receive(status.getStatusCode(), new JSONObject(json), true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + APIHandler.class.getName() + ".put()");
        }
    }
}

From source file:ai.susi.mind.SusiArgument.java

public JSONObject toJSON() {
    JSONObject json = new JSONObject(true);
    JSONArray recallJson = new JSONArray();
    this.recall.forEach(thought -> recallJson.put(thought));
    JSONArray actionsJson = new JSONArray();
    this.actions.forEach(action -> actionsJson.put(action.toJSONClone()));
    json.put("recall", recallJson);
    json.put("action", actionsJson);
    return json;/*from  ww  w.  ja v a2  s.c om*/
}

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

@Test
public void testCherryPick() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first line\nsec. line\nthird line\n");

        addFile(testTxt);/*  ww  w  .  j a v a  2 s.  com*/

        commitFile(testTxt, "lines in test.txt", false);

        // create new file
        String fileName = "new.txt";
        request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

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

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "added new.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enlarged test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsecond line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "fixed test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // remember starting point and commit to cherry-pick
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(5, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String toCherryPick = commit.getString(ProtocolConstants.KEY_NAME);
        commit = commitsArray.getJSONObject(3);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String startingPoint = commit.getString(ProtocolConstants.KEY_NAME);

        // branch
        response = branch(branchesLocation, "side", startingPoint);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        response = checkoutBranch(cloneLocation, "side");
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfeature++\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enhanced test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // CHERRY-PICK
        JSONObject cherryPick = cherryPick(gitHeadUri, toCherryPick);
        CherryPickStatus mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertTrue(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // try again, should be OK, but nothing changed
        cherryPick = cherryPick(gitHeadUri, toCherryPick);
        mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertFalse(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // 'new.txt' should be not there
        JSONObject newTxt = getChild(folder, "new.txt");
        assertNull(newTxt);

        // check cherry-pick result in the file
        request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        assertEquals("first line\nsecond line\nthird line\nfeature++\n", response.getText());

        // check log
        commitsArray = log(gitHeadUri);
        assertEquals(4, commitsArray.length());
        commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(1);
        assertEquals("enhanced test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(2);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(3);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    }
}

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

private JSONObject cherryPick(String gitHeadUri, String toCherryPick)
        throws JSONException, IOException, SAXException {
    assertCommitUri(gitHeadUri);//from w ww .  j  a  v  a 2s  .  c  o  m
    WebRequest request = getPostGitCherryPickRequest(gitHeadUri, toCherryPick);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    return new JSONObject(response.getText());
}

From source file:com.ecml.MidiOptions.java

/** Initialize the options from a json string
 * //from   www .j  a  v a 2s . c  o  m
 * @param jsonString
 */
public static MidiOptions fromJson(String jsonString) {
    if (jsonString == null) {
        return null;
    }
    MidiOptions options = new MidiOptions();
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray jsonTracks = json.getJSONArray("tracks");
        options.tracks = new boolean[jsonTracks.length()];
        for (int i = 0; i < options.tracks.length; i++) {
            options.tracks[i] = jsonTracks.getBoolean(i);
        }

        JSONArray jsonMute = json.getJSONArray("mute");
        options.mute = new boolean[jsonMute.length()];
        for (int i = 0; i < options.mute.length; i++) {
            options.mute[i] = jsonMute.getBoolean(i);
        }

        JSONArray jsonInstruments = json.getJSONArray("instruments");
        options.instruments = new int[jsonInstruments.length()];
        for (int i = 0; i < options.instruments.length; i++) {
            options.instruments[i] = jsonInstruments.getInt(i);
        }

        if (json.has("time")) {
            JSONObject jsonTime = json.getJSONObject("time");
            int numer = jsonTime.getInt("numerator");
            int denom = jsonTime.getInt("denominator");
            int quarter = jsonTime.getInt("quarter");
            int tempo = jsonTime.getInt("tempo");
            options.time = new TimeSignature(numer, denom, quarter, tempo);
        }

        options.useDefaultInstruments = json.getBoolean("useDefaultInstruments");
        options.scrollVert = json.getBoolean("scrollVert");
        options.showPiano = json.getBoolean("showPiano");
        options.showNoteColors = json.getBoolean("showNoteColors");
        options.showLyrics = json.getBoolean("showLyrics");
        options.delay = json.getInt("delay");
        options.twoStaffs = json.getBoolean("twoStaffs");
        options.showNoteLetters = json.getInt("showNoteLetters");
        options.transpose = json.getInt("transpose");
        options.key = json.getInt("key");
        options.combineInterval = json.getInt("combineInterval");
        options.shade1Color = json.getInt("shade1Color");
        options.shade2Color = json.getInt("shade2Color");
        options.showMeasures = json.getBoolean("showMeasures");
        options.playMeasuresInLoop = json.getBoolean("playMeasuresInLoop");
        options.playMeasuresInLoopStart = json.getInt("playMeasuresInLoopStart");
        options.playMeasuresInLoopEnd = json.getInt("playMeasuresInLoopEnd");
    } catch (Exception e) {
        return null;
    }
    return options;
}

From source file:blink.Message.java

/**
 * a Message object that represents a received message that will be processed from JSON
 * @param jsonReceived given JSON content of the message
 * @throws JSONException //w  w  w . ja v  a2 s.c o m
 */
public Message(String jsonReceived) {
    JSONObject json;
    try {
        json = new JSONObject(jsonReceived);
        if (json.has("timestamp")) {
            timestamp = Long.parseLong((String) json.get("timestamp"));
        }
        if (json.has("content")) {
            text = (String) json.get("content");
        }
        userId = i++;
        try {
            type = (String) json.get("type");
        } catch (Exception e) {
            System.err.println("Error receiving message. No type in JSON received.");
            System.exit(-1);
        }
    } catch (JSONException ex) {
        Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.json = jsonReceived;

}

From source file:org.everit.json.schema.EnumSchemaTest.java

@Before
public void before() {
    possibleValues = new HashSet<>();
    possibleValues.add(true);/*from www .j  ava 2  s .c om*/
    possibleValues.add("foo");
    possibleValues.add(new JSONArray());
    possibleValues.add(new JSONObject("{\"a\" : 0}"));
}

From source file:org.everit.json.schema.EnumSchemaTest.java

@Test
public void success() {
    EnumSchema subject = subject();/*from w  w w . j a  v a  2  s. co  m*/
    subject.validate(true);
    subject.validate("foo");
    subject.validate(new JSONArray());
    subject.validate(new JSONObject("{\"a\" : 0}"));
}

From source file:org.rapidandroid.activity.FormCreator.java

@Override
protected synchronized void onResume() {
    super.onResume();

    Intent intent = getIntent();/*from  w  w w  . ja va 2s.co m*/
    String currentForm = intent.getStringExtra("current_form");
    if (currentForm != null) {
        try {
            String contents = new String(currentForm);
            JSONObject readobject = new JSONObject(contents);

            EditText etxFormName = (EditText) findViewById(R.id.etx_formname);
            EditText etxFormPrefix = (EditText) findViewById(R.id.etx_formprefix);
            EditText etxDescription = (EditText) findViewById(R.id.etx_description);

            etxFormName.setText(readobject.getString(STATE_FORMNAME));
            etxFormPrefix.setText(readobject.getString(STATE_PREFIX));
            etxDescription.setText(readobject.getString(STATE_DESC));
            boolean checkForFields = true;
            int i = 0;
            do {
                checkForFields = readobject.has("Field" + i);
                if (checkForFields) {
                    JSONObject fieldBundle = (JSONObject) readobject.get("Field" + i);
                    restoreFieldFromState(fieldBundle);
                    i++;
                }
            } while (checkForFields);
        } catch (Exception e) {
            Log.e("FOOBAR", e.getMessage(), e);
        }
    }
}