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.everit.json.schema.ObjectSchema.java

private void testPatternProperties(final JSONObject subject) {
    String[] propNames = JSONObject.getNames(subject);
    if (propNames == null || propNames.length == 0) {
        return;/*from w ww. ja  v  a2s.co  m*/
    }
    for (Entry<Pattern, Schema> entry : patternProperties.entrySet()) {
        for (String propName : propNames) {
            if (entry.getKey().matcher(propName).find()) {
                entry.getValue().validate(subject.get(propName));
            }
        }
    }
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private boolean setConfig(JSONObject config) {
    try {//ww w.  j av  a  2s. c  o  m
        JSONObject merged = new JSONObject();
        JSONObject[] objs = new JSONObject[] { mConfig, config };
        for (JSONObject obj : objs) {
            Iterator it = obj.keys();
            while (it.hasNext()) {
                String key = (String) it.next();
                merged.put(key, obj.get(key));
            }
        }
        mConfig = merged;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            applyConfig();
            Bundle event = new Bundle();
            event.putString("name", BackgroundGeolocationService.ACTION_SET_CONFIG);
            event.putBoolean("request", true);
            postEvent(event);
        }
    });
    return true;
}

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

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

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

    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "change to commit");

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

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

    // commit all
    request = getPostGitCommitRequest(gitHeadUri, "Comit massage", false); // typos
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // amend last commit
    request = getPostGitCommitRequest(gitHeadUri, "Commit message", true);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    JSONArray commitsArray = log(gitHeadUri);
    assertEquals(2, commitsArray.length());
    JSONObject commit = commitsArray.getJSONObject(0);
    assertEquals("Commit message", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    commit = commitsArray.getJSONObject(1);
    assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
}

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

