Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.brickred.socialauth.provider.FourSquareImpl.java

/**
 * Gets the list of contacts of the user.
 * //from  w  w  w  .j  av  a 2s .  c o  m
 * @return List of contact objects representing Contacts. Only name and
 *         profile URL will be available
 */

@Override
public List<Contact> getContactList() throws Exception {
    LOG.info("Fetching contacts from " + CONTACTS_URL);

    Response serviceResponse;
    try {
        serviceResponse = authenticationStrategy.executeFeed(CONTACTS_URL);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL, e);
    }
    if (serviceResponse.getStatus() != 200) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL + "Status : "
                + serviceResponse.getStatus());
    }
    String respStr;
    try {
        respStr = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception exc) {
        throw new SocialAuthException("Failed to read response from  " + CONTACTS_URL, exc);
    }
    LOG.debug("User Contacts list in JSON " + respStr);
    JSONObject resp = new JSONObject(respStr);
    List<Contact> plist = new ArrayList<Contact>();
    JSONArray items = new JSONArray();
    if (resp.has("response")) {
        JSONObject robj = resp.getJSONObject("response");
        if (robj.has("friends")) {
            JSONObject fobj = robj.getJSONObject("friends");
            if (fobj.has("items")) {
                items = fobj.getJSONArray("items");
            }
        } else {
            throw new SocialAuthException("Failed to parse the user profile json : " + respStr);
        }
    } else {
        throw new SocialAuthException("Failed to parse the user profile json : " + respStr);
    }
    LOG.debug("Contacts Found : " + items.length());
    for (int i = 0; i < items.length(); i++) {
        JSONObject obj = items.getJSONObject(i);
        Contact c = new Contact();
        if (obj.has("firstName")) {
            c.setFirstName(obj.getString("firstName"));
        }
        if (obj.has("lastName")) {
            c.setLastName(obj.getString("lastName"));
        }
        if (obj.has("id")) {
            c.setProfileUrl(VIEW_PROFILE_URL + obj.getString("id"));
            c.setId(obj.getString("id"));
        }
        plist.add(c);
    }

    return plist;
}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

