Example usage for org.json.simple JSONObject keySet

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:org.phylowidget.tree.PhyloNode.java

public void setAnnotationsFromJson(String jsonString) {
    JSONObject map = (JSONObject) Json.jsonToHash(jsonString);
    Set<Object> keys = map.keySet();
    for (Object o : keys) {
        System.out.println("JSON KEY:" + o);
        System.out.println("  VALUE:" + map.get(o).toString());
        String key = o.toString();
        String val = map.get(key).toString();
        if (key.equalsIgnoreCase("name"))
            getTree().setLabel(this, val);
        else if (key.equalsIgnoreCase("branch length"))
            getTree().setBranchLength(this, Double.parseDouble(val));
        else//from  w w w  .  ja v a 2  s.c o  m
            setAnnotation(key, val);
    }
}

From source file:org.PrimeSoft.MCPainter.utils.JSONExtensions.java

/**
 * Print all unused properties/*from w w w  .j  av a2s  .c o m*/
 *
 * @param data
 * @param usedProps
 * @param msg
 */
public static void printUnused(JSONObject data, String[] usedProps, String msg) {
    HashSet<String> props = new HashSet<String>();
    for (String s : usedProps) {
        if (!props.contains(s)) {
            props.add(s);
        }
    }

    for (Object k : data.keySet()) {
        if (k != null && !props.contains(k.toString())) {
            log(msg + k.toString());
        }
    }
}

From source file:org.sonar.core.graph.graphson.GraphsonUtil.java

static Map<String, Object> readProperties(JSONObject node, boolean ignoreReservedKeys,
        boolean hasEmbeddedTypes) {
    Map<String, Object> map = new HashMap<String, Object>();

    for (Object objKey : node.keySet()) {
        String key = (String) objKey;
        Object value = node.get(key);

        if (!ignoreReservedKeys || !isReservedKey(key)) {
            map.put(key, readProperty(value, hasEmbeddedTypes));
        }//from  ww  w  . j a  va  2  s . c  om
    }

    return map;
}

From source file:org.springfield.lou.application.types.EuscreenxlitemApplication.java

public void sendContentProviderMail(Screen s, String data) {
    //System.out.println("Send mail to CP: " + data);

    JSONObject form = (JSONObject) JSONValue.parse(data);

    String mailfrom = "euscreen-portal@noterik.nl";
    String mailsubject = "Somebody showed interest in your item on EUScreen";
    String email = (String) form.get("email");
    String id = (String) form.get("identifier");
    String provider = (String) form.get("provider");
    String subject = (String) form.get("subject");
    String title = (String) form.get("title");
    String message = (String) form.get("message");
    message = message.replaceAll("(\r\n|\n)", "<br />");

    //Form validation
    JSONObject mailResponse = new JSONObject();
    Set<String> keys = form.keySet();
    boolean errors = false;
    for (String key : keys) {
        String value = (String) form.get(key);
        if (value == null || value.isEmpty()) {
            errors = true;//from  w w w .  j  a v  a  2s  . c o m
            break;
        }
    }

    if (errors) {
        mailResponse.put("status", "false");
        mailResponse.put("message", "Please fill in all the fields.");
        s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");
        return;
    }

    String toemail = null;
    //Find the provider email
    FsNode providerNode = Fs.getNode("/domain/euscreenxl/user/" + provider + "/account/default");
    toemail = providerNode.getProperty("email");

    String body = "Identifier: " + id + "<br/>";
    body += "Title: " + title + "<br/>";
    body += "Link to item on EUScreen:<br/>";
    body += "<a href=\"http://euscreen.eu/item.html?id=" + id + "\">http://euscreen.eu/item.html?id=" + id
            + "</a><br/>";
    body += "-------------------------------------------<br/><br/>";
    body += "Subject: " + subject + "<br/>";
    body += "Message:<br/>";
    body += message + "<br/><br/>";
    body += "-------------------------------------------<br/>";
    body += "You can contact the sender of this message on: <a href=\"mailto:" + email + "\">" + email
            + "</a><br/>";

    if (this.inDevelMode()) { //In devel mode always send the email to the one filled in the form
        toemail = email;
    }

    //!!! Hack to send the email to the one filled in the form (for testing purposes). When on production it should be removed
    //toemail = email;

    boolean success = true;
    if (toemail != null) {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            Session session = (Session) envCtx.lookup("mail/Session");

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(mailfrom));
            InternetAddress to[] = new InternetAddress[1];
            to[0] = new InternetAddress(toemail);
            msg.setRecipients(Message.RecipientType.TO, to);

            InternetAddress bcc[] = new InternetAddress[1];
            bcc[0] = new InternetAddress("r.rozendal@noterik.nl");
            msg.setRecipients(Message.RecipientType.BCC, bcc);

            msg.setSubject(mailsubject);
            msg.setContent(body, "text/html");
            Transport.send(msg);
        } catch (Exception e) {
            System.out.println("Failed sending email: " + e);
            success = false;
        }
    } else {
        success = false;
    }

    String response = "Your message has been successfuly sent.";
    if (!success)
        response = "There was a problem sending your mail.<br/>Please try again later.";

    mailResponse.put("status", Boolean.toString(success));
    mailResponse.put("message", response);

    s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");

}

