Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

public void handleHierarchyPayloadSend(Record thisr, Map<String, Document> body, JSONObject jsonObject,
        String thiscsid) throws JSONException, ExistException, UnderlyingStorageException {
    if (thisr.hasHierarchyUsed("screen")) {
        Spec spec = this.r.getSpec();
        ArrayList<Element> alleles = new ArrayList<Element>();
        for (Relationship rel : r.getSpec().getAllRelations()) {
            Relationship newrel = rel;// ww w . j av a 2s  .  com
            Boolean inverse = false;
            if (rel.hasInverse()) {
                newrel = thisr.getSpec().getRelation(rel.getInverse());
                inverse = true;
            }
            //does this relationship apply to this record
            if (rel.hasSourceType(r.getID())) {

                //does this record have the data in the json
                if (jsonObject.has(rel.getID())) {
                    String metaTypeField = rel.getMetaTypeField();
                    if (rel.getObject().equals("1")) {
                        if (jsonObject.has(rel.getID()) && !jsonObject.get(rel.getID()).equals("")) {
                            // Look for a metatype
                            String metaType = "";
                            if (!StringUtils.isEmpty(metaTypeField) && jsonObject.has(metaTypeField)) {
                                metaType = jsonObject.getString(metaTypeField);
                            }
                            Element bit = createRelationship(newrel, jsonObject.get(rel.getID()), thiscsid,
                                    r.getServicesURL(), metaType, inverse, spec);
                            if (bit != null) {
                                alleles.add(bit);
                            }
                        }
                    } else if (rel.getObject().equals("n")) {
                        //if()
                        JSONArray temp = jsonObject.getJSONArray(rel.getID());
                        for (int i = 0; i < temp.length(); i++) {
                            String relFieldName = rel.getChildName();
                            JSONObject relItem = temp.getJSONObject(i);
                            if (relItem.has(relFieldName) && !relItem.getString(relFieldName).equals("")) {
                                String uri = relItem.getString(relFieldName);
                                // Look for a metatype
                                String metaType = "";
                                if (!StringUtils.isEmpty(metaTypeField) && relItem.has(metaTypeField)) {
                                    metaType = relItem.getString(metaTypeField);
                                }
                                Element bit = createRelationship(newrel, uri, thiscsid, r.getServicesURL(),
                                        metaType, inverse, spec);
                                if (bit != null) {
                                    alleles.add(bit);
                                }
                            }
                        }

                    }
                }
            }
        }
        //add relationships section
        if (!alleles.isEmpty()) {
            Element[] array = alleles.toArray(new Element[0]);
            Document out = XmlJsonConversion.getXMLRelationship(array);
            body.put("relations-common-list", out);
            //log.info(out.asXML());
        } else {

            Document out = XmlJsonConversion.getXMLRelationship(null);
            body.put("relations-common-list", out);
            //log.info(out.asXML());
        }
        //probably should put empty array in if no data
    }
}

From source file:io.v.positioning.GpsLocationServlet.java

/**
 * Processes a POST request to save device's GPS location
 *
 * @param req  The servlet request that includes JSONObject with properties to be saved
 * @param resp The servlet response informing a user if the request was successful or not
 */// w  ww .  j a  v  a2 s .  co m
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    BufferedReader br = req.getReader();
    try {
        JSONObject jo = new JSONObject(br.readLine());
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Entity entity = new Entity("gps");
        entity.setProperty("androidId", jo.get("androidId"));
        entity.setProperty("latitude", jo.get("latitude"));
        entity.setProperty("longitude", jo.get("longitude"));
        entity.setProperty("deviceTime", jo.get("deviceTime"));
        entity.setProperty("serverTime", System.currentTimeMillis());
        datastore.put(entity);
        resp.getWriter().println("New GPS location added.");
    } catch (Exception e) {
        resp.getWriter().println("Recording failed. " + e.getMessage());
    }
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

