Example usage for org.json.simple JSONArray get

List of usage examples for org.json.simple JSONArray get

Introduction

In this page you can find the example usage for org.json.simple JSONArray get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.gti.redirects.Redirects.RedirectStorage.java

@Override
public List<Map<String, String>> getAll() {
    List<Map<String, String>> redirects = new ArrayList<Map<String, String>>();
    JSONArray jsonArray = null;
    try {/*from  w w w  .j  av a2 s  .  com*/
        jsonArray = parseFile();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            Map<String, String> map = new HashMap<String, String>();
            map.put("domain", object.get("domain").toString());
            map.put("status", object.get("status").toString());
            map.put("redirect_to", object.get("redirect_to").toString());

            redirects.add(map);
            // now do something with the Object
        }
    }
    return redirects;
}

From source file:data.GoogleBooksWS.java

@Override
public void parse(String tekst) throws Exception {

    //List<Book> lista=new ArrayList<>();

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(tekst);
    JSONObject jsonObject = (JSONObject) obj;
    if (prvi) {//w w  w  .jav a2  s.  c o m
        int brojRezultata = Integer.parseInt(jsonObject.get("totalItems") + "");
        ukupanBrojStrana = brojRezultata / RESULTS_PER_PAGE + 1;
        System.out.println("Broj strana" + ukupanBrojStrana);
        prvi = false;
    }

    System.out.println("Trenutni broj strane " + trenutniBrojStrane);
    JSONArray niz = (JSONArray) jsonObject.get("items");
    if (niz == null) {
        kraj = true;
    } else {
        Iterator iterator = niz.iterator();
        while (iterator.hasNext()) {
            Book b = new Book();
            b.setUri(URIGenerator.generateUri(b));
            JSONObject book = (JSONObject) iterator.next();
            b.setTitle((String) ((JSONObject) book.get("volumeInfo")).get("title"));
            JSONArray autori = (JSONArray) ((JSONObject) book.get("volumeInfo")).get("authors");
            if (autori != null) {
                Iterator it = autori.iterator();
                while (it.hasNext()) {
                    Person p = new Person();
                    p.setUri(URIGenerator.generateUri(p));
                    p.setName((String) it.next());
                    b.getAuthors().add(p);
                }
            } else {
                System.out.println("Autori su null");
            }
            Organization o = new Organization();
            o.setUri(URIGenerator.generateUri(o));
            o.setName((String) ((JSONObject) book.get("volumeInfo")).get("publisher"));
            b.setPublisher(o);
            String date = (String) ((JSONObject) book.get("volumeInfo")).get("publishedDate");
            System.out.println(date);
            b.setDatePublished(date);

            String description = (String) ((JSONObject) book.get("volumeInfo")).get("description");
            b.setDescription(description);

            Object brStr = ((JSONObject) book.get("volumeInfo")).get("pageCount");
            if (brStr != null) {
                long broj = Long.parseLong(brStr.toString());
                b.setNumberOfPages((int) broj);
            }

            JSONArray identifiers = (JSONArray) ((JSONObject) book.get("volumeInfo"))
                    .get("industryIdentifiers");
            if (identifiers != null) {
                for (int i = 0; i < identifiers.size(); i++) {
                    JSONObject identifier = (JSONObject) identifiers.get(i);
                    if ("ISBN_13".equals((String) identifier.get("type"))) {
                        b.setIsbn((String) identifier.get("identifier"));
                    }
                }
            }
            //b.setIsbn((String) ((JSONObject) ((JSONArray)((JSONObject)book.get("volumeInfo")).get("industryIdentifiers")).get(1)).get("identifier"));

            lista.add(b);

        }

        if (trenutniBrojStrane < ukupanBrojStrana) {
            trenutniBrojStrane++;
        } else {
            kraj = true;
        }
    }
}

From source file:de.xaniox.heavyspleef.core.uuid.UUIDManager.java

private GameProfile fetchGameProfile(UUID uuid) throws IOException, ParseException {
    String uuidString = uuid.toString().replace("-", "");
    URL url = new URL(String.format(UUID_BASE_URL, uuidString));

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream inputStream = connection.getInputStream();

    JSONArray result = (JSONArray) parser.parse(new InputStreamReader(inputStream));
    JSONObject current = (JSONObject) result.get(result.size() - 1);
    String name = (String) current.get("name");
    if (name == null) {
        return null;
    }/* w w w.  j a v a 2 s.  co m*/

    GameProfile profile = new GameProfile(uuid, name);
    return profile;
}

From source file:de.matzefratze123.heavyspleef.util.Updater.java