From source file:org.sssw.relrel.FactFinder.java

/**
 * Lines 1-3 of the algorithm: init the table with the outgoing links (and
 * find the categories)./*from w  w  w  .jav  a 2s. c  o  m*/
 */
private void scrapInputPage() {

    HttpURLConnection con = null;
    BufferedReader reader = null;

    InputPage = InputPage.replaceAll(" ", "_");

    // do the query and save the retrieved json in an object.
    String queryAddress = String.format("https://%s.%s%s", Locale.ENGLISH, singlePageQuery, InputPage);

    try {

        con = (HttpURLConnection) (new URL(queryAddress)).openConnection();
        con.setRequestProperty("User-Agent", userAgent);
        con.setRequestMethod("GET");
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        Object json = (new JSONParser()).parse(reader);
        // closing connection
        con.disconnect();
        // The retrieved JSON is something like:
        //
        // "query": {
        //        "pages": {
        //            "<PAGE ID NUMBER>": {
        //                "pageid": "<PAGE ID NUMBER>",
        //                "ns": 0,
        //                "title": "<PAGE TITLE>",
        //                "categories": [
        //                    {
        //                        "ns": 14,
        //                        "title": "Category:<CATEGORY 1>"
        //                    },
        //                    {
        //                        "ns": 14,
        //                        "title": "Category:<CATEGORY 2>"
        //                    },
        //                    {
        //                        "ns": 14,
        //                        "title": "Category:<CATEGORY 3>"
        //                    }
        //                ],
        //                "extract":"<TEXT>",
        //                "links": [
        //                    {
        //                        "ns": 0,
        //                        "title": "<LINK 1>"
        //                    },
        //                     {
        //                        "ns": 0,
        //                        "title": "<LINK 2>"
        //                    },
        //                    {
        //                        "ns": 0,
        //                        "title": "<LINK 3>"
        //                    }
        //                 ]
        //            }
        //        }
        //    }
        //}
        // note that NOT ALL the wikis have the "extract" property in the API
        // therefore we may not assume that it will always be there
        JSONObject queryblock = (JSONObject) json;
        JSONObject pagesBlock = (JSONObject) queryblock.get("query");
        JSONObject idBlock = (JSONObject) pagesBlock.get("pages");

        // if we pipe'd more than one title, we'll have more than one pageId entry
        for (Iterator it = idBlock.keySet().iterator(); it.hasNext();) {

            String pageId = (String) it.next();
            JSONObject block = (JSONObject) idBlock.get(pageId);

            // iterate through categories
            JSONArray jsonCats = (JSONArray) block.get("categories");
            if (jsonCats != null) {
                Iterator<JSONObject> iterator = jsonCats.iterator();
                while (iterator.hasNext()) {
                    JSONObject category = (iterator.next());
                    String catName = (String) category.get("title");
                    catName = catName.replaceFirst("Category:", "");
                    catName = catName.replaceFirst("Categoria:", "");
                    if (!catName.toLowerCase().contains("stub") && !catName.contains("Featured Articles")
                            && !catName.toLowerCase().contains("disambiguation")) {

                        if (!this.categories.containsKey(catName) && !blackTerms.contains(catName)) {
                            if (!catName.contains("births") && (!catName.contains("deaths"))) {
                                this.categories.put(catName, 0);
                            }
                        }
                    }
                }
            }

            // We can find related entities in the text
            // many articles have a "See Also" section that begins with
            //          <h2>See also</h2>\n<ul>
            // and ends with:
            //          </ul>
            // To retrieve these links, we don't need to scrap HTML.
            // We can just read the list of links included in the JSON
            // the drawback of this approach is that some pages have huge
            // amounts of links and many of them are uninteresting
            // For example, almost any page has a reference to the
            // definition of ISBN (contained in the references)
            // or of some other kind of wide-used identifier such as:
            // Pub-Med index,
            // Digital-Object-Identifier,
            // International Standard Book Number,
            // Wikisource, and so on.
            JSONArray jsonLinks = (JSONArray) block.get("links");
            if (jsonLinks != null) {
                Iterator<JSONObject> iterator = jsonLinks.iterator();
                while (iterator.hasNext()) {
                    JSONObject link = (iterator.next());
                    String linkname = (String) link.get("title");

                    if (!this.links.containsKey(linkname) && !blackTerms.contains(linkname)) {
                        this.links.put(linkname, 0);
                    }

                }
            }
        }

    } catch (ParseException ex) {
        throw new RuntimeException("Error while parsing JSON by Wikipedia for page: " + InputPage, ex);
    } catch (MalformedURLException ex) {
        throw new RuntimeException("Malformed Wikipedia URL: " + queryAddress, ex);
    } catch (IOException ex) {
        throw new RuntimeException("Error while reading Wikipedia", ex);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException("Error while closing Wikipedia stream", ex);
        }
    }

}

