Example usage for java.util HashMap remove

List of usage examples for java.util HashMap remove

Introduction

In this page you can find the example usage for java.util HashMap remove.

Prototype

public V remove(Object key) 

Source Link

Document

Removes the mapping for the specified key from this map if present.

Usage

From source file:org.gtdfree.model.GTDDataXMLTools.java

private static void _load_2_1(GTDModel model, XMLStreamReader r) throws XMLStreamException {

    HashMap<Integer, Action> withProject = new HashMap<Integer, Action>();
    HashMap<Integer, Action> queued = new HashMap<Integer, Action>();

    if (checkTagStart(r, "lists")) { //$NON-NLS-1$

        r.nextTag();/*ww w . j  a  v  a2s.  co m*/
        while (checkTagStart(r, "list")) { //$NON-NLS-1$
            Folder ff;
            String id = r.getAttributeValue(null, "id"); //$NON-NLS-1$
            if (id != null) {
                ff = model.createFolder(Integer.parseInt(id), r.getAttributeValue(null, "name"), //$NON-NLS-1$
                        FolderType.valueOf(r.getAttributeValue(null, "type"))); //$NON-NLS-1$
            } else {
                String s = r.getAttributeValue(null, "type").replace("NOTE", "INBUCKET"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                ff = model.createFolder(r.getAttributeValue(null, "name"), FolderType.valueOf(s)); //$NON-NLS-1$
            }
            String s = r.getAttributeValue(null, "closed"); //$NON-NLS-1$
            if (s != null)
                ff.setClosed(Boolean.parseBoolean(s));
            s = r.getAttributeValue(null, "description"); //$NON-NLS-1$
            if (s != null) {
                s = s.replace("\\n", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            if (!ff.isInBucket()) {
                ff.setDescription(s);
            }

            r.nextTag();

            while (checkTagStart(r, "action")) { //$NON-NLS-1$
                int i = Integer.parseInt(r.getAttributeValue(null, "id")); //$NON-NLS-1$
                Date cr = new Date(Long.parseLong(r.getAttributeValue(null, "created"))); //$NON-NLS-1$
                Date re = r.getAttributeValue(null, "resolved") == null ? null //$NON-NLS-1$
                        : new Date(Long.parseLong(r.getAttributeValue(null, "resolved"))); //$NON-NLS-1$
                String d = r.getAttributeValue(null, "description"); //$NON-NLS-1$
                if (d != null) {
                    d = d.replace("\\n", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
                }

                Action a = new Action(i, cr, re, d);

                s = r.getAttributeValue(null, "type"); //$NON-NLS-1$
                if (s != null)
                    a.setType(ActionType.valueOf(s));

                s = r.getAttributeValue(null, "url"); //$NON-NLS-1$
                if (s != null) {
                    try {
                        a.setUrl(new URL(s));
                    } catch (Exception e) {
                        Logger.getLogger(GTDDataXMLTools.class).debug("Internal error.", e); //$NON-NLS-1$
                    }
                }

                s = r.getAttributeValue(null, "start"); //$NON-NLS-1$
                if (s != null)
                    a.setStart(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "remind"); //$NON-NLS-1$
                if (s != null)
                    a.setRemind(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "due"); //$NON-NLS-1$
                if (s != null)
                    a.setDue(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "queued"); //$NON-NLS-1$
                if (s != null)
                    a.setQueued(Boolean.parseBoolean(s));

                s = r.getAttributeValue(null, "project"); //$NON-NLS-1$
                if (s != null)
                    a.setProject(Integer.parseInt(s));

                s = r.getAttributeValue(null, "priority"); //$NON-NLS-1$
                if (s != null)
                    a.setPriority(Priority.valueOf(s));

                a.setResolution(Action.Resolution.toResolution(r.getAttributeValue(null, "resolution"))); //$NON-NLS-1$

                ff.add(a);

                if (a.getProject() != null) {
                    withProject.put(a.getId(), a);
                }

                if (a.isQueued()) {
                    queued.put(a.getId(), a);
                }

                if (a.getId() > model.getLastActionID()) {
                    model.setLastActionID(a.getId());
                }
                findTagEnd(r, "action"); //$NON-NLS-1$
                r.nextTag();
            }

            findTagEnd(r, "list"); //$NON-NLS-1$
            r.nextTag();
        }

        findTagEnd(r, "lists"); //$NON-NLS-1$
        //r.nextTag();
    }

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }
    // read projects
    r.nextTag();

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    if (checkTagStart(r, "projects")) { //$NON-NLS-1$

        r.nextTag();
        while (checkTagStart(r, "project")) { //$NON-NLS-1$
            Project pp;
            String id = r.getAttributeValue(null, "id"); //$NON-NLS-1$
            if (id != null) {
                pp = (Project) model.createFolder(Integer.parseInt(id), r.getAttributeValue(null, "name"), //$NON-NLS-1$
                        FolderType.PROJECT);
            } else {
                pp = (Project) model.createFolder(r.getAttributeValue(null, "name"), FolderType.PROJECT); //$NON-NLS-1$
            }
            pp.setClosed(Boolean.parseBoolean(r.getAttributeValue(null, "closed"))); //$NON-NLS-1$
            pp.setGoal(r.getAttributeValue(null, "goal")); //$NON-NLS-1$

            String s = r.getAttributeValue(null, "actions"); //$NON-NLS-1$

            if (s != null && s.trim().length() > 0) {
                String[] ss = s.trim().split(","); //$NON-NLS-1$
                for (int i = 0; i < ss.length; i++) {
                    if (ss[i].trim().length() > 0) {
                        int ii = Integer.parseInt(ss[i].trim());
                        Action a = withProject.remove(ii);
                        if (a != null) {
                            pp.add(a);
                        }
                    }
                }
            }
            r.nextTag();
            findTagEnd(r, "project"); //$NON-NLS-1$
            r.nextTag();
        }
        findTagEnd(r, "projects"); //$NON-NLS-1$
    }

    for (Action a : withProject.values()) {
        if (a.getProject() != null) {
            Project p = model.getProject(a.getProject());

            if (p != null) {
                p.add(a);
            } else {
                System.err.println("Project " + p + " in action " + a + " does not exsist."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                a.setProject(null);
            }
        }
    }

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    // read projects
    r.nextTag();

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    if (checkTagStart(r, "queue")) { //$NON-NLS-1$
        Folder f = model.getQueue();

        String s = r.getAttributeValue(null, "actions"); //$NON-NLS-1$

        if (s != null && s.trim().length() > 0) {
            String[] ss = s.trim().split(","); //$NON-NLS-1$
            for (int i = 0; i < ss.length; i++) {
                if (ss[i].trim().length() > 0) {
                    int ii = Integer.parseInt(ss[i].trim());
                    Action a = queued.remove(ii);
                    if (a != null) {
                        f.add(a);
                    }
                }
            }
        }
        r.nextTag();
        findTagEnd(r, "queue"); //$NON-NLS-1$
        r.nextTag();
    }

    for (Action a : queued.values()) {
        if (a.isQueued()) {
            System.err.println("Action " + a + " is queued but not in queue list."); //$NON-NLS-1$ //$NON-NLS-2$
            model.getQueue().add(a);
        }
    }

}

From source file:org.gtdfree.model.GTDDataXMLTools.java

private static void _load_2_0(GTDModel model, XMLStreamReader r) throws XMLStreamException {

    HashMap<Integer, Action> withProject = new HashMap<Integer, Action>();
    HashMap<Integer, Action> queued = new HashMap<Integer, Action>();

    if (checkTagStart(r, "folders")) { //$NON-NLS-1$

        r.nextTag();//from ww w. j  a  v  a  2  s. c o  m
        while (checkTagStart(r, "folder")) { //$NON-NLS-1$
            Folder ff;
            String id = r.getAttributeValue(null, "id"); //$NON-NLS-1$
            if (id != null) {
                ff = model.createFolder(Integer.parseInt(id), r.getAttributeValue(null, "name"), //$NON-NLS-1$
                        FolderType.valueOf(r.getAttributeValue(null, "type"))); //$NON-NLS-1$
            } else {
                String s = r.getAttributeValue(null, "type").replace("NOTE", "INBUCKET"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                ff = model.createFolder(r.getAttributeValue(null, "name"), FolderType.valueOf(s)); //$NON-NLS-1$
            }
            String s = r.getAttributeValue(null, "closed"); //$NON-NLS-1$
            if (s != null)
                ff.setClosed(Boolean.parseBoolean(s));
            s = r.getAttributeValue(null, "description"); //$NON-NLS-1$
            if (s != null) {
                s = s.replace("\\n", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            if (!ff.isInBucket()) {
                ff.setDescription(s);
            }

            r.nextTag();

            while (checkTagStart(r, "action")) { //$NON-NLS-1$
                int i = Integer.parseInt(r.getAttributeValue(null, "id")); //$NON-NLS-1$
                Date cr = new Date(Long.parseLong(r.getAttributeValue(null, "created"))); //$NON-NLS-1$
                Date re = r.getAttributeValue(null, "resolved") == null ? null //$NON-NLS-1$
                        : new Date(Long.parseLong(r.getAttributeValue(null, "resolved"))); //$NON-NLS-1$
                String d = r.getAttributeValue(null, "description"); //$NON-NLS-1$
                if (d != null) {
                    d = d.replace("\\n", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
                }
                Action a = new Action(i, cr, re, d);

                s = r.getAttributeValue(null, "type"); //$NON-NLS-1$
                if (s != null)
                    a.setType(ActionType.valueOf(s));

                s = r.getAttributeValue(null, "url"); //$NON-NLS-1$
                if (s != null) {
                    try {
                        a.setUrl(new URL(s));
                    } catch (Exception e) {
                        Logger.getLogger(GTDDataXMLTools.class).debug("Internal error.", e); //$NON-NLS-1$
                    }
                }

                s = r.getAttributeValue(null, "start"); //$NON-NLS-1$
                if (s != null)
                    a.setStart(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "remind"); //$NON-NLS-1$
                if (s != null)
                    a.setRemind(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "due"); //$NON-NLS-1$
                if (s != null)
                    a.setDue(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "queued"); //$NON-NLS-1$
                if (s != null)
                    a.setQueued(Boolean.parseBoolean(s));

                s = r.getAttributeValue(null, "project"); //$NON-NLS-1$
                if (s != null)
                    a.setProject(Integer.parseInt(s));

                s = r.getAttributeValue(null, "priority"); //$NON-NLS-1$
                if (s != null)
                    a.setPriority(Priority.valueOf(s));

                a.setResolution(Action.Resolution.toResolution(r.getAttributeValue(null, "resolution"))); //$NON-NLS-1$

                ff.add(a);

                if (a.getProject() != null) {
                    withProject.put(a.getId(), a);
                }

                if (a.isQueued()) {
                    queued.put(a.getId(), a);
                }

                if (a.getId() > model.getLastActionID()) {
                    model.setLastActionID(a.getId());
                }
                findTagEnd(r, "action"); //$NON-NLS-1$
                r.nextTag();
            }

            findTagEnd(r, "folder"); //$NON-NLS-1$
            r.nextTag();
        }
        findTagEnd(r, "folders"); //$NON-NLS-1$
        //r.nextTag();

    }

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }
    // read projects
    r.nextTag();

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    if (checkTagStart(r, "projects")) { //$NON-NLS-1$

        r.nextTag();
        while (checkTagStart(r, "project")) { //$NON-NLS-1$
            Project pp;
            String id = r.getAttributeValue(null, "id"); //$NON-NLS-1$
            if (id != null) {
                pp = (Project) model.createFolder(Integer.parseInt(id), r.getAttributeValue(null, "name"), //$NON-NLS-1$
                        FolderType.PROJECT);
            } else {
                pp = (Project) model.createFolder(r.getAttributeValue(null, "name"), FolderType.PROJECT); //$NON-NLS-1$
            }
            pp.setClosed(Boolean.parseBoolean(r.getAttributeValue(null, "closed"))); //$NON-NLS-1$
            pp.setGoal(r.getAttributeValue(null, "goal")); //$NON-NLS-1$

            String s = r.getAttributeValue(null, "actions"); //$NON-NLS-1$

            if (s != null && s.trim().length() > 0) {
                String[] ss = s.trim().split(","); //$NON-NLS-1$
                for (int i = 0; i < ss.length; i++) {
                    if (ss[i].trim().length() > 0) {
                        int ii = Integer.parseInt(ss[i].trim());
                        Action a = withProject.remove(ii);
                        if (a != null) {
                            pp.add(a);
                        }
                    }
                }
            }
            r.nextTag();
            findTagEnd(r, "project"); //$NON-NLS-1$
            r.nextTag();
        }
        findTagEnd(r, "projects"); //$NON-NLS-1$
    }

    for (Action a : withProject.values()) {
        if (a.getProject() != null) {
            Project p = model.getProject(a.getProject());

            if (p != null) {
                p.add(a);
            } else {
                System.err.println("Project " + p + " in action " + a + " does not exsist."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                a.setProject(null);
            }
        }
    }

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    // read projects
    r.nextTag();

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    if (checkTagStart(r, "queue")) { //$NON-NLS-1$
        Folder f = model.getQueue();

        String s = r.getAttributeValue(null, "actions"); //$NON-NLS-1$

        if (s != null && s.trim().length() > 0) {
            String[] ss = s.trim().split(","); //$NON-NLS-1$
            for (int i = 0; i < ss.length; i++) {
                if (ss[i].trim().length() > 0) {
                    int ii = Integer.parseInt(ss[i].trim());
                    Action a = queued.remove(ii);
                    if (a != null) {
                        f.add(a);
                    }
                }
            }
        }
        r.nextTag();
        findTagEnd(r, "queue"); //$NON-NLS-1$
        r.nextTag();
    }

    for (Action a : queued.values()) {
        if (a.isQueued()) {
            System.err.println("Action " + a + " is queued but not in queue list."); //$NON-NLS-1$ //$NON-NLS-2$
            model.getQueue().add(a);
        }
    }

}

From source file:com.wasteofplastic.askygrid.commands.Challenges.java

/**
 * Checks if a player has enough for a challenge. Supports two types of
 * checks, inventory and collect. Removes items if required.
 * //from   ww  w. j ava 2s.  c  om
 * @param player
 * @param challenge
 * @param type
 * @return true if the player has everything required
 */

public boolean hasRequired(final Player player, final String challenge, final String type) {
    // Check money
    double moneyReq = 0D;
    if (Settings.useEconomy) {
        moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney",
                0D);
        if (moneyReq > 0D) {
            if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems);
                String desc = ChatColor.translateAlternateColorCodes('&',
                        getChallengeConfig().getString("challenges.challengeList." + challenge + ".description")
                                .replace("[label]", Settings.ISLANDCOMMAND));
                List<String> result = new ArrayList<String>();
                if (desc.contains("|")) {
                    result.addAll(Arrays.asList(desc.split("\\|")));
                } else {
                    result.add(desc);
                }
                for (String line : result) {
                    player.sendMessage(ChatColor.RED + line);
                }
                return false;
            }
        }
    }
    final String[] reqList = getChallengeConfig()
            .getString("challenges.challengeList." + challenge + ".requiredItems").split(" ");
    // The format of the requiredItems is as follows:
    // Material:Qty
    // or
    // Material:DamageModifier:Qty
    // This second one is so that items such as potions or variations on
    // standard items can be collected
    if (type.equalsIgnoreCase("inventory")) {
        List<ItemStack> toBeRemoved = new ArrayList<ItemStack>();
        Material reqItem;
        int reqAmount = 0;
        for (final String s : reqList) {
            final String[] part = s.split(":");
            // Material:Qty
            if (part.length == 2) {
                try {
                    // Correct some common mistakes
                    if (part[0].equalsIgnoreCase("potato")) {
                        part[0] = "POTATO_ITEM";
                    } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                        part[0] = "BREWING_STAND_ITEM";
                    } else if (part[0].equalsIgnoreCase("carrot")) {
                        part[0] = "CARROT_ITEM";
                    } else if (part[0].equalsIgnoreCase("cauldron")) {
                        part[0] = "CAULDRON_ITEM";
                    } else if (part[0].equalsIgnoreCase("skull")) {
                        part[0] = "SKULL_ITEM";
                    }
                    // TODO: add netherwart vs. netherstalk?
                    if (StringUtils.isNumeric(part[0])) {
                        reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                    } else {
                        reqItem = Material.getMaterial(part[0].toUpperCase());
                    }
                    reqAmount = Integer.parseInt(part[1]);
                    ItemStack item = new ItemStack(reqItem);
                    // plugin.getLogger().info("DEBUG: required item = " +
                    // reqItem.toString());
                    // plugin.getLogger().info("DEBUG: item amount = " +
                    // reqAmount);

                    if (!player.getInventory().contains(reqItem)) {
                        return false;
                    } else {
                        // check amount
                        int amount = 0;
                        // plugin.getLogger().info("DEBUG: Amount in inventory = "
                        // + player.getInventory().all(reqItem).size());
                        // Go through all the inventory and try to find
                        // enough required items
                        for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem)
                                .entrySet()) {
                            // Get the item
                            ItemStack i = en.getValue();
                            // If the item is enchanted, skip - it doesn't count
                            if (i.hasItemMeta()) {
                                continue;
                            }
                            // Map needs special handling because the
                            // durability increments every time a new one is
                            // made by the player
                            // TODO: if there are any other items that act
                            // in the same way, they need adding too...
                            if (i.getDurability() == 0
                                    || (reqItem == Material.MAP && i.getType() == Material.MAP)) {
                                // Clear any naming, or lore etc.
                                //i.setItemMeta(null);
                                //player.getInventory().setItem(en.getKey(), i);
                                // #1 item stack qty + amount is less than
                                // required items - take all i
                                // #2 item stack qty + amount = required
                                // item -
                                // take all
                                // #3 item stack qty + amount > req items -
                                // take
                                // portion of i
                                // amount += i.getAmount();
                                if ((amount + i.getAmount()) < reqAmount) {
                                    // Remove all of this item stack - clone
                                    // otherwise it will keep a reference to
                                    // the
                                    // original
                                    toBeRemoved.add(i.clone());
                                    amount += i.getAmount();
                                    // plugin.getLogger().info("DEBUG: amount is <= req Remove "
                                    // + i.toString() + ":" +
                                    // i.getDurability() + " x " +
                                    // i.getAmount());
                                } else if ((amount + i.getAmount()) == reqAmount) {
                                    // plugin.getLogger().info("DEBUG: amount is = req Remove "
                                    // + i.toString() + ":" +
                                    // i.getDurability() + " x " +
                                    // i.getAmount());
                                    toBeRemoved.add(i.clone());
                                    amount += i.getAmount();
                                    break;
                                } else {
                                    // Remove a portion of this item
                                    // plugin.getLogger().info("DEBUG: amount is > req Remove "
                                    // + i.toString() + ":" +
                                    // i.getDurability() + " x " +
                                    // i.getAmount());

                                    item.setAmount(reqAmount - amount);
                                    item.setDurability(i.getDurability());
                                    toBeRemoved.add(item);
                                    amount += i.getAmount();
                                    break;
                                }
                            }
                        }
                        // plugin.getLogger().info("DEBUG: amount "+
                        // amount);
                        if (amount < reqAmount) {
                            return false;
                        }
                    }
                } catch (Exception e) {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    player.sendMessage(
                            ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                    String materialList = "";
                    boolean hint = false;
                    for (Material m : Material.values()) {
                        materialList += m.toString() + ",";
                        if (m.toString().contains(s.substring(0, 3).toUpperCase())) {
                            plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                            hint = true;
                        }
                    }
                    if (!hint) {
                        plugin.getLogger()
                                .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:");
                        plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                    } else {
                        plugin.getLogger().severe("Correct challenges.yml with the correct material.");
                    }
                    return false;
                }
            } else if (part.length == 3) {
                // This handles items with durability
                // Correct some common mistakes
                if (part[0].equalsIgnoreCase("potato")) {
                    part[0] = "POTATO_ITEM";
                } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                    part[0] = "BREWING_STAND_ITEM";
                } else if (part[0].equalsIgnoreCase("carrot")) {
                    part[0] = "CARROT_ITEM";
                } else if (part[0].equalsIgnoreCase("cauldron")) {
                    part[0] = "CAULDRON_ITEM";
                } else if (part[0].equalsIgnoreCase("skull")) {
                    part[0] = "SKULL_ITEM";
                }
                if (StringUtils.isNumeric(part[0])) {
                    reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                } else {
                    reqItem = Material.getMaterial(part[0].toUpperCase());
                }
                reqAmount = Integer.parseInt(part[2]);
                int reqDurability = Integer.parseInt(part[1]);
                ItemStack item = new ItemStack(reqItem);

                // Item
                item.setDurability((short) reqDurability);
                // check amount
                int amount = 0;
                // Go through all the inventory and try to find
                // enough required items
                for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem).entrySet()) {
                    // Get the item
                    ItemStack i = en.getValue();
                    if (i.hasItemMeta()) {
                        continue;
                    }
                    if (i.getDurability() == reqDurability) {
                        // Clear any naming, or lore etc.
                        //i.setItemMeta(null);
                        // player.getInventory().setItem(en.getKey(), i);
                        // #1 item stack qty + amount is less than
                        // required items - take all i
                        // #2 item stack qty + amount = required
                        // item -
                        // take all
                        // #3 item stack qty + amount > req items -
                        // take
                        // portion of i
                        // amount += i.getAmount();
                        if ((amount + i.getAmount()) < reqAmount) {
                            // Remove all of this item stack - clone
                            // otherwise it will keep a reference to
                            // the
                            // original
                            toBeRemoved.add(i.clone());
                            amount += i.getAmount();
                            // plugin.getLogger().info("DEBUG: amount is <= req Remove "
                            // + i.toString() + ":" +
                            // i.getDurability()
                            // + " x " + i.getAmount());
                        } else if ((amount + i.getAmount()) == reqAmount) {
                            toBeRemoved.add(i.clone());
                            amount += i.getAmount();
                            break;
                        } else {
                            // Remove a portion of this item
                            // plugin.getLogger().info("DEBUG: amount is > req Remove "
                            // + i.toString() + ":" +
                            // i.getDurability()
                            // + " x " + i.getAmount());

                            item.setAmount(reqAmount - amount);
                            item.setDurability(i.getDurability());
                            toBeRemoved.add(item);
                            amount += i.getAmount();
                            break;
                        }
                    }
                }
                // plugin.getLogger().info("DEBUG: amount is " +
                // amount);
                // plugin.getLogger().info("DEBUG: req amount is " +
                // reqAmount);
                if (amount < reqAmount) {
                    return false;
                }

                // plugin.getLogger().info("DEBUG: before set amount " +
                // item.toString() + ":" + item.getDurability() + " x "
                // + item.getAmount());
                // item.setAmount(reqAmount);
                // plugin.getLogger().info("DEBUG: after set amount " +
                // item.toString() + ":" + item.getDurability() + " x "
                // + item.getAmount());
                // toBeRemoved.add(item);

            } else if (part.length == 6 && part[0].contains("POTION")) {
                // Run through player's inventory for the item
                ItemStack[] playerInv = player.getInventory().getContents();
                try {
                    reqAmount = Integer.parseInt(part[5]);
                    //plugin.getLogger().info("DEBUG: required amount is " + reqAmount);
                } catch (Exception e) {
                    plugin.getLogger().severe("Could not parse the quantity of the potion item " + s);
                    return false;
                }
                int count = reqAmount;
                for (ItemStack i : playerInv) {
                    // Catches all POTION, LINGERING_POTION and SPLASH_POTION
                    if (i != null && i.getType().toString().contains("POTION")) {
                        //plugin.getLogger().info("DEBUG:6 part potion check!");
                        // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
                        if (plugin.getServer().getVersion().contains("(MC: 1.8")
                                || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                            // Test potion
                            Potion potion = Potion.fromItemStack(i);
                            PotionType potionType = potion.getType();
                            boolean match = true;
                            // plugin.getLogger().info("DEBUG: name check " + part[1]);
                            // Name check
                            if (!part[1].isEmpty()) {
                                // There is a name
                                if (PotionType.valueOf(part[1]) != null) {
                                    if (!potionType.name().equalsIgnoreCase(part[1])) {
                                        match = false;
                                        // plugin.getLogger().info("DEBUG: name does not match");
                                    } else {
                                        // plugin.getLogger().info("DEBUG: name matches");
                                    }
                                } else {
                                    plugin.getLogger()
                                            .severe("Potion type is unknown. Please pick from the following:");
                                    for (PotionType pt : PotionType.values()) {
                                        plugin.getLogger().severe(pt.name());
                                    }
                                    match = false;
                                }
                            }
                            // Level check (upgraded)
                            // plugin.getLogger().info("DEBUG: level check " + part[2]);
                            if (!part[2].isEmpty()) {
                                // There is a level declared - check it
                                if (StringUtils.isNumeric(part[2])) {
                                    int level = Integer.valueOf(part[2]);
                                    if (level != potion.getLevel()) {
                                        // plugin.getLogger().info("DEBUG: level does not match");
                                        match = false;
                                    }
                                }
                            }
                            // Extended check
                            // plugin.getLogger().info("DEBUG: extended check " + part[3]);
                            if (!part[3].isEmpty()) {
                                if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                                if (part[3].equalsIgnoreCase("NOTEXTENDED") && potion.hasExtendedDuration()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                            }
                            // Splash check
                            // plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                            if (!part[4].isEmpty()) {
                                if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not splash");
                                }
                                if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not no splash");
                                }
                            }
                            // Quantity check
                            if (match) {
                                // plugin.getLogger().info("DEBUG: potion matches!");
                                ItemStack removeItem = i.clone();
                                if (removeItem.getAmount() > reqAmount) {
                                    // plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                    removeItem.setAmount(reqAmount);
                                }
                                count = count - removeItem.getAmount();
                                // plugin.getLogger().info("DEBUG: " + count + " left");
                                toBeRemoved.add(removeItem);
                            }
                        } else {
                            // V1.9 and above
                            PotionMeta potionMeta = (PotionMeta) i.getItemMeta();
                            // If any of the settings above are missing, then any is okay
                            boolean match = true;
                            // plugin.getLogger().info("DEBUG: name check " + part[1]);
                            // Name check
                            if (!part[1].isEmpty()) {
                                // There is a name
                                if (PotionType.valueOf(part[1]) != null) {
                                    if (!potionMeta.getBasePotionData().getType().name()
                                            .equalsIgnoreCase(part[1])) {
                                        match = false;
                                        // plugin.getLogger().info("DEBUG: name does not match");
                                    } else {
                                        // plugin.getLogger().info("DEBUG: name matches");
                                    }
                                } else {
                                    plugin.getLogger()
                                            .severe("Potion type is unknown. Please pick from the following:");
                                    for (PotionType pt : PotionType.values()) {
                                        plugin.getLogger().severe(pt.name());
                                    }
                                    match = false;
                                }
                            }
                            // Level check (upgraded)
                            // plugin.getLogger().info("DEBUG: level check " + part[2]);
                            if (!part[2].isEmpty()) {
                                // There is a level declared - check it
                                if (StringUtils.isNumeric(part[2])) {
                                    int level = Integer.valueOf(part[2]);
                                    if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) {
                                        // plugin.getLogger().info("DEBUG: level does not match");
                                        match = false;
                                    }
                                    if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) {
                                        match = false;
                                        // plugin.getLogger().info("DEBUG: level does not match");
                                    }
                                }
                            }
                            // Extended check
                            // plugin.getLogger().info("DEBUG: extended check " + part[3]);
                            if (!part[3].isEmpty()) {
                                if (part[3].equalsIgnoreCase("EXTENDED")
                                        && !potionMeta.getBasePotionData().isExtended()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                                if (part[3].equalsIgnoreCase("NOTEXTENDED")
                                        && potionMeta.getBasePotionData().isExtended()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                            }
                            // Splash or Linger check
                            // plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                            if (!part[4].isEmpty()) {
                                if (part[4].equalsIgnoreCase("SPLASH")
                                        && !i.getType().equals(Material.SPLASH_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not splash");
                                }
                                if (part[4].equalsIgnoreCase("NOSPLASH")
                                        && i.getType().equals(Material.SPLASH_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not no splash");
                                }
                                if (part[4].equalsIgnoreCase("LINGER")
                                        && !i.getType().equals(Material.LINGERING_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not linger");
                                }
                                if (part[4].equalsIgnoreCase("NOLINGER")
                                        && i.getType().equals(Material.LINGERING_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not no linger");
                                }
                            }
                            // Quantity check
                            if (match) {
                                // plugin.getLogger().info("DEBUG: potion matches!");
                                ItemStack removeItem = i.clone();
                                if (removeItem.getAmount() > reqAmount) {
                                    // plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                    removeItem.setAmount(reqAmount);
                                }
                                count = count - removeItem.getAmount();
                                // plugin.getLogger().info("DEBUG: " + count + " left");
                                toBeRemoved.add(removeItem);
                            }
                        }
                    }
                    if (count <= 0) {
                        // plugin.getLogger().info("DEBUG: Player has enough");
                        break;
                    }
                    // plugin.getLogger().info("DEBUG: still need " + count + " to complete");
                }
                if (count > 0) {
                    // plugin.getLogger().info("DEBUG: Player does not have enough");
                    return false;
                }

            } else {
                plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                return false;
            }
        }
        // Build up the items in the inventory and remove them if they are
        // all there.

        if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) {
            // checkChallengeItems(player, challenge);
            // int qty = 0;
            // plugin.getLogger().info("DEBUG: Removing items");
            for (ItemStack i : toBeRemoved) {
                // qty += i.getAmount();
                // plugin.getLogger().info("DEBUG: Remove " + i.toString() +
                // "::" + i.getDurability() + " x " + i.getAmount());
                HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i);
                if (!leftOver.isEmpty()) {
                    plugin.getLogger().warning("Exploit? Could not remove the following in challenge "
                            + challenge + " for player " + player.getName() + ":");
                    for (ItemStack left : leftOver.values()) {
                        plugin.getLogger().info(left.toString());
                    }
                    return false;
                }
            }
            // Remove money
            if (moneyReq > 0D) {
                EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq);
                if (!er.transactionSuccess()) {
                    plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq)
                            + " from " + player.getName() + " in challenge " + challenge);
                    plugin.getLogger().warning("Player's balance is "
                            + VaultHelper.econ.format(VaultHelper.econ.getBalance(player)));
                }
            }
            // plugin.getLogger().info("DEBUG: total = " + qty);
        }
        return true;
    }
    if (type.equalsIgnoreCase("collect")) {
        final HashMap<Material, Integer> neededItem = new HashMap<Material, Integer>();
        final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>();
        for (int i = 0; i < reqList.length; i++) {
            final String[] sPart = reqList[i].split(":");
            // Parse the qty required first
            try {
                final int qty = Integer.parseInt(sPart[1]);
                // Find out if the needed item is a Material or an Entity
                boolean isEntity = false;
                for (EntityType entityType : EntityType.values()) {
                    if (entityType.toString().equalsIgnoreCase(sPart[0])) {
                        isEntity = true;
                        break;
                    }
                }
                if (isEntity) {
                    // plugin.getLogger().info("DEBUG: Item " +
                    // sPart[0].toUpperCase() + " is an entity");
                    EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase());
                    if (entityType != null) {
                        neededEntities.put(entityType, qty);
                        // plugin.getLogger().info("DEBUG: Needed entity is "
                        // + Integer.parseInt(sPart[1]) + " x " +
                        // EntityType.valueOf(sPart[0].toUpperCase()).toString());
                    }
                } else {
                    Material item;
                    if (StringUtils.isNumeric(sPart[0])) {
                        item = Material.getMaterial(Integer.parseInt(sPart[0]));
                    } else {
                        item = Material.getMaterial(sPart[0].toUpperCase());
                    }
                    if (item != null) {
                        neededItem.put(item, qty);
                        // plugin.getLogger().info("DEBUG: Needed item is "
                        // + Integer.parseInt(sPart[1]) + " x " +
                        // Material.getMaterial(sPart[0]).toString());

                    } else {
                        plugin.getLogger().warning("Problem parsing required item for challenge " + challenge
                                + " in challenges.yml!");
                        return false;
                    }
                }
            } catch (Exception intEx) {
                plugin.getLogger().warning("Problem parsing required items for challenge " + challenge
                        + " in challenges.yml - skipping");
                return false;
            }

        }
        // We now have two sets of required items or entities
        // Check the items first
        final Location l = player.getLocation();
        // if (!neededItem.isEmpty()) {
        final int px = l.getBlockX();
        final int py = l.getBlockY();
        final int pz = l.getBlockZ();
        // Get search radius - min is 10, max is 50
        int searchRadius = getChallengeConfig()
                .getInt("challenges.challengeList." + challenge + ".searchRadius", 10);
        if (searchRadius < 10) {
            searchRadius = 10;
        } else if (searchRadius > 50) {
            searchRadius = 50;
        }
        for (int x = -searchRadius; x <= searchRadius; x++) {
            for (int y = -searchRadius; y <= searchRadius; y++) {
                for (int z = -searchRadius; z <= searchRadius; z++) {
                    final Material b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getType();
                    if (neededItem.containsKey(b)) {
                        if (neededItem.get(b) == 1) {
                            neededItem.remove(b);
                        } else {
                            // Reduce the require amount by 1
                            neededItem.put(b, neededItem.get(b) - 1);
                        }
                    }
                }
            }
        }
        // }
        // Check if all the needed items have been amassed
        if (!neededItem.isEmpty()) {
            // plugin.getLogger().info("DEBUG: Insufficient items around");
            for (Material missing : neededItem.keySet()) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " "
                                + neededItem.get(missing) + " x " + Util.prettifyText(missing.toString()));
            }
            return false;
        } else {
            // plugin.getLogger().info("DEBUG: Items are there");
            // Check for needed entities
            for (Entity entity : player.getNearbyEntities(searchRadius, searchRadius, searchRadius)) {
                // plugin.getLogger().info("DEBUG: Entity found:" +
                // entity.getType().toString());
                if (neededEntities.containsKey(entity.getType())) {
                    // plugin.getLogger().info("DEBUG: Entity in list");
                    if (neededEntities.get(entity.getType()) == 1) {
                        neededEntities.remove(entity.getType());
                        // plugin.getLogger().info("DEBUG: Entity qty satisfied");
                    } else {
                        neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1);
                        // plugin.getLogger().info("DEBUG: Entity qty reduced by 1");
                    }
                } else {
                    // plugin.getLogger().info("DEBUG: Entity not in list");
                }
            }
            if (neededEntities.isEmpty()) {
                return true;
            } else {
                for (EntityType missing : neededEntities.keySet()) {
                    player.sendMessage(ChatColor.RED
                            + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " "
                            + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString()));
                }
                return false;
            }
        }
    }

    return true;
}

