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:io.personium.test.jersey.bar.BarInstallTestUtils.java

/**
 * bar?????????.//from   w  ww . jav a 2s  .c  om
 * @param location bar??API?URL
 * @param schemaUrl URL
 * @param status ?
 */
public static void assertBarInstallStatus(String location, String schemaUrl, ProgressInfo.STATUS status) {
    waitBoxInstallCompleted(location);
    PersoniumResponse res = ODataCommon.getOdataResource(location);
    assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    JSONObject bodyJson = (JSONObject) ((JSONObject) res.bodyAsJson());

    assertEquals(status.value(), bodyJson.get("status"));
    assertEquals(schemaUrl, bodyJson.get("schema"));
    if (ProgressInfo.STATUS.FAILED == status) {
        assertNotNull(bodyJson.get("started_at"));
        assertNull(bodyJson.get("installed_at"));
        assertNotNull(bodyJson.get("progress"));
        assertNotNull(bodyJson.get("message"));
        assertNotNull(((JSONObject) bodyJson.get("message")).get("code"));
        assertNotNull(((JSONObject) bodyJson.get("message")).get("message"));
        assertNotNull(((JSONObject) ((JSONObject) bodyJson.get("message")).get("message")).get("value"));
        assertNotNull(((JSONObject) ((JSONObject) bodyJson.get("message")).get("message")).get("lang"));
    } else {
        assertNull(bodyJson.get("started_at"));
        assertNotNull(bodyJson.get("installed_at"));
        assertNull(bodyJson.get("progress"));
    }
}

From source file:com.storageroomapp.client.Collections.java

/**
 * Unmarshalls an Collections object from a JSONObject. This method
 * assumes the name-values are immediately attached to the passed object
 * and not nested under a key (e.g. 'array')
 *
 * @param parent the Collections object associated with the json
 * @param jsonObj the JSONObject/*  w w w .ja  v  a 2 s  .c  o m*/
 * @return an Collections object, or null if the unpacking failed
 */
static public Collections parseJsonObject(Application parent, JSONObject jsonObj) {
    Collections colls = new Collections(parent);
    colls.url = JsonSimpleUtil.parseJsonStringValue(jsonObj, "@url");
    if (colls.url == null) {
        return null;
    }

    JSONArray collsArray = (JSONArray) jsonObj.get("resources");
    @SuppressWarnings("unchecked")
    Iterator<JSONObject> collsIter = (Iterator<JSONObject>) collsArray.listIterator();
    while (collsIter.hasNext()) {
        JSONObject collJson = collsIter.next();
        Collection collection = Collection.parseJsonObject(parent, collJson);
        if (collection != null) {
            colls.add(collection);
        }
    }
    return colls;
}

From source file:gessi.ossecos.graph.GraphModel.java

