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:hoot.services.controllers.info.ReportsResourceTest.java

@Test
@Category(UnitTest.class)
public void testGetReportsList() throws Exception {
    String storePath = _rps._homeFolder + "/" + _rps._rptStorePath;
    File f = new File(storePath);
    File fWks1 = new File(storePath + "/123_test1");
    if (fWks1.exists()) {
        FileUtils.forceDelete(fWks1);//from   w  ww.  j a  v a  2s  .co m
    }

    File fWks2 = new File(storePath + "/123_test2");
    if (fWks2.exists()) {
        FileUtils.forceDelete(fWks2);
    }

    File fWks3 = new File(storePath + "/123_test3");
    if (fWks3.exists()) {
        FileUtils.forceDelete(fWks3);
    }
    FileUtils.forceMkdir(f);

    FileUtils.forceMkdir(fWks1);
    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_test1/report.pdf");
    File meta = new File(storePath + "/123_test1/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    FileUtils.forceMkdir(fWks2);
    currTime = "" + System.currentTimeMillis();
    metaData = new JSONObject();
    metaData.put("name", "Test Report2");
    metaData.put("description", "This is test report 2");
    metaData.put("created", currTime);
    metaData.put("reportpath", storePath + "/123_test2/report.pdf");
    meta = new File(storePath + "/123_test2/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    FileUtils.forceMkdir(fWks3);
    currTime = "" + System.currentTimeMillis();
    metaData = new JSONObject();
    metaData.put("name", "Test Report3");
    metaData.put("description", "This is test report 3");
    metaData.put("created", currTime);
    metaData.put("reportpath", storePath + "/123_test3/report.pdf");
    meta = new File(storePath + "/123_test3/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    JSONArray out = _rps._getReportsList();

    int nCount1 = 0;
    int nCount2 = 0;
    int nCount3 = 0;
    for (Object o : out) {
        JSONObject jo = (JSONObject) o;
        if (jo.get("name").toString().equals("Test Report1")) {
            nCount1++;
        }

        if (jo.get("name").toString().equals("Test Report2")) {
            nCount2++;
        }

        if (jo.get("name").toString().equals("Test Report3")) {
            nCount3++;
        }

    }

    assertEquals(1, nCount1);
    assertEquals(1, nCount2);
    assertEquals(1, nCount3);

    FileUtils.forceDelete(fWks1);
    FileUtils.forceDelete(fWks2);
    FileUtils.forceDelete(fWks3);
}

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

@SuppressWarnings("unchecked")
@Override/* ww  w .jav a2s  .c  o  m*/
public HttpEntity createDocument(Process process) {

    LinkedHashMap<String, String> orderedProcessMap = new LinkedHashMap<>();
    orderedProcessMap.put("name", process.getTitle());
    orderedProcessMap.put("outputName", process.getOutputName());
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String creationDate = process.getCreationDate() != null ? dateFormat.format(process.getCreationDate())
            : null;
    orderedProcessMap.put("creationDate", creationDate);
    orderedProcessMap.put("wikiField", process.getWikiField());
    String project = process.getProject() != null ? process.getProject().getId().toString() : "null";
    orderedProcessMap.put("project", project);
    String ruleset = process.getRuleset() != null ? process.getRuleset().getId().toString() : "null";
    orderedProcessMap.put("ruleset", ruleset);
    String ldapGroup = process.getDocket() != null ? process.getDocket().getId().toString() : "null";
    orderedProcessMap.put("ldapGroup", ldapGroup);

    JSONObject processObject = new JSONObject(orderedProcessMap);

    JSONArray properties = new JSONArray();
    List<ProcessProperty> processProperties = process.getProperties();
    for (ProcessProperty property : processProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

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

From source file:cpd3314.project.ProductTest.java

/**
 * Test of toJSON method, of class Product.
 *//*from   w  ww .  java2 s .c  o m*/
@Test
public void testToJSON() throws Exception {
    System.out.println("toJSON");
    Product instance = sample;
    JSONObject expected = new JSONObject();
    expected.put("name", sampleName);
    expected.put("id", sampleId);
    expected.put("description", sampleDesc);
    expected.put("quantity", sampleQuantity);
    expected.put("dateAdded", sampleDate);
    String result = instance.toJSON();
    JSONObject resultJSON = (JSONObject) JSONValue.parse(result);
    assertEquals(expected.toJSONString(), resultJSON.toJSONString());
}

From source file:connectivity.connection.java

public void getUserDetails() throws MalformedURLException, IOException, ParseException, SQLException {

    PreparedStatement ps = con.prepareStatement(
            "Select user_id from users where lastname is null and homecity is null and complete_profile is null; ");

    ResultSet rs = ps.executeQuery();

    while (rs.next()) {
        String url = "https://api.foursquare.com/v2/users/" + rs.getString("user_id")
                + "?client_id=3TFPJDCOB4NUNEX10RUZAT0EQ5OSQI1A2WZGDLVET2LRVV1I&client_secret=0Y1UEDME1QPXRQICNIHVZGZKSXOLWDMCVLJTPI5ZOXEDTB3I&v=20150317";
        String jsonresp = "";

        //print result

        try {/*from  w w  w . ja  v  a2s. c  om*/
            URL obj = new URL(url);
            HttpURLConnection htcon = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            htcon.setRequestMethod("GET");

            //System.out.println("\nSending 'GET' request to URL : " + url);
            //System.out.println("Response Code : " + responseCode);

            try (BufferedReader in = new BufferedReader(new InputStreamReader(htcon.getInputStream()))) {
                jsonresp = in.readLine();
            }
            JSONObject responsejson = (JSONObject) new JSONParser().parse(jsonresp);
            JSONObject responseObj = (JSONObject) new JSONParser()
                    .parse(responsejson.get("response").toString());
            JSONObject User = (JSONObject) new JSONParser().parse(responseObj.get("user").toString());
            //System.out.println(jsonresp);
            String Lastname = (String) User.get("lastName");
            String homeCity = (String) User.get("homeCity");
            String Complete_Profile = User.toJSONString();
            st = con.prepareStatement(
                    "UPDATE `users` SET `lastname`=?, `homecity`=?, `complete_profile`=? WHERE `user_id`=?;");
            st.setString(1, Lastname);
            st.setString(2, homeCity);
            st.setString(3, Complete_Profile);
            st.setString(4, rs.getString("user_id"));
            st.execute();
        } catch (IOException | ParseException e) {
            System.out.println("Error occured for user_id=" + rs.getString("user_id") + " error=" + e + " json="
                    + jsonresp);
            System.out.println("URL=" + url);
        } catch (SQLException e) {
            System.out.println("Sql Exception occured occured for user_id=" + rs.getString("user_id")
                    + " error=" + e + " json=" + jsonresp);
            System.out.println("URL=" + url);
        }
    }

    //st.executeBatch();

}

From source file:com.des.paperbase.ManageData.java

public void insert(String Tablename, Map<String, Object> value) throws IOException, ParseException {
    String data = g.readFileToString(PATH_FILE + "\\" + Tablename + ".json");
    JSONObject table = new JSONObject();
    JSONObject field = new JSONObject();
    JSONArray record = new JSONArray();
    List<String> keySet = g.getKeyFromMap(value);
    if (data.equalsIgnoreCase("{\"data\":[]}")) {
        for (int i = 0; i < keySet.size(); i++) {
            field.put(keySet.get(i), value.get(keySet.get(i)));
        }/*w ww.  j  a v  a2  s.co m*/
        record.add(field);
        table.put("data", record);
        g.writefile(table.toJSONString(), PATH_FILE + "\\" + Tablename + ".json");
    } else {
        JSONObject json = (JSONObject) new JSONParser().parse(data);
        JSONArray OldValue = (JSONArray) json.get("data");
        for (int i = 0; i < keySet.size(); i++) {
            field.put(keySet.get(i), value.get(keySet.get(i)));
        }
        OldValue.add(field);
        json.put("data", OldValue);
        g.writefile(json.toJSONString(), PATH_FILE + "\\" + Tablename + ".json");
    }
}

From source file:de.metalcon.musicStorageServer.protocol.CreateRequestTest.java

@SuppressWarnings("unchecked")
@Before//from   w ww  .j  a va2  s  . c o  m
public void setUp() throws IOException {
    DISK_FILE_REPOSITORY.delete();
    DISK_FILE_REPOSITORY.mkdirs();

    // MP3 music item
    final File musicItemMp3 = new File(TEST_FILE_DIRECTORY, "mp3.mp3");
    VALID_MUSIC_ITEM_MP3 = createMusicItem("audio/mpeg", musicItemMp3);
    assertEquals(musicItemMp3.length(), VALID_MUSIC_ITEM_MP3.getSize());

    // meta data
    final JSONObject metaDataCreate = new JSONObject();
    metaDataCreate.put("title", "My Great Song");
    metaDataCreate.put("album", "Testy Forever");
    metaDataCreate.put("artist", "Testy");
    metaDataCreate.put("license", "General Less AllYouCanEat License");
    metaDataCreate.put("date", "1991-11-11");
    metaDataCreate.put("description", "All your cookies belong to me!");
    VALID_CREATE_META_DATA = metaDataCreate.toJSONString();
}

From source file:edu.vt.vbi.patric.portlets.ExperimentListPortlet.java

private Map processComparisonTab(ResourceRequest request) throws IOException {

    String pk = request.getParameter("pk");
    String keyword = request.getParameter("keyword");
    String eId = request.getParameter("eId");
    String facet = request.getParameter("facet");
    Map<String, String> key = new HashMap<>();

    String json = SessionHandler.getInstance().get(SessionHandler.PREFIX + pk);
    if (json == null) {
        key.put("facet", facet);
        key.put("keyword", keyword);
        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));
    } else {//from  www . j  a va 2  s .c om
        key = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
        key.put("facet", facet);
    }

    //      String orig_keyword = key.get("keyword");
    DataApiHandler dataApi = new DataApiHandler(request);

    if (eId != null && !eId.equals("")) {
        key.put("keyword", "eid: (" + eId.replaceAll(",", " OR ") + ")");

    } else if (eId != null && eId.equals("")) {

        List<String> eIdList = new ArrayList<>();

        SolrQuery query = dataApi.buildSolrQuery(key, null, facet, 0, 10000, false);

        LOGGER.trace("processComparisonTab: [{}] {}", SolrCore.TRANSCRIPTOMICS_EXPERIMENT.getSolrCoreName(),
                query);

        String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_EXPERIMENT, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");

        List<Map> sdl = (List<Map>) respBody.get("docs");
        for (Map doc : sdl) {
            eIdList.add(doc.get("eid").toString());
        }

        key.put("keyword", "eid: (" + StringUtils.join(eIdList, " OR ") + ")");

        if (resp.containsKey("facet_counts")) {
            JSONObject facets = FacetHelper.formatFacetTree((Map) resp.get("facet_counts"));
            key.put("facets", facets.toJSONString());
            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));
        }
    }

    String start_id = request.getParameter("start");
    String limit = request.getParameter("limit");
    int start = 0;
    int end = -1;
    if (start_id != null) {
        start = Integer.parseInt(start_id);
    }
    if (limit != null) {
        end = Integer.parseInt(limit);
    }

    String sort = request.getParameter("sort");

    key.put("fields",
            "eid,expid,accession,pid,samples,expname,release_date,pmid,organism,strain,mutant,timepoint,condition,genes,sig_log_ratio,sig_z_score");

    SolrQuery query = dataApi.buildSolrQuery(key, sort, null, start, end, false);

    LOGGER.trace("processComparisonTab: [{}] {}", SolrCore.TRANSCRIPTOMICS_COMPARISON.getSolrCoreName(), query);

    String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_COMPARISON, query);

    Map resp = jsonReader.readValue(apiResponse);
    Map respBody = (Map) resp.get("response");
    List<Map> comparisons = (List<Map>) respBody.get("docs");

    int numFound = (Integer) respBody.get("numFound");

    Map response = new HashMap();
    response.put("key", key);
    response.put("numFound", numFound);
    response.put("comparisons", comparisons);

    return response;
}