From source file:com.wasteofplastic.askyblock.commands.Challenges.java

/**
 * Checks if a player has enough for a challenge. Supports two types of
 * checks, inventory and island. Removes items if required.
 * /*from w  w w.  j  a v  a 2s  . c  o  m*/
 * @param player
 * @param challenge
 * @param type
 * @return true if the player has everything required
 */

public boolean hasRequired(final Player player, final String challenge, final String type) {
    // Check money
    double moneyReq = 0D;
    if (Settings.useEconomy) {
        moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney",
                0D);
        if (moneyReq > 0D) {
            if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems);
                String desc = ChatColor.translateAlternateColorCodes('&',
                        getChallengeConfig().getString("challenges.challengeList." + challenge + ".description")
                                .replace("[label]", Settings.ISLANDCOMMAND));
                List<String> result = new ArrayList<String>();
                if (desc.contains("|")) {
                    result.addAll(Arrays.asList(desc.split("\\|")));
                } else {
                    result.add(desc);
                }
                for (String line : result) {
                    player.sendMessage(ChatColor.RED + line);
                }
                return false;
            }
        }
    }
    final String reqList = getChallengeConfig()
            .getString("challenges.challengeList." + challenge + ".requiredItems");
    // The format of the requiredItems is as follows:
    // Material:Qty
    // or
    // Material:DamageModifier:Qty
    // This second one is so that items such as potions or variations on
    // standard items can be collected
    if (type.equalsIgnoreCase("inventory")) {
        List<ItemStack> toBeRemoved = new ArrayList<ItemStack>();
        Material reqItem;
        int reqAmount = 0;
        if (!reqList.isEmpty()) {
            for (final String s : reqList.split(" ")) {
                final String[] part = s.split(":");
                // Material:Qty
                if (part.length == 2) {
                    try {
                        // Correct some common mistakes
                        if (part[0].equalsIgnoreCase("potato")) {
                            part[0] = "POTATO_ITEM";
                        } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                            part[0] = "BREWING_STAND_ITEM";
                        } else if (part[0].equalsIgnoreCase("carrot")) {
                            part[0] = "CARROT_ITEM";
                        } else if (part[0].equalsIgnoreCase("cauldron")) {
                            part[0] = "CAULDRON_ITEM";
                        } else if (part[0].equalsIgnoreCase("skull")) {
                            part[0] = "SKULL_ITEM";
                        }
                        // TODO: add netherwart vs. netherstalk?
                        if (StringUtils.isNumeric(part[0])) {
                            reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                        } else {
                            reqItem = Material.getMaterial(part[0].toUpperCase());
                        }
                        reqAmount = Integer.parseInt(part[1]);
                        ItemStack item = new ItemStack(reqItem);
                        if (DEBUG) {
                            plugin.getLogger().info("DEBUG: required item = " + reqItem.toString());
                            plugin.getLogger().info("DEBUG: item amount = " + reqAmount);
                        }
                        if (!player.getInventory().contains(reqItem)) {
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: item not in inventory");
                            return false;
                        } else {
                            // check amount
                            int amount = 0;
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: Amount in inventory = "
                                        + player.getInventory().all(reqItem).size());
                            // Go through all the inventory and try to find
                            // enough required items
                            for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem)
                                    .entrySet()) {
                                // Get the item
                                ItemStack i = en.getValue();
                                // If the item is enchanted, skip - it doesn't count
                                if (!i.getEnchantments().isEmpty()) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: item has enchantment - doesn't count");
                                    continue;
                                }
                                // Map needs special handling because the
                                // durability increments every time a new one is
                                // made by the player
                                // TODO: if there are any other items that act
                                // in the same way, they need adding too...
                                if (i.getDurability() == 0
                                        || (reqItem == Material.MAP && i.getType() == Material.MAP)) {
                                    // Clear any naming, or lore etc.
                                    //i.setItemMeta(null);
                                    //player.getInventory().setItem(en.getKey(), i);
                                    // #1 item stack qty + amount is less than
                                    // required items - take all i
                                    // #2 item stack qty + amount = required
                                    // item -
                                    // take all
                                    // #3 item stack qty + amount > req items -
                                    // take
                                    // portion of i
                                    // amount += i.getAmount();
                                    if ((amount + i.getAmount()) < reqAmount) {
                                        // Remove all of this item stack - clone
                                        // otherwise it will keep a reference to
                                        // the
                                        // original
                                        toBeRemoved.add(i.clone());
                                        amount += i.getAmount();
                                        if (DEBUG)
                                            plugin.getLogger()
                                                    .info("DEBUG: amount is <= req Remove " + i.toString() + ":"
                                                            + i.getDurability() + " x " + i.getAmount());
                                    } else if ((amount + i.getAmount()) == reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger()
                                                    .info("DEBUG: amount is = req Remove " + i.toString() + ":"
                                                            + i.getDurability() + " x " + i.getAmount());
                                        toBeRemoved.add(i.clone());
                                        amount += i.getAmount();
                                        break;
                                    } else {
                                        // Remove a portion of this item
                                        if (DEBUG)
                                            plugin.getLogger()
                                                    .info("DEBUG: amount is > req Remove " + i.toString() + ":"
                                                            + i.getDurability() + " x " + i.getAmount());

                                        item.setAmount(reqAmount - amount);
                                        item.setDurability(i.getDurability());
                                        toBeRemoved.add(item);
                                        amount += i.getAmount();
                                        break;
                                    }
                                }
                            }
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: amount " + amount);
                            if (amount < reqAmount) {
                                return false;
                            }
                        }
                    } catch (Exception e) {
                        plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                        player.sendMessage(
                                ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                        String materialList = "";
                        boolean hint = false;
                        for (Material m : Material.values()) {
                            materialList += m.toString() + ",";
                            if (m.toString().contains(s.substring(0, 3).toUpperCase())) {
                                plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                                hint = true;
                            }
                        }
                        if (!hint) {
                            plugin.getLogger()
                                    .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:");
                            plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                        } else {
                            plugin.getLogger().severe("Correct challenges.yml with the correct material.");
                        }
                        return false;
                    }
                } else if (part.length == 3) {
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: Item with durability");
                    // This handles items with durability
                    // Correct some common mistakes
                    if (part[0].equalsIgnoreCase("potato")) {
                        part[0] = "POTATO_ITEM";
                    } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                        part[0] = "BREWING_STAND_ITEM";
                    } else if (part[0].equalsIgnoreCase("carrot")) {
                        part[0] = "CARROT_ITEM";
                    } else if (part[0].equalsIgnoreCase("cauldron")) {
                        part[0] = "CAULDRON_ITEM";
                    } else if (part[0].equalsIgnoreCase("skull")) {
                        part[0] = "SKULL_ITEM";
                    }
                    if (StringUtils.isNumeric(part[0])) {
                        reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                    } else {
                        reqItem = Material.getMaterial(part[0].toUpperCase());
                    }
                    reqAmount = Integer.parseInt(part[2]);
                    int reqDurability = Integer.parseInt(part[1]);
                    ItemStack item = new ItemStack(reqItem);

                    // Item
                    item.setDurability((short) reqDurability);
                    // check amount
                    int amount = 0;
                    // Go through all the inventory and try to find
                    // enough required items
                    for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem)
                            .entrySet()) {
                        // Get the item
                        ItemStack i = en.getValue();
                        if (i.hasItemMeta()) {
                            continue;
                        }
                        if (i.getDurability() == reqDurability) {
                            // Clear any naming, or lore etc.
                            //i.setItemMeta(null);
                            // player.getInventory().setItem(en.getKey(), i);
                            // #1 item stack qty + amount is less than
                            // required items - take all i
                            // #2 item stack qty + amount = required
                            // item -
                            // take all
                            // #3 item stack qty + amount > req items -
                            // take
                            // portion of i
                            // amount += i.getAmount();
                            if ((amount + i.getAmount()) < reqAmount) {
                                // Remove all of this item stack - clone
                                // otherwise it will keep a reference to
                                // the
                                // original
                                toBeRemoved.add(i.clone());
                                amount += i.getAmount();
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: amount is <= req Remove " + i.toString()
                                            + ":" + i.getDurability() + " x " + i.getAmount());
                            } else if ((amount + i.getAmount()) == reqAmount) {
                                toBeRemoved.add(i.clone());
                                amount += i.getAmount();
                                break;
                            } else {
                                // Remove a portion of this item
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: amount is > req Remove " + i.toString()
                                            + ":" + i.getDurability() + " x " + i.getAmount());

                                item.setAmount(reqAmount - amount);
                                item.setDurability(i.getDurability());
                                toBeRemoved.add(item);
                                amount += i.getAmount();
                                break;
                            }
                        }
                    }
                    if (DEBUG) {
                        plugin.getLogger().info("DEBUG: amount is " + amount);
                        plugin.getLogger().info("DEBUG: req amount is " + reqAmount);
                    }
                    if (amount < reqAmount) {
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: Failure! Insufficient amount of " + item.toString()
                                    + " required = " + reqAmount + " actual = " + amount);
                        return false;
                    }
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: before set amount " + item.toString() + ":"
                                + item.getDurability() + " x " + item.getAmount());

                } else if (part.length == 6 && part[0].contains("POTION")) {
                    // Run through player's inventory for the item
                    ItemStack[] playerInv = player.getInventory().getContents();
                    try {
                        reqAmount = Integer.parseInt(part[5]);
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: required amount is " + reqAmount);
                    } catch (Exception e) {
                        plugin.getLogger().severe("Could not parse the quantity of the potion item " + s);
                        return false;
                    }
                    int count = reqAmount;
                    for (ItemStack i : playerInv) {
                        // Catches all POTION, LINGERING_POTION and SPLASH_POTION
                        if (i != null && i.getType().toString().contains("POTION")) {
                            //plugin.getLogger().info("DEBUG:6 part potion check!");
                            // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
                            if (plugin.getServer().getVersion().contains("(MC: 1.8")
                                    || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                                // Test potion
                                Potion potion = Potion.fromItemStack(i);
                                PotionType potionType = potion.getType();
                                boolean match = true;
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: name check " + part[1]);
                                // Name check
                                if (potion != null && potionType != null && !part[1].isEmpty()) {
                                    // There is a name
                                    // Custom potions may not have names
                                    if (potionType.name() != null) {
                                        if (!part[1].equalsIgnoreCase(potionType.name())) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name does not match");
                                        } else {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name matches");
                                        }
                                    } else {
                                        plugin.getLogger().severe(
                                                "Potion type is unknown. Please pick from the following:");
                                        for (PotionType pt : PotionType.values()) {
                                            plugin.getLogger().severe(pt.name());
                                        }
                                        match = false;
                                    }
                                }
                                // Level check (upgraded)
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: level check " + part[2]);
                                if (!part[2].isEmpty()) {
                                    // There is a level declared - check it
                                    if (StringUtils.isNumeric(part[2])) {
                                        int level = Integer.valueOf(part[2]);
                                        if (level != potion.getLevel()) {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                            match = false;
                                        }
                                    }
                                }
                                // Extended check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: extended check " + part[3]);
                                if (!part[3].isEmpty()) {
                                    if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                    if (part[3].equalsIgnoreCase("NOTEXTENDED")
                                            && potion.hasExtendedDuration()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                }
                                // Splash check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                                if (!part[4].isEmpty()) {
                                    if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not splash");
                                    }
                                    if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no splash");
                                    }
                                }
                                // Quantity check
                                if (match) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: potion matches!");
                                    ItemStack removeItem = i.clone();
                                    if (removeItem.getAmount() > reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger().info(
                                                    "DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                        removeItem.setAmount(reqAmount);
                                    }
                                    count = count - removeItem.getAmount();
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: " + count + " left");
                                    toBeRemoved.add(removeItem);
                                }
                            } else {
                                // V1.9 and above
                                PotionMeta potionMeta = (PotionMeta) i.getItemMeta();
                                // If any of the settings above are missing, then any is okay
                                boolean match = true;
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: name check " + part[1]);
                                // Name check
                                if (!part[1].isEmpty()) {
                                    // There is a name
                                    if (PotionType.valueOf(part[1]) != null) {
                                        if (!potionMeta.getBasePotionData().getType().name()
                                                .equalsIgnoreCase(part[1])) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name does not match");
                                        } else {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name matches");
                                        }
                                    } else {
                                        plugin.getLogger().severe(
                                                "Potion type is unknown. Please pick from the following:");
                                        for (PotionType pt : PotionType.values()) {
                                            plugin.getLogger().severe(pt.name());
                                        }
                                        match = false;
                                    }
                                }
                                // Level check (upgraded)
                                // plugin.getLogger().info("DEBUG: level check " + part[2]);
                                if (!part[2].isEmpty()) {
                                    // There is a level declared - check it
                                    if (StringUtils.isNumeric(part[2])) {
                                        int level = Integer.valueOf(part[2]);
                                        if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                            match = false;
                                        }
                                        if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                        }
                                    }
                                }
                                // Extended check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: extended check " + part[3]);
                                if (!part[3].isEmpty()) {
                                    if (part[3].equalsIgnoreCase("EXTENDED")
                                            && !potionMeta.getBasePotionData().isExtended()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                    if (part[3].equalsIgnoreCase("NOTEXTENDED")
                                            && potionMeta.getBasePotionData().isExtended()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                }
                                // Splash or Linger check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                                if (!part[4].isEmpty()) {
                                    if (part[4].equalsIgnoreCase("SPLASH")
                                            && !i.getType().equals(Material.SPLASH_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not splash");
                                    }
                                    if (part[4].equalsIgnoreCase("NOSPLASH")
                                            && i.getType().equals(Material.SPLASH_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no splash");
                                    }
                                    if (part[4].equalsIgnoreCase("LINGER")
                                            && !i.getType().equals(Material.LINGERING_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not linger");
                                    }
                                    if (part[4].equalsIgnoreCase("NOLINGER")
                                            && i.getType().equals(Material.LINGERING_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no linger");
                                    }
                                }
                                // Quantity check
                                if (match) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: potion matches!");
                                    ItemStack removeItem = i.clone();
                                    if (removeItem.getAmount() > reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger().info(
                                                    "DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                        removeItem.setAmount(reqAmount);
                                    }
                                    count = count - removeItem.getAmount();
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: " + count + " left");
                                    toBeRemoved.add(removeItem);
                                }
                            }
                        }
                        if (count <= 0) {
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: Player has enough");
                            break;
                        }
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: still need " + count + " to complete");
                    }
                    if (count > 0) {
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: Player does not have enough");
                        return false;
                    }

                } else {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    return false;
                }
            }
        }
        // Build up the items in the inventory and remove them if they are
        // all there.

        if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) {
            // checkChallengeItems(player, challenge);
            // int qty = 0;
            if (DEBUG)
                plugin.getLogger().info("DEBUG: Removing items");
            for (ItemStack i : toBeRemoved) {
                // qty += i.getAmount();
                if (DEBUG)
                    plugin.getLogger().info(
                            "DEBUG: Remove " + i.toString() + "::" + i.getDurability() + " x " + i.getAmount());
                HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i);
                if (!leftOver.isEmpty()) {
                    plugin.getLogger().warning("Exploit? Could not remove the following in challenge "
                            + challenge + " for player " + player.getName() + ":");
                    for (ItemStack left : leftOver.values()) {
                        plugin.getLogger().info(left.toString());
                    }
                    return false;
                }
            }
            // Remove money
            if (moneyReq > 0D) {
                EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq);
                if (!er.transactionSuccess()) {
                    plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq)
                            + " from " + player.getName() + " in challenge " + challenge);
                    plugin.getLogger().warning("Player's balance is "
                            + VaultHelper.econ.format(VaultHelper.econ.getBalance(player)));
                }
            }
            // plugin.getLogger().info("DEBUG: total = " + qty);
        }
        return true;
    }
    if (type.equalsIgnoreCase("island")) {
        final HashMap<Material, Integer> neededItem = new HashMap<Material, Integer>();
        final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>();
        if (!reqList.isEmpty()) {
            for (int i = 0; i < reqList.split(" ").length; i++) {
                final String[] sPart = reqList.split(" ")[i].split(":");
                // Parse the qty required first
                try {
                    final int qty = Integer.parseInt(sPart[1]);
                    // Find out if the needed item is a Material or an Entity
                    boolean isEntity = false;
                    for (EntityType entityType : EntityType.values()) {
                        if (entityType.toString().equalsIgnoreCase(sPart[0])) {
                            isEntity = true;
                            break;
                        }
                    }
                    if (isEntity) {
                        // plugin.getLogger().info("DEBUG: Item " +
                        // sPart[0].toUpperCase() + " is an entity");
                        EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase());
                        if (entityType != null) {
                            neededEntities.put(entityType, qty);
                            // plugin.getLogger().info("DEBUG: Needed entity is "
                            // + Integer.parseInt(sPart[1]) + " x " +
                            // EntityType.valueOf(sPart[0].toUpperCase()).toString());
                        }
                    } else {
                        Material item;
                        if (StringUtils.isNumeric(sPart[0])) {
                            item = Material.getMaterial(Integer.parseInt(sPart[0]));
                        } else {
                            item = Material.getMaterial(sPart[0].toUpperCase());
                        }
                        if (item != null) {
                            neededItem.put(item, qty);
                            // plugin.getLogger().info("DEBUG: Needed item is "
                            // + Integer.parseInt(sPart[1]) + " x " +
                            // Material.getMaterial(sPart[0]).toString());

                        } else {
                            plugin.getLogger().warning("Problem parsing required item for challenge "
                                    + challenge + " in challenges.yml!");
                            return false;
                        }
                    }
                } catch (Exception intEx) {
                    plugin.getLogger().warning("Problem parsing required items for challenge " + challenge
                            + " in challenges.yml - skipping");
                    return false;
                }
            }
        }
        // We now have two sets of required items or entities
        // Check the items first
        final Location l = player.getLocation();
        // if (!neededItem.isEmpty()) {
        final int px = l.getBlockX();
        final int py = l.getBlockY();
        final int pz = l.getBlockZ();
        // Get search radius - min is 10, max is 50
        int searchRadius = getChallengeConfig()
                .getInt("challenges.challengeList." + challenge + ".searchRadius", 10);
        if (searchRadius < 10) {
            searchRadius = 10;
        } else if (searchRadius > 50) {
            searchRadius = 50;
        }
        for (int x = -searchRadius; x <= searchRadius; x++) {
            for (int y = -searchRadius; y <= searchRadius; y++) {
                for (int z = -searchRadius; z <= searchRadius; z++) {
                    final Material b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getType();
                    if (neededItem.containsKey(b)) {
                        if (neededItem.get(b) == 1) {
                            neededItem.remove(b);
                        } else {
                            // Reduce the require amount by 1
                            neededItem.put(b, neededItem.get(b) - 1);
                        }
                    }
                }
            }
        }
        // }
        // Check if all the needed items have been amassed
        if (!neededItem.isEmpty()) {
            // plugin.getLogger().info("DEBUG: Insufficient items around");
            for (Material missing : neededItem.keySet()) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " "
                                + neededItem.get(missing) + " x " + Util.prettifyText(missing.toString()));
            }
            return false;
        } else {
            // plugin.getLogger().info("DEBUG: Items are there");
            // Check for needed entities
            for (Entity entity : player.getNearbyEntities(searchRadius, searchRadius, searchRadius)) {
                // plugin.getLogger().info("DEBUG: Entity found:" +
                // entity.getType().toString());
                if (neededEntities.containsKey(entity.getType())) {
                    // plugin.getLogger().info("DEBUG: Entity in list");
                    if (neededEntities.get(entity.getType()) == 1) {
                        neededEntities.remove(entity.getType());
                        // plugin.getLogger().info("DEBUG: Entity qty satisfied");
                    } else {
                        neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1);
                        // plugin.getLogger().info("DEBUG: Entity qty reduced by 1");
                    }
                } else {
                    // plugin.getLogger().info("DEBUG: Entity not in list");
                }
            }
            if (neededEntities.isEmpty()) {
                return true;
            } else {
                for (EntityType missing : neededEntities.keySet()) {
                    player.sendMessage(ChatColor.RED
                            + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " "
                            + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString()));
                }
                return false;
            }
        }
    }

    return true;
}

