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:eumetsat.pn.solr.SolrFeeder.java

private SolrInputDocument createInputDoc(JSONObject jsObj) {
    SolrInputDocument input = new SolrInputDocument();
    // field values should match schema.xml

    // solr can add new fields on the fly: http://heliosearch.org/solr/getting-started/
    String id = (String) jsObj.get(FILE_IDENTIFIER_PROPERTY);
    input.addField("id", id);

    JSONObject info = (JSONObject) jsObj.get("identificationInfo");
    input.addField("title", info.get("title"));
    input.addField("description", info.get("abstract"));
    if (!info.get("thumbnail").toString().isEmpty()) {
        input.addField("thumbnail_s", info.get("thumbnail"));
    }//from   w ww. j  a  va  2s. co  m

    JSONArray keywords = (JSONArray) info.get("keywords");
    if (!keywords.isEmpty()) {
        input.addField("keywords", keywords.toArray());
    }

    if (!info.get("status").toString().isEmpty()) {
        input.addField("status_s", info.get("status"));
    }

    JSONObject hierarchy = (JSONObject) jsObj.get("hierarchyNames");

    //public static final ImmutableMap<String, String> FACETS2HIERACHYNAMES = ImmutableMap.of("satellites", "hierarchyNames.satellite",
    //"instruments", "hierarchyNames.instrument",
    //"categories", "hierarchyNames.category",
    //"societalBenefitArea", "hierarchyNames.societalBenefitArea",
    //"distribution", "hierarchyNames.distribution");
    if (hierarchy.get("satellite") != null && !hierarchy.get("satellite").toString().isEmpty()) {
        input.addField("satellite_s", hierarchy.get("satellite"));
    }

    if (hierarchy.get("instrument") != null && !hierarchy.get("instrument").toString().isEmpty()) {
        input.addField("instrument_s", hierarchy.get("instrument"));
    }

    JSONArray categories = (JSONArray) hierarchy.get("category");
    if (categories != null && !categories.isEmpty()) {
        input.addField("category", categories);
    }

    JSONArray sbas = (JSONArray) hierarchy.get("societalBenefitArea");
    if (sbas != null && !sbas.isEmpty()) {
        input.addField("societalBenefitArea_ss", sbas);
    }

    Collection<String> distrs = (Collection<String>) hierarchy.get("distribution");
    if (distrs != null && !distrs.isEmpty()) {
        input.addField("distribution_ss", distrs);
    }

    // https://cwiki.apache.org/confluence/display/solr/Spatial+Search
    JSONObject location = (JSONObject) jsObj.get("location");
    String type = (String) location.get("type");
    if ("envelope".equals(type)) {
        StringBuilder envelope = new StringBuilder();
        // ISO2JSON: envelope.add(leftTopPt); envelope.add(rightDownPt);
        JSONArray coords = (JSONArray) location.get("coordinates");
        JSONArray leftTopPoint = (JSONArray) coords.get(0);
        JSONArray rightDownPoint = (JSONArray) coords.get(1);

        // Spatial search envelope: minX, maxX, maxY, minY
        envelope.append("ENVELOPE(").append(leftTopPoint.get(0)).append(", ");
        envelope.append(rightDownPoint.get(0)).append(", ");
        envelope.append(leftTopPoint.get(1)).append(", ");
        envelope.append(rightDownPoint.get(1)).append(")");
        input.addField("boundingbox", envelope.toString());
    } else {
        log.warn("Unsupported location field value: {}", location.toJSONString());
    }

    JSONObject contact = (JSONObject) jsObj.get("contact");
    input.addField("email_s", contact.get("email"));
    input.addField("address_s", contact.get("address"));

    input.addField("xmldoc", jsObj.get("xmldoc"));

    return input;
}

From source file:com.opensoc.parsing.parsers.BasicBroParser.java

