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

public void setClassData(String data) {
    try {//from  w w w  . j a  va  2s  . c  o  m
        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:net.nexxus.nntp.NntpArticleHeader.java

public void setPartsFromJSON(String json) {
    if (json == null || json.isEmpty()) {
        return;/*from  w  ww .  j a  v  a2  s . c  o  m*/
    }

    JSONParser parser = new JSONParser();
    try {
        Object o = parser.parse(json);
        JSONArray array = (JSONArray) o;

        this.parts = new NntpArticlePartID[totalParts];

        Iterator iter = array.iterator();
        int x = 0;
        while (iter.hasNext()) {
            JSONArray part = (JSONArray) iter.next();
            long partID = ((Long) part.get(0)).longValue();
            String partMsgID = (String) part.get(1);
            NntpArticlePartID articlePart = new NntpArticlePartID(partID, partMsgID);
            this.parts[x++] = articlePart;
        }
        this.multipart = true;
    } catch (Exception e) {
        log.error("failed setting parts from JSON: " + e.getMessage());
        log.debug("ID: " + this.id);
    }
}

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.
 * /* w  w w .java  2s . com*/
 * @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:edu.ncsu.epc.models.Yelp.java

public ArrayList<YelpInfo> getYelpItems(String response) {
    // Update tokens here from Yelp developers site, Manage API access.
    int i = 0;//  w w  w  .j a  v  a 2s . com
    ArrayList<YelpInfo> list = new ArrayList<YelpInfo>();
    YelpInfo yelpInfo;

    //System.out.println(response);
    try {
        JSONObject json = (JSONObject) new JSONParser().parse(response);
        JSONArray jsonArray = (JSONArray) new JSONParser().parse(json.get("businesses").toString());
        //System.out.println(json.keySet());
        //JSONObject json1 = (JSONObject) new JSONParser().parse(jsonArray.get(3).toString());
        //System.out.println(json1.keySet());

        while (i < jsonArray.size()) {
            yelpInfo = new YelpInfo();
            JSONObject json1 = (JSONObject) new JSONParser().parse(jsonArray.get(i).toString());
            i++;
            yelpInfo.rating = Double.parseDouble(json1.get("rating").toString());
            JSONObject json2 = (JSONObject) new JSONParser().parse(json1.get("location").toString());
            JSONArray jsonArray2 = (JSONArray) new JSONParser().parse(json2.get("address").toString());
            if (jsonArray2.size() == 0)
                continue;
            yelpInfo.address = jsonArray2.get(0).toString();
            //            if(yelpInfo.address.length()==2) continue;
            //            yelpInfo.address = yelpInfo.address.substring(1, yelpInfo.address.length()-1);
            //            yelpInfo.address = yelpInfo.address.substring(1, yelpInfo.address.length()-1);
            yelpInfo.address += "," + json2.get("city") + "," + json2.get("state_code");
            list.add(yelpInfo);

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

    return list;
    //        Iterator<String> iterator = jsonArray.iterator();
    //        while (iterator.hasNext()) {
    //            String str = (String)iterator.next();
    //            System.out.println(str);
    //            JSONObject json1 = (JSONObject) new JSONParser().parse(iterator.next().toString());
    //            System.out.println(json1.keySet());
    //        }

}

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

public void setRiderInfo(String data) {
    try {//from w  w  w. jav a 2  s .  com
        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.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_when_tags_are_wrong() throws Exception {
    // GIVEN//from ww w  . ja va2 s . c  o  m
    String parserFilePath = "./all-mappings-docs.json";
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(0);
        Assert.assertEquals(obj.get("wrongtag"), null);
        Assert.assertEquals(obj.get("@wrongtag"), null);
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:com.yottaa.newrelic.PostJob.java

/**
 *
 *///from   w ww.j  a  v a  2  s . co 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:com.alvexcore.repo.documents.generation.ExportDataListToXlsx.java

protected Workbook createXlsx(JSONArray rows, String XLS_SHEET_NAME) {

    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet(XLS_SHEET_NAME);

    for (int k = 0; k < rows.size(); k++) {
        Row row = sheet.createRow((short) k);
        JSONArray cells = (JSONArray) rows.get(k);
        for (int c = 0; c < cells.size(); c++) {
            String displayValue;//from  w w  w .  j a  v  a2  s . c o m
            Object item = cells.get(c);
            if (item == null)
                displayValue = I18NUtil.getMessage("label.empty");
            else if (item instanceof Boolean)
                displayValue = (Boolean) item ? I18NUtil.getMessage("label.yes")
                        : I18NUtil.getMessage("label.no");
            else
                displayValue = item.toString();
            row.createCell(c).setCellValue(createHelper.createRichTextString(displayValue));
        }
    }

    return wb;
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_whether_json_file_will_generate_unsupported_tags() throws IOException, ParseException {
    // GIVEN//from w  w  w  .  j  av  a2 s  .  co  m
    String parserFilePath = "./all-mappings-docs.json";
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(0);
        JSONObject obj1 = (JSONObject) arr.get(1);
        Assert.assertEquals(obj.get("test"), null);
        Assert.assertEquals(obj1.get("test1"), null);
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:jGPIO.DTO.java

public String createFileContents() {
    StringBuilder fileContents = new StringBuilder().append("/*\n")
            .append("* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/\n").append("*\n")
            .append("* This program is free software; you can redistribute it and/or modify\n")
            .append("* it under the terms of the GNU General Public License version 2 as\n")
            .append("* published by the Free Software Foundation.\n")
            .append("* Or something like that, I don't really care too much\n")
            .append("* Created automagically by jgpio, created by Doug Edey\n")
            .append("* github.com/dougedey\n").append("*/\n").append("/dts-v1/;\n").append("/plugin/;\n");

    // work out the values to be put into the file

    fileContents.append("/ {\n").append("\tcompatible = \"ti,beaglebone\", \"ti,beaglebone-black\";\n")
            .append("\tpart-number = \"BB-JGPIO\";\n").append("\tversion = \"00A0\";\n")
            .append("\n\texclusive-use=\n");

    // iterate the list of known GPIOs and add them
    for (int i = 0; i < gpios.size(); i++) {
        JSONObject gpioDetails = (JSONObject) gpios.get(i);

        String exclusive = (String) gpioDetails.get("key");

        if (i == (gpios.size() - 1)) { // are we at the end of the list
                                       // (there has to be an easier way
                                       // using an iterator
            fileContents.append("\t\t\"" + exclusive + "\";\n");
        } else {//from   ww  w .j  av  a 2 s. c o  m
            fileContents.append("\t\t\"" + exclusive + "\",\n");
        }
    }

    fileContents.append("\t\tfragment@0 {\n").append("\t\t\ttarget = <&am33xx_pinmux>;\n")
            .append("\t\t\t__overlay__ {\n").append("\t\t\t\tjgpio_pins: pinmux_jgpio_pins {\n")
            .append("\t\t\t\tpinctrl-single,pins = <\n");

    // iterate the list of known GPIOs and add them
    for (Object o : gpios) {
        JSONObject gpioDetails = (JSONObject) o;

        String exclusive = (String) gpioDetails.get("key");
        String muxRegOffset = (String) gpioDetails.get("muxRegOffset");
        Integer mode = (Integer) gpioDetails.get("UserMode");
        String userSelectedPin = (String) gpioDetails.get("UserSelectedPin");
        // we only need this for digital IO, analog inputs can be activated
        // using the BB-ADC file
        int pinmux = 0x00;

        if (mode == DTO.INPUT) {
            pinmux = 0x30;
        }

        if (mode == DTO.OUTPUT) {
            pinmux = 0x00;
        }

        JSONArray options = (JSONArray) gpioDetails.get("options");
        for (int i = 0; i < options.size(); i++) {
            String option = (String) options.get(i);
            if (option.equalsIgnoreCase(userSelectedPin)) {
                pinmux += i;
            }
        }

        fileContents.append("\t\t\t\t\t" + muxRegOffset + " 0x" + Integer.toHexString(pinmux) + " /* "
                + exclusive + "*/\n");
    }

    fileContents.append("\t\t\t\t>;\n").append("\t\t\t};\n").append("\t\t};\n").append("\t};\n\n");

    // Start the fragment to initialize it all
    fileContents.append("\tfragment@1 {\n").append("\t\ttarget = <&ocp>;\n").append("\t\t__overlay__ {\n")
            .append("\t\t\tstatus          = \"okay\";\n").append("\t\t\tpinctrl-names=\"default\";\n")
            .append("\t\t\tpinctrl-0 = <&jgpio_pins>;\n").append("\t\t};\n").append("\t};\n").append("};\n");

    return fileContents.toString();

}