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:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANCache.java

/**
 * Populates the package map of a given orgName with the package information from the CKAN response.
 * @param packages JSON vector from the CKAN response containing package information
 * @param orgName Organization name//from w w w .  j  av a2s  .  c o m
 * @throws Exception
 */
private void populatePackagesMap(JSONArray packages, String orgName) throws Exception {
    // this check is for debuging purposes
    if (packages.size() == 0) {
        logger.debug("The pacakges list is empty, nothing to cache");
        return;
    } // if

    logger.debug("Packages to be populated: " + packages.toJSONString() + "(orgName=" + orgName + ")");

    // iterate on the packages
    Iterator<JSONObject> iterator = packages.iterator();

    while (iterator.hasNext()) {
        // get the package name
        JSONObject pkg = (JSONObject) iterator.next();
        String pkgName = (String) pkg.get("name");

        // check if the package is in "deleted" state
        String pkgState = pkg.get("state").toString();

        if (pkgState.equals("deleted")) {
            throw new CygnusBadConfiguration("The package exists but it is in a deleted state (orgName="
                    + orgName + ", pkgName=" + pkgName + ")");
        } // if

        // put the package in the tree and in the packages map
        String pkgId = pkg.get("id").toString();
        tree.get(orgName).put(pkgName, new ArrayList<String>());
        pkgMap.put(pkgName, pkgId);
        logger.debug("Package found in CKAN, now cached (orgName=" + orgName + " -> pkgName/pkgId=" + pkgName
                + "/" + pkgId + ")");

        // get the resources
        JSONArray resources = null;

        // this piece of code tries to make the code compatible with CKAN 2.0, whose "organization_show"
        // method returns no resource lists for its packages! (not in CKAN 2.2)
        // more info --> https://github.com/telefonicaid/fiware-connectors/issues/153
        // if the resources list is null we must try to get it package by package
        if (ckanVersion.equals("2.0")) {
            logger.debug("CKAN version is 2.0, try to discover the resources for this package (pkgName="
                    + pkgName + ")");
            resources = discoverResources(pkgName);
        } else { // 2.2 or higher
            logger.debug("CKAN version is 2.2 (or higher), the resources list can be obtained from the "
                    + "organization information (pkgName=" + pkgName + ")");
            resources = (JSONArray) pkg.get("resources");
        } // if else

        // populate the resources map
        logger.debug(
                "Going to populate the resources cache (orgName=" + orgName + ", pkgName=" + pkgName + ")");
        populateResourcesMap(resources, orgName, pkgName, false);
    } // while
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANCache.java

/**
 * Populates the resourceName-resource map of a given orgName with the package information from the CKAN response.
 * @param resources JSON vector from the CKAN response containing resource information
 * @param orgName Organization name//from  www .ja va2  s . com
 * @param pkgName Package name
 * @param checkExistence If true, checks if the queried resource already exists in the cache
 */
private void populateResourcesMap(JSONArray resources, String orgName, String pkgName, boolean checkExistence) {
    // this check is for debuging purposes
    if (resources.size() == 0) {
        logger.debug("The resources list is empty, nothing to cache");
        return;
    } // if

    logger.debug("Resources to be populated: " + resources.toJSONString() + "(orgName=" + orgName + ", pkgName="
            + pkgName + ")");

    // iterate on the resources
    Iterator<JSONObject> iterator = resources.iterator();

    while (iterator.hasNext()) {
        // get the resource name and id (resources cannot be in deleted state)
        JSONObject factObj = (JSONObject) iterator.next();
        String resourceName = (String) factObj.get("name");
        String resourceId = (String) factObj.get("id");

        // put the resource in the tree and in the resource map
        if (checkExistence) {
            if (tree.get(orgName).get(pkgName).contains(resourceName)) {
                continue;
            } // if
        } // if

        tree.get(orgName).get(pkgName).add(resourceName);
        resMap.put(resourceName, resourceId);
        logger.debug("Resource found in CKAN, now cached (orgName=" + orgName + " -> pkgName=" + pkgName
                + " -> " + "resourceName/resourceId=" + resourceName + "/" + resourceId + ")");
    } // while
}

From source file:com.orthancserver.DicomDecoder.java

private String[] SortSlicesBy3D(OrthancConnection c, JSONArray instances) throws IOException {
    ArrayList<Slice> slices = new ArrayList<Slice>();
    float normal[] = null;

    float minDistance = Float.POSITIVE_INFINITY;
    float maxDistance = Float.NEGATIVE_INFINITY;

    for (int i = 0; i < instances.size(); i++) {
        String uuid = (String) instances.get(i);
        JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags?simplify");
        if (!instance.containsKey("ImageOrientationPatient") || !instance.containsKey("ImagePositionPatient")) {
            return null;
        }/*from   w w  w. ja  va2 s  .c  om*/

        if (i == 0) {
            String[] tokens = ((String) instance.get("ImageOrientationPatient")).split("\\\\");
            if (tokens.length != 6) {
                return null;
            }

            float cosines[] = new float[6];
            for (int j = 0; j < 6; j++) {
                cosines[j] = Float.parseFloat(tokens[j]);
            }

            normal = new float[] { cosines[1] * cosines[5] - cosines[2] * cosines[4],
                    cosines[2] * cosines[3] - cosines[0] * cosines[5],
                    cosines[0] * cosines[4] - cosines[1] * cosines[3] };
        }

        String[] tokens = ((String) instance.get("ImagePositionPatient")).split("\\\\");
        if (tokens.length != 3) {
            return null;
        }

        float distance = 0;
        for (int j = 0; j < 3; j++) {
            distance += normal[j] * Float.parseFloat(tokens[j]);
        }

        minDistance = Math.min(minDistance, distance);
        maxDistance = Math.max(minDistance, distance);
        slices.add(new Slice(distance, uuid));
    }

    if (maxDistance - minDistance < 0.001) {
        return null;
    }

    return SortSlices(slices);
}

From source file:iaws_desktop.VelibDispoDialogFrame.java

/**
 * Creates new form VelibDispoDialogFrame
 *///from w ww.j ava 2s . c  o m
public VelibDispoDialogFrame(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    Document doc;
    JSONArray array;
    VelibWebRequest velibR = new VelibWebRequest("/vls/v1/stations");
    velibR.addParameterGet("contract", "Toulouse");
    try {
        array = (JSONArray) new JSONParser().parse(velibR.requestWithGet());
    } catch (ParseException ex) {
        return;
    }
    listModel = new DefaultListModel<>();
    JSONObject obj = null;
    for (int i = 0; i < array.size(); i++) {
        obj = (JSONObject) array.get(i);
        listModel.addElement(new VelibStation(obj.get("number").toString(), obj.get("name").toString()));
    }
    listVelib.setModel(listModel);
}

From source file:com.theisleoffavalon.mcmanager.mobile.RestClient.java

/**
 * Gets all available Minecraft commands on the server
 * /* ww  w. jav a2s .c o m*/
 * @return A list of Minecraft commands
 * @throws IOException
 *             If an error is encountered
 */
public Map<String, MinecraftCommand> getAllMinecraftCommands() throws IOException {
    Map<String, MinecraftCommand> cmds = new HashMap<String, MinecraftCommand>();
    JSONObject request = createJSONRPCObject("getAllCommands");
    JSONObject response = sendJSONRPC(request);
    checkJSONResponse(response, request);

    // Parse result
    @SuppressWarnings("unchecked")
    Map<String, JSONObject> commands = (Map<String, JSONObject>) response.get("result");
    for (String name : commands.keySet()) {
        JSONObject paramObj = commands.get(name);
        JSONArray jparams = (JSONArray) paramObj.get("params");
        JSONArray jparamTypes = (JSONArray) paramObj.get("paramTypes");

        Map<String, ArgType> params = new HashMap<String, ArgType>();
        for (int i = 0; i < jparams.size(); i++) {
            params.put((String) jparams.get(i), ArgType.getArgTypeFromString((String) jparamTypes.get(i)));
        }
        cmds.put(name, new MinecraftCommand(name, params));
    }
    return cmds;
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> parseJsonByTag(ArrayList<String> elementsList, String json, String tag)
        throws FileNotFoundException, IOException, ParseException {
    //PrintWriter writer = new PrintWriter(filepath + "json2txt-" + tag + ".txt", "UTF-8");
    JSONParser parser = new JSONParser();
    Object obj = null;//from w  w  w .j av  a 2  s  . c om
    try {
        obj = parser.parse(json);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonArray = (JSONArray) obj;
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = (JSONObject) jsonArray.get(i);
            elementsList = readJson(elementsList, jsonObject, null /*writer*/, tag);
        }

    } catch (Exception e) {
        System.out.println("Invalid JSON String data: " + e.toString());
        return elementsList;
    }

    //writer.close();
    return elementsList;
}

From source file:mml.test.Editor.java

/**
 * Add a single option-group to the styles menu
 * @param select the selct element//from ww w  .  j  a v  a2s .  co m
 * @param dObj the dialect JSON object
 * @param name the name of the format collection in dObj
 * @param label the name of the optgroup to appear in menu
 */
private void addOptGroup(Element select, JSONObject dObj, String name, String label) {
    JSONArray items = (JSONArray) dObj.get(name);
    if (items != null) {
        Element group = new Element("optgroup");
        group.addAttribute("label", label);
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = (JSONObject) items.get(i);
            Element option = new Element("option");
            item.put("type", name);
            String value = item.toJSONString();
            value = escape(value);
            option.addAttribute("value", value);
            String text = (String) item.get("prop");
            //System.out.println(text);
            option.addText(text);
            group.addChild(option);
        }
        select.addChild(group);
    }
}

