Example usage for org.json.simple.parser JSONParser parse

List of usage examples for org.json.simple.parser JSONParser parse

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser parse.

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:mas.MAS.java

public static void extractPapers(int start) {
    String csv_file_path = "data/papers_" + start + ".csv";
    String json_dump_file_path = "data/papers_dump_" + start + ".json";
    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Paper?$select=ID,DocType,Title,Year,ConfID,JourID&$filter=Year%20gt%202001&$format=json";
    while (true) {
        IOUtils.writeDataIntoFile(start + "", paper_last, false);
        try {//from w w  w  . j a v a  2 s.  c o m
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, start);
            //                System.out.println("json=" + json);
            if (json == null) {
                System.out.println("json is null. skip. old start=" + start);
                start += 100;
                Thread.sleep(1000L);
                continue;
            }
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                System.out.println("Paper: start = " + start + " results# = " + results.size());
                for (Object paper : results) {
                    JSONObject paperObj = (JSONObject) paper;
                    Long docType = (Long) paperObj.get("DocType");
                    Long year = (Long) paperObj.get("Year");
                    Long jourID = (Long) paperObj.get("JourID");
                    Long confID = (Long) paperObj.get("ConfID");
                    Long id = (Long) paperObj.get("ID");
                    String title = (String) paperObj.get("Title");
                    title = normalized(title);
                    csv_str.append(id).append(SEPERATOR).append(docType).append(SEPERATOR).append(year)
                            .append(SEPERATOR).append(jourID).append(SEPERATOR).append(confID).append(SEPERATOR)
                            .append(title).append(NEWLINE);
                }
                IOUtils.writeDataIntoFile(json + "\n", json_dump_file_path);
                IOUtils.writeDataIntoFile(csv_str.toString(), csv_file_path);
                start += 100;
                Thread.sleep(400L);
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            System.out.println(ex.getMessage() + " Cause: " + ex.getCause());
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
            start += 100;
            try {
                Thread.sleep(10000L);
            } catch (InterruptedException ex1) {
                Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex1);
            }

        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage() + " Cause: " + ex.getCause());
            Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
            start += 100;
            try {
                Thread.sleep(10000L);
            } catch (InterruptedException ex1) {
                Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex1);
            }

        }
    }
}

From source file:mas.MAS.java

public static void getPaperAuthors(int start, String papers_filter, String csvFile, String jsonFile) {
    String csv_file_path = csvFile;
    String json_dump_file_path = jsonFile;
    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Paper_Author?$select=PaperID,SeqID,AuthorID,Name,AffiliationID&$filter="
            + papers_filter + "&$format=json";
    //        String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Paper_Ref?$select=SrcID,DstID,SeqID&$filter=" + papers_filter + "&$format=json";
    while (true) {
        IOUtils.writeDataIntoFile(start + "", paper_last, false);
        try {/*from   www .  j a  v a  2  s.c  om*/
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, start);
            //                System.out.println("json=" + json);
            if (json == null) {
                System.out.println("json is null. skip. old start=" + start);
                start += 100;
                Thread.sleep(1000L);
                continue;
            }
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                System.out.println("Paper: start = " + start + " results# = " + results.size());
                for (Object paper : results) {
                    JSONObject paperObj = (JSONObject) paper;
                    Long paperID = (Long) paperObj.get("PaperID");
                    Long seqID = (Long) paperObj.get("SeqID");
                    Long authorID = (Long) paperObj.get("AuthorID");
                    String name = normalized((String) paperObj.get("Name"));
                    //                        String affiliation = normalized((String) paperObj.get("Affiliation"));
                    Long affiliationID = (Long) paperObj.get("AffiliationID");
                    csv_str.append(paperID).append(SEPERATOR).append(seqID).append(SEPERATOR).append(authorID)
                            .append(SEPERATOR).append(name).append(SEPERATOR).append(affiliationID)
                            .append(NEWLINE);
                }
                IOUtils.writeDataIntoFile(json + "\n", json_dump_file_path);
                IOUtils.writeDataIntoFile(csv_str.toString(), csv_file_path);
                start += 100;
                Thread.sleep(300L);
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            System.out.println(ex.getMessage() + " Cause: " + ex.getCause());
            Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex);
            start += 100;
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException ex1) {
                Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex1);
            }

        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage() + " Cause: " + ex.getCause());
            Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex);
            start += 100;
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException ex1) {
                Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex1);
            }

        }
    }
}