public Document input(final String json) throws JSONException {
    JSONObject rootJson = new JSONObject(json);
    List<String> keys = Arrays.asList(JSONObject.getNames(rootJson));
    List<Namespace> namespaces = new ArrayList<Namespace>();
    Namespace namespace = getNamespace(namespaces, rootJson, keys);

    String rootKey = null;/*from  w w  w  . j  av  a 2 s.  com*/
    List<Attribute> attributes = new ArrayList<Attribute>();
    for (String key : keys) {
        if (!key.startsWith("@xmlns")) {
            if (key.startsWith("@")) {
                String value;
                if (rootJson.isNull(key)) {
                    value = "";
                } else {
                    value = getStringValue(rootJson.get(key));
                }
                attributes.add(new Attribute(key.substring(1), value));
            } else {
                // DOM can only have one root element.
                if (rootKey != null) {
                    throw new IllegalStateException("Found multiple root entries");
                }
                rootKey = key;
            }
        }
    }

    Element rootElement = new Element(rootKey, namespace);
    for (Attribute attribute : attributes) {
        rootElement.setAttribute(attribute);
    }

    Object value = rootJson.get(rootKey);
    processObject(rootKey, value, rootElement, namespace, namespaces);

    Document document = new Document();
    document.setRootElement(rootElement);
    return document;
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

private void processJSONObject(JSONObject jsonObject, Element element, List<Namespace> namespaces)
        throws JSONException {
    List<String> keys = Arrays.asList(JSONObject.getNames(jsonObject));
    Namespace namespace = getNamespace(namespaces, jsonObject, keys);
    if (namespace == null) {
        namespace = element.getNamespace();
    }//ww w.j a v a2  s  . co  m

    for (String key : keys) {
        if (jsonObject.isNull(key)) {
            continue;
        }

        // attribute
        if (key.startsWith("@")) {
            Object value = jsonObject.get(key);
            element.setAttribute(new Attribute(key.substring(1), getStringValue(value)));
            continue;
        }

        // text content
        Object value = jsonObject.get(key);
        if (key.equals("$")) {
            element.setText(getStringValue(value));
            continue;
        }

        Element child = new Element(key, namespace);
        if (listElementMap.containsKey(key)) {
            final String childKey = listElementMap.get(key);
            final Object childObject = ((JSONObject) value).get("$");
            Element grandChild = new Element(childKey, namespace);

            if (childObject instanceof JSONArray) {
                processJSONArray(key, (JSONArray) childObject, child, namespace, namespaces);
            } else if (childObject instanceof JSONObject) {
                processJSONObject((JSONObject) childObject, grandChild, namespaces);
                child.addContent(grandChild);
            }
        } else if (value instanceof JSONObject) {
            processJSONObject((JSONObject) value, child, namespaces);
        }

        element.addContent(child);
    }
}

From source file:edu.wpi.margrave.SQSReader.java

protected static Formula handleStatementCondition(JSONObject obj, Formula theCondition, MVocab vocab)
        throws JSONException, MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {
    // Condition block is a conjunctive list of conditions. all must apply.
    // Each condition is a conjunctive list of value sets. 
    // Each value set is a disjunctive list of values
    // Keys in the condition block are functions to apply
    // Keys in a condition are attribute names. Values are values.

    // Condition block
    //    Function : {}
    //    Function : {}
    // .../* ww w.  ja v a 2  s . c  o m*/

    JSONArray conditionNames = obj.names();
    for (int iCondition = 0; iCondition < conditionNames.length(); iCondition++) {
        String cFunction = (String) conditionNames.get(iCondition);
        JSONObject condition = (JSONObject) obj.get(cFunction);
        //MEnvironment.errorStream.println(cFunction + ": "+condition);

        // condition is a key:value pair or multiple such pairs. The value may be an array.
        // Each sub-condition must be met.
        HashSet<Formula> thisCondition = new HashSet<Formula>();

        JSONArray subConditionNames = condition.names();
        for (int iSubCondition = 0; iSubCondition < subConditionNames.length(); iSubCondition++) {
            String cSubKey = (String) subConditionNames.get(iSubCondition);
            Object subcondition = condition.get(cSubKey);

            // Subcondition: is it an array or a single value?
            if (subcondition instanceof JSONArray) {
                JSONArray subarr = (JSONArray) subcondition;
                HashSet<Formula> valuedisj = new HashSet<Formula>();
                for (int iValue = 0; iValue < subarr.length(); iValue++) {
                    //MEnvironment.errorStream.println(cFunction+"("+cSubKey+", "+subarr.get(iValue)+")");
                    Formula theatom = makeSQSAtom(vocab, "c", "Condition",
                            cFunction + "<" + cSubKey + "><" + subarr.get(iValue) + ">");
                    valuedisj.add(theatom);
                }

                thisCondition.add(MFormulaManager.makeDisjunction(valuedisj));
            } else {
                //MEnvironment.errorStream.println(cFunction+"("+cSubKey+", "+subcondition+")");   
                Formula theatom = makeSQSAtom(vocab, "c", "Condition",
                        cFunction + "<" + cSubKey + "><" + subcondition + ">");
                thisCondition.add(theatom);
            }

        }

        theCondition = MFormulaManager.makeAnd(theCondition, MFormulaManager.makeConjunction(thisCondition));
    }

    return theCondition;
}

From source file:edu.wpi.margrave.SQSReader.java

protected static Formula handleStatementPAR(Object obj, String varname, String parentsortname,
        Formula theTarget, MVocab vocab, String prepend) throws MGEUnsupportedSQS, JSONException,
        MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {
    // obj may be a JSONObject (Principal examples)
    //   with a child with a value OR array of values

    //"Principal": {
    //"AWS": "*"/*from   ww  w.  j  av  a2  s .c  o  m*/
    //}

    //"Principal": {
    //"AWS": ["123456789012","555566667777"]
    //}

    // may also be a simple value (Action example)
    // or an array of values (Resource examples)

    // "Action": ["SQS:SendMessage","SQS:ReceiveMessage"],
    // "Resource": "/987654321098/queue1"

    // TODO: the example principal from "Element Descriptions" doesn't parse...
    //"Principal":[
    //             "AWS": "123456789012",
    //             "AWS": "999999999999"
    //          ]
    // is this just a bad example?

    // *****************************
    // Step 1: Is this a JSONObject? If so, it should have only one key. Prepend that key
    // to all predicate names produced by its value.
    if (obj instanceof JSONObject) {
        JSONObject jobj = (JSONObject) obj;
        JSONArray names = jobj.names();
        if (names.length() != 1)
            throw new MGEUnsupportedSQS("Number of keys != 1 as expected: " + obj.toString());

        Object inner = jobj.get((String) names.get(0));
        return handleStatementPAR(inner, varname, parentsortname, theTarget, vocab,
                prepend + MEnvironment.sIDBSeparator + names.get(0));
    }

    // Now if obj is a simple value, we have a predicate name.
    // If it is an array of length n, we have n predicate names.      
    if (obj instanceof JSONArray) {
        JSONArray jarr = (JSONArray) obj;
        HashSet<Formula> possibleValues = new HashSet<Formula>();

        for (int ii = 0; ii < jarr.length(); ii++) {
            //MEnvironment.errorStream.println(prepend+"="+jarr.get(ii));

            Formula theatom = makeSQSAtom(vocab, varname, parentsortname, prepend + "=" + jarr.get(ii));
            possibleValues.add(theatom);

        }

        theTarget = MFormulaManager.makeAnd(theTarget, MFormulaManager.makeDisjunction(possibleValues));

    } else {
        Formula theatom = makeSQSAtom(vocab, varname, parentsortname, prepend + "=" + obj);
        theTarget = MFormulaManager.makeAnd(theTarget, theatom);
    }

    return theTarget;
}

From source file:edu.wpi.margrave.SQSReader.java

protected static void handleSQSStatement(JSONObject thisStatement, MPolicyLeaf result, int counter)
        throws JSONException, MGEUnsupportedSQS, MGEBadIdentifierName, MGEUnknownIdentifier,
        MGEManagerException {/*from w w w.  j a  va  2  s .com*/
    String ruleId = result.name + "_rule_" + counter;

    // Documentation says the statement ID is optional.
    if (!thisStatement.isNull("Sid"))
        ruleId = thisStatement.getString("Sid");

    String effect;
    if (!thisStatement.isNull("Effect"))
        effect = thisStatement.getString("Effect");
    else
        return; // no effect means no need to add the rule

    List<String> ruleNameOrdering = new ArrayList<String>(4);
    ruleNameOrdering.add("p");
    ruleNameOrdering.add("a");
    ruleNameOrdering.add("r");
    ruleNameOrdering.add("c");

    Formula theTarget = Formula.TRUE;
    Formula theCondition = Formula.TRUE;

    // target starts as true. All criteria must be met, so just "and" each on.

    // *************************
    // "Principal": disjunction
    if (thisStatement.isNull("Principal"))
        return; // never applies, so don't create the rule.            
    theTarget = handleStatementPAR(thisStatement.get("Principal"), "p", "Principal", theTarget, result.vocab,
            "Principal");

    // *************************      
    // "Action": disjunction
    if (thisStatement.isNull("Action"))
        return; // never applies, so don't create the rule.
    theTarget = handleStatementPAR(thisStatement.get("Action"), "a", "Action", theTarget, result.vocab,
            "Action");

    // *************************
    // "Resource": disjunction
    if (thisStatement.isNull("Resource"))
        return; // never applies, so don't create the rule.
    theTarget = handleStatementPAR(thisStatement.get("Resource"), "r", "Resource", theTarget, result.vocab,
            "Resource");

    // *************************
    // "Condition": more complex
    // Condition optional? TODO -- for now if no condition, just finalize the rule. 
    // (Why are P/A/R special?)
    if (!thisStatement.isNull("Condition"))
        theCondition = handleStatementCondition(thisStatement.getJSONObject("Condition"), theTarget,
                result.vocab);

    // Finalize the rule.
    result.addRule(ruleId, effect, ruleNameOrdering, theTarget, theCondition);
}

From source file:edu.wpi.margrave.SQSReader.java

protected static MPolicy loadSQS(String polId, String sFileName) throws MUserException {
    // Convert filename
    sFileName = MPolicy.convertSeparators(sFileName);

    // Read in the JSON text

    BufferedReader reader;//from ww  w.  j a va  2  s . c o m
    try {
        reader = new BufferedReader(new FileReader(sFileName));
        StringBuffer target = new StringBuffer();
        while (reader.ready()) {
            String line = reader.readLine();
            target.append(line + "\n");
        }
        reader.close();

        JSONObject json = new JSONObject(target.toString());

        // Use provided policy ID
        //String polId;         
        //if(!json.isNull("Id"))
        //   polId = json.getString("Id");
        //else
        //   throw new MGEUnsupportedSQS("Id element must be present.");

        MVocab env = createSQSVocab(polId);
        MPolicyLeaf result = new MPolicyLeaf(polId, env);

        result.declareVariable("p", "Principal");
        result.declareVariable("a", "Action");
        result.declareVariable("r", "Resource");
        result.declareVariable("c", "Condition");

        // Get statements; may be an array or a single statement object.
        Object statement_s = json.get("Statement");
        if (statement_s instanceof JSONArray) {
            JSONArray statements = json.getJSONArray("Statement");

            for (int ii = 0; ii < statements.length(); ii++) {
                JSONObject thisStatement = statements.getJSONObject(ii);
                handleSQSStatement(thisStatement, result, ii);
            }
        } else
            handleSQSStatement((JSONObject) statement_s, result, 0);

        // "Allow overrides a `default deny' but never an explicit deny."
        // Default deny is N/a.
        Set<String> denySet = new HashSet<String>();
        denySet.add("Deny");
        result.rCombineWhatOverrides.put("Allow", denySet); // Allow < {Deny}

        result.initIDBs();

        return result;

    } catch (IOException e) {
        throw new MGEUnsupportedSQS(e.toString());
    } catch (JSONException e) {
        throw new MGEUnsupportedSQS(e.toString());
    }

}

From source file:notaql.performance.PerformanceTest.java

private static String composeEngine(JSONObject engine) {
    final StringBuilder builder = new StringBuilder();
    builder.append(engine.get("engine"));
    builder.append("(");

    final String params = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(engine.keys(), Spliterator.ORDERED), false)
            .filter(k -> !k.equals("engine")).map(k -> k + " <- " + toArg(k, engine))
            .collect(Collectors.joining(", "));

    builder.append(params);//from   ww w .j  a v  a2  s .c o  m
    builder.append(")");

    return builder.toString();
}

From source file:notaql.performance.PerformanceTest.java

private static String toArg(String key, JSONObject engine) {
    final Object val = engine.get(key);
    if (val instanceof Boolean || val instanceof Number)
        return val.toString();

    return "'" + val.toString() + "'";
}