From source file:org.sssw.relrel.FactFinder.java

private void findFactsInPage(String pageName) {

    HttpURLConnection con = null;
    BufferedReader reader = null;

    pageName = pageName.replaceAll(" ", "_");

    // do the query and save the retrieved json in an object.
    String queryAddress = String.format("https://%s.%s%s", Locale.ENGLISH, singlePageQuery, pageName);

    try {/*w w w.ja  v  a 2 s  .c o m*/

        con = (HttpURLConnection) (new URL(queryAddress)).openConnection();
        con.setRequestProperty("User-Agent", userAgent);
        con.setRequestMethod("GET");
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        Object json = (new JSONParser()).parse(reader);
        // closing connection
        con.disconnect();

        JSONObject queryblock = (JSONObject) json;
        JSONObject pagesBlock = (JSONObject) queryblock.get("query");
        JSONObject idBlock = (JSONObject) pagesBlock.get("pages");

        for (Iterator it = idBlock.keySet().iterator(); it.hasNext();) {

            String pageId = (String) it.next();
            JSONObject block = (JSONObject) idBlock.get(pageId);

            JSONArray jsonLinks = (JSONArray) block.get("links");
            if (jsonLinks != null) {
                Iterator<JSONObject> iterator = jsonLinks.iterator();
                while (iterator.hasNext()) {
                    JSONObject link = (iterator.next());
                    String linkName = (String) link.get("title");

                    if (this.links.containsKey(linkName)) {
                        int newValue = links.get(linkName) + 1;
                        links.replace(linkName, newValue);
                    }

                }
            }
        }

    } catch (ParseException ex) {
        throw new RuntimeException("Error while parsing JSON by Wikipedia for page: " + pageName, ex);
    } catch (MalformedURLException ex) {
        throw new RuntimeException("Malformed Wikipedia URL: " + queryAddress, ex);
    } catch (IOException ex) {
        throw new RuntimeException("Error while reading Wikipedia", ex);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException("Error while closing Wikipedia stream", ex);
        }
    }

}

From source file:org.surfing.service.things.Manager.java

public static void newSensorData(String deviceName, String data) {
    Device found = null;/*  w ww.  j av  a 2  s.c  o  m*/
    for (Device device : Kernel.getInstance().getDevices()) {
        if (device.getName().equals(deviceName)) {
            found = device;
        }
    }
    if (found == null) {
        return;
    }
    JSONObject jsonObject = (JSONObject) JSONValue.parse(data);
    if (jsonObject == null || jsonObject.keySet() == null || jsonObject.keySet().iterator() == null) {
        //System.out.println("Erro json " + data);
        return;
    }

    JSONArray components = (JSONArray) jsonObject.get("components");

    Iterator i = components.iterator();
    while (i.hasNext()) {
        Object oo = i.next();
        JSONObject joo = (JSONObject) oo;
        String thing = joo.get("name").toString();
        String value = joo.get("value").toString();
        found.getThings().get(thing).setLastValue(value);

    }

}

From source file:org.surfthing.service.rest.SensorManager.java

