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() 

Source Link

Document

Construct an empty JSONObject.

Usage

From source file:com.sdspikes.fireworks.FireworksTurn.java

public JSONObject getJSONObject() {
    JSONObject retVal = new JSONObject();

    try {//from www.  j a  v  a  2 s. c om
        retVal.put("state", state.getJSONObject());
        retVal.put("turn", turnCounter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return retVal;
}

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

private JSONObject BundleToJSON(Bundle bundleObj) {
    JSONObject jsonObj = new JSONObject();

    Object[] keys = bundleObj.keySet().toArray();

    for (int i = 0; i < keys.length; i++) {
        String key = (String) keys[i];
        try {/*  w w  w .j  a  va2s  .co m*/
            jsonObj.put(key, bundleObj.get(key));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return jsonObj;
}

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

@JavascriptInterface
public void requestWithRestAPI(String[] arguments) {
    if (busy) {/*from  w ww . j a va2  s  .  c o m*/
        sendBusyEvent();
        return;
    }

    if (!session.isOpened()) {
        currentCommand = REQ_REST_API;
        currentCommandArguments = arguments;
        login(defaultLoginPermissions);
        return;
    } else {
        busy = true;
    }

    String command = arguments[0].replace("\"", "");
    String method = arguments[1].replace("\"", "");
    String parameters = arguments[2];

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

    //      try {
    //         json.put("method", "auth.expireSession");
    //      } catch (JSONException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      }

    Bundle params = new Bundle();
    //      params.putString("caption", "caption");
    //      params.putString("message", "message");
    //      params.putString("link", "link_url");
    //      params.putString("picture", "picture_url");
    //params.putString("fields", "id,name,picture");

    //MAKE THE REQUEST
    //mAsyncRunner.request(null, JSONtoBundle(json), method, new FBApiRequestListener(),true);
    Request restRequest = Request.newRestRequest(session, command, JSONtoBundle(json),
            (method.toUpperCase().equals("GET")) ? HttpMethod.GET : HttpMethod.POST);
    //Request restRequest = Request.newRestRequest(session, "me/" + command, params, HttpMethod.POST);
    restRequest.setCallback(new Request.Callback() {

        @Override
        public void onCompleted(Response response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                String js = String.format(
                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                        error.toString());
                //webView.loadUrl(js);
                injectJS(js);
                resetFBStatus();
                return;
                //                 if (error instanceof FacebookOperationCanceledException) {
                //                 }
                //                 else {
                //                    
                //                 }
            } else if (session == Session.getActiveSession()) {
                String responsestr = response.toString().replaceAll("'", "\\\\'");
                responsestr = responsestr.replaceAll("\"", "\\\\\"");

                String js = String.format(
                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=true;e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}e.error='';document.dispatchEvent(e);",
                        responsestr);
                //webView.loadUrl(js);
                injectJS(js);
                resetFBStatus();
                return;
            }
        }
    });
    //Request.executeBatchAsync(restRequest);
    restRequest.executeAndWait();
}

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

@JavascriptInterface
public void requestWithGraphAPI(String[] arguments)// path, String method, String parameters)
{
    if (busy) {// ww  w. ja  va  2s .c o  m
        sendBusyEvent();
        return;
    }

    if (!session.isOpened()) {
        currentCommand = REQ_GRAPH_API;
        currentCommandArguments = arguments;
        login(defaultLoginPermissions);
        return;
    } else {
        busy = true;
    }

    final String path = arguments[0];
    String method = arguments[1];
    String parameters = arguments[2];

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

    final JSONObject finalJson = json;

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            Request graphRequest = Request.newGraphPathRequest(session, path, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        String js = String.format(
                                "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                error.toString());
                        //webView.loadUrl(js);
                        injectJS(js);
                        resetFBStatus();
                        return;
                    } else if (session == Session.getActiveSession()) {
                        GraphObject graphObject = response.getGraphObject();
                        JSONArray array;

                        if (graphObject != null) {
                            JSONObject jsonObject = graphObject.getInnerJSONObject();

                            String responsestr = jsonObject.toString().replaceAll("'", "\\\\'");
                            responsestr = responsestr.replaceAll("\"", "\\\\\"");

                            String js = String.format(
                                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=true;e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}e.error='';document.dispatchEvent(e);",
                                    responsestr);
                            //webView.loadUrl(js);
                            injectJS(js);
                            resetFBStatus();
                            return;
                        } else {
                            String js = String.format(
                                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                    "There was a problem with the FB graph call.");
                            //webView.loadUrl(js);
                            injectJS(js);
                            resetFBStatus();
                            return;
                        }

                    }
                }
            });
            Bundle params = JSONtoBundle(finalJson);
            //params.putString("fields", "name,first_name,last_name");
            graphRequest.setParameters(params);
            graphRequest.executeAndWait();

        }
    });
}

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  ava  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   w w  w  .j  a  v  a  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();
            }

            //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:org.wso2.carbon.connector.clevertim.CreateContact.java

/**
 * Create JSON request for CreateContact.
 *
 * @return JSON payload./*from   ww w  .  ja v  a2s.c o  m*/
 * @throws JSONException thrown when parsing JSON String.
 */
