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:co.anarquianegra.rockolappServidor.mundo.ListaReproductor.java

private Cancion buscarCancionesEnApi(IListaOrdenada resultado, String pNombre, long id) {
    ApiWrapper wrapper = new ApiWrapper(client_id, client_secret, null, null);
    try {//from ww  w .java 2 s .  co  m
        Request r;
        if (id > -1)
            r = new Request("/tracks/" + id);
        else
            r = new Request("/tracks?q=" + pNombre);
        System.out.println("Buscando en sOUNDclOUD");
        HttpResponse resp = wrapper.get(r);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String s = Http.formatJSON(Http.getString(resp));
            try {
                if (id > -1) {
                    JSONObject json = (JSONObject) new JSONParser().parse(s);
                    System.out.println(json);
                    Cancion c = new Cancion((String) json.get("title"), (String) json.get("stream_url"));
                    c.setId((long) json.get("id"));
                    return c;
                } else {
                    JSONArray canciones = (JSONArray) new JSONParser().parse(s);
                    for (int i = 0; i < canciones.size(); i++) {
                        JSONObject json = (JSONObject) canciones.get(i);
                        System.out.println(json);
                        Cancion c = new Cancion((String) json.get("title"), (String) json.get("stream_url"));
                        c.setId((long) json.get("id"));
                        resultado.agregar(c);
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:de.ingrid.external.gemet.GEMETClient.java

public List<JSONArray> getParentConcepts(String conceptUri, String language) {
    // parent relations
    ConceptRelation[] relations = new ConceptRelation[] { ConceptRelation.BROADER, ConceptRelation.GROUP };

    // get parents
    List<JSONArray> conceptList = new ArrayList<JSONArray>();
    for (ConceptRelation relation : relations) {
        JSONArray concepts = getRelatedConcepts(conceptUri, relation, language);
        conceptList.add(concepts);//from   www . j ava 2s. c  o m

        // only fetch GROUP if no BROADER relations found !
        if (relation == ConceptRelation.BROADER && concepts.size() > 0) {
            break;
        }
    }

    return conceptList;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

private void addAbsoluteOffsets(JSONArray arr) {
    int offset = 0;
    for (int i = 0; i < arr.size(); i++) {
        JSONObject jObj = (JSONObject) arr.get(i);
        Number reloff = (Number) jObj.get(JSONKeys.RELOFF);
        offset += reloff.intValue();//from  w w  w. j a va  2  s.co  m
        jObj.put(JSONKeys.OFFSET, offset);
    }
}

From source file:assignment3.Populate.java

CreateUser() {
    try {//w w w  . j av a 2s .c  om

        Class.forName("oracle.jdbc.driver.OracleDriver");

    } catch (ClassNotFoundException e) {

        System.out.println("JDBC Driver Missing");
        e.printStackTrace();
        return;

    }

    System.out.println("Oracle JDBC Driver Connected");

    Connection conn = null;

    try {

        conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "MAYUR", "123456");
        conn.setAutoCommit(false);

        PreparedStatement ps = conn
                .prepareStatement("insert into yelp_user values (?, ?, ?,?, ?, ?,?, ?, ?,?,?)");

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new BufferedReader(new FileReader(
                "C:\\Users\\mayur\\Downloads\\YelpDataset\\YelpDataset-CptS451\\yelp_user.json")));

        //Object obj = parser.parse(new BufferedReader(new FileReader("C:\\Users\\mayur\\Downloads\\YelpDataset\\YelpDataset-CptS451\\yelp_user1.json")));

        JSONArray jsonArray = (JSONArray) (obj);

        // JSONArray jsonArray = (JSONArray)(obj1);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject t = (JSONObject) jsonArray.get(i);

            String c = t.get("yelping_since").toString();

            Date yelping_since = (Date) java.sql.Date.valueOf(c + "-01");

            JSONObject votes = (JSONObject) t.get("votes"); // get all votes details
            Long votes_funny = (Long) votes.get("funny");
            Long votes_useful = (Long) votes.get("useful");
            Long votes_cool = (Long) votes.get("cool");

            Long review_count = (Long) t.get("review_count");
            String name = t.get("name").toString();
            String user_id = t.get("user_id").toString();

            JSONArray friends = (JSONArray) (t).get("friends");
            int numfriends = 0;
            if (friends != null) {
                Iterator<String> iterator = friends.iterator();
                ArrayList<String> friendid_list = new ArrayList<String>();

                while (iterator.hasNext()) {
                    friendid_list.add(iterator.next());
                }

                if (friendid_list != null)
                    numfriends = friendid_list.size();

                friendid_list = null;
                iterator = null;

            }
            Long fans = (Long) t.get("fans");
            double average_stars = (double) t.get("average_stars");
            String type = t.get("type").toString();

            ps.setDate(1, yelping_since);
            ps.setLong(2, votes_funny);
            ps.setLong(3, votes_useful);
            ps.setLong(4, votes_cool);
            ps.setLong(5, review_count);
            ps.setString(6, name);
            ps.setString(7, user_id);
            ps.setLong(8, fans);
            ps.setDouble(9, average_stars);
            ps.setString(10, type);
            ps.setInt(11, numfriends);

            ps.executeUpdate();
            System.out.println("Record inserted " + i);

        }

        conn.commit();

        ps.close();

    } catch (Exception e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;

    }

}

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

/**
 * The function gets a JSON array with the ratings and returns an average
 * rating value, which is rounded to 0.5.
 * //from   w  w w  .j a v a  2s .c o m
 * @param arr
 *            the array with the ratings.
 * 
 * @return the averaged rating value rounded to 0.5-
 */
protected static double calculateAverageRating(JSONArray arr) {
    // check the parameter
    if (arr == null) {
        return -1;
    }

    int accumulatedRatingValue = 0;
    for (int i = 0; i < arr.size(); i++) {
        Map rating = (Map) arr.get(i);
        String ratingValue = (String) rating.get("ratingValue");
        accumulatedRatingValue += Integer.parseInt(ratingValue);
    }

    // round to 0.5
    double toreturn = ((double) accumulatedRatingValue) / ((double) arr.size());
    if ((toreturn - (int) toreturn) > 0.25 && (toreturn - (int) toreturn) < 0.75) {
        toreturn = ((int) toreturn) + 0.5;
    } else if ((toreturn - (int) toreturn) >= 0.75) {
        toreturn = ((int) toreturn) + 1.0;
    } else if ((toreturn - (int) toreturn) <= 0.75) {
        toreturn = ((int) toreturn);
    }

    return toreturn;
}

From source file:net.milkbowl.vault.Vault.java

public double updateCheck(double currentVersion) {
    try {/*w  ww .j  a  v a 2  s .  c om*/
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=33184");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "Vault 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.");
            return currentVersion;
        }
        // Pull the last version from the JSON
        newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name")).replace("Vault", "")
                .trim();
        return Double.valueOf(newVersionTitle.replaceFirst("\\.", "").trim());
    } catch (Exception e) {
        log.info("There was an issue attempting to check for the latest version.");
    }
    return currentVersion;
}

From source file:eu.riscoss.rdc.RDCGithub.java

/**
 * For paginated requests/* w ww . j a va  2  s.  c  o m*/
 * @param request
 * @param maxPages max pages in paginated requests
 * @param created_at_years maximum timespan for the "created at" field (used e.g. for issues). 0: no timespan
 * @return
 */
private JSONAware parsePaged(String request, int maxPages, int created_at_years) {

    JSONArray jaComplete = new JSONArray();

    char divider = '?';
    if (request.contains("?"))
        divider = '&';

    Calendar lastyear = Calendar.getInstance();//actual
    lastyear.set(Calendar.YEAR, lastyear.get(Calendar.YEAR) - created_at_years);

    try {
        for (int i = 1; i <= maxPages; i++) {

            String jsonPage = getData(repository + request + divider + "page=" + i, "");

            if (jsonPage.startsWith("WARNING")) {
                System.err.println(jsonPage); //error message - implement different handling if needed
            } else
                try {
                    JSONAware jv = (JSONAware) new JSONParser().parse(jsonPage);
                    if (jv instanceof JSONArray) {
                        JSONArray ja = (JSONArray) jv;
                        if (ja.size() == 0)
                            break;
                        jaComplete.addAll(ja);
                        //do not scan more years
                        if (created_at_years > 0) {
                            Calendar openedDate;
                            String openedAt = (String) ((JSONObject) ja.get(ja.size() - 1)).get("created_at");
                            if (openedAt != null) {
                                openedDate = DatatypeConverter.parseDateTime(openedAt);
                                //System.out.println("scan: opening date: "+openedDate.get(Calendar.YEAR)+" "+openedDate.get(Calendar.MONTH));
                                //System.out.println("scan: last    date: "+lastyear.get(Calendar.YEAR)+" "+lastyear.get(Calendar.MONTH));

                                if (openedDate.compareTo(lastyear) < 0) {
                                    System.out.println("BREAK");
                                    break;
                                }
                            }
                        }

                    }
                } catch (ParseException e) {
                    e.printStackTrace();//TODO
                }
        }

    } catch (org.apache.http.ParseException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return jaComplete;
}

From source file:com.mp.gw2api.data.GW2APIAccount.java

@Override
public void LoadFromJsonText(String text) {
    JSONParser parser = new JSONParser();
    JSONObject json = null;// ww w .  ja va  2s.  c  o m
    JSONArray ja = null;
    JSONArray jb = null;
    try {
        //Parse json array
        json = (JSONObject) parser.parse(text);

        //Check for errors
        if (json.containsKey("text")) {
            errorText = (String) json.get("text");
            return;
        }

        //Gather Account information
        id = (String) json.get("id");
        name = (String) json.get("name");
        world = (long) json.get("world");

        ja = (JSONArray) json.get("guilds");
        if (ja != null)
            if (ja.size() > 0) {
                guilds = new String[ja.size()];
                for (int i = 0; i < ja.size(); i++)
                    guilds[i] = (String) ja.get(i);
            }

        created = (String) json.get("created");

        //access
        String accessStr = (String) json.get("access");
        //For each AccessLevel String known.
        for (int i = 0; i < GW2Access.AccessStrings.length; i++)
            //If the accessStr read matches one known
            if (GW2Access.AccessStrings[i].equals(accessStr)) {
                //Fetch the enumeration related to that index
                access = AccessLevel.values()[i];
                break;//break loop
                //If no values matched (error)
            } else if (i == GW2Access.AccessStrings.length - 1)
                access = AccessLevel.NONE;

        commander = (boolean) json.get("commander");
        fractalLevel = (long) json.get("fractal_level");
        dailyAP = (long) json.get("daily_ap");
        monthlyAP = (long) json.get("monthly_ap");
        wvwRank = (long) json.get("wvw_rank");

    } catch (ParseException ex) {
        Logger.getLogger(com.mp.gw2api.lists.GW2APIMapList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testJobTags() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tags");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());

    assertTrue(jsonArray.contains("LOOP-T2-1"));
    assertTrue(jsonArray.contains("LOOP-T2-2"));
    assertTrue(jsonArray.contains("LOOP-T2-3"));
    assertTrue(jsonArray.contains("REPLICATE-T3-1"));
    assertTrue(jsonArray.contains("REPLICATE-T3-2"));
    assertEquals(5, jsonArray.size());
}

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

/**
 * Returns a list of the most popular tags.
 * /*from  www.  j a v  a  2s  .c  om*/
 * @param numberOfTags
 *            the number of popular tags to return.
 * @return the most popular tags or null if an error occurred.
 */
@Deprecated
@SuppressWarnings("unchecked")
public static JSONArray getMostPopularTagsOld(int numberOfTags) {

    // check the parameters
    if (numberOfTags <= 0) {
        return null;
    }

    // the json array to return
    JSONArray toreturn = new JSONArray();

    // the array to store rating values
    double[] ratingValues = new double[numberOfTags];
    // even tough Java does it automatically, we set the values to zero
    for (int i = 0; i < ratingValues.length; i++) {
        ratingValues[i] = 0.0;
    }

    // a help array for the package ratings
    HashMap<String, Double> packageRatings = new HashMap<String, Double>();

    // prepare the REST API call
    String RESTcall = "api/rest/tag";

    try {
        // run the REST call to obtain all tags
        String tagListString = connectorInstance.restCallWithAuthorization(RESTcall, null);
        if (tagListString == null) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
            return null;
        }

        // parse the JSON string and obtain an array of JSON objects
        Object obj = JSONValue.parse(tagListString);
        JSONArray array = (JSONArray) obj;

        // move over the tags in the array
        for (int i = 0; i < array.size(); i++) {

            // pick the tag name
            String tagName = (String) array.get(i);

            // run the REST call to obtain all packages for the tag in
            // question
            String tRESTcall = RESTcall + "/" + tagName;
            String pListString = connectorInstance.restCallWithAuthorization(tRESTcall, null);

            if (pListString == null) {
                log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
                return null;
            }

            // parse the JSON string
            Object pObj = JSONValue.parse(pListString);
            JSONArray pArray = (JSONArray) pObj;

            // iterate over the JSON array
            double tagRating = 0.0;
            for (int j = 0; j < pArray.size(); j++) {
                // pick the name of the package
                String pName = (String) (pArray.get(j));

                // check whether the average rating value has already been
                // obtained
                Double aRatingValueD = packageRatings.get(pName);

                if (aRatingValueD == null) {
                    // in case it was not obtained until now --> get it and
                    // store it locally
                    double aRatingValue = CKANGatewayUtil.getDataSetRatingsAverage(pName);
                    aRatingValueD = new Double(aRatingValue);
                    packageRatings.put(pName, aRatingValueD);
                }

                // update the tag rating
                tagRating += aRatingValueD.doubleValue();
            }

            // update the toreturn array
            if (toreturn.size() < numberOfTags) {
                toreturn.add(tagName);
                ratingValues[toreturn.size() - 1] = tagRating;

            } else {
                // get the smallest value in the rating values
                int minIndex = minDoubleArray(ratingValues);
                if (ratingValues[minIndex] < tagRating) {
                    ratingValues[minIndex] = tagRating;
                    toreturn.set(minIndex, tagName);
                }
            }
        }
    }
    // catch potential exceptions
    catch (MalformedURLException e) {
        log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
        return null;
    } catch (IOException e) {
        return null;
    }

    return toreturn;
}