Example usage for org.json.simple JSONObject toJSONString

List of usage examples for org.json.simple JSONObject toJSONString

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:org.opencastproject.adminui.endpoint.UsersSettingsEndpointTest.java

@Test
public void testPostSettingExpectsOK() throws ParseException, IOException {
    String key = "example_key";
    String value = "example_value";

    JSONObject actual = (JSONObject) parser.parse(given().formParam("key", key).formParam("value", value).log()
            .all().expect().statusCode(HttpStatus.SC_OK).contentType(ContentType.JSON).body("key", equalTo(key))
            .body("value", equalTo(value)).when().post(rt.host("setting")).asString());
    System.out.println(actual.toJSONString());
}

From source file:com.acmeair.jmeter.functions.UpdateCustomerFunction.java

/**
 * sample input:/* ww  w .  java2s  .c  o m*/
 * {"username":"uid53800@email.com","status":"GOLD","total_miles"
 * :1000000,"miles_ytd"
 * :1000,"phoneNumber":"919-123-4567","phoneNumberType":"BUSINESS"
 * ,"address":
 * {"streetAddress1":"123 Main St.","city":"Anytown","stateProvince"
 * :"NC","country":"USA","postalCode":"27617"}} sample
 * output:{"username":"uid53800@email.com"
 * ,"password":"password","status":"GOLD"
 * ,"total_miles":1000000,"miles_ytd":1000
 * ,"phoneNumber":"919-123-4567","phoneNumberType"
 * :"BUSINESS","address":{"streetAddress1"
 * :"124 Main St.","city":"Anytown","stateProvince"
 * :"NC","country":"USA","postalCode":"27618"}}
 * 
 * @param responseDataAsString
 * @return
 */
