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:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java

private ApexClassCodeCoverageBean[] processJSONResponseAndConstructCodeCoverageBeans(
        PartnerConnection connection, JSONObject responseJsonObject) {
    int classCounter = 0;
    int coveredLinesForTheTeam = 0;
    int unCoveredLinesForTheTeam = 0;
    String responseStr = responseJsonObject.toJSONString();
    LOG.debug(responseStr);// w ww .j  ava 2  s  .  com
    JSONArray recordObject = (JSONArray) responseJsonObject.get("records");
    if (recordObject != null && recordObject.size() > 0) {
        ApexClassCodeCoverageBean[] apexClassCodeCoverageBeans = new ApexClassCodeCoverageBean[recordObject
                .size()];
        for (int i = 0; i < recordObject.size(); ++i) {

            ApexClassCodeCoverageBean apexClassCodeCoverageBean = new ApexClassCodeCoverageBean();
            // The object below is one record from the ApexCodeCoverage
            // object
            JSONObject rec = (JSONObject) recordObject.get(i);

            // ApexClassOrTriggerId - The ID of the class or trigger under
            // test.
            String apexClassOrTriggerId = (String) rec.get("ApexClassOrTriggerId").toString();
            if (apexClassOrTriggerId != null) {
                int coveredLines = 0;
                if (rec.get("NumLinesCovered") != null) {
                    coveredLines = Integer.valueOf((String) rec.get("NumLinesCovered").toString());
                    coveredLinesForTheTeam += coveredLines;
                } else {
                    LOG.debug(apexClassOrTriggerId + " has NumLinesCovered as NULL !!!!!!!!!");
                }
                int unCoveredLines = 0;
                if (rec.get("NumLinesUncovered") != null) {
                    unCoveredLines = Integer.valueOf((String) rec.get("NumLinesUncovered").toString());
                    unCoveredLinesForTheTeam += unCoveredLines;
                } else {
                    LOG.debug(apexClassOrTriggerId + " has NumLinesUncovered as NULL !!!!!!!!!");
                }
                if (rec.get("Coverage") != null) {
                    JSONObject codeCoverageLineLists = (JSONObject) rec.get("Coverage");
                    JSONArray coveredLinesJsonArray = (JSONArray) codeCoverageLineLists.get("coveredLines");
                    JSONArray uncoveredLinesJsonArray = (JSONArray) codeCoverageLineLists.get("uncoveredLines");
                    List<Long> coveredLinesList = new ArrayList<Long>();
                    for (int j = 0; j < coveredLinesJsonArray.size(); j++) {
                        coveredLinesList.add((Long) coveredLinesJsonArray.get(j));
                        LOG.debug("covered " + (Long) coveredLinesJsonArray.get(j));
                    }
                    if (coveredLinesList.size() > 0) {
                        apexClassCodeCoverageBean.setCoveredLinesList(coveredLinesList);
                    }

                    List<Long> uncoveredLinesList = new ArrayList<Long>();
                    for (int k = 0; k < uncoveredLinesJsonArray.size(); k++) {
                        uncoveredLinesList.add((Long) uncoveredLinesJsonArray.get(k));
                        LOG.debug("uncovered " + (Long) uncoveredLinesJsonArray.get(k));
                    }
                    if (uncoveredLinesList.size() > 0) {
                        apexClassCodeCoverageBean.setUncoveredLinesList(uncoveredLinesList);
                    }
                }

                apexClassCodeCoverageBean.setNumLinesCovered(coveredLines);
                apexClassCodeCoverageBean.setNumLinesUncovered(unCoveredLines);
                apexClassCodeCoverageBean.setApexClassorTriggerId(apexClassOrTriggerId);
                HashMap<String, String> apexClassInfoMap = ApexClassFetcherUtils
                        .fetchApexClassInfoFromId(connection, apexClassOrTriggerId);
                String apexClassName = apexClassInfoMap.get("Name");
                String apiVersion = apexClassInfoMap.get("ApiVersion");
                String lengthWithoutComments = apexClassInfoMap.get("LengthWithoutComments");
                apexClassCodeCoverageBean.setApexClassName(apexClassName);
                apexClassCodeCoverageBean.setApiVersion(apiVersion);
                apexClassCodeCoverageBean.setLengthWithoutComments(lengthWithoutComments);
                apexClassCodeCoverageBeans[classCounter++] = apexClassCodeCoverageBean;

                LOG.info("Record number # " + classCounter + " : coveredLines : " + coveredLines
                        + " : unCoveredLines : " + unCoveredLines + " : code coverage % : "
                        + apexClassCodeCoverageBean.getCoveragePercentage() + " : apexClassOrTriggerId : "
                        + apexClassOrTriggerId + " : apexClassName : " + apexClassName + " : apiVersion : "
                        + apiVersion + " : lengthWithoutComments : " + lengthWithoutComments);
            }
        }
        double totalLines = coveredLinesForTheTeam + unCoveredLinesForTheTeam;
        if (totalLines > 0.0) {
            ApexUnitCodeCoverageResults.teamCodeCoverage = (coveredLinesForTheTeam / (totalLines)) * 100.0;
        } else {
            ApexUnitCodeCoverageResults.teamCodeCoverage = 100.0;
        }
        LOG.info(
                "####################################   Summary of code coverage computation for the team..  #################################### ");
        LOG.info("Total Covered lines : " + coveredLinesForTheTeam + "\n Total Uncovered lines : "
                + unCoveredLinesForTheTeam);

        LOG.info("Team code coverage is : " + ApexUnitCodeCoverageResults.teamCodeCoverage + "%");
        return apexClassCodeCoverageBeans;
    } else {
        // no code coverage record object found in the response. return null
        return null;
    }
}