private Bundle JSONtoBundle(JSONObject jsonObj) {
    Bundle params = new Bundle();
    Iterator<?> iter = jsonObj.keys();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        String value;/*ww  w . j ava 2 s  .co m*/
        try {
            value = jsonObj.getString(key);
            params.putString(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return params;
}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void showAppRequestDialog(final String parameters) {
    if (!session.isOpened()) {
        currentCommand = APP_REQUEST_DIALOG;
        currentCommandArguments = new String[] { parameters };
        login(defaultLoginPermissions);/* w  w  w .j  a  va 2  s  . c o  m*/
        return;
    } else {
        //busy=true;
    }

    activity.runOnUiThread(new Runnable() {
        //@Override
        public void run() {

            JSONObject json = new JSONObject();
            try {
                json = new JSONObject(parameters);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Bundle params = JSONtoBundle(json);

            params.putString("frictionless", useFrictionless);

            WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(activity, session, params))
                    .setOnCompleteListener(new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values, FacebookException error) {
                            if (error != null) {
                                if (error instanceof FacebookOperationCanceledException) {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                            error.toString());
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            } else {
                                final String requestId = values.getString("request");
                                if (requestId != null) {
                                    JSONObject jsonData = BundleToJSON(values);
                                    String extra = "";

                                    try {
                                        String request = jsonData.getString("request");
                                        extra += "e.request=" + request + ";";
                                    } catch (JSONException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    int index = 0;
                                    if (jsonData.has("to[" + index + "]")) {
                                        extra += "e.to=[";
                                        while (jsonData.has("to[" + index + "]")) {
                                            try {
                                                extra += jsonData.getString("to[" + index + "]") + ",";
                                            } catch (JSONException e) {
                                            }
                                            index++;
                                        }
                                        extra += "];";
                                    }

                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);",
                                            jsonData.toString(), extra);
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            }
                        }

                    }).build();
            requestsDialog.show();
        }
    });

}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void showNewsFeedDialog(final String parameters) {
    if (!session.isOpened()) {
        currentCommand = NEWS_FEED_DIALOG;
        currentCommandArguments = new String[] { parameters };
        login(defaultLoginPermissions);/*from ww  w.  j  ava 2 s.  co m*/
        return;
    } else {
        busy = true;
    }

    activity.runOnUiThread(new Runnable() {
        //@Override
        public void run() {

            JSONObject json = new JSONObject();
            try {
                json = new JSONObject(parameters);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //facebook.dialog(activity, "feed", JSONtoBundle(json), FBDialogListener );
            //            Bundle params = new Bundle();
            //             params.putString("name", "Facebook SDK for Android");
            //             params.putString("caption", "Build great social apps and get more installs.");
            //             params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
            //             params.putString("link", "https://developers.facebook.com/android");
            //             params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
            Bundle params = JSONtoBundle(json);

            params.putString("frictionless", useFrictionless);

            WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, session, params))
                    .setOnCompleteListener(new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values, FacebookException error) {
                            if (error == null) {
                                // When the story is posted, echo the success
                                // and the post Id.
                                final String postId = values.getString("post_id");
                                if (postId != null) {
                                    //                                 Toast.makeText(activity,
                                    //                                     "Posted story, id: "+postId,
                                    //                                     Toast.LENGTH_SHORT).show();
                                    JSONObject jsonData = BundleToJSON(values);
                                    String extra = "";

                                    try {
                                        String request = jsonData.getString("request");
                                        extra += "e.request=" + request + ";";
                                    } catch (JSONException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    int index = 0;
                                    if (jsonData.has("to[" + index + "]")) {
                                        extra += "e.to=[";
                                        while (jsonData.has("to[" + index + "]")) {
                                            try {
                                                extra += jsonData.getString("to[" + index + "]") + ",";
                                            } catch (JSONException e) {
                                            }
                                            index++;
                                        }
                                        extra += "];";
                                    }

                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);",
                                            jsonData.toString(), extra);
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    // User clicked the Cancel button
                                    //                                 Toast.makeText(activity.getApplicationContext(), 
                                    //                                     "Publish cancelled", 
                                    //                                     Toast.LENGTH_SHORT).show();
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            } else if (error instanceof FacebookOperationCanceledException) {
                                // User clicked the "x" button
                                //                             Toast.makeText(activity.getApplicationContext(), 
                                //                                 "Publish cancelled", 
                                //                                 Toast.LENGTH_SHORT).show();
                                String js = String.format(
                                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                webView.loadUrl(js);
                                resetFBStatus();
                            } else {
                                // Generic, ex: network error
                                //                             Toast.makeText(activity.getApplicationContext(), 
                                //                                 "Error posting story", 
                                //                                 Toast.LENGTH_SHORT).show();
                                String js = String.format(
                                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                        error.toString());
                                webView.loadUrl(js);
                                resetFBStatus();
                            }
                        }

                    }).build();
            feedDialog.show();
        }
    });

}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * callRunProcedure// w  ww  . ja v a  2  s  . co m
 * 
 * @param jo
 * @return the jobId of the job launched by runProcedure
 */
public static String callRunProcedure(JSONObject jo) throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject result = null;

    try {
        String encoding = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                        .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                                + props.getProperty(StringConstants.COMMANDER_PASSWORD))));

        HttpPost httpPostRequest = new HttpPost("http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/jobs?request=runProcedure");

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPostRequest.setEntity(input);
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpPostRequest);

        result = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
        return result.getString("jobId");

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * waitForJob: Waits for job to be completed and reports outcome
 * //from   w  w  w . j  av a2  s  .c  o m
 * @param jobId
 * @return outcome of job
 */
static String waitForJob(String jobId, long jobTimeOutMillis) throws Exception {

    long timeTaken = 0;

    String url = "http://" + props.getProperty(StringConstants.COMMANDER_SERVER) + ":8000/rest/v1.0/jobs/"
            + jobId + "?request=getJobStatus";
    JSONObject jsonObject = performHTTPGet(url);

    while (!jsonObject.getString("status").equalsIgnoreCase("completed")) {
        Thread.sleep(jobStatusPollIntervalMillis);
        jsonObject = performHTTPGet(url);
        timeTaken += jobStatusPollIntervalMillis;
        if (timeTaken > jobTimeOutMillis) {
            throw new Exception("Job did not completed within time.");
        }
    }

    return jsonObject.getString("outcome");

}