From source file:com.intel.genomicsdb.GenomicsDBImporter.java

/**
 * Utility function that returns a list of ChromosomeInterval objects for
 * the column partition specified by the loader JSON file and rank/partition index
 * @param loaderJSONFile path to loader JSON file
 * @param partitionIdx rank/partition index
 * @return list of ChromosomeInterval objects for the specified partition 
 * @throws ParseException when there is a bug in the JNI interface and a faulty JSON is returned
 *//*w w  w  .  j  a v  a  2  s  .  co  m*/
public static ArrayList<ChromosomeInterval> getChromosomeIntervalsForColumnPartition(
        final String loaderJSONFile, final int partitionIdx) throws ParseException {
    final String chromosomeIntervalsJSONString = jniGetChromosomeIntervalsForColumnPartition(loaderJSONFile,
            partitionIdx);
    /* JSON format
      {
        "contigs": [
           { "chr1": [ 100, 200] },
           { "chr2": [ 500, 600] }
        ]
      }
    */
    ArrayList<ChromosomeInterval> chromosomeIntervals = new ArrayList<ChromosomeInterval>();
    JSONParser parser = new JSONParser();
    JSONObject topObj = (JSONObject) (parser.parse(chromosomeIntervalsJSONString));
    assert topObj.containsKey("contigs");
    JSONArray listOfDictionaries = (JSONArray) (topObj.get("contigs"));
    for (Object currDictObj : listOfDictionaries) {
        JSONObject currDict = (JSONObject) currDictObj;
        assert currDict.size() == 1; //1 entry
        for (Object currEntryObj : currDict.entrySet()) {
            Map.Entry<String, JSONArray> currEntry = (Map.Entry<String, JSONArray>) currEntryObj;
            JSONArray currValue = currEntry.getValue();
            assert currValue.size() == 2;
            chromosomeIntervals.add(new ChromosomeInterval(currEntry.getKey(), (Long) (currValue.get(0)),
                    (Long) (currValue.get(1))));
        }
    }
    return chromosomeIntervals;
}

From source file:com.sat.common.CustomReport.java

/**
 * Reportparsejson.// w  ww .j a  v  a2 s. c  o  m
 *
 * @return the string
 * @throws FileNotFoundException the file not found exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParseException the parse exception
 * @throws AddressException the address exception
 */