From source file:org.kitodo.data.elasticsearch.index.type.HistoryType.java

@SuppressWarnings("unchecked")
@Override//from w ww  .j  av  a2  s. co  m
public HttpEntity createDocument(History history) {

    JSONObject historyObject = new JSONObject();
    historyObject.put("numericValue", history.getNumericValue());
    historyObject.put("stringValue", history.getStringValue());
    historyObject.put("type", history.getHistoryType().getValue());
    String date = history.getDate() != null ? formatDate(history.getDate()) : null;
    historyObject.put("date", date);
    Integer process = history.getProcess() != null ? history.getProcess().getId() : null;
    historyObject.put("process", process);

    return new NStringEntity(historyObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.CircleZone.java

@SuppressWarnings("unchecked")
@Override//  w  w  w . ja  v  a 2 s. c om
public String toJSONString() {
    JSONObject o = new JSONObject();
    o.put("type", "circle");
    o.put("radius", new Double(radius));

    JSONObject c = new JSONObject();
    c.put("lat", new Double(center.getLatitude()));
    c.put("lon", new Double(center.getLongitude()));
    o.put("center", c);

    JSONObject d = new JSONObject();
    d.put("lat", new Double(getDepotPosition().getLatitude()));
    d.put("lon", new Double(getDepotPosition().getLongitude()));
    o.put("depot", c);

    return o.toJSONString();
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> readJson(ArrayList<String> elementsList, JSONObject jsonObject, PrintWriter writer,
        String TagName) throws FileNotFoundException, IOException, ParseException {
    String appId = "";
    if (jsonObject.get(TagName) == null) {
        elementsList.add("null");
    } else {/*from  w  w w  .  jav  a2 s  . co  m*/
        String Objectscontent = jsonObject.get(TagName).toString();
        if (Objectscontent.startsWith("[{") && Objectscontent.endsWith("}]")) {
            JSONArray jsonArray = (JSONArray) jsonObject.get(TagName);

            for (int temp = 0; temp < jsonArray.size(); temp++) {
                System.out.println("Array:" + jsonArray.toJSONString());
                JSONObject jsonObjectResult = (JSONObject) jsonArray.get(temp);
                System.out.println("Result:" + jsonObjectResult.toJSONString());

                Set<String> jsonObjectResultKeySet = jsonObjectResult.keySet();
                System.out.println("KeySet:" + jsonObjectResultKeySet.toString());

                for (String s : jsonObjectResultKeySet) {
                    System.out.println(s);
                    readJson(elementsList, jsonObjectResult, writer, s);
                }
            }
        } else {
            appId = jsonObject.get(TagName).toString();
            elementsList.add(appId);
        }
    }
    return elementsList;
}

From source file:hoot.services.controllers.info.ReportsResourceTest.java

@Test
@Category(UnitTest.class)
public void testGetMetaData() throws Exception {
    String storePath = _rps._homeFolder + "/" + _rps._rptStorePath;
    File f = new File(storePath);
    File fWks = new File(storePath + "/123_test");
    if (fWks.exists()) {
        FileUtils.forceDelete(fWks);/*  w  w w .  ja va 2s  .  c  om*/
    }
    FileUtils.forceMkdir(f);
    JSONObject res = _rps._getMetaData("123_test");
    assertNull(res.get("name"));

    FileUtils.forceMkdir(fWks);
    String currTime = "" + System.currentTimeMillis();
    JSONObject metaData = new JSONObject();
    metaData.put("name", "Test Report1");
    metaData.put("description", "This is test report 1");
    metaData.put("created", currTime);
    metaData.put("reportpath", storePath + "/123_test/report.pdf");
    File meta = new File(storePath + "/123_test/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    res = _rps._getMetaData("123_test");

    org.junit.Assert.assertEquals("Test Report1", res.get("name").toString());
    org.junit.Assert.assertEquals("This is test report 1", res.get("description").toString());
    org.junit.Assert.assertEquals(currTime, res.get("created").toString());
    org.junit.Assert.assertEquals("reportpath", storePath + "/123_test/report.pdf",
            res.get("reportpath").toString());

    FileUtils.forceDelete(fWks);

}

From source file:com.facebook.tsdb.tsdash.server.DataEndpoint.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {//from  w  w  w  . j  a v  a 2s.c om
        long ts = System.currentTimeMillis();
        // decode parameters
        String jsonParams = request.getParameter("params");
        if (jsonParams == null) {
            throw new Exception("Parameters not specified");
        }
        JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams);
        long tsFrom = (Long) jsonParamsObj.get("tsFrom");
        long tsTo = (Long) jsonParamsObj.get("tsTo");
        JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics");
        if (metricsArray.size() == 0) {
            throw new Exception("No metrics to fetch");
        }
        MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()];
        for (int i = 0; i < metricsArray.size(); i++) {
            metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i));
        }

        TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
        Metric[] metrics = new Metric[metricQueries.length];
        for (int i = 0; i < metrics.length; i++) {
            MetricQuery q = metricQueries[i];
            metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders);
            metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator);
            if (q.rate) {
                metrics[i].computeRate();
            }
        }
        long loadTime = System.currentTimeMillis() - ts;
        JSONObject responseObj = new JSONObject();
        JSONArray encodedMetrics = new JSONArray();
        for (Metric metric : metrics) {
            encodedMetrics.add(metric.toJSONObject());
        }
        responseObj.put("metrics", encodedMetrics);
        responseObj.put("loadtime", loadTime);
        DataTable dataTable = new DataTable(metrics);
        responseObj.put("datatable", dataTable.toJSONObject());
        out.println(responseObj.toJSONString());
        long encodingTime = System.currentTimeMillis() - ts - loadTime;
        logger.info("[Data] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, "
                + "encoding time: " + encodingTime + "ms");
    } catch (Exception e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}