private String getJsonPayload() throws JSONException {

    JSONObject jsonPayload = new JSONObject();

    String firstName = (String) messageContext.getProperty(Constants.FIRST_NAME);
    if (firstName != null && !firstName.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.FIRST_NAME, firstName);
    }
    String lastName = (String) messageContext.getProperty(Constants.LAST_NAME);
    if (lastName != null && !lastName.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.LAST_NAME, lastName);
    }
    String title = (String) messageContext.getProperty(Constants.TITLE);
    if (title != null && !title.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.TITLE, title);
    }
    String description = (String) messageContext.getProperty(Constants.DESCRIPTION);
    if (description != null && !description.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.DESCRIPTION, description);
    }
    String isCompany = (String) messageContext.getProperty(Constants.IS_COMPANY);
    if (isCompany != null && !isCompany.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.IS_COMPANY, isCompany);
    }
    String companyId = (String) messageContext.getProperty(Constants.COMPANY_ID);
    if (companyId != null && !companyId.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.COMPANY_ID, companyId);
    }
    String email = (String) messageContext.getProperty(Constants.EMAIL);
    if (email != null && !email.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.EMAIL, new JSONArray(email));
    }
    String phones = (String) messageContext.getProperty(Constants.PHONES);
    if (phones != null && !phones.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.PHONES, new JSONArray(phones));
    }
    String website = (String) messageContext.getProperty(Constants.WEBSITE);
    if (website != null && !website.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.WEBSITE, new JSONArray(website));
    }
    String address = (String) messageContext.getProperty(Constants.ADDRESS);
    if (address != null && !address.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.ADDRESS, address);
    }
    String city = (String) messageContext.getProperty(Constants.CITY);
    if (city != null && !city.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CITY, city);
    }
    String postCode = (String) messageContext.getProperty(Constants.POST_CODE);
    if (postCode != null && !postCode.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.POST_CODE, postCode);
    }
    String country = (String) messageContext.getProperty(Constants.COUNTRY);
    if (country != null && !country.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.COUNTRY, country);
    }
    String socialMediaIds = (String) messageContext.getProperty(Constants.SOCIAL_MEDIA_IDS);
    if (socialMediaIds != null && !socialMediaIds.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.SOCIAL_MEDIA_IDS, new JSONArray(socialMediaIds));
    }
    String customerType = (String) messageContext.getProperty(Constants.CUSTOMER_TYPE);
    if (customerType != null && !customerType.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CUSTOMER_TYPE, customerType);
    }
    String customFields = (String) messageContext.getProperty(Constants.CUSTOM_FIELDS);
    if (customFields != null && !customFields.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CUSTOM_FIELD, new JSONObject(customFields));
    }
    String tags = (String) messageContext.getProperty(Constants.TAGS);
    if (tags != null && !tags.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.TAGS, new JSONArray(tags));
    }

    return jsonPayload.toString();
}

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

public static void setResourceAndWorkspace(String resourceName, String workspaceName, String pluginName)
        throws Exception {

    props = getProperties();//w  ww  .  j  a va2  s.c  o  m
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();
    jo.put("projectName", pluginName);
    jo.put("resourceName", resourceName);
    jo.put("workspaceName", workspaceName);

    HttpPut httpPutRequest = new HttpPut("http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
            + ":8000/rest/v1.0/projects/" + pluginName);

    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))));
    StringEntity input = new StringEntity(jo.toString());

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

    if (httpResponse.getStatusLine().getStatusCode() >= 400) {
        throw new RuntimeException("Failed to set resource  " + resourceName + " to project " + pluginName);
    }
    System.out.println("Set the resource as " + resourceName + " and workspace as " + workspaceName
            + " successfully for " + pluginName);
}

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

/**
 * Creates a new workspace. If the workspace already exists,It continues.
 * //from   w  w w  . ja  va  2 s  . c  om
 */
static void createCommanderWorkspace(String workspaceName) throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();

    try {

        String url = "http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/workspaces/";
        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(url);
        jo.put("workspaceName", workspaceName);
        jo.put("description", workspaceName);
        jo.put("agentDrivePath", "C:/Program Files/Electric Cloud/ElectricCommander");
        jo.put("agentUncPath", "C:/Program Files/Electric Cloud/ElectricCommander");
        jo.put("agentUnixPath", "/opt/electriccloud/electriccommander");
        jo.put("local", true);

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

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

        if (httpResponse.getStatusLine().getStatusCode() == 409) {
            System.out.println("Commander workspace already exists.Continuing....");
        } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException(
                    "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode() + "-"
                            + httpResponse.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

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

/**
 * //from   w  w w  .j  a va  2  s .c  o m
 * @return
 */
static void createCommanderResource(String resourceName, String workspaceName, String resourceIP)
        throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();

    try {
        HttpPost httpPostRequest = new HttpPost(
                "http://" + props.getProperty(StringConstants.COMMANDER_SERVER) + ":8000/rest/v1.0/resources/");
        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))));

        jo.put("resourceName", resourceName);
        jo.put("description", "Resource created for test automation");
        jo.put("hostName", resourceIP);
        jo.put("port", StringConstants.EC_AGENT_PORT);
        jo.put("workspaceName", workspaceName);
        jo.put("pools", "default");
        jo.put("local", true);

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

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

        if (httpResponse.getStatusLine().getStatusCode() == 409) {
            System.out.println("Commander resource already exists.Continuing....");

        } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException(
                    "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode() + "-"
                            + httpResponse.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}