public static String reportparsejson()
        throws FileNotFoundException, IOException, ParseException, AddressException {
    String failureReasonTable = "<table border style='width:100%'><tr style='background-color: rgb(70,116,209);'><colgroup><col span='1' style='width: 14%;'><col span='1' style='width: 40%;'><col span='1' style='width: 33%;'><col span='1' style='width: 13%;'></colgroup><th>Failed Test Case ID</th><th>Test Title</th><th>Failure Reason</th><th>Failure Category</th></tr>";
    String head = "<html>";
    head += "<head>";
    head += "<style>";
    head += "body{position:absolute;width:80%;height:100%;margin:0;padding:0}table,tbody{position:relative;width:100%;table-layout: auto}tr td,th{width:.5%;word-break:break-all;border:.5px solid black;} ";
    head += "</style>";
    head += "</head>";
    head += "<body border='2%'><table><tr><td style='background-color: rgb(170,187,204);'>";

    JSONParser parser = new JSONParser();
    int sno = 0;
    int pass = 0, fail = 0;
    int passed1 = 0, failed1 = 0;
    String headdetails = "<table><br><th style='background-color: rgb(25, 112, 193);'><center>Customized Automation Run Report</center></th><br></table><br><br>";
    String version = "";
    String bodydetailS = "<table> <tr style='background-color: rgb(70,116,209);'><th>#</th><th>Feature Name</th><th>Test Case Title</th><th>TIMS ID</th><th>Test Type</th><th>Component Involved</th><th>Status</th></tr>";
    String Total = "";
    Object obj = parser
            .parse(new FileReader(System.getProperty("user.dir") + "/LMS/target/reports/cucumber-report.json"));
    JSONArray msg = (JSONArray) obj;

    for (int i = 0; i < msg.size(); i++) {
        JSONObject jo = (JSONObject) msg.get(i);
        JSONArray msg1 = (JSONArray) jo.get("elements");
        String uniid = "";
        String nodeinfo = "";
        String featureFile = null;
        String timsId = null;
        String serial = null;
        String testType = null;
        String testTitle = null;
        String mid = null, mid1 = null;
        for (int j = 0; j < msg1.size(); j++) {

            JSONObject jo1 = (JSONObject) msg1.get(j);
            System.out.println("Id" + jo1.get("id"));
            if (jo1.get("id") != null) {

                JSONArray msg2 = (JSONArray) jo1.get("tags");

                String uniidstatus = "N";
                int pf = -1;
                System.out.println("satize" + msg2.size());
                for (int j2 = 0; j2 < msg2.size(); j2++) {
                    // Version
                    JSONObject jo2 = (JSONObject) msg2.get(j2);
                    if ((jo2.get("name").toString().contains("NodeInfo"))) {
                        nodeinfo = "found";
                    }
                    // Test case details
                    if ((jo2.get("name").toString().contains("Stage2"))
                            || (jo2.get("name").toString().contains("TBD"))) {
                        String stype = "Functional";
                        for (int typec = 0; typec < msg2.size(); typec++) {
                            JSONObject jotype = (JSONObject) msg2.get(typec);
                            if (jotype.get("name").toString().contains("Functional"))
                                stype = "Functional";
                            else if (jotype.get("name").toString().contains("Sanity"))
                                stype = "Sanity";

                        }
                        if (!uniid.trim().equals(jo2.get("name").toString().trim())) {

                            String fnameuri[] = jo.get("uri").toString().split("/");
                            featureFile = fnameuri[fnameuri.length - 1];
                            System.out.println("feture file" + featureFile);
                            String[] featureFile1 = featureFile.split(".feature");
                            System.out.println("split feature" + featureFile1[0]);

                            serial = "" + (++sno);
                            timsId = jo2.get("name").toString();
                            testType = stype;
                            testTitle = jo1.get("name").toString();
                            mid = "<td><center>" + serial + "</center></td><td>" + featureFile1[0]
                                    + "</center></td><td>" + testTitle + "</center></td><td><center>"
                                    + timsId.substring(1) + "</center></td><td><center>" + testType + "</td>";
                            uniidstatus = "Y";

                            mid1 = "<td><center>" + timsId.substring(1) + "</center></td><td>" + testTitle
                                    + "</td>";

                        }

                        uniid = jo2.get("name").toString();

                    }
                }

                JSONArray msg3 = (JSONArray) jo1.get("steps");
                for (int j3 = 0; j3 < msg3.size(); j3++) {
                    JSONObject jo3 = (JSONObject) msg3.get(j3);
                    JSONObject jo4 = (JSONObject) jo3.get("result");
                    System.out.println(jo4.get("status"));
                    if (jo4.get("status").equals("passed")) {
                        pf = 0;
                    } else {
                        pf = 1;
                        break;
                    }
                }

                String scenarioprint = null;
                JSONArray output = (JSONArray) jo1.get("steps");
                for (int outputj3 = 0; outputj3 < output.size(); outputj3++) {
                    JSONObject outputjo3 = (JSONObject) output.get(outputj3);
                    JSONArray outputjo4 = (JSONArray) outputjo3.get("output");
                    if (outputjo4 != null) {
                        for (int outputj33 = 0; outputj33 < outputjo4.size(); outputj33++) {
                            String tempscenarioprint = (String) outputjo4.get(outputj33);
                            tempscenarioprint = tempscenarioprint.replace("[", " ");
                            tempscenarioprint = tempscenarioprint.replace("]", " ").trim();
                            System.out.println(tempscenarioprint);
                            if (tempscenarioprint.startsWith("ComponentInvolved")) {
                                tempscenarioprint = tempscenarioprint.replace("ComponentInvolved", "Begin");
                                tempscenarioprint = tempscenarioprint.replace(",", " ");
                                scenarioprint = tempscenarioprint;
                            }
                            System.out.println("scenario" + scenarioprint);
                        }
                    }

                }

                if (uniidstatus.equals("Y")) {
                    if (pf == 0) {
                        bodydetailS += "<tr style='background-color: rgb(107,144,70);'>" + mid + "<td><center>"
                                + scenarioprint + "</center></td><td><center>Passed</center></td></tr>";
                        pass++;
                    } else if (pf == 1) {
                        bodydetailS += "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                + "<td><center>" + scenarioprint
                                + "</center></td><td><center>Failed</center></td></tr>";
                        if (!failureReasonTable
                                .contains("<tr><td><center>" + mid1 + "</td><td></td><td></td></tr>"))
                            failureReasonTable += "<tr>" + mid1 + "<td></td><td></td></tr>";
                        fail++;
                    }
                } else if (mid != null) {
                    if (bodydetailS.contains(mid)) {
                        if (pf == 0) {

                        } else if (pf == 1) {
                            if (bodydetailS.contains("<tr style='background-color: rgb(107,144,70);'>" + mid
                                    + "<td><center>" + scenarioprint
                                    + "</center></td><td><center>Passed</center></td></tr>")) {
                                failed1++;
                                passed1--;
                                bodydetailS = bodydetailS.replace(
                                        "<tr style='background-color: rgb(107,144,70);'>" + mid + "<td><center>"
                                                + scenarioprint
                                                + "</center></td><td><center>Passed</center></td></tr>",
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>");
                            }
                            if (bodydetailS
                                    .contains("<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                            + "<td><center>" + scenarioprint
                                            + "</center></td><td><center>Failed</center></td></tr>")) {
                                bodydetailS = bodydetailS.replace(
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>" + scenarioprint
                                                + "</center></td><td><center>Failed</center></td></tr>",
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>" + scenarioprint
                                                + "</center></td><td><center>Failed</center></td></tr>");

                            }

                            if (!failureReasonTable
                                    .contains("<tr><td><center>" + mid1 + "</td><td></td><td></td></tr>"))
                                failureReasonTable += "<tr>" + mid1 + "<<td></td><td></td></tr>";
                        }

                    }

                }
            }
        }
    }

    Total = "<table><tr style='background-color: rgb(70,116,209);'><th>Total</th><td>Passed</th><th>Failed</th></tr>";
    Total += "<center><tr style='background-color: rgb(170,204,204);'><td>" + sno + "</td><td>"
            + (pass + passed1) + "(" + String.format("%.2f", ((pass + passed1) * 100.0F / sno)) + "%)</td><td>"
            + (fail + failed1) + "(" + String.format("%.2f", ((fail + failed1) * 100.0F / sno))
            + "%)</td></tr></center></table><br>";
    bodydetailS += "</center></table><br><br><br>";

    System.out.println(version);
    head += headdetails + Total + version + bodydetailS;
    if (fail > 0) {
        failureReasonTable += "</table>";
        // System.out.println(failureReasonTable);
        head += failureReasonTable;
    }
    head += "</td></tr></table></body></html>";

    return head;

}

From source file:com.telefonica.iot.cygnus.sinks.NGSIOrionSink.java

/**
 * //from   w  ww  .j  ava 2 s  .c  om
 * 
 * @param jsonArrayStr
 *            String containing JSON array metadata
 * @throws CygnusRuntimeError
 */
private static String parseJsonArrayStrToMetadataJson(String jsonArrayStr) throws CygnusRuntimeError {

    JSONObject outMetadata = null;
    String salida = CommonConstants.EMPTY_MD;
    JSONParser jsonParser = new JSONParser();
    JSONArray metadataJson = new JSONArray();

    if (jsonArrayStr.equals("")) {
        try {
            LOGGER.debug("Parsing Metadata : \"" + jsonArrayStr + "\"");
            metadataJson = (JSONArray) jsonParser.parse(jsonArrayStr);

        } catch (ParseException e) {
            LOGGER.error("BadRequest : metadata must be a JSON Array");
            throw new CygnusRuntimeError("BadRequest : metadata must be a JSON Array");
        }
        try {

            outMetadata = new JSONObject();
            for (int i = 0; i < metadataJson.length(); i++) {
                JSONObject meta = (JSONObject) metadataJson.get(i);

                String name = meta.get("name").toString();
                String type = meta.get("type").toString();
                String value = meta.get("value").toString();

                JSONObject out = new JSONObject();
                out.put("type", type);
                out.put("value", value);
                outMetadata.put(name, out);
            }

            if (metadataJson.length() > 0) {
                salida = outMetadata.toString();
            }
        } catch (JSONException e) {
            LOGGER.error("BadRequest : metadata must contain Json object (name,type,value");
            throw new CygnusRuntimeError("BadRequest : metadata must contain Json object (name,type,value");
        }
    } // if
    return salida;
}

From source file:JSONParser.JSONOperations.java

public static boolean isErrorJSON(String JSONString) {
    JSONParser parser = new JSONParser();
    try {/*from w w w. ja  va  2 s .  c o m*/
        JSONObject json = (JSONObject) parser.parse(JSONString);
        JSONObject response = (JSONObject) json.get("response");
        JSONObject result = (JSONObject) response.get("result");
        JSONObject error = (JSONObject) response.get("error");
        if (result == null) {
            return true;
        }
        if (error != null) {
            return true;
        }
    } catch (ParseException ex) {
        Logger.getLogger(JSONOperations.class.getName()).log(Level.SEVERE, null, ex);
        return true;
    }

    return false;
}

From source file:Connector.AlchemyConnector.java

public void getConnection() {

    try {/*from w  w  w. j  a  v  a 2  s .co m*/
        String envServices = System.getenv("VCAP_SERVICES");

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(envServices);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray vcapArray = (JSONArray) jsonObject.get("alchemy_api");
        JSONObject vcap = (JSONObject) vcapArray.get(0);
        JSONObject credentials = (JSONObject) vcap.get("credentials");
        apiKey = credentials.get("apikey").toString();

    } catch (ParseException ex) {
    }
}

From source file:Connector.Embeddable.java

public void getConnection() {

    try {/*from   w w  w .jav a  2s.c  o  m*/
        String envServices = System.getenv("VCAP_SERVICES");

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(envServices);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray vcapArray = (JSONArray) jsonObject.get("erservice");
        JSONObject vcap = (JSONObject) vcapArray.get(0);
        JSONObject credentials = (JSONObject) vcap.get("credentials");
        url = credentials.get("url").toString();
        password = credentials.get("password").toString();
        userid = credentials.get("userid").toString();

    } catch (ParseException ex) {
    }
}

From source file:edu.isi.techknacq.topics.readinglist.ReadDocumentkey.java

public void Readfile() {
    try {/*from www .  j  a v  a  2  s .  c o  m*/
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(filename));
        for (Object key : jsonObject.keySet()) {
            JSONObject documentInfo = (JSONObject) jsonObject.get(key);
            String author = (String) documentInfo.get("author");
            String title = (String) documentInfo.get("title");
            docMap.put((String) key, "author: " + author + ", title: " + title);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReadDocumentkey.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReadDocumentkey.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(ReadDocumentkey.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

private static Connection getConnection() throws Exception {

    String url = "jdbc:postgresql://localhost:5432/liquidInfo";
    String user = "postgres";
    String password = "xiecb";

    Map<String, String> env = System.getenv();

    if (env.containsKey("VCAP_SERVICES")) {
        // we are running on cloud foundry, let's grab the service details
        // from vcap_services
        JSONParser parser = new JSONParser();
        JSONObject vcap = (JSONObject) parser.parse(env.get("VCAP_SERVICES"));
        JSONObject service = null;//from w  w  w.  j  av  a2  s  .c om

        // We don't know exactly what the service is called, but it will
        // contain "postgresql"
        for (Object key : vcap.keySet()) {
            String keyStr = (String) key;
            if (keyStr.toLowerCase().contains("postgresql")) {
                service = (JSONObject) ((JSONArray) vcap.get(keyStr)).get(0);
                break;
            }
        }

        if (service != null) {
            JSONObject creds = (JSONObject) service.get("credentials");
            String name = (String) creds.get("name");
            String host = (String) creds.get("host");
            Long port = (Long) creds.get("port");
            user = (String) creds.get("user");
            password = (String) creds.get("password");

            url = "jdbc:postgresql://" + host + ":" + port + "/" + name;
        }
    }

    return DriverManager.getConnection(url, user, password);
}