public static void IStarJsonToGraphFile(String iStarModel, String layout, String typeGraph)
        throws ParseException {
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(iStarModel);

    JSONArray jsonArrayNodes = (JSONArray) jsonObject.get("nodes");
    JSONArray jsonArrayEdges = (JSONArray) jsonObject.get("edges");
    String modelType = jsonObject.get("modelType").toString();

    // System.out.println(modelType);
    // System.out.println(jsonArrayNodes.toJSONString());
    // System.out.println(jsonArrayEdges.toJSONString());

    System.out.println(jsonObject.toJSONString());

    Hashtable<String, String> nodesHash = new Hashtable<String, String>();
    Hashtable<String, String> boundaryHash = new Hashtable<String, String>();
    Hashtable<String, Integer> countNodes = new Hashtable<String, Integer>();
    ArrayList<String> boundaryItems = new ArrayList<String>();
    ArrayList<String> actorItems = new ArrayList<String>();
    GraphViz gv = new GraphViz();
    gv.addln(gv.start_graph());/*from w w  w  . j  a v a  2s  . co m*/

    String nodeType;
    String nodeName;
    String nodeBoundary;
    for (int i = 0; i < jsonArrayNodes.size(); i++) {

        jsonObject = (JSONObject) jsonArrayNodes.get(i);
        nodeName = jsonObject.get("name").toString().replace(" ", "_");
        // .replace("(", "").replace(")", "");
        nodeName = nodeName.replaceAll("[\\W]|`[_]", "");
        nodeType = jsonObject.get("elemenType").toString();
        nodeBoundary = jsonObject.get("boundary").toString();
        // TODO: Verify type of diagram
        // if (!nodeType.equals("actor") & !nodeBoundary.equals("boundary"))
        // {
        if (countNodes.get(nodeName) == null) {
            countNodes.put(nodeName, 0);
        } else {
            countNodes.put(nodeName, countNodes.get(nodeName) + 1);
            nodeName += "_" + countNodes.put(nodeName, 0);

        }
        gv.addln(renderNode(nodeName, nodeType));

        // }

        nodesHash.put(jsonObject.get("id").toString(), nodeName);
        boundaryHash.put(jsonObject.get("id").toString(), nodeBoundary);
        if (nodeType.equals("actor")) {
            actorItems.add(nodeName);
        }
    }

    String edgeType = "";
    String source = "";
    String target = "";
    String edgeSubType = "";
    int subgraphCount = 0;
    boolean hasCluster = false;
    nodeBoundary = "na";
    String idSource;
    String idTarget;
    for (int i = 0; i < jsonArrayEdges.size(); i++) {

        jsonObject = (JSONObject) jsonArrayEdges.get(i);
        edgeSubType = jsonObject.get("linksubtype").toString();
        edgeType = renderEdge(edgeSubType, jsonObject.get("linktype").toString());
        idSource = jsonObject.get("source").toString();
        idTarget = jsonObject.get("target").toString();
        source = nodesHash.get(idSource);
        target = nodesHash.get(idTarget);

        if (!boundaryHash.get(idSource).toString().equals("boundary")
                && !boundaryHash.get(idTarget).toString().equals("boundary")) {
            if (!boundaryHash.get(idSource).toString().equals(nodeBoundary)) {
                nodeBoundary = boundaryHash.get(idSource).toString();
                if (hasCluster) {
                    gv.addln(gv.end_subgraph());
                    hasCluster = false;

                } else {
                    hasCluster = true;
                }
                gv.addln(gv.start_subgraph(subgraphCount));
                gv.addln(actorItems.get(subgraphCount++));
                gv.addln("style=filled;");
                gv.addln("color=lightgrey;");

            }
            gv.addln(source + "->" + target + edgeType);

        } else {

            boundaryItems.add(source + "->" + target + edgeType);

        }

    }
    if (subgraphCount > 0) {
        gv.addln(gv.end_subgraph());
    }
    for (String boundaryE : boundaryItems) {
        gv.addln(boundaryE);
    }
    gv.addln(gv.end_graph());

    String type = typeGraph;
    // String type = "dot";
    // String type = "fig"; // open with xfig
    // String type = "pdf";
    // String type = "ps";
    // String type = "svg"; // open with inkscape
    // String type = "png";
    // String type = "plain";

    String repesentationType = layout;
    // String repesentationType= "neato";
    // String repesentationType= "fdp";
    // String repesentationType= "sfdp";
    // String repesentationType= "twopi";
    // String repesentationType= "circo";

    // //File out = new File("/tmp/out"+gv.getImageDpi()+"."+ type); //
    // Linux
    File out = new File("Examples/out." + type); // Windows
    gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type, repesentationType), out);

}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static JSONArray pullNovaConfig(String host, String tenantId, String token) throws IOException {

    // Get list of compute nodes
    String url = String.format("http://%s:8774/v2/%s/os-hosts", host, tenantId);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendGET(obj, con, "", token);
    JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr);

    JSONArray novaDescription = new JSONArray();
    JSONArray nodes = (JSONArray) responseJSON.get("hosts");

    for (Object h : nodes) {
        if (((JSONObject) h).get("service").equals("compute")) {
            String nodeName = (String) ((JSONObject) h).get("host_name");

            url = String.format("http://%s:8774/v2/%s/os-hosts/%s", host, tenantId, nodeName);
            obj = new URL(url);
            con = (HttpURLConnection) obj.openConnection();

            responseStr = sendGET(obj, con, "", token);
            responseJSON = (JSONObject) JSONValue.parse(responseStr);

            novaDescription.add(responseJSON);
        } else if (((JSONObject) h).get("service").equals("network")) {
            String hostName = (String) ((JSONObject) h).get("host_name");
            JSONObject networkNode = (JSONObject) JSONValue
                    .parse(String.format("{\"network_host\": {\"host_name\": \"%s\", }}", hostName));
            novaDescription.add(networkNode);
        }//w w w.j a  v  a2s . c o  m
    }

    return novaDescription;
}