@SuppressWarnings("unchecked")
synchronized public String processJSonString(String responseDataAsString) {
    try {
        if (responseDataAsString == null)
            return "{}";
        JSONObject json = (JSONObject) new JSONParser().parse(responseDataAsString);
        JSONObject jsonAddress = (JSONObject) json.get("address");
        jsonAddress.put("streetAddress1", updateAddress(jsonAddress.get("streetAddress1").toString()));
        jsonAddress.put("postalCode", updatePostalCode(jsonAddress.get("postalCode").toString()));
        json.put("password", "password");
        return json.toJSONString();

    } catch (ParseException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
        System.out.println(
                "NullPointerException in UpdateCustomerFunction - ResponseData =" + responseDataAsString);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java

public int getOrgWideCodeCoverage() {
    String relativeServiceURL = "/services/data/v" + SUPPORTED_VERSION + "/tooling";
    String soql = QueryConstructor.getOrgWideCoverage();
    int coverage = 0;
    JSONObject responseJsonObject = null;
    responseJsonObject = WebServiceInvoker.doGet(relativeServiceURL, soql, OAuthTokenGenerator.getOrgToken());

    if (responseJsonObject != null) {
        String responseStr = responseJsonObject.toJSONString();
        LOG.debug("responseStr during org wide code coverage" + responseStr);
        JSONArray recordObject = (JSONArray) responseJsonObject.get("records");
        for (int i = 0; i < recordObject.size(); ++i) {

            JSONObject rec = (JSONObject) recordObject.get(i);

            coverage = Integer.valueOf((String) rec.get("PercentCovered").toString());
            LOG.info(/*from w ww  .  jav  a2s .c o m*/
                    "####################################   Org wide code coverage result  #################################### ");
            LOG.info("Org wide code coverage : " + coverage + "%");
        }
    } else {
        ApexUnitUtils.shutDownWithErrMsg("Org wide code coverage not computed");
    }
    ApexUnitCodeCoverageResults.orgWideCodeCoverage = coverage;
    return coverage;
}

From source file:com.ganji.tungsten.replicator.applier.GanjiMcQueueApplier.java

private boolean insert2Queue(String schema, String table, String actionName, JSONObject obj, Timestamp tm)
        throws ApplierException {
    obj.put("__schema", schema);
    obj.put("__table", table);
    obj.put("__action", actionName);
    obj.put("__ts", tm.getTime());

    Future<Boolean> f = mc_conn.set(queue_name, 0, obj.toJSONString());
    try {/*from  w w  w  . jav a2s . c o  m*/
        Boolean b = f.get();
        return b.booleanValue();
    } catch (InterruptedException e) {
        throw new ApplierException(e);
    } catch (ExecutionException e) {
        throw new ApplierException(e);
    }

    //return false;
}

From source file:com.fujitsu.dc.test.jersey.cell.auth.BasicAuthODataCollectionLevelTest.java

/**
 * Basic?OData????.//from w  w  w  .  jav  a 2s .  c  o m
 * @throws InterruptedException
 */
@SuppressWarnings("unchecked")
private void userData() {
    String propertyValue = "proeprty";

    JSONObject jsonBody = new JSONObject();
    jsonBody.put("__id", srcUserId);
    jsonBody.put("property", propertyValue);
    String stringBody = jsonBody.toJSONString();

    try {
        // OData?(Basic?-?)
        UserDataUtils.createWithBasic(userName, password, HttpStatus.SC_CREATED,
                stringBody, cellName, boxName, colName, srcEntityTypeName);
        // OData?(Basic?-)
        TResponse res = UserDataUtils.createWithBasic(userName + "invalid", password, HttpStatus.SC_UNAUTHORIZED,
                stringBody, cellName, boxName, colName, srcEntityTypeName);
        checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName);
        // ?????????
        AuthTestCommon.waitForAccountLock();

        // OData?(Basic?-?)
        UserDataUtils.getWithQueryAnyAuthSchema(cellName, token, boxName, colName, srcEntityTypeName, "",
                srcUserId,
                HttpStatus.SC_OK);
        // OData?(Basic?-)
        res = UserDataUtils.getWithQueryAnyAuthSchema(cellName, invalidToken, boxName, colName, srcEntityTypeName,
                "", srcUserId, HttpStatus.SC_UNAUTHORIZED);
        checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName);
        // ?????????
        AuthTestCommon.waitForAccountLock();

        // OData(Basic?-?)
        UserDataUtils.updateAnyAuthSchema(token, HttpStatus.SC_NO_CONTENT, jsonBody, cellName, boxName, colName,
                srcEntityTypeName, srcUserId, "*");
        // OData(Basic?-)
        res = UserDataUtils.updateAnyAuthSchema(invalidToken, HttpStatus.SC_UNAUTHORIZED, jsonBody, cellName,
                boxName, colName, srcEntityTypeName, srcUserId, "*");
        checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName);
        // ?????????
        AuthTestCommon.waitForAccountLock();

        // OData(Basic?-?)
        UserDataUtils.mergeAnyAuthSchema(token, HttpStatus.SC_NO_CONTENT, jsonBody, cellName, boxName, colName,
                srcEntityTypeName, srcUserId, "*");
        // OData(Basic?-)
        res = UserDataUtils.mergeAnyAuthSchema(invalidToken, HttpStatus.SC_UNAUTHORIZED, jsonBody, cellName,
                boxName, colName, srcEntityTypeName, srcUserId, "*");
        checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName);
        // ?????????
        AuthTestCommon.waitForAccountLock();

        // OData?(Basic?-?)
        UserDataUtils.listAnyAuthSchema(cellName, boxName, colName, srcEntityTypeName, "", token, HttpStatus.SC_OK);
        // OData?(Basic?-)
        res = UserDataUtils.listAnyAuthSchema(cellName, boxName, colName, srcEntityTypeName, "", invalidToken,
                HttpStatus.SC_UNAUTHORIZED);
        checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName);
        // ?????????
        AuthTestCommon.waitForAccountLock();

        // OData(Basic?-?)
        UserDataUtils.deleteAnyAuthSchema(token, HttpStatus.SC_NO_CONTENT, cellName, boxName, colName,
                srcEntityTypeName, srcUserId);
        // OData(Basic?-)
        res = UserDataUtils.deleteAnyAuthSchema(invalidToken, HttpStatus.SC_UNAUTHORIZED, cellName, boxName,
                colName, srcEntityTypeName, srcUserId);
        checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName);
        // ?????????
        AuthTestCommon.waitForAccountLock();
    } finally {
        // OData
        UserDataUtils.delete(AbstractCase.MASTER_TOKEN_NAME, -1, cellName, boxName, colName, srcEntityTypeName,
                srcUserId);
    }
}