From source file:org.apache.hadoop.dfs.FSNamesystem.java

/**
 * We want "replication" replicates for the block, but we now have too many.  
 * In this method, copy enough nodes from 'srcNodes' into 'dstNodes' such that:
 *
 * srcNodes.size() - dstNodes.size() == replication
 *
 * We pick node that make sure that replicas are spread across racks and
 * also try hard to pick one with least free space.
 * The algorithm is first to pick a node with least free space from nodes
 * that are on a rack holding more than one replicas of the block.
 * So removing such a replica won't remove a rack. 
 * If no such a node is available,/*from w w  w .j a  v a2  s.co m*/
 * then pick a node with least free space
 */
void chooseExcessReplicates(Collection<DatanodeDescriptor> nonExcess, Block b, short replication,
        DatanodeDescriptor addedNode, DatanodeDescriptor delNodeHint) {
    // first form a rack to datanodes map and
    HashMap<String, ArrayList<DatanodeDescriptor>> rackMap = new HashMap<String, ArrayList<DatanodeDescriptor>>();
    for (Iterator<DatanodeDescriptor> iter = nonExcess.iterator(); iter.hasNext();) {
        DatanodeDescriptor node = iter.next();
        String rackName = node.getNetworkLocation();
        ArrayList<DatanodeDescriptor> datanodeList = rackMap.get(rackName);
        if (datanodeList == null) {
            datanodeList = new ArrayList<DatanodeDescriptor>();
        }
        datanodeList.add(node);
        rackMap.put(rackName, datanodeList);
    }

    // split nodes into two sets
    // priSet contains nodes on rack with more than one replica
    // remains contains the remaining nodes
    ArrayList<DatanodeDescriptor> priSet = new ArrayList<DatanodeDescriptor>();
    ArrayList<DatanodeDescriptor> remains = new ArrayList<DatanodeDescriptor>();
    for (Iterator<Entry<String, ArrayList<DatanodeDescriptor>>> iter = rackMap.entrySet().iterator(); iter
            .hasNext();) {
        Entry<String, ArrayList<DatanodeDescriptor>> rackEntry = iter.next();
        ArrayList<DatanodeDescriptor> datanodeList = rackEntry.getValue();
        if (datanodeList.size() == 1) {
            remains.add(datanodeList.get(0));
        } else {
            priSet.addAll(datanodeList);
        }
    }

    // pick one node to delete that favors the delete hint
    // otherwise pick one with least space from priSet if it is not empty
    // otherwise one node with least space from remains
    boolean firstOne = true;
    while (nonExcess.size() - replication > 0) {
        DatanodeInfo cur = null;
        long minSpace = Long.MAX_VALUE;

        // check if we can del delNodeHint
        if (firstOne && delNodeHint != null && nonExcess.contains(delNodeHint)
                && (priSet.contains(delNodeHint) || (addedNode != null && !priSet.contains(addedNode)))) {
            cur = delNodeHint;
        } else { // regular excessive replica removal
            Iterator<DatanodeDescriptor> iter = priSet.isEmpty() ? remains.iterator() : priSet.iterator();
            while (iter.hasNext()) {
                DatanodeDescriptor node = iter.next();
                long free = node.getRemaining();

                if (minSpace > free) {
                    minSpace = free;
                    cur = node;
                }
            }
        }

        firstOne = false;
        // adjust rackmap, priSet, and remains
        String rack = cur.getNetworkLocation();
        ArrayList<DatanodeDescriptor> datanodes = rackMap.get(rack);
        datanodes.remove(cur);
        if (datanodes.isEmpty()) {
            rackMap.remove(rack);
        }
        if (priSet.remove(cur)) {
            if (datanodes.size() == 1) {
                priSet.remove(datanodes.get(0));
                remains.add(datanodes.get(0));
            }
        } else {
            remains.remove(cur);
        }

        nonExcess.remove(cur);

        Collection<Block> excessBlocks = excessReplicateMap.get(cur.getStorageID());
        if (excessBlocks == null) {
            excessBlocks = new TreeSet<Block>();
            excessReplicateMap.put(cur.getStorageID(), excessBlocks);
        }
        excessBlocks.add(b);
        NameNode.stateChangeLog.debug("BLOCK* NameSystem.chooseExcessReplicates: " + "(" + cur.getName() + ", "
                + b + ") is added to excessReplicateMap");

        //
        // The 'excessblocks' tracks blocks until we get confirmation
        // that the datanode has deleted them; the only way we remove them
        // is when we get a "removeBlock" message.  
        //
        // The 'invalidate' list is used to inform the datanode the block 
        // should be deleted.  Items are removed from the invalidate list
        // upon giving instructions to the namenode.
        //
        addToInvalidatesNoLog(b, cur);
        NameNode.stateChangeLog.info("BLOCK* NameSystem.chooseExcessReplicates: " + "(" + cur.getName() + ", "
                + b + ") is added to recentInvalidateSets");
    }
}