From source file:com.modeln.batam.connector.wrapper.BuildEntry.java

@SuppressWarnings("unchecked")
public static BuildEntry fromJSON(JSONObject obj) {
    String id = (String) obj.get("id");
    String name = (String) obj.get("name");
    String startDate = (String) obj.get("start_date");
    String endDate = (String) obj.get("end_date");
    String status = (String) obj.get("status");
    String description = (String) obj.get("description");
    boolean override = (Boolean) obj.get("override") == null ? false : (Boolean) obj.get("override");

    List<Pair> criterias = new ArrayList<Pair>();
    JSONArray criteriasArray = (JSONArray) obj.get("criterias");
    if (criteriasArray != null) {
        for (Iterator<JSONObject> it = criteriasArray.iterator(); it.hasNext();) {
            JSONObject criteria = it.next();
            criterias.add(Pair.fromJSON(criteria));
        }/*from w  w w  .  ja  v  a2 s . c  om*/
    }

    List<Pair> infos = new ArrayList<Pair>();
    JSONArray infosArray = (JSONArray) obj.get("infos");
    if (infosArray != null) {
        for (Iterator<JSONObject> it = infosArray.iterator(); it.hasNext();) {
            JSONObject info = it.next();
            infos.add(Pair.fromJSON(info));
        }
    }

    List<Pair> reports = new ArrayList<Pair>();
    JSONArray reportsArray = (JSONArray) obj.get("reports");
    if (reportsArray != null) {
        for (Iterator<JSONObject> it = reportsArray.iterator(); it.hasNext();) {
            JSONObject report = it.next();
            reports.add(Pair.fromJSON(report));
        }
    }

    List<Step> steps = new ArrayList<Step>();
    JSONArray stepsArray = (JSONArray) obj.get("steps");
    if (stepsArray != null) {
        for (Iterator<JSONObject> it = stepsArray.iterator(); it.hasNext();) {
            JSONObject step = it.next();
            steps.add(Step.fromJSON(step));
        }
    }

    List<Commit> commits = new ArrayList<Commit>();
    JSONArray commitsArray = (JSONArray) obj.get("commits");
    if (commitsArray != null) {
        for (Iterator<JSONObject> it = commitsArray.iterator(); it.hasNext();) {
            JSONObject commit = it.next();
            commits.add(Commit.fromJSON(commit));
        }
    }
    boolean isCustomFormatEnabled = (Boolean) obj.get("isCustomFormatEnabled") == null ? false
            : (Boolean) obj.get("isCustomFormatEnabled");
    String customFormat = (String) obj.get("customFormat");
    String customEntry = (String) obj.get("customEntry");

    return new BuildEntry(id, name, startDate == null ? null : new Date(Long.valueOf(startDate)),
            endDate == null ? null : new Date(Long.valueOf(endDate)), status, description, criterias, infos,
            reports, steps, commits, override, isCustomFormatEnabled, customFormat, customEntry);
}

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

public static void removePackage(String id) throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Packages may not be removed from the main thread!");
    id = id.toLowerCase();//from  w w  w .jav  a 2 s  .  c  o  m
    if (((JSONObject) Main.packageStore.get("packages")).containsKey(id)) {
        JSONObject pack = (JSONObject) ((JSONObject) Main.packageStore.get("packages")).get(id);
        if (pack.containsKey("installed")) {
            lockStores();
            if (pack.containsKey("files")) {
                for (Object e : (JSONArray) pack.get("files")) {
                    File f = new File(Bukkit.getWorldContainer(), e.toString());
                    if (f.exists()) {
                        if (!f.delete()) {
                            if (VERBOSE) {
                                Main.log.warning("Failed to delete file " + f.getName());
                            }
                        } else {
                            checkParent(f);
                        }
                    }
                }
                pack.remove("files");
            } else
                Main.log.warning("No file listing for package " + id + "!");
            File archive = new File(Main.plugin.getDataFolder(), "cache" + File.separator + id + ".zip");
            if (archive.exists()) {
                if (!archive.delete() && VERBOSE) {
                    Main.log.warning("Failed to delete archive from cache");
                }
            }
            pack.remove("installed");
            try {
                writePackageStore();
            } catch (IOException ex) {
                unlockStores();
                throw new MPTException(ERROR_COLOR + "Failed to save changes to disk!");
            }
            unlockStores();
        } else
            throw new MPTException(
                    ERROR_COLOR + "Package " + ID_COLOR + id + ERROR_COLOR + " is not installed!");
    } else
        throw new MPTException(ERROR_COLOR + "Cannot find package with id " + ID_COLOR + id);
    unlockStores();
}

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

