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:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

@GET
@Path("/resources")
@Produces("application/xml")
public ListStrings getNodes() {
    ListStrings list = new ListStrings();
    ArrayList<String> hostsNames = new ArrayList<String>();

    String hosts = oStackClient.getHosts();
    JSONObject jsonHosts = (JSONObject) JSONValue.parse(hosts);
    JSONArray jsonHostsArray = (JSONArray) jsonHosts.get("hosts");

    for (int i = 0; i < jsonHostsArray.size(); ++i) {
        JSONObject flavor = (JSONObject) jsonHostsArray.get(i);
        String hostName = flavor.get("host_name").toString();
        hostsNames.add(hostName);//w w  w  .  ja  v  a2  s . c  o m
    }

    list.addAll(hostsNames);

    //        list.addAll(super.getNodes());
    //GenericEntity<ListStrings> entity = new GenericEntity<ListStrings>(list) {};
    //Response response = Response.ok(entity).build();
    return list;
}

From source file:de.jaide.courier.email.MessageHandlerEMail.java

/**
 * Loads the SMTP configuration from a JSON file.
 * /*from  ww w  .  j a va2 s . c  o  m*/
 * @param smtpConfigurationJsonLocation The SMTP configuration to load. Needs to be an absolute URL, e.g. "/configs/smtp.json" that is
 *          loaded from the
 *          classpath.
 * @throws IOException Thrown, if the SMTP configuration couldn't be read.
 */
