Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:com.controlj.addon.weather.util.ResponseWriter.java

public void appendToArray(String arrayName, String[] values) {
    try {/*from w  w w .  j a va  2 s.  com*/
        JSONArray array = getOrCreateArray(arrayName);
        JSONArray next = new JSONArray();
        for (String value : values) {
            next.put(value);
        }
        array.put(next);
    } catch (JSONException e) {
        Logging.println("Error adding to JSON array", e);
    }
}

From source file:com.controlj.addon.weather.util.ResponseWriter.java

public void appendToArray(String arrayName, Map<String, Object>[] values) {
    try {//from w w  w.j a  v a  2 s. c o m
        JSONArray array = getOrCreateArray(arrayName);
        JSONArray next = new JSONArray();
        for (Map<String, Object> value : values) {
            next.put(new JSONObject(value));
        }
        array.put(next);
    } catch (JSONException e) {
        Logging.println("Error adding to JSON array", e);
    }
}

From source file:com.controlj.addon.weather.util.ResponseWriter.java

private JSONArray getOrCreateArray(String arrayName) throws JSONException {
    JSONArray result;//  w  w  w. j a v a2  s  .  c  om
    if (jsonRoot.has(arrayName)) {
        result = (JSONArray) jsonRoot.get(arrayName);
    } else {
        result = new JSONArray();
        jsonRoot.put(arrayName, result);
    }
    return result;
}

From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java

private boolean save() {
    Collection<Participant> participants;
    synchronized (participantsMap) {
        participants = participantsMap.values();
    }//from w w w. jav  a  2s  . com

    JSONArray contactsJson;
    try {
        contactsJson = new JSONArray();
        for (Participant participant : participants) {
            JSONObject contactJson = new JSONObject();
            contactJson.put("id", participant.userId);
            contactJson.put("first_name", participant.firstName);
            contactJson.put("last_name", participant.lastName);
            contactsJson.put(contactJson);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Error while saving", e);
        return false;
    }

    SharedPreferences.Editor editor = context.getSharedPreferences("contacts", Context.MODE_PRIVATE).edit();
    editor.putString("json", contactsJson.toString());
    editor.commit();

    return true;
}

From source file:ca.viaware.dlna.webinterface.InterfaceServer.java

public void start() {

    server.createContext("/list/", new HttpHandler() {

        private void exploreEntries(JSONArray children, ArrayList<LibraryEntry> entries, int parent) {
            for (LibraryEntry e : entries) {
                if (e.getParent() == parent) {
                    JSONObject entryJson = new JSONObject();
                    entryJson.put("name", e.getName());
                    entryJson.put("id", e.getId());
                    entryJson.put("type", e.getTypeID());
                    if (e.getTypeID() == EntryType.CONTAINER) {
                        JSONArray sub = new JSONArray();
                        entryJson.put("children", sub);
                        exploreEntries(sub, entries, e.getId());
                    }/*from   www . j av  a2s . com*/
                    children.put(entryJson);
                }
            }
        }

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String json = (String) Library.runInstance(new LibraryInstanceRunner() {
                @Override
                public Object run(LibraryFactory factory) {
                    JSONArray root = new JSONArray();
                    ArrayList<LibraryEntry> entries = factory.getAll();

                    exploreEntries(root, entries, -1);
                    return new JSONObject().put("entries", root).toString(4);
                }
            });

            while (exchange.getRequestBody().read() != -1) {
            }

            byte[] bytes = json.getBytes("UTF-8");

            Headers headers = exchange.getResponseHeaders();
            headers.set("CONTENT-TYPE", "application/json");
            headers.set("CONTENT-LANGUAGE", "en");
            exchange.sendResponseHeaders(200, bytes.length);

            exchange.getResponseBody().write(bytes);
            exchange.getResponseBody().close();
        }
    });

    server.start();
    Log.info("Started Web Interface HTTP server");
}

