Пример #1
0
 public static int grabPage(int current, String group, Direction direction) {
   // Calculate number of slots
   int slots = 0;
   int groupId = Karma.getGroupId(group);
   if (groupId == -1) {
     if (RootConfig.getBoolean(ConfigNode.DEBUG_INVENTORY)) {
       plugin.getLogger().warning("Tried to grabPage for invalid group: " + group);
     }
     return 1;
   }
   final Query all =
       plugin
           .getDatabaseHandler()
           .select("SELECT * FROM " + Table.ITEMS.getName() + " WHERE groups='" + groupId + "';");
   try {
     if (all.getResult().next()) {
       do {
         final int amount = all.getResult().getInt("amount");
         if (!all.getResult().wasNull()) {
           final ItemStack item = new ItemStack(all.getResult().getInt("itemid"), amount);
           if (item != null) {
             int maxStack = item.getType().getMaxStackSize();
             if (maxStack <= 0) {
               maxStack = 1;
             }
             int stacks = amount / maxStack;
             final double rem = (double) amount % (double) maxStack;
             if (rem != 0) {
               stacks++;
             }
             slots += stacks;
           }
         }
       } while (all.getResult().next());
     }
     all.closeQuery();
   } catch (SQLException e) {
     if (RootConfig.getBoolean(ConfigNode.DEBUG_INVENTORY)) {
       plugin
           .getLogger()
           .warning(
               "SQLException on grabPage("
                   + current
                   + ","
                   + group
                   + ","
                   + direction.toString()
                   + ")");
     }
     e.printStackTrace();
   }
   // if no slots, return 1
   if (slots <= 0) {
     return 1;
   }
   // Calculate pages
   int pageTotal = slots / chestSize;
   final double rem = (double) slots % (double) chestSize;
   if (rem != 0) {
     pageTotal++;
   }
   // Check against maximum
   if (current >= Integer.MAX_VALUE) {
     // Cycle back as we're at the max value for an integer
     return 1;
   }
   int page = current;
   switch (direction) {
     case FORWARD:
       {
         page++;
         break;
       }
     case BACKWARD:
       {
         page--;
         break;
       }
     default:
       {
         break;
       }
   }
   if (page <= 0) {
     // Was negative or zero, loop back to max page
     page = (pageTotal + 1);
   }
   // Allow for empty page
   else if (page > (pageTotal + 1)) {
     // Going to page beyond the total items, cycle back to
     // first
     page = 1;
   }
   if (RootConfig.getBoolean(ConfigNode.DEBUG_INVENTORY)) {
     plugin
         .getLogger()
         .info("grabPage(" + current + "," + group + "," + direction.toString() + ") : " + page);
   }
   return page;
 }