public static void newSensorData(String deviceName, String data) {
    Device found = null;/*from  w w w.j  av a  2 s. c  o  m*/
    for (Device device : Kernel.getInstance().getDevices()) {
        if (device.getName().equals(deviceName)) {
            found = device;
        }
    }
    if (found == null) {
        return;
    }
    JSONObject jsonObject = (JSONObject) JSONValue.parse(data);
    if (jsonObject == null || jsonObject.keySet() == null || jsonObject.keySet().iterator() == null) {
        //System.out.println("Erro json " + data);
        return;
    }

    Iterator i = jsonObject.keySet().iterator();
    //System.out.println("atualizando objetos");
    while (i.hasNext()) {
        String thing = (String) i.next();
        Object value = jsonObject.get(thing);
        //System.out.println("Thing" + thing + " Value " + value);
        found.getThings().get(thing).setLastValue(value.toString());
    }
}

From source file:org.topicquests.persist.json.es.blueprints.JSONDocStoreBlueprintsElement.java

public JSONDocStoreBlueprintsElement(JSONObject jo, final JSONDocStoreBlueprintsGraph g) {
    graph = g;//from   w ww.  j  a v  a  2 s. c o  m
    util = GraphUtil.getInstance();
    id = (String) jo.get(IBlueprintsGraphOntology.ID_PROPERTY);
    util.logDebug("JSONDocStoreBlueprintsElement-2 " + id);
    Iterator<String> itr = jo.keySet().iterator();
    String key;
    while (itr.hasNext()) {
        key = itr.next();
        this.setProperty(key, jo.get(key));
    }

}

From source file:org.topicquests.solr.agents.merge.SolrMergeEngine.java

public void studyDocument(String jsonString) {
    log.logDebug("SolrMergeEngine.studyDocument " + jsonString);
    System.out.println(jsonString);
    tracer.trace(0, jsonString);/* w w  w .  java2s. c o m*/
    Map<String, Object> o = new HashMap<String, Object>();
    try {
        JSONObject jo = (JSONObject) parser.parse(jsonString);
        String locator = (String) jo.get(ITopicQuestsOntology.LOCATOR_PROPERTY);
        // are we busy looking at this puppy
        synchronized (nodesInMerge) {
            if (nodesInMerge.contains(locator))
                return;
        }
        //TODO dump the JSONObject to this map
        Iterator<String> itr = jo.keySet().iterator();
        Object vo;
        String key;

        while (itr.hasNext()) {
            key = itr.next();
            vo = jo.get(key);
            if (vo instanceof String)
                o.put(key, vo);
            else if (vo instanceof JSONArray) {
                JSONArray ja = (JSONArray) vo;
                Iterator<String> jitr = ja.iterator();
                List<String> vl = new ArrayList<String>();
                while (jitr.hasNext())
                    vl.add(jitr.next());
                o.put(key, vl);
            }
        }
    } catch (Exception e) {
        agentEnvironment.logError(e.getMessage(), e);
        e.printStackTrace();
        return; //we cannot study this document
    }
    //should not try to merge tuples
    Object isTuple = o.get(ITopicQuestsOntology.TUPLE_SUBJECT_PROPERTY);
    //should not have an isVirtual property
    Object isVirtual = o.get(ITopicQuestsOntology.IS_VIRTUAL_PROXY);
    //should not have a mergeTuple property
    Object hasVirtual = o.get(ITopicQuestsOntology.MERGE_TUPLE_PROPERTY);
    //which nodeType?
    String typ = (String) o.get(ITopicQuestsOntology.INSTANCE_OF_PROPERTY_TYPE);
    boolean ismerge = false;
    if (typ != null)
        ismerge = (typ.equals(ITopicQuestsOntology.MERGE_ASSERTION_TYPE)
                || typ.equals(ITopicQuestsOntology.POSSIBLE_MERGE_ASSERTIONTYPE)
                || typ.equals(ITopicQuestsOntology.UNMERGE_ASSERTION_TYPE));
    // we do not merge virtual proxies or merge assertion tuples
    log.logDebug(
            "SolrMergeEngine.studyDocument-1 " + isVirtual + " " + hasVirtual + " " + ismerge + " " + isTuple);

    if (isVirtual == null && hasVirtual == null && !ismerge && isTuple == null) {
        INode node = new Node(o);
        TopicMergePortfolio pf = new TopicMergePortfolio(agentEnvironment, this);
        pf.studyNode(node);

        //poof! It's gone. That's a threaded activity
        //Trust me: it will be back!
    }
}