From source file:org.telegram.android.MessagesController.java

public void sendTyping(final long dialog_id, final int action, int classGuid) {
    if (dialog_id == 0) {
        return;//  w w w .ja  v a  2  s.c  om
    }
    HashMap<Long, Boolean> typings = sendingTypings.get(action);
    if (typings != null && typings.get(dialog_id) != null) {
        return;
    }
    if (typings == null) {
        typings = new HashMap<>();
        sendingTypings.put(action, typings);
    }
    int lower_part = (int) dialog_id;
    int high_id = (int) (dialog_id >> 32);
    if (lower_part != 0) {
        if (high_id == 1) {
            return;
        }

        TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping();
        if (lower_part < 0) {
            req.peer = new TLRPC.TL_inputPeerChat();
            req.peer.chat_id = -lower_part;
        } else {
            TLRPC.User user = getUser(lower_part);
            if (user != null) {
                if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {
                    req.peer = new TLRPC.TL_inputPeerForeign();
                    req.peer.user_id = user.id;
                    req.peer.access_hash = user.access_hash;
                } else {
                    req.peer = new TLRPC.TL_inputPeerContact();
                    req.peer.user_id = user.id;
                }
            } else {
                return;
            }
        }
        if (action == 0) {
            req.action = new TLRPC.TL_sendMessageTypingAction();
        } else if (action == 1) {
            req.action = new TLRPC.TL_sendMessageRecordAudioAction();
        } else if (action == 2) {
            req.action = new TLRPC.TL_sendMessageCancelAction();
        } else if (action == 3) {
            req.action = new TLRPC.TL_sendMessageUploadDocumentAction();
        } else if (action == 4) {
            req.action = new TLRPC.TL_sendMessageUploadPhotoAction();
        } else if (action == 5) {
            req.action = new TLRPC.TL_sendMessageUploadVideoAction();
        }
        typings.put(dialog_id, true);
        long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        HashMap<Long, Boolean> typings = sendingTypings.get(action);
                        if (typings != null) {
                            typings.remove(dialog_id);
                        }
                    }
                });
            }
        }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
        if (classGuid != 0) {
            ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
        }
    } else {
        if (action != 0) {
            return;
        }
        TLRPC.EncryptedChat chat = getEncryptedChat(high_id);
        if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) {
            TLRPC.TL_messages_setEncryptedTyping req = new TLRPC.TL_messages_setEncryptedTyping();
            req.peer = new TLRPC.TL_inputEncryptedChat();
            req.peer.chat_id = chat.id;
            req.peer.access_hash = chat.access_hash;
            req.typing = true;
            typings.put(dialog_id, true);
            long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
                @Override
                public void run(TLObject response, TLRPC.TL_error error) {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            HashMap<Long, Boolean> typings = sendingTypings.get(action);
                            if (typings != null) {
                                typings.remove(dialog_id);
                            }
                        }
                    });
                }
            }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
            if (classGuid != 0) {
                ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
            }
        }
    }
}