From source file:com.mobicage.rogerthat.CallbackApiServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json-rpc; charset=utf-8");

    // Validate incomming request
    final String contentType = req.getHeader("Content-type");
    if (contentType == null || !contentType.startsWith("application/json-rpc")) {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        return;/*from   w w  w .  ja v  a 2  s.c  o  m*/
    }
    final String sikKey = req.getHeader("X-Nuntiuz-Service-Key");
    if (!validateSIK(sikKey)) {
        resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }

    // Parse
    final InputStream is = req.getInputStream();
    final JSONObject request;
    try {
        request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8")));
    } finally {
        is.close();
    }

    if (logTraffic)
        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey,
                request.toJSONString()));

    final String id = (String) request.get("id");

    if (callbackDedup != null) {
        byte[] response = callbackDedup.getResponse(id);
        if (response != null) {
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(response);
            outputStream.flush();
            return;
        }
    }

    final JSONObject result = new JSONObject();
    final RequestContext requestContext = new RequestContext(id, sikKey);
    try {
        processor.process(request, result, requestContext);
    } finally {
        String jsonString = result.toJSONString();
        if (logTraffic)
            log.info("Returning result:\n" + jsonString);

        byte[] response = jsonString.getBytes("UTF-8");
        if (callbackDedup != null) {
            callbackDedup.storeResponse(id, response);
        }

        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(response);
        outputStream.flush();
    }
}

From source file:copter.ServerConnection.java

/**
 * this function make a post request to server and send the copter geo info
 *///from   w  w  w. jav a2  s.c  o  m
public String sendCopterGeoInfoToServer(CopterGpsData gpsData) {
    if (gpsData == null) {
        return "Empty gps data!";
    }
    String copter_unique_id = Config.getInstance().getString("copter", "unique_id");
    JSONObject obj = new JSONObject();
    obj.putAll(gpsData.toMap());
    String postUrl = Config.getInstance().getString("main", "send_gps_data_server_url");
    Map parameters = new HashMap<String, String>();
    parameters.put("unique_id", copter_unique_id);
    parameters.put("gps_data_json", obj.toJSONString());
    return postToServer(postUrl, parameters);
}

