Example usage for org.json.simple JSONArray size

List of usage examples for org.json.simple JSONArray size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:at.ac.tuwien.dsg.rSybl.cloudInteractionUnit.enforcementPlugins.dryRun.DryRunEnforcementAPI.java

public void readParameters() {
    JSONParser parser = new JSONParser();

    try {// w  w w. j  av a2s.  c  om
        InputStream inputStream = Configuration.class.getClassLoader()
                .getResourceAsStream("config/resources.json");
        Object obj = parser.parse(new InputStreamReader(inputStream));

        JSONObject jsonObject = (JSONObject) obj;

        for (Object p : jsonObject.keySet()) {
            String pluginName = (String) p;
            JSONObject plugin = (JSONObject) jsonObject.get(pluginName);
            if (pluginName.toLowerCase().contains("dry")) {
                for (Object a : plugin.keySet()) {
                    String actionName = (String) a;
                    JSONObject action = (JSONObject) plugin.get(actionName);
                    JSONArray jSONArray = (JSONArray) action.get("parameters");
                    for (int i = 0; i < jSONArray.size(); i++) {
                        parameters.add((String) jSONArray.get(i));
                    }

                }
            }
        }
    } catch (Exception e) {
        RuntimeLogger.logger.info(e.getMessage());
    }
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * Populate the texts with the correct instances based on the importspec.
 * @throws Exception /* ww w.ja  v  a2  s  . com*/
 */
private void setupTexts() throws Exception {
    // get the texts, if any
    JSONArray textsInfo = (JSONArray) this.importspec.get("texts");
    if (textsInfo == null) {
        return;
    }

    for (int j = 0; j < textsInfo.size(); ++j) {
        JSONObject textJson = (JSONObject) textsInfo.get(j);
        String instanceID = (String) textJson.get("textId");
        String textVal = (String) textJson.get("text");
        this.textsAvailable.put(instanceID, textVal);
    }
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * Populate the texts with the correct instances based on the importspec.
 * @throws Exception /*ww w . ja va  2  s .  c o m*/
 */
private void setupColumns() throws Exception {
    // get the texts, if any
    JSONArray colsInfo = (JSONArray) this.importspec.get("columns");
    if (colsInfo == null) {
        return;
    }

    for (int j = 0; j < colsInfo.size(); ++j) {
        JSONObject colsJson = (JSONObject) colsInfo.get(j);
        String colId = (String) colsJson.get("colId");
        String colName = ((String) colsJson.get("colName")).toLowerCase();
        this.colsAvailable.put(colId, colName);
    }
}

From source file:functionaltests.RestSchedulerJobPaginationTest.java

private void checkJobIds(boolean indexAndRange, int index, int limit, String... expectedIds) throws Exception {
    JSONObject page;/*from  w  w  w .ja va2 s.c  o m*/
    JSONArray jobs;

    Set<String> expected = new HashSet<>(Arrays.asList(expectedIds));
    Set<String> actual = new HashSet<>();

    String url;

    // test 'jobs' request
    if (indexAndRange) {
        url = getResourceUrl("jobs?index=" + index + "&limit=" + limit);
    } else {
        url = getResourceUrl("jobs");
    }
    page = getRequestJSONObject(url);
    jobs = (JSONArray) page.get("list");
    for (int i = 0; i < jobs.size(); i++) {
        actual.add((String) jobs.get(i));
    }

    Assert.assertEquals("Unexpected result of 'jobs' request (" + url + ")", expected, actual);

    // test 'jobsinfo' request
    if (indexAndRange) {
        url = getResourceUrl("jobsinfo?index=" + index + "&limit=" + limit);
    } else {
        url = getResourceUrl("jobsinfo");
    }
    page = getRequestJSONObject(url);
    jobs = (JSONArray) page.get("list");
    actual.clear();
    for (int i = 0; i < jobs.size(); i++) {
        JSONObject job = (JSONObject) jobs.get(i);
        actual.add((String) job.get("jobid"));
    }
    Assert.assertEquals("Unexpected result of 'jobsinfo' request (" + url + ")", expected, actual);

    // test 'revisionjobsinfo' request
    if (indexAndRange) {
        url = getResourceUrl("revisionjobsinfo?index=" + index + "&limit=" + limit);
    } else {
        url = getResourceUrl("revisionjobsinfo");
    }
    checkRevisionJobsInfo(url, expectedIds);
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

public String getCollectionValues(JsonSimple emailConfig, JsonSimple tfPackage, String varField) {
    String formattedCollectionValues = "";
    JSONArray subKeys = emailConfig.getArray("collections", varField, "subKeys");
    String tfPackageField = emailConfig.getString("", "collections", varField, "payloadKey");
    if (StringUtils.isNotBlank(tfPackageField) && subKeys instanceof JSONArray) {
        List<JsonObject> jsonList = new StorageDataUtil().getJavaList(tfPackage, tfPackageField);
        log.debug("Collating collection values for email template...");
        JSONArray fieldSeparators = emailConfig.getArray("collections", varField, "fieldSeparators");
        String recordSeparator = emailConfig.getString(IOUtils.LINE_SEPARATOR, "collections", varField,
                "recordSeparator");
        String nextDelimiter = " ";

        for (JsonObject collectionRow : jsonList) {
            if (fieldSeparators instanceof JSONArray && fieldSeparators.size() > 0) {
                // if no more delimiters, continue to use the last one specified
                Object nextFieldSeparator = fieldSeparators.remove(0);
                if (nextFieldSeparator instanceof String) {
                    nextDelimiter = (String) nextFieldSeparator;
                } else {
                    log.warn("Unable to retrieve String value from fieldSeparator: "
                            + fieldSeparators.toString());
                }/*  ww  w.j  a v  a  2 s .  c  om*/
            }
            List<String> collectionValuesList = new ArrayList<String>();
            for (Object requiredKey : subKeys) {
                Object rawKeyValue = collectionRow.get(requiredKey);
                if (rawKeyValue instanceof String) {
                    String keyValue = StringUtils.trim((String) rawKeyValue);
                    if (StringUtils.isNotBlank(keyValue)) {
                        collectionValuesList.add(keyValue);
                    } else if (!isVariableNameHiddenIfEmpty) {
                        collectionValuesList.add("$" + requiredKey);
                    } else {
                        log.info("blank variable name will be hidden: " + keyValue);
                    }
                } else {
                    log.warn("No string value returned from: " + requiredKey);
                }
            }
            formattedCollectionValues += StringUtils.join(collectionValuesList, nextDelimiter)
                    + recordSeparator;
        }
        formattedCollectionValues = StringUtils.chomp(formattedCollectionValues, recordSeparator);
        log.debug("email formatted collection values: " + formattedCollectionValues);
    }
    return formattedCollectionValues;
}

From source file:gov.usda.DataCatalogClient.Catalog.java

/**
 * Adds bureau name and bureau abbreviation to a dataset from a config file, normally
 * bureau_config_data.json.  Called from addBureaNameToDataset which goes through
 * the entire catalog./*from   w ww.  j a  v  a 2 s .c o m*/
 * @param ds
 * @param bureauArray
 */
private void addBureauName(Dataset ds, JSONArray bureauArray) {
    Boolean found = false;
    List<String> bureauCodeList = ds.getBureauCodeList();
    for (String bureauCode : bureauCodeList) {
        for (int i = 0; i < bureauArray.size(); i++) {
            JSONObject bureauObject = (JSONObject) bureauArray.get(i);
            if (bureauCode.equals(bureauObject.get("bureau_code"))) {
                ds.setBureauName((String) bureauObject.get("bureau_name"));
                ds.setBureauAbbreviation((String) bureauObject.get("bureau_abbreviation"));
                found = true;
            }
        }
        if (!found) {
            ds.setBureauName(
                    "Name not found for bureau code: " + bureauCode + ", see bureau configuration file.");
        }
        found = false;
    }
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private boolean existsImage(String imageID) {
    boolean exists = false;

    //Get the Response Content in a String
    String images = oStackClient.getAllImages();

    // Parsing the JSON response to get all the images
    JSONObject allImages = (JSONObject) JSONValue.parse(images);
    JSONArray jsonImages = (JSONArray) allImages.get("images");

    for (int i = 0; i < jsonImages.size(); ++i) {
        JSONObject image = (JSONObject) jsonImages.get(i);
        String tmpImgID = image.get("name").toString();
        if (tmpImgID.equals(imageID)) {
            exists = true;/*w w  w .ja v  a  2s .  c o m*/
            break;
        }
    }
    return exists;
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private OVFWrapper[] getAllServersWrappers() {
    ArrayList<OVFWrapper> wrappers = new ArrayList<OVFWrapper>();
    String servers = oStackClient.getAllServers();

    JSONObject allServers = (JSONObject) JSONValue.parse(servers);
    JSONArray jsonServers = (JSONArray) allServers.get("servers");

    for (int i = 0; i < jsonServers.size(); ++i) {
        JSONObject server = (JSONObject) jsonServers.get(i);
        OVFWrapper wTmp = this.parse(server.toString());
        wrappers.add(wTmp);/*from  ww w .  j  a  va 2s. c om*/
    }

    OVFWrapper vms[] = wrappers.toArray(new OVFWrapper[wrappers.size()]);

    return vms;
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * Return a pointer to every PropertyItem in ng that has a mapping in the import spec
 * @param ng//w w  w  .j a  v  a2 s.  c o  m
 * @return
 */
public ArrayList<PropertyItem> getMappedPropItems(NodeGroup ng) {
    ArrayList<PropertyItem> ret = new ArrayList<PropertyItem>();

    JSONArray nodes = (JSONArray) this.importspec.get("nodes");

    // loop through the json nodes in the import spec
    for (int i = 0; i < nodes.size(); i++) {
        JSONObject nodeJson = (JSONObject) nodes.get(i);

        // get the related node from the NodeGroup
        String sparqlID = nodeJson.get("sparqlID").toString();
        Node snode = ng.getNodeBySparqlID(sparqlID);

        // loop through Json node's properties
        JSONArray propsJArr = (JSONArray) nodeJson.get("props");
        for (int j = 0; j < propsJArr.size(); j++) {
            JSONObject propJson = (JSONObject) propsJArr.get(j);
            String uriRelation = propJson.get("URIRelation").toString();

            // if propertyJson has a mapping, return the PropertyItem
            JSONArray propMapJArr = (JSONArray) propJson.get("mapping");
            if (propMapJArr != null && propMapJArr.size() > 0) {
                PropertyItem pItem = snode.getPropertyByURIRelation(uriRelation);
                ret.add(pItem);
            }
        }
    }

    return ret;
}

From source file:MemoryController.java

@RequestMapping("/memory")
public @ResponseBody Memory memory(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);/*  www  .java  2  s  . c  o m*/

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "memory");
    params.put("search", search);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL);
    putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj2 = new JSONObject();
    jsonObj2.put("jsonrpc", "2.0");
    jsonObj2.put("method", "item.get");
    JSONObject params2 = new JSONObject();
    params2.put("output", "extend");
    params2.put("hostid", hostid);
    JSONObject search2 = new JSONObject();
    search2.put("key_", "swap");
    params2.put("search", search2);
    params2.put("sortfield", "name");
    jsonObj2.put("params", params2);
    jsonObj2.put("auth", authentication);// todo
    jsonObj2.put("id", new Integer(1));

    putMethod2.setRequestBody(jsonObj2.toString());

    String loginResponse = "";
    String loginResponse2 = "";
    String memory = "";
    String clock = "";
    String metricType = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response

        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        client.executeMethod(putMethod2); // send to request to the zabbix api

        loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response

        Object obj3 = parser.parse(loginResponse2);
        JSONObject obj4 = (JSONObject) obj3;
        String jsonrpc2 = (String) obj4.get("jsonrpc");
        JSONArray array2 = (JSONArray) obj4.get("result");

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            //         lastValue = getLastValue(tobj);
            //         lastClock = getLastClock(tobj);
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Total Memeory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Cached Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Free Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Buffered Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Shared Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }
        }

        for (int i = 0; i < array2.size(); i++) {
            JSONObject tobj2 = (JSONObject) array2.get(i);

            if (!tobj2.get("hostid").equals(hostid))
                continue;
            if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) {
                memory = (String) tobj2.get("lastvalue");
                clock = (String) tobj2.get("lastclock");
                metricType = "Free Swap Space";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }

        }

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    return new Memory(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}