@Test
public void testCommitAllInFolder() throws Exception {
    // see bug 349480
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

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

        String fileName = "folder2.txt";
        JSONObject folder = getChild(cloneFolder, "folder");
        request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        JSONObject testTxt = getChild(cloneFolder, "test.txt");

        // drill down to 'folder'
        JSONObject folderGitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String folderGitStatusUri = folderGitSection.getString(GitConstants.KEY_STATUS);
        String folderGitCloneUri = folderGitSection.getString(GitConstants.KEY_CLONE);

        JSONObject folder2Txt = getChild(folder, "folder2.txt");
        JSONObject folderTxt = getChild(folder, "folder.txt");

        // git section for the new file
        JSONObject folder2TxtGitSection = folder2Txt.getJSONObject(GitConstants.KEY_GIT);
        String folder2TxtGitIndexUri = folder2TxtGitSection.getString(GitConstants.KEY_INDEX);
        String folder2TxtGitHeadUri = folder2TxtGitSection.getString(GitConstants.KEY_HEAD);

        // stage the new file
        request = GitAddTest.getPutGitIndexRequest(folder2TxtGitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit the new file
        request = getPostGitCommitRequest(folder2TxtGitHeadUri, "folder/folder2.txt added", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // check status - clean
        assertStatus(StatusResult.CLEAN, folderGitStatusUri);

        // modify all
        modifyFile(testTxt, "change");
        modifyFile(folderTxt, "change");
        modifyFile(folder2Txt, "change");

        // check status - modified=3
        assertStatus(new StatusResult().setModified(3), folderGitStatusUri);

        addFile(folderTxt);//from   w w  w. j  a  v a 2  s.  c om
        addFile(testTxt);

        // check status - modified=1, changed=2
        assertStatus(new StatusResult().setModified(1).setChanged(2), folderGitStatusUri);

        // commit all
        // XXX: using HEAD URI for folder will commit all files in the folder, regardless of index state
        // request = getPostGitCommitRequest(folderGitHeadUri, "test.txt and folder/folder.txt changed", false);
        // the UI should use HEAD URI for the clone/root to commit all staged files
        JSONObject clone = getCloneForGitResource(folder);
        String cloneFolderGitHeadUri = clone.getString(GitConstants.KEY_HEAD);

        request = getPostGitCommitRequest(cloneFolderGitHeadUri, "test.txt and folder/folder.txt changed",
                false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // check status - changed=1
        assertStatus(new StatusResult().setModifiedNames("folder/folder2.txt"), folderGitStatusUri);

        // check the last commit for the repo
        JSONArray commitsArray = log(cloneFolderGitHeadUri);
        assertEquals(3, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("test.txt and folder/folder.txt changed", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        JSONArray diffs = commit.getJSONArray(GitConstants.KEY_COMMIT_DIFFS);
        assertEquals(2, diffs.length());
        String oldPath = diffs.getJSONObject(0).getString(GitConstants.KEY_COMMIT_DIFF_OLDPATH);
        assertTrue("folder/folder.txt".equals(oldPath) || "test.txt".equals(oldPath));
        oldPath = diffs.getJSONObject(1).getString(GitConstants.KEY_COMMIT_DIFF_OLDPATH);
        assertTrue("folder/folder.txt".equals(oldPath) || "test.txt".equals(oldPath));
    }
}

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

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

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);

        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

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

        // commit all
        final String commiterName = "committer name";
        final String commiterEmail = "committer email";

        request = getPostGitCommitRequest(gitHeadUri, "Comit message", false, commiterName, commiterEmail, null,
                null);/*  ww  w . j av a2  s  .c o m*/
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals(commiterName, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(commiterEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
    }
}

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

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

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);

        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

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

        // commit all
        final String commiterName = "committer name";
        final String commiterEmail = "committer email";

        request = getPostGitCommitRequest(gitHeadUri, "Comit message", false, commiterName, commiterEmail, null,
                null);//from  w w  w .j a  va2 s  .  c o  m
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals(commiterName, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(commiterEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
    }
}

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

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

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);

        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        // set user.name and user.email
        final String name = "name";
        final String email = "email";
        final String defaultName = "default name";
        final String defaultEmail = "default email";
        request = GitConfigTest.getPostGitConfigRequest(gitConfigUri, "user.name", defaultName);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        request = GitConfigTest.getPostGitConfigRequest(gitConfigUri, "user.email", defaultEmail);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_CREATED, response.getResponseCode());

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

        // commit - author and committer not specified
        request = getPostGitCommitRequest(gitHeadUri, "1", false, null, null, null, null);
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log - expect default values
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals(defaultName, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertEquals(defaultName, commit.get(GitConstants.KEY_AUTHOR_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_AUTHOR_EMAIL));

        // commit - only committer given
        request = getPostGitCommitRequest(gitHeadUri, "2", true, name, email, null, null);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log - expect author is the same as committer
        commitsArray = log(gitHeadUri);/*  w w  w.  j av a  2s.  c o m*/
        assertEquals(2, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals(name, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(email, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertEquals(name, commit.get(GitConstants.KEY_AUTHOR_NAME));
        assertEquals(email, commit.get(GitConstants.KEY_AUTHOR_EMAIL));

        // commit - only committer name given
        request = getPostGitCommitRequest(gitHeadUri, "3", true, name, null, null, null);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // log - expect author is the same as committer and their email is defaultEmail
        commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals(name, commit.get(GitConstants.KEY_COMMITTER_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertEquals(name, commit.get(GitConstants.KEY_AUTHOR_NAME));
        assertEquals(defaultEmail, commit.get(GitConstants.KEY_AUTHOR_EMAIL));
    }
}

From source file:eu.codeplumbers.cosi.api.tasks.SyncDocumentTask.java

@Override
protected String doInBackground(JSONObject... jsonObjects) {
    for (int i = 0; i < jsonObjects.length; i++) {
        JSONObject jsonObject = jsonObjects[i];

        URL urlO = null;/*from  w w  w .j a  v a  2s  .  c  o m*/
        try {
            publishProgress("Syncing " + jsonObject.getString("docType") + ":", i + "",
                    jsonObjects.length + "");
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(url);
                requestMethod = "POST";
            } else {
                urlO = new URL(url + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");

                if (jsonObject.get("docType").equals("Sms")) {
                    Sms sms = Sms.load(Sms.class, objectId);
                    sms.setRemoteId(result);
                    sms.save();
                }

                if (jsonObject.get("docType").equals("Note")) {
                    Note note = Note.load(Note.class, objectId);
                    note.setRemoteId(result);
                    note.save();
                }

                if (jsonObject.get("docType").equals("Call")) {
                    Call call = Call.load(Call.class, objectId);
                    call.setRemoteId(result);
                    call.save();
                }

                if (jsonObject.get("docType").equals("Expense")) {
                    Expense expense = Expense.load(Expense.class, objectId);
                    expense.setRemoteId(result);
                    expense.save();
                }
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            result = "error";
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (JSONException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Method to find the definitionID which is necessary to start a process instance
 *
 * @param deploymentID the deployment id is used to identify the deployment uniquely
 * @return String Array containing status and definitionID
 * @throws IOException// www.  j a v  a2  s .  c o  m
 * @throws JSONException
 */
public String[] findProcessDefinitionInfoById(String deploymentID) throws IOException, JSONException {
    String url = serviceURL + "repository/process-definitions";
    String definitionId = "";
    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpClient.execute(httpget);

    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    JSONArray data = jsonResponseObject.getJSONArray("data");

    int responseObjectSize = Integer.parseInt(jsonResponseObject.get("total").toString());

    for (int j = 0; j < responseObjectSize; j++) {
        if (data.getJSONObject(j).getString("deploymentId").equals(deploymentID)) {
            definitionId = data.getJSONObject(j).getString("id");
        }
    }
    return new String[] { status, definitionId };

}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * This method is used to validate/check if the process instance is present or not
 *
 * @param processDefinitionID used to identify the process instance
 * @return a String value of the status//  w  w w .j a v a 2s.com
 * @throws IOException
 * @throws JSONException
 */
public String validateProcessInstanceById(String processDefinitionID) throws Exception {
    String url = serviceURL + "runtime/process-instances";
    HttpHost target = new HttpHost(hostname, port, "http");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpClient.execute(httpget);
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    JSONArray data = jsonResponseObject.getJSONArray("data");

    int responseObjectSize = Integer.parseInt(jsonResponseObject.get("total").toString());

    for (int j = 0; j < responseObjectSize; j++) {
        if (data.getJSONObject(j).getString("processDefinitionId").equals(processDefinitionID)) {
            return AVAILABLE;
        }
    }
    throw new RestClientException(NOT_AVAILABLE);
}