From source file:org.ow2.proactive.procci.service.RequestUtils.java

/**
 * Send a service to pca service with a header containing the session id and sending content
 *
 * @param content is which is send to the cloud automation service
 * @return the information about gathered from cloud automation service
 *//*from   ww w . j  a  va2s  . c o  m*/
public JSONObject postRequest(JSONObject content, String url) {

    final String PCA_SERVICE_SESSIONID = "sessionid";
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost postRequest = new HttpPost(url);
        postRequest.addHeader(PCA_SERVICE_SESSIONID, getSessionId());
        StringEntity input = new StringEntity(content.toJSONString());
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        String serverOutput = readHttpResponse(response, url, "POST " + content.toJSONString());
        return parseJSON(serverOutput);
    } catch (IOException ex) {
        logger.error(" IO exception in CloudAutomationInstanceClient::postRequest ", ex);
        throw new ServerException();
    }
}

From source file:com.glluch.ecf2xmlmaven.Competence.java

public void jsonIEEEWriter(String path) throws IOException {
    String m = this.terms.toString();
    JSONObject jsonCompetence = new JSONObject();
    jsonCompetence.put("code", this.code);
    jsonCompetence.put("txt", m);
    String fileTitle = this.code + "json";
    FileUtils.writeStringToFile(new File(path + fileTitle), jsonCompetence.toJSONString(), "utf8");
}

From source file:com.appdynamics.monitors.pingdom.communicator.PingdomCommunicator.java

