Example usage for org.json.simple JSONArray toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:com.bigml.histogram.Gap.java

@Override
@SuppressWarnings("unchecked")
public String toString() {
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(_weight);//from w  ww  . j  a  v  a  2  s  . c o m
    jsonArray.add(_startBin);
    jsonArray.add(_endBin);
    return jsonArray.toJSONString();
}

From source file:com.gti.redirects.Redirects.RedirectStorage.java

private boolean writeJsonArray(JSONArray jsonArray) {
    try (FileWriter file = new FileWriter(jsonFile.getPath())) {
        file.write(jsonArray.toJSONString());
        System.out.println("Successfully Copied JSON Object to File...");
        System.out.println("\nJSON Object: " + jsonArray);
        return true;
    } catch (IOException e) {
        e.printStackTrace();//from   w  ww . j  a  v a2  s .c o m
    }
    return false;
}

From source file:compare.handler.get.TableInfoHandler.java

/**
 * Handle a request to get some metadata for a document
 * @param request the http request/*  ww w . j  a  v a2s  . c o  m*/
 * @param response the response
 * @param urn the current urn (ignored)
 * @throws CompareException if loading of MVD failed
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws CompareException {
    Map map = request.getParameterMap();
    docid = request.getParameter(JSONKeys.DOCID);
    version1 = getStringOption(map, Params.VERSION1, "");
    String json = "{}";
    try {
        if (docid != null && docid.length() > 0) {
            EcdosisMVD mvd = loadMVD(Database.CORTEX, docid);
            String selected = getStringOption(map, Params.SELECTED, ALL);
            String baseVersion = selectVersion1(mvd, selected);
            short base = mvd.getBaseVersion(baseVersion);
            int baseLen = getBaseVersionLen(mvd, base);
            int[] offsets = mvd.measureTable(base);
            int numSegs = Math.round((float) offsets.length / (float) CHUNK);
            if (numSegs == 0)
                numSegs = 1;
            int[] segs = new int[numSegs + 1];
            if (numSegs == 2) {
                segs[0] = 0;
                segs[1] = baseLen;
            } else {
                for (int i = 0; i < numSegs; i++)
                    segs[i] = offsets[i * CHUNK];
            }
            segs[segs.length - 1] = baseLen;
            JSONArray arr = new JSONArray();
            for (int i = 0; i < segs.length; i++)
                arr.add(segs[i]);
            json = arr.toJSONString();
        } else
            throw new Exception("CORTEX mvd " + docid + " not found");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    } catch (Exception e) {
        throw new CompareException(e);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.ISTConnectDA.java

private void writeJSONObject(HttpServletResponse response, final JSONArray jsonObject) throws IOException {
    final ServletOutputStream outputStream = response.getOutputStream();
    outputStream.write(jsonObject.toJSONString().getBytes());
    outputStream.close();/*from  w  w  w. j a v a  2s  .  com*/
}

From source file:com.telefonica.iot.cygnus.utils.NGSIUtilsTest.java

/**
 * [NGSIUtils.getGeometry] -------- When getting a geometry, a CartoDB point is obtained when passing
 * an attribute with 'geometry' metadata.
 *//*from   www  .  j a va  2 s .  co m*/
@Test
public void testGetGeometryMetadata() {
    System.out.println(getTestTraceHead("[Utils.getLocation]")
            + "-------- When getting a geometry, a CartoDB point is obtained when passing an attribute "
            + "with 'location' metadata");
    JSONObject metadataJson = new JSONObject();
    metadataJson.put("name", "location");
    metadataJson.put("type", "string");
    metadataJson.put("value", "WGS84");
    JSONArray metadatasJson = new JSONArray();
    metadatasJson.add(metadataJson);
    String attrMetadataStr = metadatasJson.toJSONString();
    String attrValue = "-3.7167, 40.3833";
    String attrType = "coordinates"; // irrelevant for this test
    boolean swapCoordinates = false; // irrelevant for this test
    ImmutablePair<String, Boolean> geometry = NGSIUtils.getGeometry(attrValue, attrType, attrMetadataStr,
            swapCoordinates);

    try {
        assertEquals("ST_SetSRID(ST_MakePoint(-3.7167,40.3833), 4326)", geometry.getLeft());
        System.out.println(getTestTraceHead("[Utils.getLocation]") + "-  OK  - Geometry '" + geometry.getLeft()
                + "' obtained for an attribute with metadata '" + attrMetadataStr + "' and value '" + attrValue
                + "'");
    } catch (AssertionError e) {
        System.out.println(getTestTraceHead("[Utils.getLocation]") + "- FAIL - Geometry '" + geometry.getLeft()
                + "' obtained for an attribute with metadata '" + attrMetadataStr + "' and value '" + attrValue
                + "'");
        throw e;
    } // try catch // try catch
}

From source file:c3.ops.priam.backup.MetaData.java

@SuppressWarnings("unchecked")
public void set(List<AbstractBackupPath> bps, String snapshotName) throws Exception {
    File metafile = createTmpMetaFile();
    FileWriter fr = new FileWriter(metafile);
    try {/*from  www .j  a  va 2s.  c o  m*/
        JSONArray jsonObj = new JSONArray();
        for (AbstractBackupPath filePath : bps)
            jsonObj.add(filePath.getRemotePath());
        fr.write(jsonObj.toJSONString());
    } finally {
        IOUtils.closeQuietly(fr);
    }
    AbstractBackupPath backupfile = pathFactory.get();
    backupfile.parseLocal(metafile, BackupFileType.META);
    backupfile.time = backupfile.parseDate(snapshotName);
    try {
        upload(backupfile);

        addToRemotePath(backupfile.getRemotePath());
        if (metaRemotePaths.size() > 0) {
            notifyObservers();
        }
    } finally {
        FileUtils.deleteQuietly(metafile);
    }
}

From source file:bhl.pages.handler.PagesCropRectHandler.java

/**
 * Get the plain text of a page. Assume parameters version1, pageid 
 * (image file name minus extension) and docid. Assume also that there 
 * is a corcode at docid/pages. (Should already have checked for this)
 * @param request the original http request
 * @param response the response/*from   w  ww.j  av  a 2 s  .  c  om*/
 * @param urn the urn used for the request
 * @throws MissingDocumentException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws MissingDocumentException {
    try {
        Connection conn = Connector.getConnection();
        String pageid = request.getParameter(Params.PAGEID);
        Integer num = new Integer(pageid);
        String content = conn.getFromDbByIntField(Database.PAGES, num.intValue(), JSONKeys.BHL_PAGE_ID);
        JSONObject jobj = (JSONObject) JSONValue.parse(content);
        JSONArray cropRect = (JSONArray) jobj.get(JSONKeys.CROP_RECT);
        if (cropRect == null)
            cropRect = getDefaultCropRect();
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println(cropRect.toJSONString());
    } catch (Exception e) {
        throw new MissingDocumentException(e);
    }
}

From source file:formatter.handler.get.MetadataHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws FormatterException {
    // we need the docid only
    // return the metadata for the document
    try {//from w ww  .j  a  va  2s.  co  m
        this.docid = request.getParameter(Params.DOCID);
        Connection conn = Connector.getConnection();
        String bson = conn.getFromDb(Database.METADATA, docid);
        if (bson != null) {
            JSONObject jObj = (JSONObject) JSONValue.parse(bson);
            JSONArray sources;
            if (jObj.containsKey(JSONKeys.SOURCES)) {
                sources = (JSONArray) jObj.get(JSONKeys.SOURCES);
            } else
                sources = new JSONArray();
            response.setContentType("application/json");
            response.getWriter().write(sources.toJSONString());
        }
    } catch (Exception e) {
        throw new FormatterException(e);
    }
}

From source file:eu.edisonproject.classification.main.BatchMain.java

private static void profile(String csvFile1, String csvFile2, String output) throws IOException, Exception {
    Map<String, Collection<Double>> cv = CSVFileReader.csvCompetanceToMap(csvFile1, ",", Boolean.TRUE);
    Map<String, Collection<Double>> jobVec = CSVFileReader.csvCompetanceToMap(csvFile2, ",", Boolean.TRUE);
    CosineSimilarityMatrix cosineFunction = new CosineSimilarityMatrix();

    String k1 = cv.keySet().iterator().next();
    Map<String, Double> winners = new HashMap<>();
    for (String k : jobVec.keySet()) {
        Collection<Double> j = jobVec.get(k);
        double d = cosineFunction.computeDistance(cv.get(k1), j);
        //      if (!Double.isNaN(d)) {
        winners.put(k, d);/*from   www . ja  va 2s.co m*/
        //      }
    }
    StringBuilder lines = new StringBuilder();
    ReaderFile rf = new ReaderFile(csvFile1);
    String fileHeader = rf.readFileWithN().split("\n")[0];
    String[] header = fileHeader.split(",");
    lines.append("rank").append(",");
    lines.append(fileHeader);
    lines.append("\n");

    int rank = 0;

    JSONObject cvJson = new JSONObject();
    Collection<Double> vector = cv.get(k1);
    String val = vector.toString().replaceAll("\\[", "").replaceAll("\\]", "");
    lines.append(rank).append(",").append(k1).append(",").append(val).append("\n");
    Iterator<Double> iter = vector.iterator();
    int i = 0;
    cvJson.put(header[i++], k1);
    while (iter.hasNext()) {
        String key = header[i++];
        Double value = iter.next();
        cvJson.put(key, value);
    }
    cvJson.put("rank", rank);
    JSONArray profileJson = new JSONArray();
    profileJson.add(cvJson);
    ValueComparator bvc = new ValueComparator(winners);
    Map<String, Double> sorted_map = new TreeMap(bvc);
    sorted_map.putAll(winners);

    for (String k : sorted_map.keySet()) {
        JSONObject jobJason = new JSONObject();
        rank++;
        vector = jobVec.get(k);
        val = vector.toString().replaceAll("\\[", "").replaceAll("\\]", "");
        lines.append(rank).append(",").append(k).append(",").append(val).append("\n");

        i = 0;
        jobJason.put(header[i++], k);
        iter = vector.iterator();
        while (iter.hasNext()) {
            String key = header[i++];
            Double value = iter.next();
            jobJason.put(key, value);
        }
        jobJason.put("rank", rank);
        profileJson.add(jobJason);
    }
    WriterFile wf = new WriterFile(output + File.separator + "result.csv");
    wf.writeFile(lines.toString());

    wf = new WriterFile(output + File.separator + "result.json");
    wf.writeFile(profileJson.toJSONString());
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskResultByUnknownTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/unknownTag/result");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());
    assertEquals(0, jsonArray.size());/* ww w . j ava  2s  . c o  m*/
}