Example usage for org.json.simple JSONArray isEmpty

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

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this list contains no elements.

Usage

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 w  ww. j a v a  2 s  .  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.skelril.aurora.authentication.AuthComponent.java

public synchronized JSONArray getFrom(String subAddress) {

    JSONArray objective = new JSONArray();
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {//from   www  .  j a  v  a2 s . co  m
        JSONParser parser = new JSONParser();
        for (int i = 1; true; i++) {

            try {
                // Establish the connection
                URL url = new URL(config.websiteUrl + subAddress + "?page=" + i);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(1500);
                connection.setReadTimeout(1500);

                // Check response codes return if invalid
                if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300)
                    return null;

                // Begin to read results
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                // Parse Data
                JSONObject o = (JSONObject) parser.parse(builder.toString());
                JSONArray ao = (JSONArray) o.get("characters");
                if (ao.isEmpty())
                    break;
                Collections.addAll(objective, (JSONObject[]) ao.toArray(new JSONObject[ao.size()]));
            } catch (ParseException e) {
                break;
            } finally {
                if (connection != null)
                    connection.disconnect();

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    } catch (IOException e) {
        return null;
    }

    return objective;
}

From source file:com.versul.main.MainClass.java

private ComponentBuilder<?, ?> createSumComponent(String label) throws IOException {
    if (aggregations != null && aggregations.containsKey("sum")) {

        JSONArray sumArray = (JSONArray) aggregations.get("sum");

        if (sumArray != null && !sumArray.isEmpty()) {

            String key, value;/*  w w  w  .j  a va2 s.c  o  m*/

            VerticalListBuilder listSuper = cmp.verticalList();

            for (Object sumObject : sumArray) {

                HorizontalListBuilder cardComponent = createCardComponent();

                JSONObject sumField = (JSONObject) sumObject;

                key = (String) sumField.keySet().toArray()[0];
                log("key " + key);

                value = String.valueOf(sumField.get(key));
                log("value " + sumField.get(key));

                VerticalListBuilder content = cmp.verticalList();

                HorizontalListBuilder labelSum = cmp.horizontalList();
                labelSum.add(cmp.text("<b>" + key + "</b> : " + value).setStyle(getStyleMarkedUp()));
                content.add(labelSum);
                //                    content.setFixedWidth(150);

                cardComponent.add(content);

                listSuper.add(cardComponent);
            }

            return cmp.verticalList(cmp.text(label).setStyle(templateDefault.boldStyle), listSuper);
        }
    }
    return null;
}

From source file:com.versul.main.MainClass.java

private ComponentBuilder<?, ?> createGroupsComponent(String label) throws IOException {
    if (aggregations != null && aggregations.containsKey("group")) {

        JSONArray groups = (JSONArray) aggregations.get("group");

        if (groups != null && !groups.isEmpty()) {
            VerticalListBuilder listSuper = cmp.verticalList();

            String key;/*  ww  w  .  j  a  v  a 2  s .  co m*/
            JSONArray group;

            for (Object groupObj : groups) {
                HorizontalListBuilder cardComponent = createCardComponent();
                // Aggregation object
                JSONObject groupField = (JSONObject) groupObj;
                key = (String) groupField.keySet().toArray()[0];
                group = (JSONArray) groupField.get(key);

                VerticalListBuilder content = cmp.verticalList();
                content.add(cmp.text(key));

                for (Object segmentObj : group) {
                    String groupText = "";

                    JSONObject segment = (JSONObject) segmentObj;
                    Object[] segmentKeys = segment.keySet().toArray();
                    for (Object statisticKey : segmentKeys) {
                        groupText += "    " + statisticKey.toString() + ": ";
                        JSONObject statistics = (JSONObject) segment.get(statisticKey);
                        Object[] statisticKeys = statistics.keySet().toArray();

                        String totalKey = statisticKeys[0].toString();
                        String totalObject = statistics.get(totalKey).toString();

                        groupText += "<b>(" + totalKey + "</b> : " + totalObject;

                        if (statisticKeys.length > 1) {
                            groupText += " | ";
                            String amountKey = statisticKeys[1].toString();
                            String amountObject = statistics.get(amountKey).toString();
                            groupText += "<b>" + amountKey + "</b> : " + amountObject;
                        }
                        groupText += ")";

                        content.add(cmp.text(groupText).setStyle(getStyleMarkedUp()));
                    }
                }

                cardComponent.add(content);
                listSuper.add(cardComponent);
            }

            return cmp.verticalList(cmp.text(label).setStyle(templateDefault.boldStyle), listSuper);
        }
    }
    return null;
}

From source file:carolina.pegaLatLong.LatLong.java

private void buscaLtLong(List<InformacoesTxt> lista) throws MalformedURLException, IOException, ParseException {
    String status = "Processando...";
    edtEncontrados.setText("Encontrados:");
    edtNaoEncontrados.setText("No encontrados:");
    edtMaisDeUm.setText("Mais de um encontrados:");
    edtProcessados.setText("Processados:");
    edtStatus.setText(status);/*from  www.  j  ava 2s .  c  o  m*/
    int processados = 1;

    URL ul;

    for (InformacoesTxt in : lista) {
        if (processados == 2499) {
            break;
        }
        edtProcessados.setText("Processados: " + processados);
        String resto = "";
        String vet[] = in.getEndereco().split(" ");

        for (String vet1 : vet) {
            resto += vet1 + "+";
        }

        //            String vet2[] = in.getBairro().split(" ");
        //            for (String vet21 : vet2) {
        //                resto += vet21 + "+";
        //            }
        //
        //            String vet3[] = in.getCep().split(" ");
        //            for (String vet31 : vet3) {
        //                resto += vet31 + "+";
        //            }
        String vet4[] = in.getCidade().split(" ");
        for (String vet41 : vet4) {
            resto += vet41 + "+";
        }

        ul = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + resto
                + "&key=AIzaSyDFg9GJIbgHKbZP3b5H2qRV_cAhhvlBaoE");
        //System.err.println("URL: " + ul);
        HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
        // conn.setRequestMethod("GET");
        //conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            listaBadRequest.add(in);
            System.err.println("Codigo: " + conn.getResponseMessage());
            //System.err.println("URL: " + ul);
            //JOptionPane.showMessageDialog(null, "Falha ao obter a localizao!");
            //break;
        } else {
            BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String pega = "";
            String result = "";
            while ((pega = bf.readLine()) != null) {
                result += pega;
            }
            System.err.println(result);

            org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
            Object obj = parser.parse(result);

            JSONObject tudo = (JSONObject) obj;

            JSONArray arrayResultado = (JSONArray) tudo.get("results");
            if (arrayResultado.isEmpty()) {
                listaNaoEncontrados.add(in);
                edtNaoEncontrados.setText("No encontrados: " + listaNaoEncontrados.size());
            } else if (arrayResultado.size() == 1) {
                JSONObject primeiro = (JSONObject) arrayResultado.get(0);
                JSONObject jsonObject3 = (JSONObject) primeiro.get("geometry");
                JSONObject location = (JSONObject) jsonObject3.get("location");
                InformacaoGerada gerado = new InformacaoGerada();
                gerado.setEnderecoFormatado(primeiro.get("formatted_address").toString());
                String latitude = location.get("lat").toString().replace(".", ",");
                gerado.setLatitude(latitude);
                String longitude = location.get("lng").toString().replace(".", ",");
                gerado.setLongitude(longitude);
                listaResultado.add(gerado);
                edtEncontrados.setText("Encontrados: " + listaResultado.size());
            } else {
                listaMaisDeUm.add(in);
                edtMaisDeUm.setText("Mais de um encontrados: " + listaMaisDeUm.size());
            }

            //                System.err.println("Endereo Formatado: " + primeiro.get("formatted_address"));
            //                System.out.println("Lat = " + location.get("lat"));
            //                System.out.println("Lng = " + location.get("lng"));
        }

        processados++;
    }

    edtStatus.setForeground(Color.GREEN);
    edtStatus.setText("Concludo");
    btnGerar.setEnabled(true);

}

