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.relayrides.pushy.apns.util.ApnsPayloadBuilderTest.java

@SuppressWarnings("unchecked")
@Test/*  www.  ja  v a  2s . c  om*/
public void testSetLocalizedAlertMessage() throws ParseException {
    final String alertKey = "test.alert";
    this.builder.setLocalizedAlertMessage(alertKey, null);

    {
        final JSONObject aps = this
                .extractApsObjectFromPayloadString(this.builder.buildWithDefaultMaximumLength());
        final JSONObject alert = (JSONObject) aps.get("alert");

        assertEquals(alertKey, alert.get("loc-key"));
        assertNull(alert.get("loc-args"));
    }

    final String[] alertArgs = new String[] { "Moose", "helicopter" };
    this.builder.setLocalizedAlertMessage(alertKey, alertArgs);

    {
        final JSONObject aps = this
                .extractApsObjectFromPayloadString(this.builder.buildWithDefaultMaximumLength());
        final JSONObject alert = (JSONObject) aps.get("alert");

        assertEquals(alertKey, alert.get("loc-key"));

        final JSONArray argsArray = (JSONArray) alert.get("loc-args");
        assertEquals(alertArgs.length, argsArray.size());
        assertTrue(argsArray.containsAll(java.util.Arrays.asList(alertArgs)));
    }
}

From source file:com.skelril.ShivtrAuth.AuthenticationCore.java

private synchronized void loadBackupWhiteList() {

    File charactersDirectory = new File(plugin.getDataFolder().getPath() + "/characters");
    File characterFile = new File(charactersDirectory, "character-list.json");
    if (!characterFile.exists()) {
        log.warning("No offline file found!");
        return;/*  www.j  ava 2  s.c o  m*/
    }

    BufferedReader reader = null;
    JSONParser parser = new JSONParser();

    try {
        reader = new BufferedReader(new FileReader(characterFile));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        JSONArray characterArray = ((JSONArray) parser.parse(builder.toString()));
        loadCharacters((JSONObject[]) characterArray.toArray(new JSONObject[characterArray.size()]));
    } catch (IOException e) {
        log.warning("Could not read file: " + characterFile.getName() + ".");
    } catch (ParseException p) {
        log.warning("Could not parse file: " + characterFile.getName() + ".");
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }

    log.info("The offline file has been loaded.");
}

From source file:at.ac.tuwien.dsg.depic.common.utils.RestfulWSClient.java