From source file:com.skelril.aurora.authentication.AuthComponent.java

public synchronized JSONArray getFrom(String subAddress) {

    JSONArray objective = new JSONArray();
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {/*from  www  . j a va 2s.c  om*/
        JSONParser parser = new JSONParser();
        for (int i = 1; true; i++) {

            try {
                // Establish the connection
                URL url = new URL(config.websiteUrl + subAddress + "?page=" + i);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(1500);
                connection.setReadTimeout(1500);

                // Check response codes return if invalid
                if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300)
                    return null;

                // Begin to read results
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                // Parse Data
                JSONObject o = (JSONObject) parser.parse(builder.toString());
                JSONArray ao = (JSONArray) o.get("characters");
                if (ao.isEmpty())
                    break;
                Collections.addAll(objective, (JSONObject[]) ao.toArray(new JSONObject[ao.size()]));
            } catch (ParseException e) {
                break;
            } finally {
                if (connection != null)
                    connection.disconnect();

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    } catch (IOException e) {
        return null;
    }

    return objective;
}

From source file:com.dagobert_engine.portfolio.service.MtGoxPortfolioService.java

/**
 * Get the transaction history with a given page. Result is always 50 as
 * maximum/*w w w .ja  v  a2 s  . com*/
 * 
 */
public List<Transaction> getTransactions(CurrencyType curr, int page) {

    // create url and params
    final String url = API_MONEY_WALLET_HISTORY;
    final HashMap<String, String> params = QueryArgBuilder.create().add("currency", curr.name())
            .add("page", "" + page).build();

    // Get json string
    final String jsonString = adapter.query(url, params);
    try {
        JSONObject root = (JSONObject) parser.parse(jsonString);
        String result = (String) root.get("result");

        if (!"success".equals(result)) {
            throw new MtGoxException(result);
        } else {
            JSONObject data = (JSONObject) root.get("data");
            JSONArray transactions = (JSONArray) data.get("result");

            final List<Transaction> resultList = new ArrayList<>();

            for (int i = 0; i < transactions.size(); i++) {
                JSONObject currentObj = (JSONObject) transactions.get(i);

                Transaction transaction = new Transaction();

                // int index = Integer.parseInt((String)
                // currentObj.get("Index"));
                Date time = new Date(((long) currentObj.get("Date")) * 1000);
                Transaction.RecordType type = Transaction.RecordType
                        .valueOf(((String) currentObj.get("Type")).toUpperCase());
                CurrencyData value = adapter.getCurrencyForJsonObj((JSONObject) currentObj.get("Value"));
                CurrencyData balance = adapter.getCurrencyForJsonObj((JSONObject) currentObj.get("Balance"));
                String info = (String) currentObj.get("Info");

                JSONArray link = (JSONArray) currentObj.get("Link");

                transaction.setCurrency(curr);

                if (info == null)
                    return null;

                String rateText = info.split("at ")[1].replace(",", "");
                Pattern pattern = Pattern.compile("[0-9]*\\.[0-9]{5}");
                Matcher matcher = pattern.matcher(rateText);

                if (matcher.find()) {

                    transaction.setRate(new CurrencyData(Double.parseDouble(matcher.group(0)),
                            config.getDefaultCurrency()));
                }

                transaction.setTime(time);
                transaction.setType(type);
                transaction.setValue(value);
                transaction.setBalance(balance);
                transaction.setInfo(info);

                if (link.size() > 0) {
                    transaction.setTransactionUuid((String) link.get(0));
                    transaction.setTransactionCategory(
                            Transaction.TransactionCategory.forLink((String) link.get(1)));
                    transaction.setIdentifier((String) link.get(2));
                }

                resultList.add(transaction);
            }
            return resultList;
        }

    } catch (ParseException e) {
        throw new MtGoxException(e);
    }

}

From source file:com.telefonica.iot.cygnus.backends.ckan.CKANCache.java

/**
 * Populates the package map of a given orgName with the package information from the CKAN response.
 * @param packages JSON vector from the CKAN response containing package information
 * @param orgName Organization name/*from w  w w  .  j  a va  2  s  .  c o m*/
 * @throws Exception
 */
private void populatePackagesMap(JSONArray packages, String orgName) throws Exception {
    // this check is for debuging purposes
    if (packages.size() == 0) {
        LOGGER.debug("The pacakges list is empty, nothing to cache");
        return;
    } // if

    LOGGER.debug("Packages to be populated: " + packages.toJSONString() + "(orgName=" + orgName + ")");

    // iterate on the packages
    Iterator<JSONObject> iterator = packages.iterator();

    while (iterator.hasNext()) {
        // get the package name
        JSONObject pkg = (JSONObject) iterator.next();
        String pkgName = (String) pkg.get("name");

        // check if the package is in "deleted" state
        String pkgState = pkg.get("state").toString();

        if (pkgState.equals("deleted")) {
            throw new CygnusBadConfiguration("The package exists but it is in a deleted state (orgName="
                    + orgName + ", pkgName=" + pkgName + ")");
        } // if

        // put the package in the tree and in the packages map
        String pkgId = pkg.get("id").toString();
        tree.get(orgName).put(pkgName, new ArrayList<String>());
        pkgMap.put(pkgName, pkgId);
        LOGGER.debug("Package found in CKAN, now cached (orgName=" + orgName + " -> pkgName/pkgId=" + pkgName
                + "/" + pkgId + ")");

        // get the resources
        JSONArray resources;

        // this piece of code tries to make the code compatible with CKAN 2.0, whose "organization_show"
        // method returns no resource lists for its packages! (not in CKAN 2.2)
        // more info --> https://github.com/telefonicaid/fiware-cygnus/issues/153
        // if the resources list is null we must try to get it package by package
        if (ckanVersion.equals("2.0")) {
            LOGGER.debug("CKAN version is 2.0, try to discover the resources for this package (pkgName="
                    + pkgName + ")");
            resources = discoverResources(pkgName);
        } else { // 2.2 or higher
            LOGGER.debug("CKAN version is 2.2 (or higher), the resources list can be obtained from the "
                    + "organization information (pkgName=" + pkgName + ")");
            resources = (JSONArray) pkg.get("resources");
        } // if else

        // populate the resources map
        LOGGER.debug(
                "Going to populate the resources cache (orgName=" + orgName + ", pkgName=" + pkgName + ")");
        populateResourcesMap(resources, orgName, pkgName, false);
    } // while
}