From source file:com.skelril.aurora.authentication.AuthComponent.java

@Override
public synchronized void run() {

    JSONArray charactersL = getFrom("characters.json");

    log.info("Testing the connection to " + config.websiteUrl + "...");
    if (charactersL != null) {
        log.info("Connection test successful.");
        if (!charactersL.isEmpty()) {
            updateWhiteList(charactersL);
        } else {//w  w w. j a va  2s  . co m
            log.warning("No characters could be downloaded!");
            log.info("Your website could be under maintenance or contain no characters.");
        }
    } else {
        log.warning("Connection test failed!");
    }

    if (characters.isEmpty()) {
        log.info("Attempting to load offline files...");
        loadBackupWhiteList();
    }

    log.info(characters.size() + " characters have been loaded.");
}

From source file:com.strategicgains.docussandra.controller.IndexControllerTest.java

/**
 * Tests that the POST /{databases}/{setTable}/indexes/ endpoint properly
 * creates a index and that the GET/{database}/{setTable}/index_status/
 * endpoint is working.//from  ww w.j a  v a2  s. c om
 */
@Test
public void postIndexAndCheckStatusAllTest() throws Exception {
    String restAssuredBasePath = RestAssured.basePath;
    try {
        //data insert
        Database testDb = Fixtures.createTestPlayersDatabase();
        Table testTable = Fixtures.createTestPlayersTable();
        f.insertDatabase(testDb);
        f.insertTable(testTable);
        List<Document> docs = Fixtures.getBulkDocuments("./src/test/resources/players-short.json", testTable);
        f.insertDocuments(docs);//put in a ton of data directly into the db
        Index lastname = Fixtures.createTestPlayersIndexLastName();
        String indexString = "{" + "\"fields\" : [\"" + lastname.getFieldsValues().get(0) + "\"],"
                + "\"name\" : \"" + lastname.getName() + "\"}";
        RestAssured.basePath = "/" + lastname.getDatabaseName() + "/" + lastname.getTableName() + "/indexes";
        //act -- create index
        given().body(indexString).expect().statusCode(201).body("index.name", equalTo(lastname.getName()))
                .body("index.fields", notNullValue()).body("index.createdAt", notNullValue())
                .body("index.updatedAt", notNullValue()).body("index.active", equalTo(false))//should not yet be active
                .body("id", notNullValue()).body("dateStarted", notNullValue())
                .body("statusLastUpdatedAt", notNullValue()).body("eta", notNullValue())
                .body("precentComplete", notNullValue()).body("totalRecords", equalTo(3308))
                .body("recordsCompleted", equalTo(0)).when().log().ifValidationFails()
                .post("/" + lastname.getName());

        //start a timer
        StopWatch sw = new StopWatch();
        sw.start();

        RestAssured.basePath = "/index_status/";

        //check to make sure it shows as present at least once
        ResponseOptions res = expect().statusCode(200)
                .body("_embedded.indexcreatedevents[0].id", notNullValue())
                .body("_embedded.indexcreatedevents[0].dateStarted", notNullValue())
                .body("_embedded.indexcreatedevents[0].statusLastUpdatedAt", notNullValue())
                .body("_embedded.indexcreatedevents[0].eta", notNullValue())
                .body("_embedded.indexcreatedevents[0].index", notNullValue())
                .body("_embedded.indexcreatedevents[0].index.active", equalTo(false))//should not yet be active
                .body("_embedded.indexcreatedevents[0].totalRecords", notNullValue())
                .body("_embedded.indexcreatedevents[0].recordsCompleted", notNullValue())
                .body("_embedded.indexcreatedevents[0].precentComplete", notNullValue()).when().log()
                .ifValidationFails().get("/").andReturn();
        LOGGER.debug("Status Response: " + res.getBody().prettyPrint());
        //wait for it to dissapear (meaning it's gone active)
        boolean active = false;
        while (!active) {
            res = expect().statusCode(200).when().get("/").andReturn();
            String body = res.getBody().prettyPrint();
            LOGGER.debug("Status Response: " + body);

            JSONObject bodyObject = (JSONObject) parser.parse(body);
            JSONObject embedded = (JSONObject) bodyObject.get("_embedded");
            JSONArray resultSet = (JSONArray) embedded.get("indexcreatedevents");
            if (resultSet.isEmpty()) {
                active = true;
                sw.stop();
                break;
            }
            LOGGER.debug("Waiting for index to go active for: " + sw.getTime());
            if (sw.getTime() >= 60000) {
                fail("Index took too long to create");
            }
            Thread.sleep(2000);
        }
        LOGGER.info("It took: " + (sw.getTime() / 1000) + " seconds to create the index.");

    } finally {
        RestAssured.basePath = restAssuredBasePath;
    }
}