From source file:at.alladin.rmbt.qos.QoSUtil.java

/**
 * /*from ww  w  .  j  a va2  s  . c o  m*/
 * @param settings
 * @param conn
 * @param answer
 * @param lang
 * @param errorList
 * @throws SQLException 
 * @throws JSONException 
 * @throws HstoreParseException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
public static void evaluate(final ResourceBundle settings, final Connection conn, final TestUuid uuid,
        final JSONObject answer, String lang, final ErrorList errorList) throws SQLException,
        HstoreParseException, JSONException, IllegalArgumentException, IllegalAccessException {
    // Load Language Files for Client

    final List<String> langs = Arrays.asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

    if (langs.contains(lang)) {
        errorList.setLanguage(lang);
    } else {
        lang = settings.getString("RMBT_DEFAULT_LANGUAGE");
    }

    if (conn != null) {

        final Client client = new Client(conn);
        final Test test = new Test(conn);

        boolean necessaryDataAvailable = false;

        if (uuid != null && uuid.getType() != null && uuid.getUuid() != null) {
            switch (uuid.getType()) {
            case OPEN_TEST_UUID:
                if (test.getTestByOpenTestUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            case TEST_UUID:
                if (test.getTestByUuid(UUID.fromString(uuid.getUuid())) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {
                    necessaryDataAvailable = true;
                }
                break;
            }
        }

        final long timeStampFullEval = System.currentTimeMillis();

        if (necessaryDataAvailable) {

            final Locale locale = new Locale(lang);
            final ResultOptions resultOptions = new ResultOptions(locale);
            final JSONArray resultList = new JSONArray();

            QoSTestResultDao resultDao = new QoSTestResultDao(conn);
            List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid());
            if (testResultList == null || testResultList.isEmpty()) {
                throw new UnsupportedOperationException("test " + test + " has no result list");
            }
            //map that contains all test types and their result descriptions determined by the test result <-> test objectives comparison
            Map<TestType, TreeSet<ResultDesc>> resultKeys = new HashMap<>();

            //test description set:
            Set<String> testDescSet = new TreeSet<>();
            //test summary set:
            Set<String> testSummarySet = new TreeSet<>();

            //Staring timestamp for evaluation time measurement
            final long timeStampEval = System.currentTimeMillis();

            //iterate through all result entries
            for (final QoSTestResult testResult : testResultList) {

                //reset test counters
                testResult.setFailureCounter(0);
                testResult.setSuccessCounter(0);

                //get the correct class of the result;
                TestType testType = null;
                try {
                    testType = TestType.valueOf(testResult.getTestType().toUpperCase(Locale.US));
                } catch (IllegalArgumentException e) {
                    final String errorMessage = "WARNING: QoS TestType '"
                            + testResult.getTestType().toUpperCase(Locale.US)
                            + "' not supported by ControlServer. Test with UID: " + testResult.getUid()
                            + " skipped.";
                    System.out.println(errorMessage);
                    errorList.addErrorString(errorMessage);
                    testType = null;
                }

                if (testType == null) {
                    continue;
                }

                Class<? extends AbstractResult<?>> clazz = testType.getClazz();
                //parse hstore data
                final JSONObject resultJson = new JSONObject(testResult.getResults());
                AbstractResult<?> result = QoSUtil.HSTORE_PARSER.fromJSON(resultJson, clazz);
                result.setResultJson(resultJson);

                if (result != null) {
                    //add each test description key to the testDescSet (to fetch it later from the db)
                    if (testResult.getTestDescription() != null) {
                        testDescSet.add(testResult.getTestDescription());
                    }
                    if (testResult.getTestSummary() != null) {
                        testSummarySet.add(testResult.getTestSummary());
                    }
                    testResult.setResult(result);

                }

                //compare test results
                compareTestResults(testResult, result, resultKeys, testType, resultOptions);

                //resultList.put(testResult.toJson());

                //save all test results after the success and failure counters have been set
                //resultDao.updateCounter(testResult);
            }

            //ending timestamp for evaluation time measurement
            final long timeStampEvalEnd = System.currentTimeMillis();

            //-------------------------------------------------------------
            //fetch all result strings from the db
            QoSTestDescDao descDao = new QoSTestDescDao(conn, locale);

            //FIRST: get all test descriptions
            Set<String> testDescToFetchSet = testDescSet;
            testDescToFetchSet.addAll(testSummarySet);

            Map<String, String> testDescMap = descDao.getAllByKeyToMap(testDescToFetchSet);

            for (QoSTestResult testResult : testResultList) {

                //and set the test results + put each one to the result list json array
                String preParsedDesc = testDescMap.get(testResult.getTestDescription());
                if (preParsedDesc != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestDescription()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestDescription(description);
                }

                //do the same for the test summary:
                String preParsedSummary = testDescMap.get(testResult.getTestSummary());
                if (preParsedSummary != null) {
                    String description = String.valueOf(
                            TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestSummary()),
                                    QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions));
                    testResult.setTestSummary(description);
                }

                resultList.put(testResult.toJson(uuid.getType()));
            }

            //finally put results to json
            answer.put("testresultdetail", resultList);

            JSONArray resultDescArray = new JSONArray();

            //SECOND: fetch all test result descriptions 
            for (TestType testType : resultKeys.keySet()) {
                TreeSet<ResultDesc> descSet = resultKeys.get(testType);
                //fetch results to same object
                descDao.loadToTestDesc(descSet);

                //another tree set for duplicate entries:
                //TODO: there must be a better solution 
                //(the issue is: compareTo() method returns differnt values depending on the .value attribute (if it's set or not))
                TreeSet<ResultDesc> descSetNew = new TreeSet<>();
                //add fetched results to json

                for (ResultDesc desc : descSet) {
                    if (!descSetNew.contains(desc)) {
                        descSetNew.add(desc);
                    } else {
                        for (ResultDesc d : descSetNew) {
                            if (d.compareTo(desc) == 0) {
                                d.getTestResultUidList().addAll(desc.getTestResultUidList());
                            }
                        }
                    }
                }

                for (ResultDesc desc : descSetNew) {
                    if (desc.getValue() != null) {
                        resultDescArray.put(desc.toJson());
                    }
                }

            }
            //System.out.println(resultDescArray);
            //put result descriptions to json
            answer.put("testresultdetail_desc", resultDescArray);

            QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
            JSONArray testTypeDescArray = new JSONArray();
            for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                final JSONObject testTypeDesc = desc.toJson();
                if (testTypeDesc != null) {
                    testTypeDescArray.put(testTypeDesc);
                }
            }

            //put result descriptions to json
            answer.put("testresultdetail_testdesc", testTypeDescArray);
            JSONObject evalTimes = new JSONObject();
            evalTimes.put("eval", (timeStampEvalEnd - timeStampEval));
            evalTimes.put("full", (System.currentTimeMillis() - timeStampFullEval));
            answer.put("eval_times", evalTimes);

            //System.out.println(answer);
        } else
            errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

    } else
        errorList.addError("ERROR_DB_CONNECTION");
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public void save() throws IOException {
    JSONObject json = new JSONObject();
    JSONArray listID = new JSONArray(), listText = new JSONArray(), listProp = new JSONArray();
    JSONArray listVal = new JSONArray(), listLit = new JSONArray(), listRef = new JSONArray(),
            listAsrt = new JSONArray();

    for (Identifier id : identifiers) {
        JSONObject obj = new JSONObject();
        obj.put("regex", id.regex);
        obj.put("prefix", id.prefix);
        listID.put(obj);//from www. j  a  v a 2 s  . c  o m
    }
    for (TextBlock txt : textBlocks) {
        JSONObject obj = new JSONObject();
        obj.put("regex", txt.regex);
        obj.put("title", txt.title);
        listText.put(obj);
    }
    for (Property prop : properties) {
        JSONObject obj = new JSONObject();
        obj.put("regex", prop.regex);
        obj.put("propURI", prop.propURI);
        obj.put("groupNest", prop.groupNest);
        listProp.put(obj);
    }
    for (Value val : values) {
        JSONObject obj = new JSONObject();
        obj.put("regex", val.regex);
        obj.put("valueRegex", val.valueRegex);
        obj.put("valueURI", val.valueURI);
        obj.put("propURI", val.propURI);
        obj.put("groupNest", val.groupNest);
        listVal.put(obj);
    }
    for (Literal lit : literals) {
        JSONObject obj = new JSONObject();
        obj.put("regex", lit.regex);
        obj.put("valueRegex", lit.valueRegex);
        obj.put("propURI", lit.propURI);
        obj.put("groupNest", lit.groupNest);
        listLit.put(obj);
    }
    for (Reference ref : references) {
        JSONObject obj = new JSONObject();
        obj.put("regex", ref.regex);
        obj.put("valueRegex", ref.valueRegex);
        obj.put("prefix", ref.prefix);
        obj.put("propURI", ref.propURI);
        obj.put("groupNest", ref.groupNest);
        listRef.put(obj);
    }
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", asrt.propURI);
        obj.put("groupNest", asrt.groupNest);
        obj.put("valueURI", asrt.valueURI);
        listAsrt.put(obj);
    }

    json.put("identifiers", listID);
    json.put("textBlocks", listText);
    json.put("properties", listProp);
    json.put("values", listVal);
    json.put("literals", listLit);
    json.put("references", listRef);
    json.put("assertions", listAsrt);

    Writer wtr = new FileWriter(file);
    wtr.write(json.toString(2));
    wtr.close();
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;//w ww  . j  a v a  2s.c  o m
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:com.amossys.hooker.common.InterceptEvent.java