@SuppressWarnings("rawtypes")
private void getChecks(Map<String, Integer> metrics) {

    try {/*  www. jav a2s.com*/
        HttpClient httpclient = new DefaultHttpClient();

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        HttpGet httpget = new HttpGet(baseAddress + "/api/2.0/checks");
        httpget.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        httpget.addHeader("App-Key", appkey);

        HttpResponse response;
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        // reading in the JSON response
        String result = "";
        if (entity != null) {
            InputStream instream = entity.getContent();
            int b;
            try {
                while ((b = instream.read()) != -1) {
                    result += Character.toString((char) b);
                }
            } finally {
                instream.close();
            }
        }

        // parsing the JSON response
        try {

            JSONParser parser = new JSONParser();

            ContainerFactory containerFactory = new ContainerFactory() {

                public List creatArrayContainer() {
                    return new LinkedList();
                }

                public Map createObjectContainer() {
                    return new LinkedHashMap();
                }

            };

            // retrieving the metrics and populating HashMap
            JSONObject obj = (JSONObject) parser.parse(result);
            if (obj.get("checks") == null) {
                logger.error("Error retrieving data. " + obj);
                return;
            }
            JSONArray array = (JSONArray) parser.parse(obj.get("checks").toString());
            for (Object checkObj : array) {
                JSONObject check = (JSONObject) checkObj;

                Map json = (Map) parser.parse(check.toJSONString(), containerFactory);

                String metricName = "";

                if (json.containsKey("name")) {
                    metricName = "Checks|" + json.get("name") + "|";
                } else {
                    logger.error("Encountered error while parsing metrics for a check: no name found!");
                    continue;
                }

                if (json.containsKey("id")) {
                    try {
                        metrics.put(metricName + "id", Integer.parseInt(json.get("id").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "id");
                    }
                }

                if (json.containsKey("lastresponsetime")) {
                    try {
                        metrics.put(metricName + "lastresponsetime",
                                Integer.parseInt(json.get("lastresponsetime").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "lastresponsetime");
                    }
                }

                if (json.containsKey("lasttesttime")) {
                    try {
                        int testTime = Integer.parseInt(json.get("lasttesttime").toString());
                        java.util.Date date = new java.util.Date(testTime);
                        Calendar cal = GregorianCalendar.getInstance();
                        cal.setTime(date);

                        metrics.put(metricName + "lasttesttime", cal.get(Calendar.HOUR_OF_DAY));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "lasttesttime");
                    } catch (Throwable t) {
                        logger.error("Error parsing metric value for " + metricName
                                + "lasttesttime: can't get hour of day");
                    }
                }

                if (json.containsKey("resolution")) {
                    try {
                        metrics.put(metricName + "resolution",
                                Integer.parseInt(json.get("resolution").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "resolution");
                    }
                }

                if (json.containsKey("status")) {
                    String status = json.get("status").toString();
                    if (status != null) {
                        if (status.equals("down")) {
                            metrics.put(metricName + "status", 0);
                        } else if (status.equals("up")) {
                            metrics.put(metricName + "status", 1);
                        } else if (status.equals("unconfirmed_down")) {
                            metrics.put(metricName + "status", 5);
                        } else if (status.equals("unknown")) {
                            metrics.put(metricName + "status", 20);
                        } else if (status.equals("paused")) {
                            metrics.put(metricName + "status", 50);
                        } else {
                            logger.error("Error parsing metric value for " + metricName
                                    + "status: Unknown status '" + status + "'");
                        }
                    } else {
                        logger.error("Error parsing metric value for " + metricName + "status");
                    }
                }
            }

        } catch (ParseException e) {
            logger.error("JSON Parsing error: " + e.getMessage());
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }

        // parse header in the end to get the Req-Limits
        Header[] responseHeaders = response.getAllHeaders();
        getLimits(metrics, responseHeaders);
    } catch (IOException e1) {
        logger.error(e1.getMessage());
    } catch (Throwable t) {
        logger.error(t.getMessage());
    }

}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java

/**
 * This method is not used currently Calculate code coverage results for the
 * Apex classes using Tooling API's This method is intended to provide code
 * coverage at method level for each class . This indicates which exact
 * method needs more coverage//from  w w  w .j av  a  2s .c o m
 * 
 * @return
 */
public void calculateCodeCoverageUsingToolingAPI(String classArrayAsStringForQuery) {
    int classCounter = 0;
    String relativeServiceURL = "/services/data/v" + SUPPORTED_VERSION + "/tooling";
    String soqlcc = QueryConstructor.getClassLevelCodeCoverage(classArrayAsStringForQuery);
    LOG.debug("OAuthTokenGenerator.getOrgToken() : " + OAuthTokenGenerator.getOrgToken());
    JSONObject responseJsonObject = null;
    responseJsonObject = WebServiceInvoker.doGet(relativeServiceURL, soqlcc, OAuthTokenGenerator.getOrgToken());

    if (responseJsonObject != null) {
        String responseStr = responseJsonObject.toJSONString();
        LOG.debug(responseStr);
        JSONArray recordObject = (JSONArray) responseJsonObject.get("records");
        for (int i = 0; i < recordObject.size(); ++i) {
            classCounter++;
            // The object below is one record from the ApexCodeCoverage
            // object
            JSONObject rec = (JSONObject) recordObject.get(i);

            int coveredLines = Integer.valueOf((String) rec.get("NumLinesCovered").toString());
            int unCoveredLines = Integer.valueOf((String) rec.get("NumLinesUncovered").toString());
            // ApexTestClassId - The ID of the test class.
            String apexTestClassID = (String) rec.get("ApexTestClassId").toString();
            // ApexClassOrTriggerId - The ID of the class or trigger under
            // test.
            String apexClassorTriggerId = (String) rec.get("ApexClassOrTriggerId").toString();
            String testMethodName = (String) rec.get("TestMethodName").toString();
            LOG.info("Record number # " + classCounter + " : coveredLines : " + coveredLines
                    + " : unCoveredLines : " + unCoveredLines + " : apexTestClassID : " + apexTestClassID
                    + " : apexClassorTriggerId : " + apexClassorTriggerId + " : testMethodName : "
                    + testMethodName);

        }

    }
}

From source file:com.glluch.ecf2xmlmaven.Competence.java

public void jsonWriterRaw(String path) throws IOException {
    String m = this.code;
    m += " " + this.toString();
    m = m.replace("\n", " ");
    JSONObject jsonCompetence = new JSONObject();
    jsonCompetence.put("code", this.code);
    jsonCompetence.put("txt", m);
    String fileTitle = this.code + ".json";
    FileUtils.writeStringToFile(new File(path + fileTitle), jsonCompetence.toJSONString(), "utf8");

}