private void loadSmtpConfigurations(String smtpConfigurationJsonLocation) {
    /*
     * Now load the SMTP configuration JSON file and try to parse it.
     */
    try {
        /*
         * Load the JSON-based SMTP configuration file.
         */
        JSONArray keyArray = (JSONArray) new JSONParser()
                .parse(IOUtils.toString((InputStream) MessageHandlerEMail.class
                        .getResource(smtpConfigurationJsonLocation).getContent()));

        /*
         * Iterate through the outer array
         */
        for (int i = 0; i < keyArray.size(); i++) {

            /*
             * Iterate through the inner array of configuration keys.
             */
            JSONObject keysArray = (JSONObject) keyArray.get(i);
            for (Object keyObject : keysArray.keySet()) {

                /*
                 * Get the name of the key...
                 */
                String key = (String) keyObject;
                JSONObject configArray = (JSONObject) keysArray.get(key);

                /*
                 * ... and load the associated configuration values.
                 */
                String smtpHostname = (String) configArray.get("smtpHostname");
                Long smtpPort = (Long) (configArray.get("smtpPort"));
                Boolean tls = (Boolean) configArray.get("tls");
                Boolean ssl = (Boolean) configArray.get("ssl");
                String username = (String) configArray.get("username");
                String password = (String) configArray.get("password");
                String fromEMail = (String) configArray.get("fromEMail");
                String fromSenderName = (String) configArray.get("fromSenderName");

                /*
                 * Use the obtained values and create a new SMTP configuration.
                 */
                SmtpConfiguration smtpConfiguration = new SmtpConfiguration(key, smtpHostname,
                        smtpPort.intValue(), tls, ssl, username, password, fromEMail, fromSenderName);
                smtpConfigurations.put(key, smtpConfiguration);
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException("SMTP configuration not found at '" + smtpConfigurationJsonLocation + "'",
                ioe);
    } catch (ParseException pe) {
        throw new RuntimeException(
                "SMTP configuration couldn't be loaded from '" + smtpConfigurationJsonLocation + "'", pe);
    }
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to get an item randomly from the response array of a previous REST
 * call//from w  w  w .  j  av a2s. c om
 *
 * @return the value if it's found (else it'll be null)
 * @throws ParseException
 */
public String getRandomlyAnItemFromResponseArray() throws ParseException {
    final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
    if (jsonArray != null && !jsonArray.isEmpty())
        return (String) jsonArray.get(new Random().nextInt(jsonArray.size()));
    return null;
}

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

/**
 * Returns the private IPs associated to the server ID
 *
 * @param vmID/*from w w  w.ja  v a2  s  . co m*/
 * @return
 */
public String[] getIPs(String serverID) {

    ArrayList<String> ips = new ArrayList<String>();
    String serverDetails = null;
    String status = "UNKNOWN";

    // Until VM has ACTIVE status, no IP is assigned
    while (!status.equals("ACTIVE")) {
        serverDetails = oStackClient.getServer(serverID);
        status = oStackClient.getVMStatus(serverID);
        System.out.println("DRP4OST>DRP4OST.getIPs(), VM has status=" + status);
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Parsing the JSON response to get all the images
    JSONObject allFlavors = (JSONObject) JSONValue.parse(serverDetails);
    JSONObject jsonServer = (JSONObject) allFlavors.get("server");
    JSONObject jsonAddresses = (JSONObject) jsonServer.get("addresses");
    JSONArray jsonPrivate = (JSONArray) jsonAddresses.get("private");

    for (int i = 0; i < jsonPrivate.size(); ++i) {
        JSONObject addr = (JSONObject) jsonPrivate.get(i);
        String tmpAddr = addr.get("addr").toString();
        ips.add(tmpAddr);
        System.out.println("DRP4OST>DRP4OST.getIPs(), VM has ip=" + tmpAddr);
    }

    String[] ipsArray = ips.toArray(new String[ips.size()]);
    return ipsArray;

}

From source file:eumetsat.pn.common.ISO2JSON.java

private JSONObject convert(Document xmlDocument) throws XPathExpressionException, IOException {
    String expression = null;// www.  j ava2 s  . c o m
    String result = null;
    XPath xPath = XPathFactory.newInstance().newXPath();
    JSONObject jsonObject = new JSONObject();

    String xpathFileID = "//*[local-name()='fileIdentifier']/*[local-name()='CharacterString']";
    String fileID = xPath.compile(xpathFileID).evaluate(xmlDocument);
    log.trace("{} >>> {}", xpathFileID, fileID);
    if (fileID != null) {
        jsonObject.put(FILE_IDENTIFIER_PROPERTY, fileID);
    }

    expression = "//*[local-name()='hierarchyLevelName']/*[local-name()='CharacterString']";
    JSONArray list = new JSONArray();
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }
    if (list.size() > 0) {
        JSONObject hierarchies = parseThemeHierarchy((String) jsonObject.get(FILE_IDENTIFIER_PROPERTY), list);
        hierarchies.writeJSONString(writer);
        jsonObject.put("hierarchyNames", hierarchies);
        log.trace("{} >>> {}", expression, jsonObject.get("hierarchyNames"));
    }

    // Get Contact info
    String deliveryPoint = "//*[local-name()='address']//*[local-name()='deliveryPoint']/*[local-name()='CharacterString']";
    String city = "//*[local-name()='address']//*[local-name()='city']/*[local-name()='CharacterString']";
    String administrativeArea = "//*[local-name()='address']//*[local-name()='administrativeArea']/*[local-name()='CharacterString']";
    String postalCode = "//*[local-name()='address']//*[local-name()='postalCode']/*[local-name()='CharacterString']";
    String country = "//*[local-name()='address']//*[local-name()='country']/*[local-name()='CharacterString']";
    String email = "//*[local-name()='address']//*[local-name()='electronicMailAddress']/*[local-name()='CharacterString']";

    StringBuilder addressString = new StringBuilder();
    StringBuilder emailString = new StringBuilder();

    appendIfResultNotNull(xPath, xmlDocument, addressString, deliveryPoint);

    result = xPath.compile(postalCode).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(city).evaluate(xmlDocument);
    if (result != null) {
        addressString.append(" ").append(result.trim());
    }

    result = xPath.compile(administrativeArea).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(country).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(email).evaluate(xmlDocument);
    if (result != null) {
        emailString.append(result.trim());
    }

    HashMap<String, String> map = new HashMap<>();
    map.put("address", addressString.toString());
    map.put("email", emailString.toString());
    jsonObject.put("contact", map);
    log.trace("contact: {}", Arrays.toString(map.entrySet().toArray()));

    // add identification info
    String abstractStr = "//*[local-name()='identificationInfo']//*[local-name()='abstract']/*[local-name()='CharacterString']";
    String titleStr = "//*[local-name()='identificationInfo']//*[local-name()='title']/*[local-name()='CharacterString']";
    String statusStr = "//*[local-name()='identificationInfo']//*[local-name()='status']/*[local-name()='MD_ProgressCode']/@codeListValue";
    String keywords = "//*[local-name()='keyword']/*[local-name()='CharacterString']";

    HashMap<String, Object> idMap = new HashMap<>();

    result = xPath.compile(titleStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("title", result.trim());
    }

    result = xPath.compile(abstractStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("abstract", result.trim());
    }

    result = xPath.compile(statusStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("status", result.trim());
    }

    list = new JSONArray();
    nodeList = (NodeList) xPath.compile(keywords).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }

    if (list.size() > 0) {
        idMap.put("keywords", list);
    }

    jsonObject.put("identificationInfo", idMap);
    log.trace("idMap: {}", idMap);

    // get thumbnail product
    String browseThumbnailStr = "//*[local-name()='graphicOverview']//*[local-name()='MD_BrowseGraphic']//*[local-name()='fileName']//*[local-name()='CharacterString']";
    result = xPath.compile(browseThumbnailStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("thumbnail", result.trim());
        log.trace("thumbnail: {}", result);
    }

    // add Geo spatial information
    String westBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='westBoundLongitude']/*[local-name()='Decimal']";
    String eastBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='eastBoundLongitude']/*[local-name()='Decimal']";
    String northBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='northBoundLatitude']/*[local-name()='Decimal']";
    String southBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='southBoundLatitude']/*[local-name()='Decimal']";

    // create a GeoJSON envelope object
    HashMap<String, Object> latlonMap = new HashMap<>();
    latlonMap.put("type", "envelope");

    JSONArray envelope = new JSONArray();
    JSONArray leftTopPt = new JSONArray();
    JSONArray rightDownPt = new JSONArray();

    result = xPath.compile(westBLonStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(northBLatStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(eastBLonStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(southBLatStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    envelope.add(leftTopPt);
    envelope.add(rightDownPt);

    latlonMap.put("coordinates", envelope);
    jsonObject.put("location", latlonMap);

    DOMImplementationLS domImplementation = (DOMImplementationLS) xmlDocument.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    String xmlString = lsSerializer.writeToString(xmlDocument);

    jsonObject.put("xmldoc", xmlString);

    return jsonObject;
}

From source file:com.kdao.cmpe235_project.UploadActivity.java

/**
 * Private function to populate comments
 * @method populateTrees//ww  w . j  a  v  a 2 s  .c  om
 */
private void populateTrees(JSONArray arrayObj) {
    //System.out.println(arrayObj.size());
    for (int i = 0; i < arrayObj.size(); i++) {
        try {
            JSONObject object = (JSONObject) arrayObj.get(i);
            Location location = new Location(Double.parseDouble(object.get("longitude").toString()),
                    Double.parseDouble(object.get("latitude").toString()), object.get("address").toString(),
                    object.get("title").toString());
            Sensor sensor = new Sensor();
            trees.add(new Tree(object.get("id").toString(), object.get("description").toString(), "",
                    object.get("youtubeId").toString(), location, sensor));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    if (arrayObj.size() > 0) { //get treeId on initial load
        treeId = trees.get(0).getId();
        APIurl = "/tree/" + treeId + "/photo";
    }
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> parseJsonMetrics(ArrayList<String> metricsList, String json)
        throws FileNotFoundException, IOException, ParseException {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(json);
    JSONArray jsonArray = new JSONArray();
    String metric;/* w  ww.  j  av  a2  s  . c o  m*/

    if (obj.getClass() != jsonArray.getClass()) {
        System.out.println("Total number of metrics = 0");
        System.out.println("obj = " + obj.toString());
        return metricsList;
    }

    jsonArray = (JSONArray) obj;

    System.out.println("Total number of metrics = " + jsonArray.size());

    for (int i = 0; i < jsonArray.size(); i++) {
        metric = jsonArray.get(i).toString();
        metricsList.add(metric);
        System.out.println("metric # " + i + " = " + metric);

    }
    return metricsList;
}

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

/**
 * Populate nodegroup with a single record (row) of data
 *//* w w w  .ja v  a 2  s.  c  om*/
public NodeGroup importRecord(NodeGroup ng, ArrayList<String> record) throws Exception {
    // this is a really naive implementation. it could probably be sped up drastically by caching
    // the digested template instead of re-processing it for eac incoming record.
    // the lack of conditional logic in this method would make that do-able. 

    NodeGroup retval = ng;
    if (ng == null) {
        throw new Exception("Null nodegroup passed to ImportSpecHandler.getValues");
    }
    if (record == null) {
        throw new Exception("incoming record cannot be null for ImportSpecHandler.getValues");
    }
    if (this.headerPositioningInfo.isEmpty()) {
        throw new Exception("the header positions were never set for the importspechandler");
    }

    JSONArray nodes = (JSONArray) this.importspec.get("nodes"); // the "nodes" part of the JSON
    int nodesArraySize = nodes.size();

    for (int i = 0; i < nodesArraySize; i++) {
        // loop through all of the values and get the parts we need to fill in the nodegroup entries. 
        JSONObject currnode = (JSONObject) nodes.get(i);
        JSONArray uriMap = (JSONArray) currnode.get("mapping");
        JSONArray props = (JSONArray) currnode.get("props");

        // get the related node from the NodeGroup
        String sparqlID = currnode.get("sparqlID").toString();
        //System.out.println("sparqlID: " + sparqlID);
        Node curr = ng.getNodeBySparqlID(sparqlID);

        // generate the uri value. all of this can be simplified later into a structure that actually remembers the format 
        // because position info will not drift as each line is processed. this was done for expedience of development. 

        String uri = this.buildMappingString(uriMap, record);

        // check for a null column mapping having been found. if so, change the URI to a guid and make this a blank node. 
        // encode uri and set it. 
        if (StringUtils.isBlank(uri)) {
            curr.setInstanceValue(null);
        } else {
            uri = this.uriResolver.getInstanceUriWithPrefix(curr.getFullUriName(), uri);
            if (!SparqlToXUtils.isLegalURI(uri)) {
                throw new Exception("Attempting to insert ill-formed URI: " + uri);
            }
            curr.setInstanceValue(uri);
        }

        // set any applicable property values. again, this could be greatly simplified in terms of number of look ups and, 
        // potentially, running time. it should be encapsulated into an object that understands the nodes itself and stores
        // this sort of info. this was done the hard way in the interest of simplifying implementation and debugging. 

        ArrayList<PropertyItem> inScopeProperties = curr.getPropertyItems();

        Iterator<JSONObject> pMap = props.iterator();
        while (pMap.hasNext()) {
            String[] namesOfTransformsToApplyProp = null;

            // go through all the parts of the property as well. 
            JSONObject currProp = pMap.next();
            String uriRelation = currProp.get("URIRelation").toString();

            JSONArray mapping = (JSONArray) currProp.get("mapping");

            String instanceValue = this.buildMappingString(mapping, record);

            // find and set the actual property value. 
            for (PropertyItem pi : inScopeProperties) {
                if (pi.getUriRelationship().equals(uriRelation)) { // e.g. http://research.ge.com/print/testconfig#cellId

                    if (this.notEmpty(instanceValue)) {
                        if (pi.getValueType().equalsIgnoreCase("string")) {
                            instanceValue = SparqlToXUtils.safeSparqlString(instanceValue);
                        }

                        instanceValue = this.validateDataType(instanceValue, pi.getValueType());
                        pi.addInstanceValue(instanceValue);
                    }
                    break;
                }
            }
        }
    }

    // prune nodes that no longer belong (no uri and no properties)
    ng.pruneAllUnused(true);

    // set URI for nulls
    ng = this.setURIsForBlankNodes(ng);

    return retval;
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to get the specified property randomly from the response array of
 * a previous REST call/*from  w  ww .  j av a 2s  .  c  o m*/
 *
 * @param property
 * @return the value if it's found (else it'll be null)
 * @throws ParseException
 */
public String getRandomlyPropertyFromResponseArray(@NonNull String property) throws ParseException {
    final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
    if (jsonArray != null && !jsonArray.isEmpty())
        return JSONHelper.getValue((JSONObject) jsonArray.get(new Random().nextInt(jsonArray.size())),
                property);
    return null;
}