@SuppressWarnings("unchecked")
public JSONObject parse(byte[] msg) {

    _LOG.trace("[OpenSOC] Starting to parse incoming message");

    String raw_message = null;/*from  w  w w  .j a v a 2  s .  com*/

    try {

        raw_message = new String(msg, "UTF-8");
        _LOG.trace("[OpenSOC] Received message: " + raw_message);

        JSONObject cleaned_message = cleaner.Clean(raw_message);
        _LOG.debug("[OpenSOC] Cleaned message: " + raw_message);

        if (cleaned_message == null || cleaned_message.isEmpty())
            throw new Exception("Unable to clean message: " + raw_message);

        String key = cleaned_message.keySet().iterator().next().toString();

        if (key == null)
            throw new Exception("Unable to retrieve key for message: " + raw_message);

        JSONObject payload = (JSONObject) cleaned_message.get(key);

        String originalString = " |";
        for (Object k : payload.keySet()) {
            originalString = originalString + " " + k.toString() + ":" + payload.get(k).toString();
        }
        originalString = key.toUpperCase() + originalString;
        payload.put("original_string", originalString);

        if (payload == null)
            throw new Exception("Unable to retrieve payload for message: " + raw_message);

        if (payload.containsKey("ts")) {
            String ts = payload.remove("ts").toString();
            payload.put("timestamp", ts);
            _LOG.trace("[OpenSOC] Added ts to: " + payload);
        }

        if (payload.containsKey("id.orig_h")) {
            String source_ip = payload.remove("id.orig_h").toString();
            payload.put("ip_src_addr", source_ip);
            _LOG.trace("[OpenSOC] Added ip_src_addr to: " + payload);
        } else if (payload.containsKey("tx_hosts")) {
            JSONArray txHosts = (JSONArray) payload.remove("tx_hosts");
            if (txHosts != null && !txHosts.isEmpty()) {
                payload.put("ip_src_addr", txHosts.get(0));
                _LOG.trace("[OpenSOC] Added ip_src_addr to: " + payload);
            }
        }

        if (payload.containsKey("id.resp_h")) {
            String source_ip = payload.remove("id.resp_h").toString();
            payload.put("ip_dst_addr", source_ip);
            _LOG.trace("[OpenSOC] Added ip_dst_addr to: " + payload);
        } else if (payload.containsKey("rx_hosts")) {
            JSONArray rxHosts = (JSONArray) payload.remove("rx_hosts");
            if (rxHosts != null && !rxHosts.isEmpty()) {
                payload.put("ip_dst_addr", rxHosts.get(0));
                _LOG.trace("[OpenSOC] Added ip_dst_addr to: " + payload);
            }
        }

        if (payload.containsKey("id.orig_p")) {
            String source_port = payload.remove("id.orig_p").toString();
            payload.put("ip_src_port", source_port);
            _LOG.trace("[OpenSOC] Added ip_src_port to: " + payload);
        }
        if (payload.containsKey("id.resp_p")) {
            String dest_port = payload.remove("id.resp_p").toString();
            payload.put("ip_dst_port", dest_port);
            _LOG.trace("[OpenSOC] Added ip_dst_port to: " + payload);
        }

        //         if (payload.containsKey("host")) {
        //
        //            String host = payload.get("host").toString().trim();
        //            String tld = tldex.extractTLD(host);
        //
        //            payload.put("tld", tld);
        //            _LOG.trace("[OpenSOC] Added tld to: " + payload);
        //
        //         }
        //         if (payload.containsKey("query")) {
        //            String host = payload.get("query").toString();
        //            String[] parts = host.split("\\.");
        //            int length = parts.length;
        //            if (length >= 2) {
        //               payload.put("tld", parts[length - 2] + "."
        //                     + parts[length - 1]);
        //               _LOG.trace("[OpenSOC] Added tld to: " + payload);
        //            }
        //         }

        _LOG.trace("[OpenSOC] Inner message: " + payload);

        payload.put("protocol", key);
        _LOG.debug("[OpenSOC] Returning parsed message: " + payload);

        return payload;

    } catch (Exception e) {

        _LOG.error("Unable to Parse Message: " + raw_message);
        e.printStackTrace();
        return null;
    }

}

From source file:com.p000ison.dev.simpleclans2.updater.jenkins.JenkinsBuild.java