/**
 * @return//from  ww  w. j  a v a2 s  .  co  m
 */
public String toJson() {
    JSONObject object = new JSONObject();

    try {
        //      object.put("IdEvent", this.getIdEvent().toString());

        object.put("Timestamp", this.getTimestamp());
        object.put("RelativeTimestamp", this.getRelativeTimestamp());
        object.put("HookerName", this.getHookerName());
        object.put("IntrusiveLevel", this.getIntrusiveLevel());
        object.put("InstanceID", this.getInstanceID());
        object.put("PackageName", this.getPackageName());

        object.put("ClassName", this.getClassName());
        object.put("MethodName", this.getMethodName());

        JSONArray parameters = new JSONArray();
        if (this.getParameters() != null) {
            for (Entry<String, String> parameter : this.getParameters()) {
                JSONObject jsonParameter = new JSONObject();
                jsonParameter.put("ParameterType", parameter.getKey());
                jsonParameter.put("ParameterValue", parameter.getValue());
                parameters.put(jsonParameter);
            }
        }
        object.put("Parameters", parameters);

        JSONObject returns = new JSONObject();
        if (this.getReturns() != null) {
            returns.put("ReturnType", this.getReturns().getKey());
            returns.put("ReturnValue", this.getReturns().getValue());
        }
        object.put("Return", returns);

        JSONArray data = new JSONArray();
        if (this.getData() != null) {
            for (String dataName : this.getData().keySet()) {
                if (dataName != null && this.getData().get(dataName) != null) {
                    JSONObject dataP = new JSONObject();
                    dataP.put("DataName", dataName);
                    dataP.put("DataValue", this.getData().get(dataName));
                }
            }
        }
        object.put("Data", data);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return object.toString();
}

From source file:com.apress.progwt.server.web.controllers.GearsLocalServerManifestController.java

private JSONArray getEntries(File dir, String localServerURL) throws JSONException {
    JSONArray fileArray = new JSONArray();
    return getEntries(dir, localServerURL, "", fileArray);
}