From source file:com.whizzosoftware.hobson.rest.v1.resource.task.TasksResource.java

/**
 * @api {post} /api/v1/users/:userId/hubs/:hubId/tasks Create task
 * @apiVersion 0.1.3/*  www.j  a va 2s.  c  o m*/
 * @apiName AddTask
 * @apiDescription Creates a new task.
 * @apiGroup Tasks
 * @apiExample Example Request (simple event task):
 * {
 *   "name": "My Event Task",
 *   "provider": "com.whizzosoftware.hobson.hub.hobson-hub-rules",
 *   "conditions": [{
 *     "event": "variableUpdate",
 *     "pluginId": "com.whizzosoftware.hobson.hub.hobson-hub-zwave",
 *     "deviceId": "zwave-32",
 *     "changeId": "turnOff"
 *   }],
 *   "actions": [{
 *     "pluginId": "com.whizzosoftware.hobson.hub.hobson-hub-actions",
 *     "actionId": "log",
 *     "name": "My Action 1",
 *     "properties": {
 *       "message": "Event task fired"
 *     }
 *   }]
 * }
 * @apiExample Example Request (advanced event task):
 * {
 *   "name": "My Event Task",
 *   "provider": "com.whizzosoftware.hobson.hub.hobson-hub-rules",
 *   "conditions": [{
 *     "event": "variableUpdate",
 *     "pluginId": "com.whizzosoftware.hobson.hub.hobson-hub-zwave",
 *     "deviceId": "zwave-32",
 *     "variable": {
 *       "name": "on",
 *       "comparator": "eq",
 *       "value": true
 *     }
 *   }],
 *   "actions": [{
 *     "pluginId": "com.whizzosoftware.hobson.hub.hobson-hub-actions",
 *     "actionId": "log",
 *     "name": "My Action 1",
 *     "properties": {
 *       "message": "Event task fired"
 *     }
 *   }]
 * }
 * @apiExample Example Request (scheduled task):
 * {
 *   "name": "My Scheduled Task",
 *   "provider": "com.whizzosoftware.hobson.hub.hobson-hub-scheduler",
 *   "conditions": [{
 *     "start": "20140701T100000",
 *     "recurrence": "FREQ=MINUTELY;INTERVAL=1"
 *   }],
 *   "actions": [{
 *     "pluginId": "com.whizzosoftware.hobson.hub.hobson-hub-actions",
 *     "actionId": "log",
 *     "name": "My Action 2",
 *   }],
 *   "properties": {
 *     "nextRunTime": 1234567890
 *   }
 * }
 * @apiSuccessExample Success Response:
 * HTTP/1.1 202 Accepted
 */
@Override
protected Representation post(Representation entity) {
    HobsonRestContext ctx = HobsonRestContext.createContext(this, getRequest());
    JSONObject json = JSONMarshaller.createJSONFromRepresentation(entity);
    taskManager.addTask(ctx.getUserId(), ctx.getHubId(), json.getString("provider"), json);
    getResponse().setStatus(Status.SUCCESS_ACCEPTED);
    return new EmptyRepresentation();
}

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);/*from w ww .  j a  v a 2  s .c o  m*/

        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.prx.prp.utility.ParsedJSONObject.java

public ParsedJSONObject(JSONObject object) {
    int index;/*from   w ww.  ja va 2s. c o m*/
    values = new String[names.length];
    for (index = 0; index < this.names.length; index++) {
        try {
            values[index] = object.getString(names[index]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    checkForDelete(object);
}

From source file:org.prx.prp.utility.ParsedJSONObject.java

private void checkForDelete(JSONObject object) {
    try {/*w w w  .ja  va2  s  .  c o m*/
        if (object.getString("deleted_at") != "null")
            toBeDeleted = true;
        else
            toBeDeleted = false;
    } catch (JSONException e) {
        e.printStackTrace();
    }
}