@Override
public void fetchInformation() throws IOException {
    URL buildAPIURL = new URL("http", JENKINS_HOST, 80, "/job/" + job + "/" + updateType + "/" + API_FILE);

    URLConnection connection = buildAPIURL.openConnection();
    Reader reader = new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8"));

    JSONObject content = parseJSON(reader);

    this.buildNumber = content.get("number").hashCode();
    this.started = (Long) content.get("timestamp");
    this.duration = (Long) content.get("duration");

    try {/* w w w. jav a 2s .  com*/
        JSONArray artifactsInfo = (JSONArray) content.get("artifacts");
        if (artifactsInfo == null || artifactsInfo.isEmpty()) {
            return;
        }

        final String artifactURL = content.get("url").toString().substring(httpLength + JENKINS_HOST.length())
                + "artifact/";

        for (Object rawArtifact : artifactsInfo) {
            JSONObject artifactInfo = (JSONObject) rawArtifact;
            String path = (String) artifactInfo.get("relativePath");

            for (JenkinsArtifact artifact : artifacts) {
                if (path.contains(artifact.getName())) {
                    artifact.setURL(new URL("http", JENKINS_HOST, 80, artifactURL + path));
                }
            }
        }

        JSONObject changes = (JSONObject) content.get("changeSet");
        JSONArray items = (JSONArray) changes.get("items");
        if (!items.isEmpty()) {
            JSONObject buildInfo = (JSONObject) items.get(0);

            this.commitId = buildInfo.get("commitId").toString();
            this.pusher = ((JSONObject) buildInfo.get("author")).get("fullName").toString();
            this.comment = buildInfo.get("msg").toString();

            for (Object element : (JSONArray) buildInfo.get("paths")) {
                JSONObject entry = (JSONObject) element;

                if (entry.get("editType").equals("edit")) {
                    modifiedFiles.add(entry.get("file").toString());
                } else if (entry.get("editType").equals("delete")) {
                    deletedFiles.add(entry.get("file").toString());
                } else if (entry.get("editType").equals("add")) {
                    createdFiles.add(entry.get("file").toString());
                }
            }
        }
    } catch (ClassCastException e) {
        Logging.debug(e, true, "The format of the api changed! Could not fetch the cause!");
    }
}

From source file:graphvk.Search.java

/**
*    user/*from www.  ja va 2  s . com*/
* @param string userId
*      ?
* @param string params
*    ?   
*/
public void getUserFriend(String userId, String params) throws IOException {
    String resultFriendJson = null;
    String strFriend = urlApi + methodFriendsGet + "user_id=" + userId + params;
    URL urlFriend = new URL(strFriend);
    try (BufferedReader readerOne = new BufferedReader(new InputStreamReader(urlFriend.openStream()))) {
        resultFriendJson = readerOne.readLine();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
    //?  Json
    JSONParser parser = new JSONParser();
    try {
        Object objF = parser.parse(resultFriendJson);
        JSONObject jsonFriendObject = (JSONObject) objF;
        JSONArray listResultF = (JSONArray) jsonFriendObject.get("response");
        if (listResultF == null) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            getUserFriend(userId, params);
        }
        JSONObject jsonFriendObj;
        String f; //  users
        FileWriter fo = new FileWriter(pathOne, true);
        try {
            Integer countFriends = 0;
            Boolean flagZapis = false;
            for (int i = 0; i < listResultF.size(); i++) {
                flagZapis = false;
                jsonFriendObj = (JSONObject) listResultF.get(i);
                for (Map.Entry<String, String> item : fieldsZaprosa.entrySet()) {
                    f = "" + jsonFriendObj.get(item.getKey());
                    if (item.getKey().equals("universities")) {
                        if (!f.equals("null")) {
                            JSONArray arrUniversiti = (JSONArray) jsonFriendObj.get("universities");
                            if (!arrUniversiti.isEmpty()) {
                                JSONObject jsonUniverObj;
                                for (int j = 0; j < arrUniversiti.size(); j++) {
                                    jsonUniverObj = (JSONObject) arrUniversiti.get(j);
                                    String idUniver;
                                    idUniver = "" + jsonUniverObj.get("id");
                                    if (!idUniver.equals(item.getValue())) { // ?  ,  ? ??
                                        flagZapis = true;
                                    } else {
                                        flagZapis = false;
                                        break;
                                    }
                                }
                            } else {
                                flagZapis = true;
                            }
                        } else {
                            flagZapis = true;
                            break;
                        }
                        continue;
                    }
                    if (flagZapis == true) {
                        break;
                    }
                    if (!f.equals(item.getValue())) {
                        flagZapis = true;
                        break;
                    }
                }
                if (flagZapis == false) {
                    countFriends++;
                    fo.write(userId + ";" + jsonFriendObj.get("uid") + "\r\n");
                    checkAndAddUser("" + jsonFriendObj.get("uid"));
                }
            }
            if (countFriends == 0) {
                fo.write(userId + "\r\n");
            }
        } catch (IOException ex) {
            // handle exception
        } finally { //  ?? ?  finally   ?   try-catch 
            try {
                fo.flush();
                fo.close();
            } catch (IOException ex) {
            }
        }
    } catch (Exception e) {
        System.out.println(userId + " ");
    }
}

