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:com.net.h1karo.sharecontrol.ShareControl.java

public void updateCheck() {
    String CBuildString = "", NBuildString = "";

    int CMajor = 0, CMinor = 0, CMaintenance = 0, CBuild = 0, NMajor = 0, NMinor = 0, NMaintenance = 0,
            NBuild = 0;//from  w  ww  .  j a  v  a 2 s .co m

    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=90354");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "ShareControl Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.getLogger().warning("No files found, or Feed URL is bad.");
            result = UpdateResult.ERROR;
            return;
        }
        String newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name"));
        newVersion = newVersionTitle.replace("ShareControl v", "").trim();

        /**\\**/
        /**\\**//**\\**/
        /**\    GET VERSIONS    /**\
          /**\\**/
        /**\\**//**\\**/

        String[] CStrings = currentVersion.split(Pattern.quote("."));

        CMajor = Integer.parseInt(CStrings[0]);
        if (CStrings.length > 1)
            if (CStrings[1].contains("-")) {
                CMinor = Integer.parseInt(CStrings[1].split(Pattern.quote("-"))[0]);
                CBuildString = CStrings[1].split(Pattern.quote("-"))[1];
                if (CBuildString.contains("b")) {
                    beta = true;
                    CBuildString = CBuildString.replace("b", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 1;
                } else if (CBuildString.contains("a")) {
                    alpha = true;
                    CBuildString = CBuildString.replace("a", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 10;
                } else
                    CBuild = Integer.parseInt(CBuildString);
            } else {
                CMinor = Integer.parseInt(CStrings[1]);
                if (CStrings.length > 2)
                    if (CStrings[2].contains("-")) {
                        CMaintenance = Integer.parseInt(CStrings[2].split(Pattern.quote("-"))[0]);
                        CBuildString = CStrings[2].split(Pattern.quote("-"))[1];
                        if (CBuildString.contains("b")) {
                            beta = true;
                            CBuildString = CBuildString.replace("b", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 1;
                        } else if (CBuildString.contains("a")) {
                            alpha = true;
                            CBuildString = CBuildString.replace("a", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 10;
                        } else
                            CBuild = Integer.parseInt(CBuildString);
                    } else
                        CMaintenance = Integer.parseInt(CStrings[2]);
            }

        String[] NStrings = newVersion.split(Pattern.quote("."));

        NMajor = Integer.parseInt(NStrings[0]);
        if (NStrings.length > 1)
            if (NStrings[1].contains("-")) {
                NMinor = Integer.parseInt(NStrings[1].split(Pattern.quote("-"))[0]);
                NBuildString = NStrings[1].split(Pattern.quote("-"))[1];
                if (NBuildString.contains("b")) {
                    beta = true;
                    NBuildString = NBuildString.replace("b", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 1;
                } else if (NBuildString.contains("a")) {
                    alpha = true;
                    NBuildString = NBuildString.replace("a", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 10;
                } else
                    NBuild = Integer.parseInt(NBuildString);
            } else {
                NMinor = Integer.parseInt(NStrings[1]);
                if (NStrings.length > 2)
                    if (NStrings[2].contains("-")) {
                        NMaintenance = Integer.parseInt(NStrings[2].split(Pattern.quote("-"))[0]);
                        NBuildString = NStrings[2].split(Pattern.quote("-"))[1];
                        if (NBuildString.contains("b")) {
                            beta = true;
                            NBuildString = NBuildString.replace("b", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 1;
                        } else if (NBuildString.contains("a")) {
                            alpha = true;
                            NBuildString = NBuildString.replace("a", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 10;
                        } else
                            NBuild = Integer.parseInt(NBuildString);
                    } else
                        NMaintenance = Integer.parseInt(NStrings[2]);
            }

        /**\\**/
        /**\\**//**\\**/
        /**\   CHECK VERSIONS   /**\
          /**\\**/
        /**\\**//**\\**/
        if ((CMajor < NMajor) || (CMajor == NMajor && CMinor < NMinor)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance < NMaintenance)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance == NMaintenance && CBuild < NBuild))
            result = UpdateResult.UPDATE_AVAILABLE;
        else
            result = UpdateResult.NO_UPDATE;
        return;
    } catch (Exception e) {
        console.sendMessage(" There was an issue attempting to check for the latest version.");
    }
    result = UpdateResult.ERROR;
}

From source file:com.telefonica.iot.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   w  w w  .  j a va 2  s . co m*/
 * @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:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * The function receives a vector with details for a set of revisions and
 * returns the details for the packages affected by these revisions.
 * /*from w  ww . j av  a2  s.  com*/
 * @param revisionsDetails
 *            a vector of strings containing the JSON details for the
 *            revisions.
 * @return a vector of maps with the details for each affected package.
 */
@SuppressWarnings("rawtypes")
public static Vector<Map> getUpdatedCategoriesDetails(Vector<String> revisionsDetails) {

    // pass the request to the function for the updated data sets
    Vector uDataSetResults = getUpdatedDataSetsDetails(revisionsDetails);
    if (uDataSetResults == null) {
        return null;
    }

    // the vector to contain the visited groups
    Vector<String> visitedGroups = new Vector<String>();

    // the variable which will be returned
    Vector<Map> toreturn = new Vector<Map>();

    // iterate over the data set results
    for (int i = 0; i < uDataSetResults.size(); i++) {

        // get the groups which where updated as a result of the data set
        // update
        Map m = (Map) uDataSetResults.get(i);
        JSONArray arr = (JSONArray) m.get("groups");

        for (int j = 0; j < arr.size(); j++) {

            // get the next group and check if its data was already obtained
            String grp = (String) arr.get(j);
            if (visitedGroups.contains(grp)) {
                continue;
            }

            visitedGroups.add(grp);

            // prepare the next rest call
            String RESTcall = "api/rest/group/" + grp;

            try {
                String restResponse = connectorInstance.restCallWithAuthorization(RESTcall, null);
                Map grMap = (Map) JSONValue.parse(restResponse);

                toreturn.add(grMap);

            } catch (MalformedURLException e) {
                log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
                continue;
            } catch (IOException e) {
                continue;
            }
        }
    }

    return toreturn;
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * List the statuses of the files/directories in the given path if the path is
 * a directory.//from w  ww  .jav a2  s  . co m
 *
 * @param f
 *          given path
 * @return the statuses of the files/directories in the given patch
 * @throws IOException
 */
@Override
public FileStatus[] listStatus(Path f) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("op", "list");
    HttpURLConnection conn = getConnection("GET", params, f);
    validateResponse(conn, HttpURLConnection.HTTP_OK);
    JSONArray json = (JSONArray) jsonParse(conn);
    FileStatus[] array = new FileStatus[json.size()];
    for (int i = 0; i < json.size(); i++) {
        array[i] = createFileStatus((JSONObject) json.get(i));
    }
    return array;
}

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

/**
 * 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
 * @param pkgName/*from  w  w  w .  j  av  a 2 s  . co m*/
 * @return The discovered resources for the given package.
 * @throws Exception
 */
private JSONArray discoverResources(String pkgName) throws Exception {
    // query CKAN for the resources within the given package
    String urlPath = "/api/3/action/package_show?id=" + pkgName;
    CKANResponse res = requester.doCKANRequest("GET", urlPath);

    if (res.getStatusCode() == 200) {
        JSONObject result = (JSONObject) res.getJsonObject().get("result");
        JSONArray resources = (JSONArray) result.get("resources");
        logger.debug("Resources successfully discovered (pkgName=" + pkgName + ", numResources="
                + resources.size() + ")");
        return resources;
    } else {
        throw new CygnusRuntimeError("Don't know how to treat response code " + res.getStatusCode() + ")");
    } // if else
}

From source file:com.mobicage.rogerthat.registration.RegistrationWizard2.java

@SuppressWarnings("unchecked")
@Override//ww w. j  av  a 2s.  c om
public void readFromPickle(int version, DataInput in) throws IOException, PickleException {
    T.UI();
    super.readFromPickle(version, in);
    boolean set = in.readBoolean();
    if (set)
        mCredentials = new Credentials(new Pickle(in.readInt(), in));
    set = in.readBoolean();
    mEmail = set ? in.readUTF() : null;
    mTimestamp = in.readLong();
    mRegistrationId = in.readUTF();
    mInGoogleAuthenticationProcess = in.readBoolean();
    mInstallationId = in.readUTF();
    // A version bump was forgotten when serializing mDeviceId, so we need a try/catch
    try {
        mDeviceId = in.readUTF();
    } catch (EOFException e) {
        mDeviceId = null;
    }
    if (version >= 2) {
        try {
            set = in.readBoolean();
            mBeaconRegions = set
                    ? new GetBeaconRegionsResponseTO((Map<String, Object>) JSONValue.parse(in.readUTF()))
                    : null;

            set = in.readBoolean();
            if (set) {
                String detectedBeacons = in.readUTF();
                JSONArray db1 = (JSONArray) JSONValue.parse(detectedBeacons);
                if (db1 != null) {
                    mDetectedBeacons = new HashSet<String>();
                    for (int i = 0; i < db1.size(); i++) {
                        mDetectedBeacons.add((String) db1.get(i));
                    }
                } else {
                    mDetectedBeacons = null;
                }
            } else {
                mDetectedBeacons = null;
            }
        } catch (IncompleteMessageException e) {
            L.bug(e);
        }
    }
}

From source file:com.dsh105.commodus.data.Updater.java

private boolean read() {
    try {//from w  ww .j a v a2 s .c o m
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", "Updater (by Gravity)");

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.plugin.getLogger()
                    .warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.plugin.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            this.plugin.getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * Get the number of existing comments for a package.
 * /*from ww w.j av  a  2  s  . c o  m*/
 * @param dataSetId
 *            the dataset ID.
 * 
 * @return the number of existing comments or -1 in case of an error.
 */
public static int getDataSetCommentsCount(String dataSetId) {

    JSONArray arr = CKANGatewayUtil.getDataSetComments(dataSetId);
    if (arr == null) {
        return -1;
    }

    return arr.size();
}

From source file:com.alvexcore.repo.masterdata.getConstraintWork.java

protected List<Map<String, String>> getRestJsonMasterData(NodeRef source) throws Exception {
    NodeService nodeService = serviceRegistry.getNodeService();
    String urlStr = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL);
    String rootPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_ROOT_QUERY);
    String labelField = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_LABEL_FIELD);
    String valueField = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_VALUE_FIELD);
    String caching = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE);

    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    InputStream inputStream = conn.getInputStream();
    String str = IOUtils.toString(inputStream);

    Object jsonObj = JSONValue.parse(str);

    List<Map<String, String>> res = new ArrayList<Map<String, String>>();
    if (jsonObj.getClass().equals(JSONArray.class)) {
        JSONArray arr = (JSONArray) jsonObj;
        for (int k = 0; k < arr.size(); k++) {
            JSONObject item = (JSONObject) arr.get(k);
            String value = item.get(valueField).toString();
            String label = item.get(labelField).toString();
            HashMap<String, String> resItem = new HashMap<String, String>();
            resItem.put("ref", "");
            resItem.put("value", value);
            resItem.put("label", label);
            res.add(resItem);// w ww  .  j a  va2s.  c  o m
        }
    }

    return res;
}

From source file:net.phyloviz.goeburst.GoeBurstItemFactory.java

private void updateEdgeStats(JSONArray edgesStatsArray, Map<Integer, GOeBurstClusterWithStats> groups) {

    for (Iterator<JSONObject> esIt = edgesStatsArray.iterator(); esIt.hasNext();) {
        JSONObject edgeStat = esIt.next();
        Integer groupId = (int) (long) edgeStat.get("group");
        JSONArray ne = (JSONArray) edgeStat.get("ne");
        JSONArray fne = (JSONArray) edgeStat.get("fne");
        JSONArray xLV = (JSONArray) edgeStat.get("xLV");
        Integer withoutTies = (int) (long) edgeStat.get("withoutTies");

        GOeBurstClusterWithStats group = groups.get(groupId);
        group.setEdgeTieStatsWithoutTies(withoutTies);
        int i = 0;
        for (; i < ne.size(); i++) {

            group.setEdgeTieStatsNE(i, (int) (long) ne.get(i));
            group.setEdgeTieStatsFNE(i, (int) (long) fne.get(i));
            group.setEdgeTieStatsNE(i, (int) (long) xLV.get(i));

        }/* www . j  av a2  s  . c  om*/
        for (; i < xLV.size(); i++)
            group.setEdgeTieStatsXlv(i, (int) (long) xLV.get(i));

    }

}