public void query() {
    URL url;/*from w w  w .ja  v a  2s  .  c o  m*/

    try {
        url = new URL(API_HOST + API_QUERY + PROJECT_ID);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return;
    }

    try {
        URLConnection conn = url.openConnection();

        conn.setConnectTimeout(6000);
        conn.addRequestProperty("User-Agent", "HeavySpleef-Updater (by matzefratze123)");

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

        JSONArray array = (JSONArray) JSONValue.parse(query);

        String version = null;

        if (array.size() > 0) {

            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            fileTitle = (String) latest.get(API_TITLE_VALUE);
            fileName = (String) latest.get(API_NAME_VALUE);
            downloadUrl = (String) latest.get(API_LINK_VALUE);

            String[] parts = fileTitle.split(" v");
            if (parts.length >= 2) {
                version = parts[1];
            }

            checkVersions(version);
            done = true;
        }
    } catch (IOException e) {
        Logger.severe("Failed querying the curseforge api: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:net.bashtech.geobot.JSONUtil.java

public static String getGameChannel(String gameName) {
    gameName = gameName.replaceAll(" ", "+");
    try {//from   w w  w . j  a v a 2  s .  co m
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(
                BotManager.getRemoteContent("https://api.twitch.tv/kraken/search/streams?q=" + gameName));

        JSONObject jsonObject = (JSONObject) obj;
        Long total = (Long) jsonObject.get("_total");
        if (total > 0) {
            JSONArray streams = (JSONArray) jsonObject.get("streams");
            int numStreams = streams.size();
            int randomChannel = (int) (Math.random() * (numStreams - 1));
            JSONObject stream = (JSONObject) streams.get(randomChannel);
            JSONObject channel = (JSONObject) stream.get("channel");
            String url = (String) channel.get("display_name");

            return url;
        } else
            return "No other channels playing this game";

    } catch (Exception ex) {
        ex.printStackTrace();
        return "Error Querying API";
    }
}

From source file:com.capitalone.dashboard.collector.DefaultNexusIQClient.java

/**
 * Get the report details given a url for the report data.
 * @param url url of the report/*from ww w .  j a  v a  2s  .  c o m*/
 * @return LibraryPolicyResult
 */
@SuppressWarnings({ "PMD.AvoidDeeplyNestedIfStmts", "PMD.NPathComplexity" }) // agreed PMD, fixme

@Override
public LibraryPolicyResult getDetailedReport(String url) {
    LibraryPolicyResult policyResult = null;
    try {
        JSONObject obj = parseAsObject(url);
        JSONArray componentArray = (JSONArray) obj.get("components");
        if ((componentArray == null) || (componentArray.isEmpty()))
            return null;
        for (Object element : componentArray) {
            JSONObject component = (JSONObject) element;
            int licenseLevel = 0;
            JSONArray pathArray = (JSONArray) component.get("pathnames");

            String componentName = !CollectionUtils.isEmpty(pathArray) ? (String) pathArray.get(0)
                    : getComponentNameFromIdentifier((JSONObject) component.get("componentIdentifier"));

            JSONObject licenseData = (JSONObject) component.get("licenseData");

            if (licenseData != null) {
                //process license data
                JSONArray effectiveLicenseThreats = (JSONArray) licenseData.get("effectiveLicenseThreats");
                if (!CollectionUtils.isEmpty(effectiveLicenseThreats)) {
                    for (Object et : effectiveLicenseThreats) {
                        JSONObject etJO = (JSONObject) et;
                        Long longvalue = toLong(etJO, "licenseThreatGroupLevel");
                        if (longvalue != null) {
                            int newlevel = longvalue.intValue();
                            if (licenseLevel == 0) {
                                licenseLevel = newlevel;
                            } else {
                                licenseLevel = nexusIQSettings.isSelectStricterLicense()
                                        ? Math.max(licenseLevel, newlevel)
                                        : Math.min(licenseLevel, newlevel);
                            }
                        }
                    }

                }
            }

            if (policyResult == null) {
                policyResult = new LibraryPolicyResult();
            }

            if (licenseLevel > 0) {
                policyResult.addThreat(LibraryPolicyType.License,
                        LibraryPolicyThreatLevel.fromInt(licenseLevel), componentName);
            }

            JSONObject securityData = (JSONObject) component.get("securityData");
            if (securityData != null) {
                //process security data
                JSONArray securityIssues = (JSONArray) securityData.get("securityIssues");
                if (!CollectionUtils.isEmpty(securityIssues)) {
                    for (Object si : securityIssues) {
                        JSONObject siJO = (JSONObject) si;
                        BigDecimal bigDecimalValue = decimal(siJO, "severity");
                        double securityLevel = (bigDecimalValue == null)
                                ? getSeverityLevel(str(siJO, "threatCategory"))
                                : bigDecimalValue.doubleValue();
                        policyResult.addThreat(LibraryPolicyType.Security,
                                LibraryPolicyThreatLevel.fromDouble(securityLevel), componentName);
                    }
                }
            }
        }
    } catch (ParseException e) {
        LOG.error("Could not parse response from: " + url, e);
    } catch (RestClientException rce) {
        LOG.error("RestClientException from: " + url + ". Error code=" + rce.getMessage());
    }
    return policyResult;
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java

public int getOrgWideCodeCoverage() {
    String relativeServiceURL = "/services/data/v" + SUPPORTED_VERSION + "/tooling";
    String soql = QueryConstructor.getOrgWideCoverage();
    int coverage = 0;
    JSONObject responseJsonObject = null;
    responseJsonObject = WebServiceInvoker.doGet(relativeServiceURL, soql, OAuthTokenGenerator.getOrgToken());

    if (responseJsonObject != null) {
        String responseStr = responseJsonObject.toJSONString();
        LOG.debug("responseStr during org wide code coverage" + responseStr);
        JSONArray recordObject = (JSONArray) responseJsonObject.get("records");
        for (int i = 0; i < recordObject.size(); ++i) {

            JSONObject rec = (JSONObject) recordObject.get(i);

            coverage = Integer.valueOf((String) rec.get("PercentCovered").toString());
            LOG.info(/*from w  w  w.  j  a  va 2s .co m*/
                    "####################################   Org wide code coverage result  #################################### ");
            LOG.info("Org wide code coverage : " + coverage + "%");
        }
    } else {
        ApexUnitUtils.shutDownWithErrMsg("Org wide code coverage not computed");
    }
    ApexUnitCodeCoverageResults.orgWideCodeCoverage = coverage;
    return coverage;
}

From source file:functionaltests.RestSchedulerJobPaginationTest.java

@Test
public void testJobsPagination() throws Exception {
    Assert.assertEquals("Test expects only one node", 1, RestFuncTHelper.DEFAULT_NUMBER_OF_NODES);

    JobId jobId1 = getScheduler().submit(createJob(NonTerminatingJob.class));
    waitJobState(jobId1, JobStatus.RUNNING, 30000);

    JobId jobId2 = submitDefaultJob();//from  w  w  w  .  ja  v  a2s  .  c  o  m
    JobId jobId3 = submitDefaultJob();

    checkPagingRequests1();

    // check 'jobsinfo' and 'revisionjobsinfo' provide job's attributes

    JSONObject page;
    JSONArray jobs;

    page = getRequestJSONObject(getResourceUrl("jobsinfo"));
    jobs = (JSONArray) page.get("list");
    checkJob((JSONObject) jobs.get(2), JobStatus.RUNNING, 1, 0);

    page = getRequestJSONObject(getResourceUrl("revisionjobsinfo"));
    JSONObject map = (JSONObject) page.get("map");
    Assert.assertEquals(1, map.keySet().size());
    jobs = (JSONArray) map.get(map.keySet().iterator().next());
    checkJob((JSONObject) jobs.get(2), JobStatus.RUNNING, 1, 0);

    checkFiltering1();

    String resource = "jobs/" + jobId1.value() + "/kill";
    String schedulerUrl = getResourceUrl(resource);
    HttpPut httpPut = new HttpPut(schedulerUrl);
    setSessionHeader(httpPut);
    HttpResponse response = executeUriRequest(httpPut);
    assertHttpStatusOK(response);

    waitJobState(jobId1, JobStatus.KILLED, 30000);
    waitJobState(jobId2, JobStatus.FINISHED, 30000);
    waitJobState(jobId3, JobStatus.FINISHED, 30000);

    checkFiltering2();

    // check 'jobsinfo' and 'revisionjobsinfo' provide updated job's attributes

    JSONObject job = null;

    page = getRequestJSONObject(getResourceUrl("jobsinfo"));
    jobs = (JSONArray) page.get("list");
    checkJob(findJob("1", jobs), JobStatus.KILLED, 0, 0);

    page = getRequestJSONObject(getResourceUrl("revisionjobsinfo"));
    map = (JSONObject) page.get("map");
    Assert.assertEquals(1, map.keySet().size());
    jobs = (JSONArray) map.get(map.keySet().iterator().next());
    checkJob(findJob("1", jobs), JobStatus.KILLED, 0, 0);

    checkPagingRequests2();
}

From source file:iphonestalker.util.FindMyIPhoneReader.java

public boolean pollLocation(int device) {

    if (device < numDevices) {
        try {/*  www.  j  av  a  2 s . c o  m*/
            // Poll for data
            HttpResponse response = client.execute(post);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

            // Read the data
            JSONObject object = (JSONObject) JSONValue.parse(reader);
            JSONArray array = ((JSONArray) object.get("content"));
            //int devices = array.size();
            //System.out.println("Found " + devices + " devices");

            // Get the device data
            object = (JSONObject) array.get(device);

            // Update the route information
            IPhoneLocation iPhoneLocation = getLocation(object);

            if (iPhoneLocation != null) {
                iPhoneRouteList.get(device).addLocation(iPhoneLocation);
            }
        } catch (ClientProtocolException ex) {
            logger.log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        logger.log(Level.WARNING, "Device {0} is out of range ({1} max)",
                new Object[] { (device + 1), numDevices });
        return false;
    }

    return true;
}

From source file:de.fhg.fokus.odp.portal.datasets.searchresults.BrowseDataSetsSearchResults.java

/**
 * This method reverses a JSONArray.//from   w  ww.  jav a2s  .co m
 * 
 * @param comments
 *            the JSONArray to be reversed
 * @return the reversed JSONArray
 */
private JSONArray reverseJSONArray(JSONArray comments) {
    JSONArray toReturn = new JSONArray();
    for (int i = comments.size() - 1; i >= 0; i--) {
        toReturn.add(comments.get(i));
    }
    return toReturn;
}