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.wcmc.Software.screens.RegistrationScreen.java

public void setClassData(String data) {
    try {//from  w ww  . j av a  2  s  .  com
        JSONObject json = (JSONObject) jsonParser.parse(data);
        JSONArray json_classes = (JSONArray) json.get("classes");
        if (json_classes != null) {
            for (int i = 0; i < json_classes.size(); i++) {
                JSONObject json_class = (JSONObject) json_classes.get(i);

                ClassItem classItem = new ClassItem();
                classItem.setText(json_class.get("title"));
                classItem.setID(Integer.parseInt(json_class.get("id").toString()));
                classItem.setY(i * 15);
                classItem.setWidth(classes.getWidth());
                classes.add(classItem);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.fujitsu.dc.test.jersey.ODataCommon.java

/**
 * Json???()./*from w  ww . j a v a 2s. c  o  m*/
 * @param json JSONObject
 * @param uri ?URI??
 * @param type ?
 * @param additional ???
 * @param key 
 * @param np NP???
 * @param etag etag
 */
public static final void checkResponseBodyList(final JSONObject json, final Map<String, String> uri,
        final String type, final Map<String, Map<String, Object>> additional, String key,
        Map<String, String> np, Map<String, String> etag) {
    // __count??
    checkResponseBodyCount(json, COUNT_NONE);

    // results
    JSONArray results = (JSONArray) ((JSONObject) json.get("d")).get("results");

    // ???
    if (uri == null) {
        assertEquals(0, results.size());
    } else {
        assertEquals(uri.size(), results.size());
    }

    // results??
    for (Object result : results) {
        if (etag != null) {
            // Etag??
            checkResponseEtagList(result, etag, key);
        }

        String reskey = (String) ((JSONObject) result).get(key);
        checkResults((JSONObject) result, uri.get(reskey), type, additional.get(reskey), np, null);
    }
}

From source file:chat.com.client.ChatClient.java

private void typeChat(String msg) {
    try {//from ww w .  java2s . co m
        JSONParser jsonParser = new JSONParser();
        JSONObject jsontypeChat = (JSONObject) jsonParser.parse(msg);
        //   jTextAreaChat.append(msg + '\n');
        String type = jsontypeChat.get("type").toString();

        if (type.equals("me")) {
            // get id for user
            id = jsontypeChat.get("id").toString();
            jTextAreaChat.append(id + '\n');
        } else if (type.equals("userOnline")) {
            // add item
            JSONArray jsonArray = (JSONArray) jsontypeChat.get("listUser");
            jComboBoxListUser.removeAllItems();
            jComboBoxListUser.addItem("all");
            for (int i = 0; i < jsonArray.size(); i++) {
                if (!jsonArray.get(i).equals(id)) {
                    //
                    jComboBoxListUser.addItem(jsonArray.get(i));
                }
            }
        } else {
            //(type.equals("chat"))
            String idWho = (String) jsontypeChat.get("id");
            String message = (String) jsontypeChat.get("message");
            jTextAreaChat.append(idWho + " say: " + message + '\n');
        }
    } catch (ParseException ex) {
        Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.codelanx.playtime.update.UpdateHandler.java

/**
 * Gets the {@link JSONObject} from the CurseAPI of the newest project version.
 * /*  ww  w  .  j av a 2s.  c  om*/
 * @since 1.4.5
 * @version 1.4.5
 */
private void getJSON() {
    InputStream stream = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    String json = null;
    try {
        URL call = new URL(this.VERSION_URL);
        stream = call.openStream();
        isr = new InputStreamReader(stream);
        reader = new BufferedReader(isr);
        json = reader.readLine();
    } catch (MalformedURLException ex) {
        plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : "");
        this.result = Result.ERROR_BADID;
        this.latest = null;
    } catch (IOException ex) {
        plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : "");
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            this.plugin.getLogger().log(Level.SEVERE, "Error closing updater streams!",
                    this.debug >= 3 ? ex : "");
        }
    }
    if (json != null) {
        JSONArray arr = (JSONArray) JSONValue.parse(json);
        this.latest = (JSONObject) arr.get(arr.size() - 1);
    } else {
        this.latest = null;
    }
}

From source file:com.wcmc.Software.screens.RegistrationScreen.java

public void setRiderInfo(String data) {
    try {//ww w. jav a 2  s .co m
        if (!data.equals("{}")) {
            JSONObject json = (JSONObject) jsonParser.parse(data);
            if (json != null) {
                String name = json.get("first_name").toString() + " " + json.get("last_name").toString();
                if (!json.get("middle_name").toString().equals("")) {
                    name = json.get("first_name").toString() + " \"" + json.get("middle_name").toString()
                            + "\" " + json.get("last_name").toString();
                }
                Client.ms.rS.currentRider = Integer.parseInt(json.get("id").toString());
                rider.setName(name);
                rider.setRiderID(Integer.parseInt(json.get("id").toString()));
                rider.setAddress(json.get("address").toString(), json.get("city").toString(),
                        json.get("state").toString(), json.get("country").toString());
                rider.setHomePhone(json.get("home_phone").toString());
                rider.setCellPhone(json.get("cell_phone").toString());
                rider.setEmail(json.get("email").toString());
                rider.setLicense(json.get("license").toString());
                JSONArray classes = (JSONArray) json.get("classes");
                rider.clear();
                for (int i = 0; i < classes.size(); i++) {
                    JSONObject classInfo = (JSONObject) classes.get(i);
                    ClassesCheckbox classBox = new ClassesCheckbox();
                    classBox.setTitle(classInfo.get("title").toString());
                    classBox.setID(Integer.parseInt(classInfo.get("id").toString()));
                    classBox.setNumber(Integer.parseInt(classInfo.get("bike_number").toString()));
                    classBox.setBrand(classInfo.get("bike_brand").toString());
                    classBox.setIsActive((boolean) classInfo.get("signed_in"));
                    rider.addClass(classBox);
                }
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java

/**
 * Gets the package identifiers/names within a given organization id/name.
 * @param orgId/*  w ww  .  j a va 2s. c  o  m*/
 * @return The package identifiers/names within the given organization id/name
 */
public List<String> getPackages(String orgId) {
    logger.debug("Getting the packages within " + orgId + " organization");
    List<String> pkgNames = new ArrayList<String>();

    try {
        String url = "http" + (ssl ? "s" : "") + "://" + ckanHost + ":" + ckanPort
                + "/api/3/action/organization_show?id=" + orgId;
        CKANResponse resp = doCKANRequest("GET", url, "");
        JSONObject result = (JSONObject) resp.getJsonObject().get("result");
        JSONArray pkgs = (JSONArray) result.get("packages");

        if (pkgs == null || pkgs.size() == 0) {
            logger.debug("No packages got from organization " + orgId);
            return pkgNames;
        } // if

        for (Object pkg1 : pkgs) {
            JSONObject pkg = (JSONObject) pkg1;
            pkgNames.add((String) pkg.get("id"));
        } // for

        return pkgNames;
    } catch (Exception e) {
        logger.debug("An exception occured, returning partial package list. Details = " + e.getMessage());
        return pkgNames;
    } // try catch // try catch
}

From source file:interfaceTisseoWS.ST3.java

private void listResMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listResMouseClicked

    String x = (String) ((JSONObject) ((JSONArray) ((JSONObject) array.get("placesList")).get("place"))
            .get(listRes.getSelectedIndex())).get("x");
    String y = (String) ((JSONObject) ((JSONArray) ((JSONObject) array.get("placesList")).get("place"))
            .get(listRes.getSelectedIndex())).get("y");

    double distanceAParcourir = getDistance(1.46944, 43.561255, Double.valueOf(x), Double.valueOf(y));

    double ax = Double.valueOf(x) - 0.005;
    double ay = Double.valueOf(y) - 0.003;
    double bx = Double.valueOf(x) + 0.005;
    double by = Double.valueOf(y) + 0.003;

    // x+-0.005  y+-0.003
    boolean contientTisseo, contientVelib = false;

    try {//from   w  w w . java  2s  .  com
        //recherche lignes tisseo dans la zone
        RequestTisseo r = new RequestTisseo();
        JSONParser parser = new JSONParser();

        r.setPathURIB("/stopPointsList");
        r.addParamURIB("srid", "4326");
        r.addParamURIB("displayLines", "1");
        r.addParamURIB("sortByDistance", "1");

        String bbox = Double.toString(ax) + "," + Double.toString(ay) + "," + Double.toString(bx) + ","
                + Double.toString(by);
        r.addParamURIB("bbox", bbox);
        Object obj = parser.parse(r.request());
        JSONObject array2 = (JSONObject) obj;

        contientTisseo = (((JSONArray) ((JSONObject) array2.get("physicalStops")).get("physicalStop"))
                .size()) > 0;

        //recherche stations velib dans la zone si point  moins de 3 kilomtre
        if (distanceAParcourir < 3.0) {
            RequestJCDecaux r3 = new RequestJCDecaux();
            JSONParser parser3 = new JSONParser();

            r3.setPathURIB("/vls/v1/stations");

            Object obj3 = parser3.parse(r3.request());
            JSONArray array3 = (JSONArray) obj3;

            int nbStations = array3.size();
            double X, Y;
            int i = 0;
            while (i < nbStations && !contientVelib) {
                X = (double) ((JSONObject) ((JSONObject) (JSONObject) array3.get(i)).get("position"))
                        .get("lng");
                Y = (double) ((JSONObject) ((JSONObject) (JSONObject) array3.get(i)).get("position"))
                        .get("lat");
                if (X > ax && X < bx && Y > ay && Y < by) {
                    contientVelib = true;
                }
                i++;
            }
        }
        if (!contientTisseo && !contientVelib) {
            lblResultat.setText("Aucun rsultat");
        } else {
            if (contientTisseo && !contientVelib) {
                lblResultat.setText("Utilisez le rseau Tisso");
            } else {
                if (!contientTisseo && contientVelib) {
                    lblResultat.setText("Utilisez VelToulouse");
                } else {
                    int nbArrivees = (((JSONArray) ((JSONObject) array2.get("physicalStops"))
                            .get("physicalStop")).size());
                    int j = 0;
                    while (j < nbArrivees) {
                        if (estDeservieDepuisPS(((JSONArray) ((JSONObject) ((JSONArray) ((JSONObject) array2
                                .get("physicalStops")).get("physicalStop")).get(j)).get("destinations")))) {
                            break;
                        }
                        j++;
                        if (j == nbArrivees) {
                            lblResultat.setText(
                                    "Aucun ligne Tisso ne dssert directement votre zone depuis \nPaul Sabatier, la distance est infrieure  3 km donc nous vous \nconseillons d'utiliser le service VelToulouse");
                        }
                    }
                }
            }
        }

    } catch (ParseException ex) {
        Logger.getLogger(ST3.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ST3.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(ST3.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.greatmancode.tools.utils.Updater.java

private boolean read() {
    try {//from  w w  w .jav a  2 s.com
        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) {
            caller.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")) {
            caller.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            caller.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            caller.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            caller.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:com.nubits.nubot.utils.FrozenBalancesManager.java

private void parseFrozenBalancesFile() {
    JSONParser parser = new JSONParser();
    String FrozenBalancesManagerString = FilesystemUtils.readFromFile(this.pathToFrozenBalancesFiles);
    try {//from   w  ww .j av  a2s .co m
        JSONObject frozenBalancesJSON = (JSONObject) (parser.parse(FrozenBalancesManagerString));
        double quantity = Double.parseDouble((String) frozenBalancesJSON.get("frozen-quantity-total"));
        Amount frozenAmount = new Amount(quantity, toFreezeCurrency);
        setInitialFrozenAmount(frozenAmount, false);

        JSONArray historyArr = (JSONArray) frozenBalancesJSON.get("history");
        for (int i = 0; i < historyArr.size(); i++) {
            JSONObject tempHistoryRow = (JSONObject) historyArr.get(i);

            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
            Date timestamp = df.parse((String) tempHistoryRow.get("timestamp"));

            double frozeQuantity = Double.parseDouble((String) tempHistoryRow.get("froze-quantity"));
            String currencyCode = (String) tempHistoryRow.get("currency-code");

            history.add(new HistoryRow(timestamp, frozeQuantity, currencyCode));
        }

    } catch (ParseException | NumberFormatException | java.text.ParseException e) {
        LOG.error("Error while parsing the frozen balances file (" + pathToFrozenBalancesFiles + ")\n"
                + e.toString());
    }
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 * /*from  w  ww .j  a va  2  s.co  m*/
 * @since 0.0.1
 * @version 0.1.0
 * 
 * @param output Whether or not to print output
 * @param log The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of player names to their {@link UUID}s
 * @throws IOException If there's a problem sending or receiving the request
 * @throws ParseException If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 */
public Map<String, UUID> callWithProgessOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    //Method start
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            log.warning("[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...");
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }
        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();
        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }
        if (output) {
            int processed = completed + failed;
            if (doOutput.test(processed) || processed == totalNames) {
                log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                        totalNames, ((double) processed / totalNames) * 100D, failed));
            }
        }
    }
    return uuidMap;
}