Example usage for org.json.simple JSONObject get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.nubits.nubot.trading.TradeUtils.java

public static String getCCDKEvalidNonce(String htmlString) {

    JSONParser parser = new JSONParser();
    try {/*from w w w  .  j a  va  2  s .  co m*/
        //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"}
        JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
        JSONObject errors = (JSONObject) httpAnswerJson.get("errors");
        String nonceError = (String) errors.get("nonce");

        //String startStr = " must be from";
        //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2;
        //String from = nonceError.substring(indexStart, indexStart + 10);

        String startStr2 = " till";
        int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2;
        String to = nonceError.substring(indexStart2, indexStart2 + 10);

        //if (to.equals(from)) {
        //    LOG.info("Detected ! " + to + " = " + from);
        //    return "retry";
        //}

        return to;
    } catch (ParseException ex) {
        LOG.severe(htmlString + " " + ex.toString());
        return "1234567891";
    }
}

From source file:com.apigee.edge.config.mavenplugin.MaskConfigMojo.java

public static List getOrgMaskConfig(ServerProfile profile) throws IOException {

    HttpResponse response = RestUtil.getOrgConfig(profile, "maskconfigs");
    if (response == null)
        return new ArrayList();
    JSONArray masks = null;/* w  w  w .jav  a 2 s.c o  m*/
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"masks\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        masks = (JSONArray) obj1.get("masks");

    } catch (ParseException pe) {
        logger.error("Get Mask Config parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get Mask Config error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return masks;
}

From source file:com.apigee.edge.config.mavenplugin.MaskConfigMojo.java

public static List getAPIMaskConfig(ServerProfile profile, String api) throws IOException {

    HttpResponse response = RestUtil.getAPIConfig(profile, api, "maskconfigs");
    if (response == null)
        return new ArrayList();
    JSONArray masks = null;//from w w w .  j av  a  2  s .  co  m
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"masks\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        masks = (JSONArray) obj1.get("masks");

    } catch (ParseException pe) {
        logger.error("Get Mask Config parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get Mask Config error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return masks;
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static JSONObject wrap(JSONObject jo, Class c) {
    JSONObject result = new JSONObject();
    String indicatorName = Indication.getIndicatorName(c);
    String indicatedName = Indication.getIndicatedName(c);
    result.put(indicatorName, jo.get(indicatorName));
    result.put(indicatedName, jo);/*from w  ww  . j av  a2 s.c o  m*/
    return result;
}

From source file:IrqaQuery.java

public static void pipeline(String basedir, String indexpath, String set, JSONObject lookup_sent)
        throws Exception {
    System.out.println(set + " started...");
    String index = basedir + "/index_all" + indexpath + "/";

    String stopwords = basedir + "/stopwords.txt";
    IrqaQuery lp = new IrqaQuery();

    String answer_filename = String.format(basedir + "/stats/data_for_analysis/newTACL/%s_raw_list.json", set);
    String file = String.format(basedir + "/stats/data_for_analysis/newTACL/WikiQASent-%s.txt", set);

    //        String lookup_8kfn = basedir+"/data/wikilookup_8k.json";
    String documents2_fn = basedir + "/data/documents2.json";

    JSONParser parser = new JSONParser();
    JSONArray answer_list = (JSONArray) parser.parse(new FileReader(answer_filename));

    //        Object obj2 = parser.parse(new FileReader(lookup_8kfn));
    //        JSONObject lookup_8k = (JSONObject) obj2;

    Object obj3 = parser.parse(new FileReader(documents2_fn));
    JSONArray documents2 = (JSONArray) obj3;

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

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    String outfilename = String.format(basedir + "/stats/data_for_analysis/newTACL/newsplit%s_%s.txt",
            indexpath, set);//from www.  ja  v  a2  s.c  o m
    BufferedWriter outfile = new BufferedWriter(new FileWriter(outfilename));

    int numline = 0;

    ArrayList<ArrayList<String>> sentlistAll = new ArrayList<ArrayList<String>>();
    ArrayList<ArrayList<String>> alistAll = new ArrayList<ArrayList<String>>();

    try {
        String r;
        String cquestion = "";

        ArrayList<String> sentlist = new ArrayList<>();
        ArrayList<String> alist = new ArrayList<>();

        while ((r = br.readLine()) != null) {
            numline++;
            String[] line = r.split("\t");

            if (cquestion.compareTo(line[0]) != 0) {
                if (cquestion.compareTo("") != 0) {
                    sentlistAll.add(sentlist);
                    alistAll.add(alist);
                    questions.add(cquestion);
                }

                sentlist = new ArrayList<>();
                alist = new ArrayList<>();
                sentlist.add(line[1]);
                alist.add(line[2]);

                cquestion = line[0];
            } else {
                sentlist.add(line[1]);
                alist.add(line[2]);
            }
        }

        sentlistAll.add(sentlist);
        alistAll.add(alist);
        questions.add(cquestion);

    } finally {
        br.close();
    }

    System.out.println(questions.size());

    for (int i = 0; i < questions.size(); i++) {
        String query = questions.get(i);
        List<Document> docs = lp.query(index, stopwords, query, 5, "BM25");
        //            Object o = (Object) answer_list.get(0);
        JSONObject rl = (JSONObject) answer_list.get(i);
        String gold_pid = (String) rl.get("paragraph_id");
        //            String gold_q =(String) rl.get("question");

        for (Document d : docs) {
            String docid = d.get("docid");

            if (gold_pid.compareTo(docid) == 0) {
                //                    get sentences from gold (alistAll, sentlistAll)
                for (int j = 0; j < sentlistAll.get(i).size(); j++) {
                    if (sentlistAll.get(i).get(j).length() < 1 || sentlistAll.get(i).get(j).compareTo(" ") == 0
                            || sentlistAll.get(i).get(j).compareTo("  ") == 0
                            || sentlistAll.get(i).get(j).compareTo("''") == 0
                            || sentlistAll.get(i).get(j).compareTo("   ") == 0)
                        continue;
                    String outstring = String.format("%s\t%s\t%s\n", query, sentlistAll.get(i).get(j),
                            alistAll.get(i).get(j));
                    outfile.write(outstring);
                }
            } else {
                //                    get_sentence_from_lookup();
                //                    lookup_sent.get(docid)
                //                    JSONArray sents = (JSONArray) lookup_sent.get("Timeline_of_classical_mechanics-Abstract");
                JSONArray sents = (JSONArray) lookup_sent.get(docid);

                if (sents == null) {
                    System.out.println("noway, " + docid + "\n");
                } else {
                    for (int kk = 0; kk < sents.size(); kk++) {
                        if (sents.get(kk).toString().length() < 1
                                || sents.get(kk).toString().compareTo(" ") == 0
                                || sents.get(kk).toString().compareTo("  ") == 0
                                || sents.get(kk).toString().compareTo("''") == 0
                                || sents.get(kk).toString().compareTo("   ") == 0)
                            continue;
                        String outstring = String.format("%s\t%s\t%s\n", query, sents.get(kk).toString(), "0");
                        outfile.write(outstring);

                        //                            System.out.printf("%s\t%s\t%s\n", query, sents.get(kk).toString(), "0");
                        //                            System.out.println(sents.get(kk));
                    }
                }
            }
        }
    }

    outfile.close();

    //        System.out.println(raw_list.size());
    System.out.println(numline);
}

From source file:net.amigocraft.mpt.command.InstallCommand.java

public static void installPackage(String id) throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Packages may not be installed from the main thread!");
    id = id.toLowerCase();//from   w ww .j  av  a  2  s .  c  o  m
    try {
        File file = new File(Main.plugin.getDataFolder(), "cache" + File.separator + id + ".zip");
        if (!file.exists())
            downloadPackage(id);
        if (!Main.packageStore.containsKey("packages")
                && ((JSONObject) Main.packageStore.get("packages")).containsKey(id))
            throw new MPTException(
                    ERROR_COLOR + "Cannot find package by id " + ID_COLOR + id + ERROR_COLOR + "!");
        JSONObject pack = (JSONObject) ((JSONObject) Main.packageStore.get("packages")).get(id);
        List<String> files = new ArrayList<>();
        lockStores();
        boolean success = MiscUtil.unzip(new ZipFile(file), Bukkit.getWorldContainer(), files);
        if (!KEEP_ARCHIVES)
            file.delete();
        pack.put("installed", pack.get("version").toString());
        JSONArray fileArray = new JSONArray();
        for (String str : files)
            fileArray.add(str);
        pack.put("files", fileArray);
        try {
            writePackageStore();
        } catch (IOException ex) {
            ex.printStackTrace();
            unlockStores();
            throw new MPTException(ERROR_COLOR + "Failed to write package store to disk!");
        }
        unlockStores();
        if (!success)
            throw new MPTException(
                    ERROR_COLOR + "Some files were not extracted. Use verbose logging for details.");
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Failed to access archive!");
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
private static JSONObject stripLoginDetails(JSONObject obj, boolean includeUsername) {
    if (obj == null) {
        return null;
    }/*from   w  ww. j  a va2 s  . c  o m*/
    String clientToken = (String) obj.get("clientToken");
    String accessToken = (String) obj.get("accessToken");

    if (clientToken == null || accessToken == null) {
        return null;
    }

    JSONObject selectedProfile = (JSONObject) obj.get("selectedProfile");

    if (selectedProfile == null) {
        return null;
    }

    String username = (String) selectedProfile.get("name");
    if (username == null) {
        return null;
    }

    String id = (String) selectedProfile.get("id");
    if (id == null) {
        return null;
    }

    JSONObject stripped = new JSONObject();

    stripped.put("accessToken", accessToken);
    stripped.put("clientToken", clientToken);

    if (includeUsername) {
        JSONObject selectedProfileNew = new JSONObject();
        selectedProfileNew.put("name", username);
        selectedProfileNew.put("id", id);

        stripped.put("selectedProfile", selectedProfileNew);
    }
    return stripped;

}

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

/**
 * Reportparsejson./*from ww w . ja  va 2  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.storageroomapp.client.field.ImageValue.java

static public ImageValue parseJSONObject(ImageField parentField, JSONObject jsonObj) {
    if (jsonObj == null) {
        return null;
    }/*from  w  w  w  . j  a  va  2  s.c  o m*/
    String url = JsonSimpleUtil.parseJsonStringValue(jsonObj, "@url");
    if (url == null) {
        return null;
    }

    ImageValue value = new ImageValue(parentField, url);
    value.isProcessing = JsonSimpleUtil.parseJsonBooleanValue(jsonObj, "@processing", false);

    JSONObject versionObject = (JSONObject) jsonObj.get("@versions");
    if (versionObject != null) {
        value.versions = ImageVersion.parseJSONListObject(versionObject);
    }
    return value;
}

From source file:freebase.api.FreebaseAPI2.java

private static List<Film> encodeJSON(JSONArray results) {
    List<Film> films = new ArrayList<>();
    for (Object flmObj : results) {
        JSONObject flmJObj = (JSONObject) flmObj;
        Film film = new Film(getId((String) flmJObj.get("mid"), film_map), (String) flmJObj.get("mid"),
                (String) flmJObj.get("name"));

        JSONArray directed_by_arr = (JSONArray) flmJObj.get("directed_by");
        JSONObject directed_by = (JSONObject) directed_by_arr.get(0);
        Directedby directedby = new Directedby();
        directedby.setId(directedbyIDs.next());

        Director director = new Director(getId((String) directed_by.get("mid"), director_map),
                (String) directed_by.get("mid"), (String) directed_by.get("name"));
        directedby.setDirector(director);
        film.setDirectedBy(directedby);/*from   ww w  .j a v a 2 s  . c  o  m*/

        JSONArray starrings = (JSONArray) flmJObj.get("starring");
        for (Object starringObj : starrings) {
            JSONObject starringJObj = (JSONObject) starringObj;
            Starring starring = new Starring();
            starring.setMid((String) starringJObj.get("mid"));
            starring.setId(getId((String) starringJObj.get("mid"), starring_map));

            JSONArray actorJObj_arr = (JSONArray) starringJObj.get("actor");
            JSONObject actorJObj = (JSONObject) actorJObj_arr.get(0);
            Actor actor = new Actor(getId((String) actorJObj.get("mid"), actor_map),
                    (String) actorJObj.get("mid"), (String) actorJObj.get("name"));
            starring.setActor(actor);

            JSONArray characterJObj_arr = (JSONArray) starringJObj.get("character");
            JSONObject characterJObj = (JSONObject) characterJObj_arr.get(0);
            freebase.api.entity.movie.FCharacter character = new freebase.api.entity.movie.FCharacter(
                    getId((String) characterJObj.get("mid"), character_map), (String) characterJObj.get("mid"),
                    (String) characterJObj.get("name"));
            starring.setCharacter(character);

            starring.setFilm(film);
            film.addStarring(starring);
        }

        films.add(film);
    }
    return films;
}