From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java

private HashMap reshuffleErrorGroupNamesKK(HashMap errors, List<DisplayItemWithGroupBean> allItems,
        HttpServletRequest request) {/*from   w  w  w . j a va2s . c om*/
    int manualRows = 0;
    if (errors == null || errors.size() < 1) {
        return errors;
    }
    for (int i = 0; i < allItems.size(); i++) {
        DisplayItemWithGroupBean diwb = allItems.get(i);

        if (diwb.isInGroup()) {
            List<DisplayItemGroupBean> dgbs = diwb.getItemGroups();
            for (int j = 0; j < dgbs.size(); j++) {
                DisplayItemGroupBean digb = dgbs.get(j);

                ItemGroupBean igb = digb.getItemGroupBean();
                List<DisplayItemBean> dibs = digb.getItems();

                if (j == 0) { // first repeat
                    for (DisplayItemBean dib : dibs) {
                        String intendedKey = digb.getInputId() + getInputName(dib);
                        String replacementKey = digb.getItemGroupBean().getOid() + "_" + j + getInputName(dib);
                        if (!replacementKey.equals(intendedKey) && errors.containsKey(intendedKey)) {
                            // String errorMessage = (String)errors.get(intendedKey);
                            errors.put(replacementKey, errors.get(intendedKey));
                            errors.remove(intendedKey);
                            LOGGER.debug(
                                    "removing: " + intendedKey + " and replacing it with " + replacementKey);
                        }
                    }
                }

                else { // everything in between
                    manualRows++;
                    for (DisplayItemBean dib : dibs) {
                        String intendedKey = digb.getInputId() + getInputName(dib);
                        String replacementKey = digb.getItemGroupBean().getOid() + "_manual" + j
                                + getInputName(dib);
                        if (!replacementKey.equals(intendedKey) && errors.containsKey(intendedKey)) {
                            // String errorMessage = (String)errors.get(intendedKey);
                            errors.put(replacementKey, errors.get(intendedKey));
                            errors.remove(intendedKey);
                            LOGGER.debug(
                                    "removing: " + intendedKey + " and replacing it with " + replacementKey);
                        }
                    }
                }
            }
        }
    }
    request.setAttribute("manualRows", new Integer(manualRows));
    return errors;
}