@SuppressWarnings("unchecked")
public static void updateStore() throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Package store may not be updated from the main thread!");
    lockStores();/*from  w w  w. ja  v a2 s  . c  o  m*/
    final File rStoreFile = new File(Main.plugin.getDataFolder(), "repositories.json");
    if (!rStoreFile.exists())
        Main.initializeRepoStore(rStoreFile); // gotta initialize it before using it
    final File pStoreFile = new File(Main.plugin.getDataFolder(), "packages.json");
    if (!pStoreFile.exists())
        Main.initializePackageStore(pStoreFile);
    JSONObject repos = (JSONObject) Main.repoStore.get("repositories");
    Set<Map.Entry> entries = repos.entrySet();
    JSONObject localPackages = (JSONObject) Main.packageStore.get("packages");
    List<Object> remove = new ArrayList<Object>();
    for (Object k : localPackages.keySet()) {
        if (!((JSONObject) localPackages.get(k)).containsKey("installed"))
            remove.add(k);
    }
    for (Object r : remove)
        localPackages.remove(r);
    for (Map.Entry<String, JSONObject> e : entries) {
        final String id = e.getKey().toLowerCase();
        JSONObject repo = e.getValue();
        final String url = repo.get("url").toString();
        if (VERBOSE)
            Main.log.info("Updating repository \"" + id + "\"");
        JSONObject json = MiscUtil.getRemoteIndex(url);
        String repoId = json.get("id").toString();
        JSONObject packages = (JSONObject) json.get("packages");
        Set<Map.Entry> pEntries = packages.entrySet();
        for (Map.Entry en : pEntries) {
            String packId = en.getKey().toString().toLowerCase();
            JSONObject o = (JSONObject) en.getValue();
            if (o.containsKey("name") && o.containsKey("version") && o.containsKey("url")) {
                if (o.containsKey("sha1") || !Config.ENFORCE_CHECKSUM) {
                    String name = o.get("name").toString();
                    String desc = o.containsKey("description") ? o.get("description").toString() : "";
                    String version = o.get("version").toString();
                    String contentUrl = o.get("url").toString();
                    String sha1 = o.containsKey("sha1") ? o.get("sha1").toString() : "";
                    if (VERBOSE)
                        Main.log.info("Fetching package \"" + packId + "\"");
                    String installed = localPackages.containsKey(packId)
                            && ((JSONObject) localPackages.get(packId)).containsKey("installed")
                                    ? (((JSONObject) localPackages.get(packId)).get("installed")).toString()
                                    : "";
                    JSONArray files = localPackages.containsKey(packId)
                            && ((JSONObject) localPackages.get(packId)).containsKey("files")
                                    ? ((JSONArray) ((JSONObject) localPackages.get(packId)).get("files"))
                                    : null;
                    JSONObject pObj = new JSONObject();
                    pObj.put("repo", repoId);
                    pObj.put("name", name);
                    if (!desc.isEmpty())
                        pObj.put("description", desc);
                    pObj.put("version", version);
                    pObj.put("url", contentUrl);
                    if (!sha1.isEmpty())
                        pObj.put("sha1", sha1);
                    if (!installed.isEmpty())
                        pObj.put("installed", installed);
                    if (files != null)
                        pObj.put("files", files);
                    localPackages.put(packId, pObj);
                } else if (VERBOSE)
                    Main.log.warning("Missing checksum for package \"" + packId + ".\" Ignoring package...");
            } else if (VERBOSE)
                Main.log.warning(
                        "Found invalid package definition \"" + packId + "\" in repository \"" + repoId + "\"");
        }
    }
    Main.packageStore.put("packages", localPackages);
    try {
        writePackageStore();
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Failed to save repository store to disk!");
    }
    unlockStores();
}