From source file:naftoreiclag.villagefive.util.math.Vec2.java

public String toJSONString() {
    JSONObject obj = new JSONObject();

    obj.put("x", this.getX());
    obj.put("y", this.getY());

    return obj.toJSONString();
}

From source file:hoot.services.controllers.job.ExportJobResource.java

/**
 * <NAME>Export Service Job Execute</NAME>
 * <DESCRIPTION>//from   w  w w. j  ava 2s  . c  om
 *    Asynchronous export service.
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    Translation script name.
 * </translation>
 * <inputtype>
 *  [db | file] db means input from hoot db will be used. file mean a file path will be specified.
 * </inputtype>
 * <input>
 * Input name. for inputtype = db then specify name from hoot db. For inputtype=file, specify full path to a file.
 * </input>
 * <outputtype>
 *    [gdb | shp | wfs]. gdb will produce file gdb, shp will output shapefile. if outputtype = wfs then a wfs front end will be created
 * </outputtype>
 * <removereview>
 * Removes all unreviewed items. NOTE: removereview will alway be true.
 * </removereview>
 * </PARAMETERS>
 * <OUTPUT>
 *    Job ID
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/export/execute</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {
* "translation":"MGCP.js",
* "inputtype":"db",
* "input":"ToyTestA",
* "outputtype":"gdb",
* "removereview" : "false"
*
* }
 *   </INPUT>
 * <OUTPUT>{"jobid":"24d1400e-434e-45e0-9afe-372215490be2"}</OUTPUT>
 * </EXAMPLE>
 * @param params
 * @return
 */
@POST
@Path("/execute")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response process(String params) {
    String jobId = UUID.randomUUID().toString();
    jobId = "ex_" + jobId.replace("-", "");
    try {
        JSONArray commandArgs = parseParams(params);

        JSONObject arg = new JSONObject();
        arg.put("outputfolder", tempOutputPath + "/" + jobId);
        commandArgs.add(arg);

        arg = new JSONObject();
        arg.put("output", jobId);
        commandArgs.add(arg);

        String type = getParameterValue("outputtype", commandArgs);
        if (type != null && type.equalsIgnoreCase("wfs")) {
            arg = new JSONObject();
            arg.put("outputname", jobId);
            commandArgs.add(arg);

            String dbname = HootProperties.getProperty("dbName");
            String userid = HootProperties.getProperty("dbUserId");
            String pwd = HootProperties.getProperty("dbPassword");
            String host = HootProperties.getProperty("dbHost");
            String[] hostParts = host.split(":");

            String pgUrl = "host='" + hostParts[0] + "' port='" + hostParts[1] + "' user='" + userid
                    + "' password='" + pwd + "' dbname='" + wfsStoreDb + "'";

            arg = new JSONObject();
            arg.put("PG_URL", pgUrl);
            commandArgs.add(arg);

            JSONObject osm2orgCommand = _createPostBody(commandArgs);
            // this may need change in the future if we decided to use user defined ouputname..
            String outname = jobId;

            JSONArray wfsArgs = new JSONArray();
            JSONObject param = new JSONObject();
            param.put("value", outname);
            param.put("paramtype", String.class.getName());
            param.put("isprimitivetype", "false");
            wfsArgs.add(param);

            JSONObject prepareItemsForReviewCommand = _createReflectionSycJobReq(wfsArgs,
                    "hoot.services.controllers.wfs.WfsManager", "createWfsResource");

            JSONArray jobArgs = new JSONArray();
            jobArgs.add(osm2orgCommand);
            jobArgs.add(prepareItemsForReviewCommand);

            postChainJobRquest(jobId, jobArgs.toJSONString());
        } else {
            // replace with with getParameterValue
            boolean paramFound = false;
            for (int i = 0; i < commandArgs.size(); i++) {
                JSONObject jo = (JSONObject) commandArgs.get(i);
                Object oo = jo.get("outputname");
                if (oo != null) {
                    String strO = (String) oo;
                    if (strO.length() > 0) {
                        paramFound = true;
                        break;
                    }
                }
            }

            if (paramFound == false) {
                arg = new JSONObject();
                arg.put("outputname", jobId);
                commandArgs.add(arg);
            }

            String argStr = createPostBody(commandArgs);
            postJobRquest(jobId, argStr);
        }
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error exporting data: " + ex.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }
    JSONObject res = new JSONObject();
    res.put("jobid", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}