From source file:ca.fastenalcompany.servlet.ProductServlet.java

/**
 * Provides GET /products and GET /products?id={id}
 *
 * @param request servlet request/*from  w w  w  .j  a  va2  s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    response.setContentType("application/json");
    Set<String> keySet = request.getParameterMap().keySet();
    String id = request.getParameter("id");
    if (!keySet.contains("id")) {
        response.getWriter().write(query(PropertyManager.getProperty("db_selectAll")).toString());
    } else if (!id.isEmpty()) {
        JSONArray products = query(PropertyManager.getProperty("db_select"), id);
        response.getWriter()
                .write(products.isEmpty() ? new JSONObject().toString() : products.get(0).toString());
    }
}

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

public synchronized JSONArray getFrom(String subAddress) {

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

    try {/*from w  w  w.  j a  v a2  s .c  om*/
        JSONParser parser = new JSONParser();
        for (int i = 1; true; i++) {

            try {
                // Establish the connection
                URL url = new URL(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:is.brendan.WarpMarkers.WarpMarkers.java

protected JSONArray getUpdatesJSON() {
    if (warpInfo == null)
        return null; /* Essentials has been disabled */
    JSONArray result = warpInfo.getUpdates(updateLife);
    if (result.isEmpty()) {
        if (previousUpdateWasEmpty)
            return null;
        previousUpdateWasEmpty = true;/*  w  w  w  . ja v  a  2s .com*/
    } else {
        previousUpdateWasEmpty = false;
    }
    return result;
}

From source file:de.themoep.chestshoptools.ShopInfoCommand.java

public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    if (args.length > 0) {
        return false;
    }//from   w  w w  .j  a v a 2s.  c  o m
    if (!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command can only be run by a player!");
        return true;
    }
    Block lookingAt = ((Player) sender).getTargetBlock((Set<Material>) null, 10);
    if (lookingAt == null) {
        sender.sendMessage(
                ChatColor.RED + "Please look at a shop sign or chest!" + ChatColor.DARK_GRAY + " (0)");
        return true;
    }
    Sign shopSign = null;
    if (lookingAt.getState() instanceof Chest) {
        shopSign = uBlock.getConnectedSign((Chest) lookingAt.getState());
    } else if (lookingAt.getState() instanceof Sign && ChestShopSign.isValid(lookingAt)) {
        shopSign = (Sign) lookingAt.getState();
    }
    if (shopSign == null) {
        sender.sendMessage(
                ChatColor.RED + "Please look at a shop sign or chest!" + ChatColor.DARK_GRAY + " (1)");
        return true;
    }

    String name = shopSign.getLine(ChestShopSign.NAME_LINE);
    String quantity = shopSign.getLine(ChestShopSign.QUANTITY_LINE);
    String prices = shopSign.getLine(ChestShopSign.PRICE_LINE);
    String material = shopSign.getLine(ChestShopSign.ITEM_LINE);

    String ownerName = NameManager.getFullNameFor(NameManager.getUUIDFor(name));
    ItemStack item = MaterialUtil.getItem(material);

    if (item == null || !NumberUtil.isInteger(quantity)) {
        sender.sendMessage(Messages.prefix(Messages.INVALID_SHOP_DETECTED));
        return true;
    }

    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Besitzer: " + ChatColor.WHITE + ownerName));
    if (plugin.getShowItem() == null) {
        sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Item: " + ChatColor.WHITE + material));
    } else {
        String itemJson = plugin.getShowItem().getItemConverter().itemToJson(item, Level.FINE);

        String icon = "";
        if (plugin.getShowItem().useIconRp()) {
            icon = plugin.getShowItem().getIconRpMap().getIcon(item, true);
        }

        JSONArray textJson = new JSONArray();

        textJson.add(new JSONObject(ImmutableMap.of("text", Messages.prefix(ChatColor.GREEN + "Item: "))));

        JSONObject hoverJson = new JSONObject();
        hoverJson.put("action", "show_item");
        hoverJson.put("value", itemJson);
        ChatColor nameColor = plugin.getShowItem().getItemConverter().getNameColor(item);

        if (plugin.getShowItem().useIconRp()) {
            JSONObject iconJson = new JSONObject();
            iconJson.put("text", icon);
            iconJson.put("hoverEvent", hoverJson);

            textJson.add(iconJson);
        }

        JSONObject typeJson = new JSONObject();
        typeJson.put("translate", plugin.getShowItem().getItemConverter().getTranslationKey(item));
        JSONArray translateWith = new JSONArray();
        translateWith.addAll(plugin.getShowItem().getItemConverter().getTranslateWith(item));
        if (!translateWith.isEmpty()) {
            typeJson.put("with", translateWith);
        }

        typeJson.put("hoverEvent", hoverJson);
        typeJson.put("color", nameColor.name().toLowerCase());

        textJson.add(typeJson);

        String itemName = plugin.getShowItem().getItemConverter().getCustomName(item);
        if (!itemName.isEmpty()) {
            textJson.add(new JSONObject(ImmutableMap.of("text", ": ", "color", "green")));

            JSONObject nameJson = new JSONObject();
            nameJson.put("text", itemName);
            nameJson.put("hoverEvent", hoverJson);
            nameJson.put("color", nameColor.name().toLowerCase());

            textJson.add(nameJson);
        }

        plugin.getShowItem().tellRaw((Player) sender, textJson.toString());
    }
    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Anzahl: " + ChatColor.WHITE + quantity));
    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Preis: " + ChatColor.WHITE + prices));

    return true;
}

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

/**
 * Get report links for a given application.
 * @param application nexus application/*  w w w .j  a  v a  2 s.co  m*/
 * @return a list of report links
 */
@Override
public List<LibraryPolicyReport> getApplicationReport(NexusIQApplication application) {
    List<LibraryPolicyReport> applicationReports = new ArrayList<>();

    String appReportLinkUrl = String.format(application.getInstanceUrl() + API_V2_REPORTS_LINKS,
            application.getApplicationId());

    try {
        JSONArray reports = parseAsArray(appReportLinkUrl);
        if ((reports == null) || (reports.isEmpty()))
            return null;
        for (Object element : reports) {
            LibraryPolicyReport appReport = new LibraryPolicyReport();
            String stage = str((JSONObject) element, "stage");
            appReport.setStage(stage);
            appReport.setEvaluationDate(timestamp((JSONObject) element, "evaluationDate"));
            appReport.setReportDataUrl(
                    application.getInstanceUrl() + "/" + str((JSONObject) element, "reportDataUrl"));
            appReport.setReportUIUrl(
                    application.getInstanceUrl() + "/" + str((JSONObject) element, "reportHtmlUrl"));
            applicationReports.add(appReport);
        }
    } catch (ParseException e) {
        LOG.error("Could not parse response from: " + appReportLinkUrl, e);
    } catch (RestClientException rce) {
        LOG.error("RestClientException: " + appReportLinkUrl + ". Error code=" + rce.getMessage());
    }
    return applicationReports;
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testGetNoJob() throws Exception {
    cleanScheduler();/*from  w w w.  jav  a  2 s  .  co m*/
    String resourceUrl = getResourceUrl("jobs");
    HttpGet httpGet = new HttpGet(resourceUrl);
    setSessionHeader(httpGet);
    HttpResponse response = executeUriRequest(httpGet);
    assertHttpStatusOK(response);
    JSONObject jsonObject = toJsonObject(response);
    JSONArray jsonArray = (JSONArray) jsonObject.get("list");
    assertTrue(jsonArray.isEmpty());
}