From source file:jGPIO.DTO.java

public static JSONObject findDetails(String gpio_name) {
    // Do we have a valid definition file, or should we just direct map?
    if (pinDefinitions == null) {
        autoDetectSystemFile();//w w  w  .  ja  va  2  s . c  o m
    }
    if (pinDefinitions == null) {
        System.out.println("No definitions file found, assuming direct mapping");
        return null;
    }
    for (Object obj : pinDefinitions) {
        JSONObject jObj = (JSONObject) obj;
        String key = (String) jObj.get("key");
        if (key.equalsIgnoreCase(gpio_name)) {
            return jObj;
        }
        if (jObj.containsKey("options")) {
            JSONArray options = (JSONArray) jObj.get("options");
            for (int i = 0; i < options.size(); i++) {
                String option = (String) options.get(i);
                if (option.equalsIgnoreCase(gpio_name)) {
                    return jObj;
                }
            }
        }
    }

    // not found
    return null;
}

From source file:com.walmartlabs.mupd8.application.Config.java

@SuppressWarnings("unchecked")
private static void apply(JSONObject destination, JSONObject source) {
    for (Object k : source.keySet()) {
        String key = (String) k;
        if (destination.containsKey(key) && (destination.get(key) != null)
                && (destination.get(key) instanceof JSONObject) && (source.get(key) instanceof JSONObject)) {
            try {
                JSONObject subDestination = (JSONObject) destination.get(key);
                JSONObject subSource = (JSONObject) source.get(key);
                apply(subDestination, subSource);
            } catch (ClassCastException e) {
                throw new ClassCastException("Config: cannot override key " + key
                        + " with new value because it is not a JSON object");
            }/*from   www  .  java2  s.c om*/
        } else {
            destination.put(key, source.get(key));
        }
    }
}

From source file:fr.inria.oak.paxquery.xparser.client.XClient.java

private static String pactJSONtoDOT(String pact_json) {

    int colorIndex = 0;
    String[] color = new String[] { "#ffcfbf", "#99ff99", "#ff99cc" };
    String[] fillColor = new String[] { "#ff9999", "#cfffbf", "#ffbfef" };

    StringBuilder output = new StringBuilder();
    String newline = System.getProperty("line.separator");
    try {//from ww  w  .ja v a  2 s . com
        output.append("digraph PACT {");
        output.append(newline);
        //output.append("size =\"4,4\"");
        //output.append(newline);

        JSONParser parser = new JSONParser();
        JSONObject mainobject = (JSONObject) parser.parse(pact_json);
        JSONArray array = (JSONArray) mainobject.get("nodes");
        for (Object object : array) {
            JSONObject jsonobject = (JSONObject) object;
            // print node
            Number id = (Number) jsonobject.get("id");
            String pact = (String) jsonobject.get("pact");
            String contents = (String) jsonobject.get("contents");
            output.append("N" + id + " [label=\"");
            output.append(pact);
            if (pact.compareTo("Data Source") == 0) {
                output.append("\" color=\"" + color[colorIndex] + "\" style=\"filled\" fillcolor=\""
                        + fillColor[colorIndex] + "\" shape=box];");
                colorIndex = (colorIndex + 1) % color.length;
            } else if (pact.compareTo("Data Sink") == 0)
                output.append("\" shape=box];");
            else
                output.append(" (" + contents + ")\" shape=box];");
            output.append(newline);
            // print edges
            JSONArray preds_array = (JSONArray) jsonobject.get("predecessors");
            if (preds_array != null) {
                for (Object preds_object : preds_array) {
                    Number pred_id = (Number) ((JSONObject) preds_object).get("id");
                    output.append("N" + id + " -> N" + pred_id + " [dir=back];");
                    output.append(newline);
                }
            }
        }
        output.append("}");

    } catch (ParseException je) {
        return "";
    }

    return output.toString();
}