From source file:com.anto89.processor.ProcessorManager.java

public boolean run(String urlString) {

    JSONArray json = null;
    try {//  ww w .  ja v  a2 s. c om
        URL url = new URL(urlString);
        String jsonResult = IOUtils.toString(url);
        json = (JSONArray) JSONValue.parseWithException(jsonResult);

    } catch (MalformedURLException ex) {
        Logger.getLogger(ProcessorManager.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException | ParseException ex) {
        Logger.getLogger(ProcessorManager.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

    // data valid only
    if (json == null || json.isEmpty()) {
        return false;
    }

    // setup result
    result.put("url_data", urlString);
    result.put("process_time", new Date());
    for (Processor p : list) {
        p.setReturnJson(result);
    }

    // main processing
    for (int i = 0; i < json.size(); i++) {
        JSONObject data = (JSONObject) json.get(i);
        for (Processor p : list) {
            p.run(data);
        }
    }

    // return result
    for (Processor p : list) {
        p.getReturnJson();
    }
    return true;
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to get the specified 0th property from the response array of
 * a previous REST call//  ww  w.  ja  v  a2s.  co  m
 *
 * @param property
 * @return the value if it's found (else it'll be null)
 * @throws ParseException
 */
public String getFirstPropertyFromResponseArray(@NonNull String property) throws ParseException {
    final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
    if (jsonArray != null && !jsonArray.isEmpty())
        return JSONHelper.getValue((JSONObject) jsonArray.get(0), property);
    return null;
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to get an item randomly from the response array of a previous REST
 * call/*from   w w w .j  a  va2  s  .co m*/
 *
 * @return the value if it's found (else it'll be null)
 * @throws ParseException
 */
public String getRandomlyAnItemFromResponseArray() throws ParseException {
    final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
    if (jsonArray != null && !jsonArray.isEmpty())
        return (String) jsonArray.get(new Random().nextInt(jsonArray.size()));
    return null;
}