From source file:bizlogic.Sensors.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st = null;/*from  w ww  .  j  av a2 s. co m*/
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Sensors.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    try {
        FileWriter sensorsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/sensors.json");
        sensorsFile.write("");
        sensorsFile.flush();

        JSONParser parser = new JSONParser();

        JSONObject Records = new JSONObject();

        JSONObject operation_Obj = new JSONObject();
        JSONObject operand_Obj = new JSONObject();
        JSONObject unit_Obj = new JSONObject();
        JSONObject name_Obj = new JSONObject();
        JSONObject ip_Obj = new JSONObject();
        JSONObject port_Obj = new JSONObject();

        int _total = 0;

        JSONArray sensorList = new JSONArray();

        while (rs.next()) {

            JSONObject sensor_Obj = new JSONObject();
            int id = rs.getInt("sensor_id");
            String operation = rs.getString("operation");
            int operand = rs.getInt("operand");
            String unit = rs.getString("unit");
            String name = rs.getString("name");
            String ip = rs.getString("IP");
            int port = rs.getInt("port");

            sensor_Obj.put("recid", id);
            sensor_Obj.put("operation", operation);
            sensor_Obj.put("operand", operand);
            sensor_Obj.put("unit", unit);
            sensor_Obj.put("name", name);
            sensor_Obj.put("IP", ip);
            sensor_Obj.put("port", port);

            sensorList.add(sensor_Obj);
            _total++;

        }
        rs.close();

        Records.put("total", _total);
        Records.put("records", sensorList);

        sensorsFile.write(Records.toJSONString());
        sensorsFile.flush();
        sensorsFile.close();
    }

    catch (IOException ex) {
        Logger.getLogger(Sensors.class.getName()).log(Level.WARNING, null, ex);
    }
}

