Example usage for org.json.simple JSONArray remove

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

Introduction

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

Prototype

public E remove(int index) 

Source Link

Document

Removes the element at the specified position in this list.

Usage

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops repSell(String shopName, String cost, String index, Player player) {
    if (!shops.containsKey(shopName)) {
        player.sendMessage("\u00a7eThat shop does not exist!");

        return this;
    }/*from w  w w.ja  v a 2 s  .  co  m*/

    try {
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONObject shopObj = (JSONObject) jsonObj.get(shopName);

        JSONArray shopItems = (JSONArray) shopObj.get("ShopItems");

        if (shopItems.size() <= Integer.parseInt(index)) {
            player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!");

            return this;
        }

        String itemName = (String) shopItems.get(Integer.parseInt(index));
        shopObj.remove(itemName);
        shopItems.remove(Integer.parseInt(index));

        String newItem = player.getItemInHand().getType().name();

        Bukkit.getLogger()
                .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName);

        shopItems.add(Integer.parseInt(index), newItem + ":sell:" + player.getItemInHand().getDurability());

        shopObj.put("ShopItems", shopItems);

        JSONObject itemStub = new JSONObject();
        itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount()));
        itemStub.put("price", cost);
        itemStub.put("type", "sell");
        itemStub.put("durability", "" + player.getItemInHand().getDurability());

        shopObj.put(newItem + ":sell:" + player.getItemInHand().getDurability(), itemStub);

        shopObj.put("ShopItems", shopItems);

        jsonObj.put(shopName, shopObj);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        player.sendMessage("\u00a7aShop updated!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in repBuy()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in repBuy()");
        e.printStackTrace();
    }

    return this;
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops moveShop(String shopName, String x, String y, String z, Player player) {
    try {//from w w  w . jav  a  2 s. c  o  m
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONArray shopList = (JSONArray) jsonObj.get("shopsArray");

        // Make sure that our array isn't empty
        if (shopList == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error\u00A7e>");

            return this;
        }

        JSONObject shopObj = new JSONObject();

        String shopName2;
        boolean foundShop = false;
        int index = 0;
        // Make sure the shop exists         
        for (index = 0; index < shopList.size(); index++) {
            shopObj = (JSONObject) (shopList.get(index));

            shopName2 = (String) shopObj.get("shopName");

            if (shopName2.equals(shopName)) {
                shopList.remove(index);
                foundShop = true;
                break;
            }
        }

        if (!foundShop) {
            player.sendMessage("\u00a7aThat shop doesn't exist!");
            return this;
        }

        // Update the coordinates in memory
        shopObj.put("x", x);
        shopObj.put("y", y);
        shopObj.put("z", z);
        shopObj.put("world", player.getWorld().getName());
        shopObj.put("shopName", shopName);

        shopList.add(shopObj);

        // Update the entire JSON table in memory
        jsonObj.put("shopsArray", shopList);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        player.sendMessage("\u00a7aShop moved!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addShop()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addShop()");
        e.printStackTrace();
    }

    return this;
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops delShop(String shopName, Player player) {
    try {/*  ww w .ja  v  a2  s .c o  m*/
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONArray shopList = (JSONArray) jsonObj.get("shopsArray");

        // Make sure that our array isn't empty
        if (shopList == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error 0x00\u00A7e>");

            return this;
        } else if (jsonObj.get(shopName) == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error 0x01\u00A7e>");

            return this;
        }

        JSONObject shopObj;

        String shopName2;
        int index;
        // Find our shop in our array         
        for (index = 0; index < shopList.size(); index++) {
            shopObj = (JSONObject) (shopList.get(index));

            shopName2 = (String) shopObj.get("shopName");

            if (shopName2.equals(shopName)) {
                break;
            }

        }

        // Remove shop from array
        shopList.remove(index);

        // Update the entire JSON table in memory
        jsonObj.put("shopsArray", shopList);

        // Now remove the shop data from the root
        jsonObj.remove(shopName);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        Shops.shops.remove(shopName);

        player.sendMessage("\u00a7aShop removed!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addShop()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addShop()");
        e.printStackTrace();
    }

    return this;
}

From source file:com.fujitsu.dc.core.model.impl.es.DavCmpEsImpl.java

/**
 * ID?URL?. jsonObj?IDURL???/* w  w  w.j a va  2 s  .c  om*/
 * @param jsonObj ID??JSON
 * @param baseUrlStr xml:base
 */
@SuppressWarnings("unchecked")
private void roleIdToName(Object jsonObj, String baseUrlStr) {

    JSONArray array = new JSONArray();
    if (jsonObj instanceof JSONObject) {
        array.add(jsonObj);
    } else {
        array = (JSONArray) jsonObj;
    }
    if (array != null) {
        // xml:base
        for (int i = 0; i < array.size(); i++) {
            JSONObject aceJson = (JSONObject) array.get(i);
            JSONObject principal = (JSONObject) aceJson.get(KEY_ACL_PRINCIPAL);
            if (principal.get(KEY_ACL_HREF) != null) {
                // ID????????????????
                String roloResourceUrl = roleIdToRoleResourceUrl((String) principal.get(KEY_ACL_HREF));
                if (roloResourceUrl == null) {
                    // ID???????????????ACE???
                    array.remove(i);
                    --i;
                    // ????ID??????ACE??
                    if (array.isEmpty() && jsonObj instanceof JSONObject) {
                        JSONObject objJson = (JSONObject) jsonObj;
                        objJson.clear();
                    }
                    continue;
                }
                // base:xml?URL?
                roloResourceUrl = baseUrlToRoleResourceUrl(baseUrlStr, roloResourceUrl);
                principal.put(KEY_ACL_HREF, roloResourceUrl);
            } else if (principal.get(KEY_ACL_ALL) != null) {
                principal.put(KEY_ACL_ALL, null);
            }
        }
    }
}

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

public boolean removeFromList(String listName, int index) {
    JSONObject list1 = (JSONObject) lists.get(listName);
    JSONArray list = (JSONArray) list1.get("items");
    if (list.size() > index) {
        list.remove(index);
        list1.put("items", list);
        lists.put(listName, list1);//from ww w . ja  va  2 s.c om
        config.put("lists", lists);
        saveConfig(true);
        return true;
    } else {
        return false;
    }
}

From source file:gov.usda.DataCatalogClient.Dataset.java

/**
 * Complies the extra list in special CKAN format that supports Project Open Data.
 * @return/*from   w w  w  .j a va 2s. c om*/
 */
//Suppressing Warnings, there is no way to turn fix this with JSON Object unless I change
//the package
@SuppressWarnings("unchecked")
private JSONArray addCkanExtras() {
    JSONArray extrasArray = new JSONArray();

    //The fields title and description are added at both the Dataset and Extra
    extrasArray.add(createExtraObject(PROJECT_OPEN_DATA_DATASET_TITLE, title));
    extrasArray.add(createExtraObject("notes", description));
    extrasArray.add(createExtraObject(CKAN_DATASET_ACCESS_LEVEL, accessLevel));
    extrasArray.add(createExtraObject(CKAN_DATASET_ACCRUAL_PERIODICITY, accrualPeriodicity));
    if (contactPoint != null) {
        extrasArray.add(createExtraObject(Contact.CKAN_CONTACT_EMAIL_ADDRESS, contactPoint.getEmailAddress()));
        extrasArray.add(createExtraObject(Contact.CKAN_CONTACT_FULL_NAME, contactPoint.getFullName()));
    }
    if (conformsTo != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_CONFORMS_TO, conformsTo));
    }
    if (dataQuality != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_DATA_QUALITY, dataQuality.toString()));
    }
    if (describedBy != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_DESCRIBED_BY, describedBy));
    }
    if (describedByType != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_DESCRIBED_BY_TYPE, describedByType));
    }
    if (isPartOf != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_IS_PART_OF, isPartOf));
    }
    if (landingPage != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_LANDING_PAGE, landingPage.toString()));
    }
    if (license != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_LICENSE, license));
    }
    if (modified != null) {
        //TODO: uncomment this line, testing create on ckan
        //extrasArray.add(createExtraObject(CKAN_DATASET_MODIFIED, Utils.convertDateToISOString(modified)));
    }
    extrasArray.add(createExtraObject(CKAN_DATASET_PRIMARY_IT_INVESTMENT_UII, primaryITInvestmentUII));
    if (publisher != null) {
        extrasArray.add(createExtraObject(Publisher.CKAN_PUBLISHER, publisher.getName()));
    }

    if (issued != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_ISSUED, Utils.convertDateToISOString(issued)));
    }

    if (rights != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_RIGHTS, rights));
    }
    //spatial might break create, this was commented out
    //This should really be spatial-text.  spatial is a reserverd word, more here: http://docs.ckan.org/en/ckan-1.7/geospatial.html
    if (spatial != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_SPATIAL_TEXT, spatial));
    }
    if (systemOfRecords != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_SYSTEM_OF_RECORDS, systemOfRecords));
    }
    if (temporal != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_TEMPORAL, temporal));
    }
    if (uniqueIdentifier != null) {
        extrasArray.add(createExtraObject(CKAN_DATASET_UNIQUE_IDENTIFIER, uniqueIdentifier));
    }
    //add lists
    extrasArray.add(createExtraObject(CKAN_DATASET_BUREAU_CODE_LIST, Utils.listToCSV(bureauCodeList)));
    extrasArray.add(createExtraObject(CKAN_DATASET_LANGUAGE, Utils.listToCSV(languageList)));
    extrasArray.add(createExtraObject(CKAN_DATASET_PROGRAM_CODE, Utils.listToCSV(programCodeList)));
    extrasArray.add(createExtraObject(CKAN_DATASET_REFERENCES, Utils.listToCSV(referenceList)));
    if (themeList.size() > 0) {
        extrasArray.add(createExtraObject(CKAN_DATASET_THEME, Utils.listToCSV(themeList)));
    }
    //get rid of nulls, ckan will give errors
    //TODO: Optimize where null values are added, too many if!null is cluttering code.
    for (int i = 0; i < extrasArray.size(); i++) {
        JSONObject extraObject = (JSONObject) extrasArray.get(i);
        if (extraObject.get("value") == null) {
            extrasArray.remove(i);
        }
    }
    return extrasArray;
}

