Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

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

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

    try {/*from   w w  w  . j  a v a  2 s. co m*/
        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 {/*from w w  w  .j a  v a 2  s.  com*/
            jsonObj.put(key, bundleObj.get(key));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return jsonObj;
}

From source file:org.wso2.carbon.connector.clevertim.CreateContact.java

/**
 * Create JSON request for CreateContact.
 *
 * @return JSON payload./*from w  w  w  .  j a  v a2 s. co 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();//from   w ww. j  ava  2 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.
 * /* ww w  . ja  v a  2 s  . co  m*/
 */
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  v a 2s  .  com*/
 * @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();
    }
}

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

public @Nonnull APIResponse post(@Nonnull String resource, @Nonnull String json)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + APIHandler.class.getName() + ".post(" + resource + "," + json + ")");
    }/*from   w  ww  . jav  a2  s.  c om*/
    try {
        String target = getEndpoint(resource, null);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [POST (" + (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();
                }

                HttpPost post = new HttpPost(target);

                post.addHeader("Accept", "application/json");
                post.addHeader("Content-type", "application/json");

                if (!resource.contains("Auth/Logon/")) {
                    post.addHeader("Cookie", provider.logon());
                }

                try {
                    post.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(post.getRequestLine().toString());
                    for (Header header : post.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                    wire.debug(json);
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "POST " + resource);
                    response = client.execute(post);
                    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) {
                    throw new CloudException("No such endpoint: " + target);
                }
                if (resource.contains("/Logon/") && status.getStatusCode() == OK) {
                    APIResponse r = new APIResponse();

                    try {
                        JSONObject jsonCookie = new JSONObject();

                        // handle logon response specially
                        Header[] cookieHdrs = response.getHeaders("Set-Cookie");
                        for (int c = 0; c < cookieHdrs.length; c++) {
                            Header cookieHdr = cookieHdrs[c];
                            if (cookieHdr.getValue().startsWith("Tier3.API.Cookie")) {
                                jsonCookie.put("Session", cookieHdr.getValue());
                                break;
                            }
                        }

                        r.receive(status.getStatusCode(), jsonCookie, true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;

                } else if (status.getStatusCode() != ACCEPTED && status.getStatusCode() != CREATED
                        && status.getStatusCode() != OK) {
                    logger.error(
                            "Expected OK, 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 POST");
                    }
                    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("<<< [POST (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + APIHandler.class.getName() + ".post()");
        }
    }
}

From source file:game.objects.Board.java

public JSONArray getBoardJSON() throws JSONException {
    JSONArray arr = new JSONArray();
    for (String key : countries.keySet()) {
        JSONObject json = new JSONObject();
        json.put("CountryID", key);
        json.put("CountryName", countries.get(key).getName());
        json.put("Owner", countries.get(key).getOwner());
        json.put("Troops", countries.get(key).getTroops());
        arr.put(json);// w  w w . j  a  va2  s .  c  om
    }
    return arr;
}

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  . j  a  v a2s .co  m
}

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

private static WebRequest getPostGitCherryPickRequest(String location, String toCherryPick)
        throws JSONException, UnsupportedEncodingException {
    String requestURI = toAbsoluteURI(location);
    JSONObject body = new JSONObject();
    body.put(GitConstants.KEY_CHERRY_PICK, toCherryPick);
    WebRequest request = new PostMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()),
            "UTF-8");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request);//from   ww  w.ja v  a 2  s . c o  m
    return request;
}