Пример #2
0
  private static void populateInventory(Inventory inventory, int page, String group) {
    try {
      int count = 0;
      int start = (page - 1) * chestSize;
      int groupId = Karma.getGroupId(group);
      if (groupId == -1) {
        if (RootConfig.getBoolean(ConfigNode.DEBUG_INVENTORY)) {
          plugin.getLogger().warning("Tried to populateInventory for invalid group: " + group);
        }
        return;
      }
      Query itemList =
          plugin
              .getDatabaseHandler()
              .select(
                  "SELECT * FROM " + Table.ITEMS.getName() + " WHERE groups='" + groupId + "';");
      if (itemList.getResult().next()) {
        boolean done = false;
        do {
          // Generate item
          int id = itemList.getResult().getInt("itemid");
          int amount = itemList.getResult().getInt("amount");
          byte data = itemList.getResult().getByte("data");
          short dur = itemList.getResult().getShort("durability");
          ItemStack item = null;
          if (Item.isTool(id)) {
            item = new ItemStack(id, amount, dur);
          } else {
            item = new ItemStack(id, amount, dur, data);
          }
          // Generate psudo item to calculate slots taken up
          int maxStack = item.getType().getMaxStackSize();
          if (maxStack <= 0) {
            maxStack = 1;
          }
          int stacks = amount / maxStack;
          final double rem = (double) amount % (double) maxStack;
          if (rem != 0) {
            stacks++;
          }
          for (int x = 0; x < stacks; x++) {
            ItemStack add = item.clone();
            if (amount < maxStack) {
              add.setAmount(amount);
            } else {
              add.setAmount(maxStack);
              amount -= maxStack;
            }

            if (count >= start) {
              Item meta = new Item(id, data, dur);
              try {
                // If tool
                if (meta.isTool()) {
                  // Check for enchantments
                  String enchantments = itemList.getResult().getString("enchantments");
                  if (!itemList.getResult().wasNull()) {
                    if (!enchantments.equals("")) {
                      String[] cut = enchantments.split("i");
                      for (int s = 0; s < cut.length; s++) {
                        String[] cutter = cut[s].split("v");
                        EnchantmentWrapper e = new EnchantmentWrapper(Integer.parseInt(cutter[0]));
                        add.addUnsafeEnchantment(e.getEnchantment(), Integer.parseInt(cutter[1]));
                      }
                    }
                  }
                  final HashMap<Integer, ItemStack> residual = inventory.addItem(add);
                  if (!residual.isEmpty()) {
                    done = true;
                  }
                } else if (meta.isPotion()) {
                  // Remove data for full potion compatibility
                  item = new ItemStack(id, amount, dur);
                  final HashMap<Integer, ItemStack> residual = inventory.addItem(add);
                  if (!residual.isEmpty()) {
                    done = true;
                  }
                } else {
                  final HashMap<Integer, ItemStack> residual = inventory.addItem(add);
                  if (!residual.isEmpty()) {
                    done = true;
                  }
                }
              } catch (NumberFormatException e) {
                // Ignore faulty item
              }
            }
            count++;
          }
        } while (itemList.getResult().next() && !done);
      } else {
        // No items to add.
        inventory.clear();
      }
      // Close select
      itemList.closeQuery();
    } catch (SQLException e) {
      if (RootConfig.getBoolean(ConfigNode.DEBUG_INVENTORY)) {
        plugin
            .getLogger()
            .warning(
                "SQLException on populateInventory("
                    + inventory.getName()
                    + ","
                    + page
                    + ","
                    + group
                    + ")");
      }
      e.printStackTrace();
    }
  }