public String callJcatascopiaAgentIDWS(String agentIP, String uri) {
    String agentID = "";
    try {/*from  ww  w.  ja v  a2 s.com*/

        Client client = Client.create();

        WebResource webResource = client.resource(uri);

        ClientResponse response = webResource

                .accept("application/json").get(ClientResponse.class);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        String output = response.getEntity(String.class);
        System.out.println("\n============getResponse============");
        System.out.println(output);

        JSONObject json = (JSONObject) new JSONParser().parse(output);
        String allMetricsStr = json.get("agents").toString();

        System.out.println(allMetricsStr);

        try {

            JSONArray nameArray = (JSONArray) new JSONParser().parse(allMetricsStr);
            System.out.println(nameArray.size());
            for (Object js : nameArray) {
                JSONObject element = (JSONObject) js;

                if (agentIP.equals(element.get("agentIP"))) {
                    agentID = element.get("agentID").toString();
                }

            }

        } catch (Exception e) {

        }

        System.out.println("FOUND ID: " + agentID);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return agentID;
}

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 ww  .j a  v  a2 s .  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:com.yottaa.newrelic.PostJob.java

/**
 *
 *///from   w  w  w . j a  v a  2s. c  o m
public void postJobMethod() {

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

    logger.info("Posting Yottaa metrics to New Relic @ " + dateFormat.format(System.currentTimeMillis()));

    ResourceBundle bundle = ResourceBundle.getBundle("yottaa");
    YottaaHttpClientPublic yottaaHttpClientPublic = new YottaaHttpClientPublic(
            bundle.getString("yottaaAPIKey"));

    YottaaHttpClientPartner yottaaHttpClientPartner = new YottaaHttpClientPartner(false);

    // Prepare JSON data that will be posted to New Relic
    JSONObject jsonData = new JSONObject();

    JSONObject agentData = new JSONObject();
    agentData.put("host", "apps.yottaa.com");
    agentData.put("pid", 0);
    agentData.put("version", "1.0.0");

    jsonData.put("agent", agentData);

    JSONArray components = new JSONArray();

    JSONArray sites = yottaaHttpClientPartner.getAccountSites(bundle.getString("yottaaUserId"));

    logger.info("Total number of sites is " + sites.size() + ".");

    for (int i = 0, len = sites.size(); i < len; i++) {
        JSONObject siteObj = (JSONObject) sites.get(i);
        String host = (String) siteObj.get("host");

        logger.info("Retrieve last sample for host " + host + "(" + i + " of " + len + ").");

        JSONObject lastSampleMetrics = yottaaHttpClientPublic.getLastSample(host);

        JSONObject yottaaMetricsObj = new JSONObject();
        yottaaMetricsObj.put("guid", "com.yottaa.Yottaa");
        yottaaMetricsObj.put("duration", 60);
        //yottaaMetricsObj.put("name", host);
        yottaaMetricsObj.put("name", (String) lastSampleMetrics.get("name"));

        JSONObject yottaaMetricsData = new JSONObject();

        // Http Metrics
        if (lastSampleMetrics.get("http_metrics") != null) {
            JSONObject httpMetrics = (JSONObject) lastSampleMetrics.get("http_metrics");

            JSONObject httpMetricsFirstByte = (JSONObject) httpMetrics.get("first_byte");
            JSONObject httpMetricsWait = (JSONObject) httpMetrics.get("wait");
            JSONObject httpMetricsDNS = (JSONObject) httpMetrics.get("dns");
            JSONObject httpMetricsConnect = (JSONObject) httpMetrics.get("connect");

            yottaaMetricsData.put("Component/Http Metrics/Time To First Byte[sec]",
                    Double.parseDouble(httpMetricsFirstByte.get("average").toString()));
            yottaaMetricsData.put("Component/Http Metrics/Waiting Time[sec]",
                    Double.parseDouble(httpMetricsWait.get("average").toString()));
            yottaaMetricsData.put("Component/Http Metrics/DNS Time[sec]",
                    Double.parseDouble(httpMetricsDNS.get("average").toString()));
            yottaaMetricsData.put("Component/Http Metrics/Connection Time[sec]",
                    Double.parseDouble(httpMetricsConnect.get("average").toString()));
        }

        // Issue Metrics
        if (lastSampleMetrics.get("issue_metrics") != null) {
            JSONObject issueMetrics = (JSONObject) lastSampleMetrics.get("issue_metrics");

            yottaaMetricsData.put("Component/Issue Metrics/Critical Error Count[times]",
                    Integer.parseInt(issueMetrics.get("critical_error_count").toString()));
            yottaaMetricsData.put("Component/Issue Metrics/Error Count[times]",
                    Integer.parseInt(issueMetrics.get("error_count").toString()));
            yottaaMetricsData.put("Component/Issue Metrics/Info Count[times]",
                    Integer.parseInt(issueMetrics.get("info_count").toString()));
            yottaaMetricsData.put("Component/Issue Metrics/Warning Count[times]",
                    Integer.parseInt(issueMetrics.get("warning_count").toString()));
        }

        //Webpage Metrics
        if (lastSampleMetrics.get("webpage_metrics") != null) {
            JSONObject webpageMetrics = (JSONObject) lastSampleMetrics.get("webpage_metrics");
            JSONObject webpageMetricsTimeToRender = (JSONObject) webpageMetrics.get("time_to_render");
            JSONObject webpageMetricsTimeToDisplay = (JSONObject) webpageMetrics.get("time_to_display");
            JSONObject webpageMetricsTimeToInteract = (JSONObject) webpageMetrics.get("time_to_interact");

            yottaaMetricsData.put("Component/Webpage Metrics/Time To Render[sec]",
                    Double.parseDouble(webpageMetricsTimeToRender.get("average").toString()));
            yottaaMetricsData.put("Component/Webpage Metrics/Time To Display[sec]",
                    Double.parseDouble(webpageMetricsTimeToDisplay.get("average").toString()));
            yottaaMetricsData.put("Component/Webpage Metrics/Time To Interact[sec]",
                    Double.parseDouble(webpageMetricsTimeToInteract.get("average").toString()));
        }
        yottaaMetricsObj.put("metrics", yottaaMetricsData);

        components.add(yottaaMetricsObj);

        logger.info("Finished Retrieve last sample for host " + host + "(" + i + " of " + len + ").");
    }

    jsonData.put("components", components);

    logger.info("Posted Yottaa Metrics :" + jsonData);

    this.newrelicPost(null, bundle.getString("newrelicLicenseKey"), jsonData);

}

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

/**
 * This method iterates over the JSONArray and adds for each dataset an
 * entry in arePackagesOpen and returns this boolean array.
 * /*from   w w  w. j a  v a2  s  .  c o m*/
 * @param array
 *            the {@link JSONArray}
 * @return filled boolean array
 */
private boolean[] createArePackagesOpen(JSONArray array) {

    boolean[] arePackagesOpen = new boolean[array.size()];
    for (int i = 0; i < array.size(); i++) {
        String license_id = (String) ((JSONObject) array.get(i)).get("license_id");
        arePackagesOpen[i] = isLicenseOpen(license_id);
    }
    return arePackagesOpen;
}

From source file:de.tobiyas.racesandclasses.chat.channels.container.ChannelSaveContainer.java

/**
 * Generates the List of Participants from the value saved in the DB.
 * //  w  w  w.j a v a2 s  .co  m
 * @return
 */
public List<String> generateParitipants() {
    try {
        List<String> participants = new LinkedList<String>();
        JSONArray tempObject = (JSONArray) new JSONParser().parse(this.participants);

        //early out for error in reading.
        if (tempObject == null || tempObject.size() == 0)
            return participants;

        for (int i = 0; i < tempObject.size(); i++) {
            participants.add(tempObject.get(i).toString());
        }

        return participants;
    } catch (ParseException e) {
        e.printStackTrace();
        return new LinkedList<String>();
    }
}

From source file:com.respam.comniq.Controller.java

public Task OMDBworker() {
    return new Task() {
        @Override/*from w w  w .j  a  v a 2s.c om*/
        protected Object call() throws Exception {
            OMDBParser op = new OMDBParser();
            JSONParser parser = new JSONParser();
            String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator
                    + "output";
            try {
                Object obj = parser.parse(new FileReader(path + File.separator + "LocalList.json"));
                JSONArray parsedArr = (JSONArray) obj;

                // Loop JSON Array
                for (int i = 0; i < parsedArr.size(); i++) {
                    JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                    String movieName = (String) parsedObj.get("movie");
                    String movieYear = (String) parsedObj.get("year");
                    System.out.println(movieName + "-" + movieYear);
                    op.requestOMDB(movieName, movieYear);
                    updateProgress(i, parsedArr.size() - 1);
                }
                op.movieInfoWriter();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return true;
        }
    };
}

From source file:com.respam.comniq.Controller.java

public Task createExportWorker() {
    return new Task() {
        @Override/*from  ww w  .  j a va2 s.co  m*/
        protected Object call() throws Exception {
            JSONParser parser = new JSONParser();
            String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator
                    + "output";

            try {
                POIexcelExporter export = new POIexcelExporter();
                Object obj = parser.parse(new FileReader(path + File.separator + "MovieInfo.json"));
                JSONArray parsedArr = (JSONArray) obj;

                // Loop JSON Array
                for (int i = 0; i < parsedArr.size(); i++) {
                    JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                    if (null != parsedObj.get("Title")) {
                        export.excelWriter(parsedObj, i);
                        System.out.println("Done with " + "\"" + parsedObj.get("Title") + "\"");
                    }
                    updateProgress(i, parsedArr.size() - 1);
                }
                //                    export.addImages(parsedArr);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return true;
        }
    };
}

From source file:edu.sjsu.cohort6.esp.service.rest.CourseResource.java

@Override
@PUT/*ww  w  .j  ava2  s  .c  o m*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{id}")
public Course update(@Auth User user, @PathParam("id") String id, @Valid String courseJson)
        throws ResourceNotFoundException, InternalErrorException, IOException {
    try {
        if (isAdminUser(user)) {
            Course course = null;
            List<Course> courseList = courseDAO.fetchById(getListFromEntityId(id));
            if (courseList != null && !courseList.isEmpty()) {
                course = courseList.get(0);
            }
            if (course == null) {
                throw new ResourceNotFoundException();
            }
            // Parse JSON payload and update the fields that are updated.
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(courseJson);

            String val = (String) json.get("courseName");
            if (val != null) {
                course.setCourseName(val);
            }
            JSONArray arr = (JSONArray) json.get("instructors");
            if (arr != null) {
                course.setInstructors(arr.subList(0, arr.size()));
            }
            val = (String) json.get("startTime");
            if (val != null) {
                course.setStartTime(CommonUtils.getDateFromString(val));
            }
            val = (String) json.get("endTime");
            if (val != null) {
                course.setEndTime(CommonUtils.getDateFromString(val));
            }
            val = json.get("availabilityStatus").toString();
            if (val != null) {
                course.setAvailabilityStatus(Integer.parseInt(val));
            }
            val = (String) json.get("maxCapacity").toString();
            if (val != null) {
                course.setMaxCapacity(Integer.parseInt(val));
            }
            val = (String) json.get("price").toString();
            if (val != null) {
                course.setPrice(Double.parseDouble(val));
            }
            val = (String) json.get("location");
            if (val != null) {
                course.setLocation(val);
            }
            arr = (JSONArray) json.get("keywords");
            if (arr != null) {
                course.setKeywords(arr.subList(0, arr.size()));
            }

            courseDAO.update(getListFromEntity(course));
            return course;
        } else {
            throw new AuthorizationException(
                    "User " + user.getUserName() + " is not allowed to perform this operation");
        }
    } catch (Exception e) {
        throw new InternalErrorException(e);
    }
}