From source file:bookUtilities.BookSearchServlet.java

private JSONArray getSearchResults(String searchPhrase) {
    JSONArray booksToReturn = new JSONArray();
    try {/*  www.  j a  va2  s.c om*/
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();
        if (searchPhrase.equals("newest")) {
            String query = "SELECT * " + "FROM [HardCover].[dbo].[Book] " + "WHERE Active = 1 "
                    + "ORDER BY DateAdded DESC;";

            ResultSet rs = st.executeQuery(query);
            while (rs.next()) {
                String bookId = rs.getString("BookUuid");
                Statement st2 = con.createStatement();
                query = "SELECT AuthorName " + "FROM [HardCover].[dbo].[Author] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs2 = st2.executeQuery(query);
                String authors = "";
                while (rs2.next()) {
                    if (authors.isEmpty()) {
                        authors = rs2.getString("AuthorName");
                    } else {
                        authors = authors + ", " + rs2.getString("AuthorName");
                    }
                }
                Statement st3 = con.createStatement();
                query = "SELECT Genre " + "FROM [HardCover].[dbo].[Genre] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs3 = st3.executeQuery(query);
                String genres = "";
                while (rs3.next()) {
                    if (genres.isEmpty()) {
                        genres = rs3.getString("Genre");
                    } else {
                        genres = genres + ", " + rs3.getString("Genre");
                    }
                }
                JSONObject bookToAdd = new JSONObject();
                bookToAdd.put("bookId", bookId);
                bookToAdd.put("numCopies", rs.getString("NumCopies"));
                bookToAdd.put("title", rs.getString("Title"));
                bookToAdd.put("cover", rs.getString("Cover"));
                bookToAdd.put("author", authors);
                bookToAdd.put("genres", genres);
                booksToReturn.add(bookToAdd);
            }
        } else if (searchPhrase.equals("popular")) {
            String query = "SELECT * " + "FROM [HardCover].[dbo].[Book] " + "WHERE Active = 1 "
                    + "ORDER BY TimesBorrowed DESC;";

            ResultSet rs = st.executeQuery(query);
            while (rs.next()) {
                String bookId = rs.getString("BookUuid");
                Statement st2 = con.createStatement();
                query = "SELECT AuthorName " + "FROM [HardCover].[dbo].[Author] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs2 = st2.executeQuery(query);
                String authors = "";
                while (rs2.next()) {
                    if (authors.isEmpty()) {
                        authors = rs2.getString("AuthorName");
                    } else {
                        authors = authors + ", " + rs2.getString("AuthorName");
                    }
                }
                Statement st3 = con.createStatement();
                query = "SELECT Genre " + "FROM [HardCover].[dbo].[Genre] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs3 = st3.executeQuery(query);
                String genres = "";
                while (rs3.next()) {
                    if (genres.isEmpty()) {
                        genres = rs3.getString("Genre");
                    } else {
                        genres = genres + ", " + rs3.getString("Genre");
                    }
                }
                JSONObject bookToAdd = new JSONObject();
                bookToAdd.put("bookId", bookId);
                bookToAdd.put("numCopies", rs.getString("NumCopies"));
                bookToAdd.put("title", rs.getString("Title"));
                bookToAdd.put("cover", rs.getString("Cover"));
                bookToAdd.put("author", authors);
                bookToAdd.put("genres", genres);
                booksToReturn.add(bookToAdd);
            }
        } else {
            String query = "SELECT * " + "FROM HardCover.dbo.Book JOIN HardCover.dbo.Author "
                    + "ON HardCover.dbo.Book.BookUuid = HardCover.dbo.Author.BookId "
                    + "JOIN HardCover.dbo.Genre ON HardCover.dbo.Book.BookUuid = HardCover.dbo.Genre.BookId "
                    + "WHERE (FREETEXT((Title, Publisher, BookDescription, BookLanguage), '" + searchPhrase
                    + "') OR FREETEXT(AuthorName,'" + searchPhrase + "') OR FREETEXT(Genre,'" + searchPhrase
                    + "')) AND Active = 1 " + " ORDER BY Title;";

            ResultSet rs = st.executeQuery(query);
            String oldTitle = "";
            String oldAuthor = "";
            String oldGenre = "";
            while (rs.next()) {
                JSONObject bookToAdd = new JSONObject();
                String newTitle = rs.getString("Title");
                String newAuthor = rs.getString("AuthorName");
                String newGenre = rs.getString("Genre");
                if (oldTitle.equals(newTitle)) {
                    if (!(oldAuthor.equals(newAuthor))) {
                        bookToAdd = ((JSONObject) booksToReturn.remove(booksToReturn.size() - 1));
                        bookToAdd.put("author", bookToAdd.get("author") + ", " + newAuthor);
                        oldAuthor = newAuthor;
                        booksToReturn.add(bookToAdd);
                    } else if (!(oldGenre.equals(newGenre))) {
                        bookToAdd = ((JSONObject) booksToReturn.remove(booksToReturn.size() - 1));
                        bookToAdd.put("genres", bookToAdd.get("genres") + ", " + newGenre);
                        oldGenre = newGenre;
                        booksToReturn.add(bookToAdd);
                    }
                } else {
                    bookToAdd.put("bookId", rs.getString("BookUuid"));
                    bookToAdd.put("numCopies", rs.getString("NumCopies"));
                    bookToAdd.put("title", newTitle);
                    bookToAdd.put("cover", rs.getString("Cover"));
                    bookToAdd.put("author", newAuthor);
                    bookToAdd.put("genres", newGenre);
                    oldTitle = newTitle;
                    oldAuthor = newAuthor;
                    oldGenre = newGenre;
                    booksToReturn.add(bookToAdd);
                }
            }
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return booksToReturn;
}

From source file:niclients.main.getni.java

/**
 * Main of the GET NI./*from   w ww  .ja v  a  2  s  .c  o  m*/
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    boolean done;
    String dst = null;
    JSONArray loc_array = new JSONArray();
    String c_type;
    HttpResponse response;
    int resp_code = 0;

    if (commandparser(args)) {

        dst = fqdn;
        done = false;

        try {
            while (!done) {
                if (createget(dst, niname)) {

                    response = client.execute(post);
                    resp_code = response.getStatusLine().getStatusCode();

                    if (200 == resp_code) {
                        // Get content type
                        c_type = response.getEntity().getContentType().getValue();

                        if ("application/json".equalsIgnoreCase(c_type)) {
                            // Response is location list
                            InputStream content = response.getEntity().getContent();
                            String resp = convertStreamToString(content);

                            // String to JSONArray
                            Object obj = JSONValue.parse(resp);
                            JSONArray array = (JSONArray) obj;

                            // add new locations to loc_array   
                            for (int i = 0; i < array.size(); i++) {
                                loc_array.add(array.get(i));
                            }
                            // Get next location from the loc_array and remove it from the loc_array
                            if (!loc_array.isEmpty()) {

                                // Check if new dst is type ni://
                                String tmp_dst = loc_array.get(0).toString();
                                tmp_dst = niUtils.mapNiToWKU(loc_array.get(0).toString());

                                if (tmp_dst == null) {
                                    //Check id new dst is type nihttp://
                                    tmp_dst = niUtils.mapNiHttpToWKU(loc_array.get(0).toString());
                                    if (tmp_dst != null)
                                        // is nihttp://
                                        dst = tmp_dst;
                                    else
                                        // is http://
                                        dst = loc_array.get(0).toString();
                                } else {
                                    // is ni://
                                    dst = tmp_dst;
                                }
                                loc_array.remove(0);
                            }
                        } else if ("application/octet-stream".equalsIgnoreCase(c_type)) {
                            // Response is content
                            InputStream content = response.getEntity().getContent();
                            if (output_filename == null)
                                writeCacheCopyToStdOut(content);
                            else {
                                writeCacheCopy(content, output_filename);
                                System.err.println("Content was stored to '" + output_filename + "'");
                            }
                            // so we can end the while
                            done = true;
                        } else {
                            // Response content type is not something we expected
                            System.err.println("Unsupported Content type = " + c_type);
                        }
                    } else {
                        // Response codetype is not success (we expected that)
                        System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                    }
                } else {
                    System.err.println("Command parse failed!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}