Пример #3
0
 /**
  * Lists the items in the pool. Allows for pagination of the cache of items in pool.
  *
  * @param CommandSender of the "list" command so we know who we're outputting to
  * @param Integer of the page to change to, if needed. Zero shows current page.
  */
 @SuppressWarnings("unchecked")
 static void listPool(CommandSender sender, int pageAdjust) {
   String current = Karma.selectedGroup.get(sender.getName());
   if (current == null) {
     Karma.selectedGroup.put(sender.getName(), "global");
     current = "global";
   }
   final int groupId = Karma.getGroupId(current);
   if (groupId == -1) {
     return;
   }
   // Get list of items from database
   Query itemlist =
       plugin
           .getDatabaseHandler()
           .select("SELECT * FROM " + Table.ITEMS.getName() + " WHERE groups='" + groupId + "';");
   boolean empty = false;
   try {
     final Map<Item, Integer> cache = new LinkedHashMap<Item, Integer>();
     if (itemlist.getResult().next()) {
       // Add player to page hashmap, if they're not in it
       // so we know their position in the result list
       if (!Karma.page.containsKey(sender.getName())) {
         Karma.page.put(sender.getName(), 0);
       } else if (pageAdjust != 0) {
         // They already exist, so adjust if necessary
         int adj = Karma.page.get(sender.getName()).intValue() + pageAdjust;
         Karma.page.put(sender.getName(), adj);
       }
       // Clear cache
       cache.clear();
       do {
         // update cache with current result set
         Item i =
             new Item(
                 itemlist.getResult().getInt("itemid"),
                 itemlist.getResult().getByte("data"),
                 itemlist.getResult().getShort("durability"));
         if (i.isTool()) {
           // add to current amount
           int itemAmount = itemlist.getResult().getInt("amount");
           if (cache.containsKey(i)) {
             itemAmount += cache.get(i).intValue();
           }
           cache.put(i, itemAmount);
         } else {
           cache.put(i, itemlist.getResult().getInt("amount"));
         }
       } while (itemlist.getResult().next());
     } else {
       // No items in pool
       sender.sendMessage(ChatColor.RED + KarmicShare.TAG + " No items in pool.");
       // Clear hashmap (for memory reasons?)
       // considering no items, therefore no pages,
       // and thus no need to know what page a player is on
       Karma.page.clear();
       empty = true;
     }
     // Close query
     itemlist.closeQuery();
     if (!empty) {
       // Set hashmap to array
       Object[] array = cache.entrySet().toArray();
       boolean valid = true;
       // Caluclate amount of pages
       int num = array.length / RootConfig.getInt(ConfigNode.LIST_LIMIT);
       double rem = (double) array.length % (double) RootConfig.getInt(ConfigNode.LIST_LIMIT);
       if (rem != 0) {
         num++;
       }
       if (Karma.page.get(sender.getName()).intValue() < 0) {
         // They tried to use /ks prev when they're on page 0
         sender.sendMessage(ChatColor.YELLOW + KarmicShare.TAG + " Page does not exist");
         // reset their current page back to 0
         Karma.page.put(sender.getName(), 0);
         valid = false;
       } else if ((Karma.page.get(sender.getName()).intValue())
               * RootConfig.getInt(ConfigNode.LIST_LIMIT)
           > array.length) {
         // They tried to use /ks next at the end of the list
         sender.sendMessage(ChatColor.YELLOW + KarmicShare.TAG + " Page does not exist");
         // Revert to last page
         Karma.page.put(sender.getName(), num - 1);
         valid = false;
       }
       if (valid) {
         // Header with amount of pages
         sender.sendMessage(
             ChatColor.BLUE
                 + "==="
                 + ChatColor.GOLD
                 + current
                 + ChatColor.BLUE
                 + "==="
                 + ChatColor.GREEN
                 + "Page: "
                 + ((Karma.page.get(sender.getName()).intValue()) + 1)
                 + " of "
                 + num
                 + ChatColor.BLUE
                 + "===");
         // list
         for (int i =
                 ((Karma.page.get(sender.getName()).intValue())
                     * RootConfig.getInt(ConfigNode.LIST_LIMIT));
             i
                 < ((Karma.page.get(sender.getName()).intValue())
                         * RootConfig.getInt(ConfigNode.LIST_LIMIT))
                     + RootConfig.getInt(ConfigNode.LIST_LIMIT);
             i++) {
           // Don't try to pull something beyond the bounds
           if (i < array.length) {
             StringBuilder sb = new StringBuilder();
             sb.append(
                 ChatColor.WHITE
                     + "Item: "
                     + ChatColor.AQUA
                     // Thanks to DiddiZ for id -> material name
                     // using built-in class
                     + ((Map.Entry<Item, Integer>) array[i]).getKey().name);
             sb.append(
                 ChatColor.WHITE
                     + " Amount: "
                     + ChatColor.GOLD
                     + ((Map.Entry<Item, Integer>) array[i]).getValue());
             // sb.append(ChatColor.WHITE
             // + " ID: "
             // + ChatColor.LIGHT_PURPLE
             // + ((Map.Entry<Item, Integer>) array[i])
             // .getKey().itemId());
             // sb.append(ChatColor.WHITE + " Data: "
             // + ChatColor.LIGHT_PURPLE);
             // if (((Map.Entry<Item, Integer>)
             // array[i]).getKey()
             // .isPotion())
             // {
             // sb.append(((Map.Entry<Item, Integer>) array[i])
             // .getKey().itemDurability());
             // }
             // else
             // {
             // sb.append(((Map.Entry<Item, Integer>) array[i])
             // .getKey().itemData());
             // }
             sender.sendMessage(sb.toString());
           } else {
             break;
           }
         }
       }
     }
   } catch (SQLException e) {
     sender.sendMessage(ChatColor.RED + KarmicShare.TAG + "SQL error.");
     e.printStackTrace();
   } catch (NullPointerException n) {
     sender.sendMessage(ChatColor.RED + KarmicShare.TAG + " Error getting item list.");
     n.printStackTrace();
   }
 }