From source file:mml.handler.post.MMLPostAnnotationsHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {/*from ww w .  j  a v a  2  s  .  c  o  m*/
        if (ServletFileUpload.isMultipartContent(request)) {
            parseImportParams(request);
            if (docid != null && version1 != null && annotations != null) {
                Connection conn = Connector.getConnection();
                String[] docids = conn.listDocuments(Database.SCRATCH, docid + ".*", JSONKeys.DOCID);
                if (docids != null && docids.length > 0) {
                    HashMap<Integer, JSONObject> map = new HashMap<Integer, JSONObject>();
                    for (int i = 0; i < docids.length; i++) {
                        JSONObject jObj = fetchAnnotation(conn, Database.SCRATCH, docids[i]);
                        if (jObj != null && jObj.containsKey(JSONKeys.ID)) {
                            int key = ((Number) jObj.get(JSONKeys.ID)).intValue();
                            map.put(key, jObj);
                        }
                    }
                    // existing annotations are int eh map
                    // overwrite them with the new ones
                    // and add any new ones
                    // any annotations in SCRATCH have been put there 
                    // by this method
                    for (int i = 0; i < annotations.size(); i++) {
                        JSONObject ann = (JSONObject) annotations.get(i);
                        int key = ((Number) ann.get(JSONKeys.ID)).intValue();
                        if (map.containsKey(key)) {
                            JSONObject old = (JSONObject) map.get(key);
                            conn.removeFromDb(Database.SCRATCH, (String) old.get(JSONKeys.DOCID));
                            conn.putToDb(Database.SCRATCH,
                                    docid + "/" + version1 + "/" + UUID.randomUUID().toString(),
                                    ann.toJSONString());
                        }
                    }
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<p>OK</p>");
        }
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:mn.EngineForge.module.player.java

public void saveRegisteration() throws IOException {
    JSONObject reg = new JSONObject();
    reg.put("ID", id);
    reg.put("USERNAME", username);
    reg.put("PASSWORD", password);
    reg.put("REG_DATE", null);
    reg.put("LAST_LOGIN", null);
    reg.put("POSITION", null);
    /* JSON ARRAY NOTE//from   ww  w  .  j a  v  a  2  s  .c o m
    JSONArray company = new JSONArray();
    company.add("Compnay: eBay");
    company.add("Compnay: Paypal");
    company.add("Compnay: Google");
    reg.put("Company List", company);
    */
    FileWriter file = new FileWriter(this.path);
    try {
        file.write(reg.toJSONString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        file.flush();
        file.close();
    }
}