From source file:SeedGenerator.MainForm.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    try {//from w w w.j a  v  a2s . co  m
        PreparedStatement pstmtIDF = con.prepareStatement("SELECT * FROM crawler.recommender_comment_idf;");
        PreparedStatement pstmtTF = con.prepareStatement("SELECT * FROM crawler.recommender_comment_tf;");

        ResultSet rsIDF = pstmtIDF.executeQuery();
        ResultSet rsTF = pstmtTF.executeQuery();

        HashMap<String, Integer> tfCount = new HashMap();
        HashMap<String, Integer> idfCount = new HashMap();

        while (rsTF.next()) {
            String idword = String.valueOf(rsTF.getInt("endpointid")) + "-" + rsTF.getString("word");
            int count = rsTF.getInt("count");
            tfCount.put(idword, count);
        }
        while (rsIDF.next()) {
            String word = rsIDF.getString("word");
            int count = rsIDF.getInt("count");
            idfCount.put(word, count);
        }
        int idflimit = 100;

        HashMap<String, Integer> toberemoved = new HashMap();

        Iterator ittf = tfCount.entrySet().iterator();
        while (ittf.hasNext()) {
            Map.Entry pair = (Map.Entry) ittf.next();
            String idword = pair.getKey().toString();
            int count = Integer.parseInt(pair.getValue().toString());
            if (idfCount.get(idword.split("-")[1]) != null) {
                if (idfCount.get(idword.split("-")[1]) > idflimit || idfCount.get(idword.split("-")[1]) < 10
                        || count < 10) {
                    toberemoved.put(idword, 0);
                }
            }
        }

        Iterator itremove = toberemoved.entrySet().iterator();
        while (itremove.hasNext()) {
            Map.Entry pair = (Map.Entry) itremove.next();
            try {
                tfCount.remove(pair.getKey().toString());
            } catch (Exception ex) {

            }
        }

        Iterator itidf = idfCount.entrySet().iterator();
        try {
            PreparedStatement updatestmt = con.prepareStatement(
                    "update recommender_class_label_hypernym set tf=? where endpointid=? and word=?");
            int count = 0;
            while (ittf.hasNext()) {
                Map.Entry pair = (Map.Entry) ittf.next();
                //<>
                if (Integer.parseInt(pair.getValue().toString()) > 0) {
                    updatestmt.setInt(1, Integer.parseInt(pair.getValue().toString()));
                    updatestmt.setInt(2, Integer.parseInt(pair.getKey().toString().split("-")[0]));
                    updatestmt.setString(3, pair.getKey().toString().split("-")[1]);
                    updatestmt.addBatch();
                    count++;
                }
            }
            updatestmt.executeBatch();
        } catch (Exception ex) {
            System.out.println("tf update edilemedi");
        }
        try {
            PreparedStatement updatestmt = con
                    .prepareStatement("update recommender_class_label_hypernym set idf=? where word=?");

            while (itidf.hasNext()) {
                Map.Entry pair = (Map.Entry) itidf.next();
                //<>
                if (Integer.parseInt(pair.getValue().toString()) > 0) {
                    updatestmt.setInt(1, Integer.parseInt(pair.getValue().toString()));
                    updatestmt.setString(2, pair.getKey().toString());
                    updatestmt.addBatch();
                }
            }
            updatestmt.executeBatch();
        } catch (Exception ex) {
            System.out.println("tf update edilemedi");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    // TODO add your handling code here:

    // TODO add your handling code here:
}

From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java

private void reshuffleReasonForChangeHashAndDiscrepancyNotes(List<DisplayItemWithGroupBean> allItems,
        HttpServletRequest request, EventCRFBean ecb) {
    int manualRows = 0;
    HashMap<String, Boolean> noteSubmitted = (HashMap<String, Boolean>) request.getSession()
            .getAttribute(DataEntryServlet.NOTE_SUBMITTED);
    FormDiscrepancyNotes noteTree = (FormDiscrepancyNotes) request.getSession()
            .getAttribute(CreateDiscrepancyNoteServlet.FLAG_DISCREPANCY_RFC);

    ArrayList<DiscrepancyNoteBean> fieldNote = null;
    String intendedKey = null;/*from www.  java 2 s . c  om*/
    String replacementKey = null;

    if ((noteSubmitted == null || noteSubmitted.size() < 1)
            && (noteTree == null || noteTree.getFieldNotes() == null || noteTree.getFieldNotes().size() < 1)) {
        return;
    }

    for (int i = 0; i < allItems.size(); i++) {
        DisplayItemWithGroupBean diwb = allItems.get(i);

        if (diwb.isInGroup()) {
            List<DisplayItemGroupBean> dgbs = diwb.getItemGroups();
            for (int j = 0; j < dgbs.size(); j++) {
                DisplayItemGroupBean digb = dgbs.get(j);

                ItemGroupBean igb = digb.getItemGroupBean();
                List<DisplayItemBean> dibs = digb.getItems();

                if (j == 0) { // first repeat
                    for (DisplayItemBean dib : dibs) {
                        intendedKey = ecb.getId() + "_" + digb.getInputId() + getInputName(dib);
                        replacementKey = ecb.getId() + "_" + digb.getItemGroupBean().getOid() + "_" + j
                                + getInputName(dib);
                        if (!replacementKey.equals(intendedKey)) {
                            if (noteSubmitted.containsKey(intendedKey)) {

                                noteSubmitted.put(replacementKey, Boolean.TRUE);
                                noteSubmitted.remove(intendedKey);
                            }
                            if (noteTree.getNotes(intendedKey) != null) {
                                fieldNote = (ArrayList<DiscrepancyNoteBean>) noteTree.getNotes(intendedKey);
                                if (fieldNote != null && fieldNote.size() > 0) {
                                    noteTree.getFieldNotes().put(replacementKey, fieldNote);
                                    noteTree.getFieldNotes().remove(intendedKey);
                                }
                                //not changing here because this hash should not be used
                                //                                      noteTree.addIdNote(note.getEntityId(), field);
                                //
                            }
                        }
                    }
                }

                else { // everything in between
                    manualRows++;
                    for (DisplayItemBean dib : dibs) {
                        intendedKey = ecb.getId() + "_" + digb.getInputId() + getInputName(dib);
                        replacementKey = ecb.getId() + "_" + digb.getItemGroupBean().getOid() + "_manual" + (j)
                                + getInputName(dib);
                        if (!replacementKey.equals(intendedKey)) {
                            if (noteSubmitted != null && noteSubmitted.containsKey(intendedKey)) {

                                noteSubmitted.put(replacementKey, Boolean.TRUE);
                                noteSubmitted.remove(intendedKey);
                            }
                            if (noteTree != null && noteTree.getNotes(intendedKey) != null) {
                                fieldNote = (ArrayList<DiscrepancyNoteBean>) noteTree.getNotes(intendedKey);
                                if (fieldNote != null && fieldNote.size() > 0) {
                                    noteTree.getFieldNotes().put(replacementKey, fieldNote);
                                    noteTree.getFieldNotes().remove(intendedKey);
                                }
                            }
                        }
                    }
                }
                LOGGER.debug("removing: " + intendedKey + " and replacing it with " + replacementKey);

            }
        }
    }
    request.getSession().setAttribute(DataEntryServlet.NOTE_SUBMITTED, noteSubmitted);

}

From source file:org.gtdfree.model.GTDDataXMLTools.java

private static void _load_2_2(GTDModel model, XMLStreamReader r) throws XMLStreamException {

    HashMap<Integer, Action> withProject = new HashMap<Integer, Action>();
    HashMap<Integer, Action> queued = new HashMap<Integer, Action>();

    if (checkTagStart(r, "lists")) { //$NON-NLS-1$

        r.nextTag();// w w  w  . j  a va  2 s  . c o m
        while (checkTagStart(r, "list")) { //$NON-NLS-1$
            Folder ff;
            String id = r.getAttributeValue(null, "id"); //$NON-NLS-1$
            if (id != null) {
                ff = model.createFolder(Integer.parseInt(id), r.getAttributeValue(null, "name"), //$NON-NLS-1$
                        FolderType.valueOf(r.getAttributeValue(null, "type"))); //$NON-NLS-1$
            } else {
                String s = r.getAttributeValue(null, "type").replace("NOTE", "INBUCKET"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                ff = model.createFolder(r.getAttributeValue(null, "name"), FolderType.valueOf(s)); //$NON-NLS-1$
            }
            String s = r.getAttributeValue(null, "closed"); //$NON-NLS-1$
            if (s != null)
                ff.setClosed(Boolean.parseBoolean(s));

            s = StringEscapeUtils.unescapeJava(r.getAttributeValue(null, "description")); //$NON-NLS-1$

            if (!ff.isInBucket()) {
                ff.setDescription(s);
            }

            Date cr = null, mo = null, re = null;
            s = r.getAttributeValue(null, "created"); //$NON-NLS-1$
            if (s != null) {
                cr = new Date(Long.parseLong(s));
            }
            s = r.getAttributeValue(null, "modified"); //$NON-NLS-1$
            if (s != null) {
                mo = new Date(Long.parseLong(s));
            }
            s = r.getAttributeValue(null, "resolved"); //$NON-NLS-1$
            if (s != null) {
                re = new Date(Long.parseLong(s));
            }
            ff.setDates(cr, mo, re);

            r.nextTag();

            while (checkTagStart(r, "action")) { //$NON-NLS-1$
                int i = Integer.parseInt(r.getAttributeValue(null, "id")); //$NON-NLS-1$
                cr = new Date(Long.parseLong(r.getAttributeValue(null, "created"))); //$NON-NLS-1$
                re = r.getAttributeValue(null, "resolved") == null ? null //$NON-NLS-1$
                        : new Date(Long.parseLong(r.getAttributeValue(null, "resolved"))); //$NON-NLS-1$
                mo = r.getAttributeValue(null, "modified") == null ? null //$NON-NLS-1$
                        : new Date(Long.parseLong(r.getAttributeValue(null, "modified"))); //$NON-NLS-1$

                String d = StringEscapeUtils.unescapeJava(r.getAttributeValue(null, "description")); //$NON-NLS-1$

                Action a = new Action(i, cr, re, d, mo);

                s = r.getAttributeValue(null, "type"); //$NON-NLS-1$
                if (s != null)
                    a.setType(ActionType.valueOf(s));

                s = r.getAttributeValue(null, "url"); //$NON-NLS-1$
                if (s != null) {
                    try {
                        a.setUrl(new URL(s));
                    } catch (Exception e) {
                        Logger.getLogger(GTDDataXMLTools.class).debug("Internal error.", e); //$NON-NLS-1$
                    }
                }

                s = r.getAttributeValue(null, "start"); //$NON-NLS-1$
                if (s != null)
                    a.setStart(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "remind"); //$NON-NLS-1$
                if (s != null)
                    a.setRemind(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "due"); //$NON-NLS-1$
                if (s != null)
                    a.setDue(new Date(Long.parseLong(s)));

                s = r.getAttributeValue(null, "queued"); //$NON-NLS-1$
                if (s != null)
                    a.setQueued(Boolean.parseBoolean(s));

                s = r.getAttributeValue(null, "project"); //$NON-NLS-1$
                if (s != null)
                    a.setProject(Integer.parseInt(s));

                s = r.getAttributeValue(null, "priority"); //$NON-NLS-1$
                if (s != null)
                    a.setPriority(Priority.valueOf(s));

                a.setResolution(Action.Resolution.toResolution(r.getAttributeValue(null, "resolution"))); //$NON-NLS-1$

                ff.add(a);

                if (a.getProject() != null) {
                    withProject.put(a.getId(), a);
                }

                if (a.isQueued()) {
                    queued.put(a.getId(), a);
                }

                if (a.getId() > model.getLastActionID()) {
                    model.setLastActionID(a.getId());
                }

                findTagEnd(r, "action"); //$NON-NLS-1$
                r.nextTag();
            }

            findTagEnd(r, "list"); //$NON-NLS-1$
            r.nextTag();
        }
        findTagEnd(r, "lists"); //$NON-NLS-1$
        //r.nextTag();
    }

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }
    // read projects
    r.nextTag();

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    if (checkTagStart(r, "projects")) { //$NON-NLS-1$

        r.nextTag();
        while (checkTagStart(r, "project")) { //$NON-NLS-1$
            Project pp;
            String id = r.getAttributeValue(null, "id"); //$NON-NLS-1$
            if (id != null) {
                pp = (Project) model.createFolder(Integer.parseInt(id), r.getAttributeValue(null, "name"), //$NON-NLS-1$
                        FolderType.PROJECT);
            } else {
                pp = (Project) model.createFolder(r.getAttributeValue(null, "name"), FolderType.PROJECT); //$NON-NLS-1$
            }
            pp.setClosed(Boolean.parseBoolean(r.getAttributeValue(null, "closed"))); //$NON-NLS-1$
            pp.setGoal(r.getAttributeValue(null, "goal")); //$NON-NLS-1$

            String s = StringEscapeUtils.unescapeJava(r.getAttributeValue(null, "description")); //$NON-NLS-1$
            if (s != null) {
                pp.setDescription(s);
            }

            Date cr = null, mo = null, re = null;
            s = r.getAttributeValue(null, "created"); //$NON-NLS-1$
            if (s != null) {
                cr = new Date(Long.parseLong(s));
            }
            s = r.getAttributeValue(null, "modified"); //$NON-NLS-1$
            if (s != null) {
                mo = new Date(Long.parseLong(s));
            }
            s = r.getAttributeValue(null, "resolved"); //$NON-NLS-1$
            if (s != null) {
                re = new Date(Long.parseLong(s));
            }
            pp.setDates(cr, mo, re);

            s = r.getAttributeValue(null, "actions"); //$NON-NLS-1$

            if (s != null && s.trim().length() > 0) {
                String[] ss = s.trim().split(","); //$NON-NLS-1$
                for (int i = 0; i < ss.length; i++) {
                    if (ss[i].trim().length() > 0) {
                        int ii = Integer.parseInt(ss[i].trim());
                        Action a = withProject.remove(ii);
                        if (a != null) {
                            pp.add(a);
                        }
                    }
                }
            }
            r.nextTag();
            findTagEnd(r, "project"); //$NON-NLS-1$
            r.nextTag();
        }
        findTagEnd(r, "projects"); //$NON-NLS-1$
    }

    for (Action a : withProject.values()) {
        if (a.getProject() != null) {
            Project p = model.getProject(a.getProject());

            if (p != null) {
                p.add(a);
            } else {
                System.err.println("Project " + p + " in action " + a + " does not exsist."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                a.setProject(null);
            }
        }
    }

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    // read projects
    r.nextTag();

    if (r.getEventType() == XMLStreamReader.END_DOCUMENT) {
        return;
    }

    if (checkTagStart(r, "queue")) { //$NON-NLS-1$
        Folder f = model.getQueue();

        String s = r.getAttributeValue(null, "actions"); //$NON-NLS-1$

        if (s != null && s.trim().length() > 0) {
            String[] ss = s.trim().split(","); //$NON-NLS-1$
            for (int i = 0; i < ss.length; i++) {
                if (ss[i].trim().length() > 0) {
                    int ii = Integer.parseInt(ss[i].trim());
                    Action a = queued.remove(ii);
                    if (a != null) {
                        f.add(a);
                    }
                }
            }
        }
        r.nextTag();
        findTagEnd(r, "queue"); //$NON-NLS-1$
        r.nextTag();
    }

    for (Action a : queued.values()) {
        if (a.isQueued()) {
            System.err.println("Action " + a + " is queued but not in queue list."); //$NON-NLS-1$ //$NON-NLS-2$
            model.getQueue().add(a);
        }
    }

}