added file based categories

This commit is contained in:
mfnalex 2018-08-23 12:11:58 +02:00
parent 8489cf0e4b
commit ffe2ba8265
9 changed files with 376 additions and 127 deletions

View File

@ -16,3 +16,5 @@ commands:
permissions: permissions:
chestsort.use: chestsort.use:
description: Allows usage of automatic chest sorting description: Allows usage of automatic chest sorting
chestsort.reload:
description: Allows usage of /chestsort reload

View File

@ -0,0 +1,24 @@
package de.jeffclan.JeffChestSort;
public class JeffChestSortCategory {
public String name;
public String[] typeMatches;
public JeffChestSortCategory(String name, String[] typeMatches) {
this.name=name;
this.typeMatches = typeMatches;
}
public boolean matches(String itemname) {
for(String typeMatch : typeMatches) {
if(itemname.equalsIgnoreCase(typeMatch)) {
return true;
}
}
return false;
}
}

View File

@ -5,6 +5,8 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import net.md_5.bungee.api.ChatColor;
public class JeffChestSortCommandExecutor implements CommandExecutor { public class JeffChestSortCommandExecutor implements CommandExecutor {
JeffChestSortPlugin plugin; JeffChestSortPlugin plugin;
@ -17,6 +19,19 @@ public class JeffChestSortCommandExecutor implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] arg3) { public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] arg3) {
if (arg1.getName().equalsIgnoreCase("chestsort")) { if (arg1.getName().equalsIgnoreCase("chestsort")) {
if(arg3.length>0) {
if(arg3[0].equalsIgnoreCase("reload")) {
if(sender.hasPermission("chestsort.reload")) {
/* Reload Configuration */
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
sender.sendMessage(ChatColor.GOLD + "ChestSort " + ChatColor.GRAY + plugin.getDescription().getVersion() + " has been reloaded.");
return true;
}
}
}
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
sender.sendMessage(plugin.messages.MSG_PLAYERSONLY); sender.sendMessage(plugin.messages.MSG_PLAYERSONLY);
return true; return true;

View File

@ -1,148 +1,195 @@
package de.jeffclan.JeffChestSort; package de.jeffclan.JeffChestSort;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class JeffChestSortOrganizer { public class JeffChestSortOrganizer {
JeffChestSortPlugin plugin; JeffChestSortPlugin plugin;
String[] colors = { "white", "orange", "magenta", "light_blue", "light_gray", "yellow", "lime", "pink", "gray",
String[] colors = {"white","orange","magenta","light_blue","light_gray","yellow","lime","pink","gray","cyan","purple","blue","brown","green","red","black"}; "cyan", "purple", "blue", "brown", "green", "red", "black" };
String[] tools = {"pickaxe","axe","shovel","hoe","flint_and_steel"};
String[] loot = {"rotten_flesh","string","spider_eye"}; ArrayList<JeffChestSortCategory> categories = new ArrayList<JeffChestSortCategory>();
String[] loot = { "rotten_flesh", "string", "spider_eye", "gunpowder" };
String[] tools = { "_pickaxe", "_shovel", "_hoe", "flint_and_steel", "_axe" , "compass","fishing_rod","clock","shears","lead"};
String[] woodBlocks = { "_log", "_wood", "_planks", "acacia_", "oak_", "birch_", "jungle_", "dark_oak_",
"spruce_" };
String[] redstone = { "dispenser","note_block","sticky_piston","piston","tnt","lever","_pressure_plate","redstone", "_button","tripwire","trapped_chest","daylight_detector","hopper","dropper","observer","iron_trapdoor","iron_door","repeater","comparator","powered_rail","detector_rail","rail","activator_rail","minecart" };
String[] food = { "apple", "baked_potato", "beef", "beetroot", "beetroot_soup", "bread", "mushroom_stew",
"porkchop", "cooked_porkchop", "cod", "salmon", "cooked_cod", "cooked_salmon", "cake", "cookie",
"melon_slice", "dried_kelp", "cooked_beef", "chicken", "cooked_chicken", "carrot", "potato", "pumpkin_pie",
"rabbit", "cooked_rabbit", "rabbit_stew", "mutton", "cooked_mutton" };
String[] combat = { "turtle_helmet","bow","arrow","_sword","_helmet","_chestplate","_leggings","_boots","spectral_arrow","tipped_arrow","shield","totem_of_undying","trident"};
String[] plants = { "_sapling","_leaves","grass","fern","dead_bush","seagrass","sea_pickle","dandelion","poppy","blue_orchid","allium","azure_bluet","red_tulip","orange_tulip","white_tulip","pink_tulip","oxeye_daisy","brown_mushroom","red_mushroom","chorus_plant","chorus_flower","cactus","brown_mushroom_block","red_mushroom_block","mushroom_stem","vine","lily_pad","sunflower","lilac","rose_bush","peony","tall_grass","large_fern","_coral","flower_pot"};
public JeffChestSortOrganizer(JeffChestSortPlugin plugin) { public JeffChestSortOrganizer(JeffChestSortPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
//categories.add(new JeffChestSortCategory("tools", tools));
//categories.add(new JeffChestSortCategory("loot", loot));
//categories.add(new JeffChestSortCategory("wood_blocks", woodBlocks));
// Load Categories
File categoriesFolder = new File(plugin.getDataFolder().getAbsolutePath() + File.separator + "categories" + File.separator);
File[] listOfCategoryFiles = categoriesFolder.listFiles();
for (File file : listOfCategoryFiles) {
if (file.isFile()) {
String categoryName = file.getName().replaceFirst(".txt", "");
try {
categories.add(new JeffChestSortCategory(categoryName,getArrayFromCategoryFile(file)));
plugin.getLogger().info("Loaded category file "+file.getName());
} catch (FileNotFoundException e) {
plugin.getLogger().warning("Could not load category file: "+file.getName());
//e.printStackTrace();
}
}
}
} }
String[] getArrayFromCategoryFile(File file) throws FileNotFoundException {
Scanner sc = new Scanner(file);
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
sc.close();
return arr;
}
String[] getTypeAndColor(String typeName) { String[] getTypeAndColor(String typeName) {
String myColor = "<none>"; String myColor = "<none>";
typeName = typeName.toLowerCase(); typeName = typeName.toLowerCase();
for (String color : colors) {
for(String color : colors) { if (typeName.startsWith(color)) {
if(typeName.startsWith(color)) {
typeName = typeName.replaceFirst(color + "_", ""); typeName = typeName.replaceFirst(color + "_", "");
myColor = color; myColor = color;
} }
} }
// Wool (sort by color) // Wool (sort by color)
/*if(typeName.endsWith("_wool")) { /*
* if(typeName.endsWith("_wool")) {
typeName = typeName.replaceFirst("_wool", ""); *
return "wool_" + typeName; * typeName = typeName.replaceFirst("_wool", ""); return "wool_" + typeName; } }
} */
}*/
String[] typeAndColor = new String[2]; String[] typeAndColor = new String[2];
typeAndColor[0] = typeName; typeAndColor[0] = typeName;
typeAndColor[1] = myColor; typeAndColor[1] = myColor;
return typeAndColor; return typeAndColor;
} }
String getCategory(String typeName) { String getCategory(String typeName) {
typeName = typeName.toLowerCase(); typeName = typeName.toLowerCase();
for (String pattern : tools) { for (JeffChestSortCategory cat : categories) {
if(typeName.contains(pattern)) { if (cat.matches(typeName)) {
return "tools"; return cat.name;
}
}
for(String pattern : loot) {
if(typeName.contains(pattern)) {
return "loot";
} }
} }
return "<none>"; return "<none>";
} }
String getSortableString(ItemStack item) { String getSortableString(ItemStack item) {
char blocksFirst; char blocksFirst;
char itemsFirst; char itemsFirst;
if(item.getType().isBlock()) { if (item.getType().isBlock()) {
blocksFirst='!'; blocksFirst = '!';
itemsFirst='#'; itemsFirst = '#';
if(plugin.debug) System.out.println(item.getType().name() + " is a block."); if (plugin.debug)
} else { System.out.println(item.getType().name() + " is a block.");
blocksFirst='#'; } else {
itemsFirst='!'; blocksFirst = '#';
if(plugin.debug) System.out.println(item.getType().name() + " is an item."); itemsFirst = '!';
} if (plugin.debug)
System.out.println(item.getType().name() + " is an item.");
String[] typeAndColor = getTypeAndColor(item.getType().name()); }
String typeName = typeAndColor[0];
String color = typeAndColor[1];
String category = getCategory(item.getType().name());
String hashCode = String.valueOf(item.hashCode());
String sortableString = plugin.sortingMethod.replaceAll("\\{itemsFirst\\}", String.valueOf(itemsFirst)); String[] typeAndColor = getTypeAndColor(item.getType().name());
sortableString = sortableString.replaceAll("\\{blocksFirst\\}", String.valueOf(blocksFirst)); String typeName = typeAndColor[0];
sortableString = sortableString.replaceAll("\\{name\\}", typeName); String color = typeAndColor[1];
sortableString = sortableString.replaceAll("\\{color\\}", color); String category = getCategory(item.getType().name());
sortableString = sortableString.replaceAll("\\{category\\}", category);
sortableString = sortableString + "," + hashCode;
return sortableString; String hashCode = String.valueOf(item.hashCode());
} String sortableString = plugin.sortingMethod.replaceAll("\\{itemsFirst\\}", String.valueOf(itemsFirst));
sortableString = sortableString.replaceAll("\\{blocksFirst\\}", String.valueOf(blocksFirst));
sortableString = sortableString.replaceAll("\\{name\\}", typeName);
sortableString = sortableString.replaceAll("\\{color\\}", color);
sortableString = sortableString.replaceAll("\\{category\\}", category);
sortableString = sortableString + "," + hashCode;
void sortInventory(Inventory inv) { return sortableString;
ItemStack[] items = inv.getContents();
inv.clear();
String[] itemList = new String[inv.getSize()];
int i = 0; }
for (ItemStack item : items) {
if (item != null) {
itemList[i] = getSortableString(item);
if(plugin.debug) System.out.println(itemList[i]);
i++;
}
}
// count all items that are not null void sortInventory(Inventory inv) {
int count = 0; ItemStack[] items = inv.getContents();
for (String s : itemList) { inv.clear();
if (s != null) { String[] itemList = new String[inv.getSize()];
count++;
}
}
// create new array with just the size we need int i = 0;
String[] shortenedArray = new String[count]; for (ItemStack item : items) {
if (item != null) {
itemList[i] = getSortableString(item);
if (plugin.debug)
System.out.println(itemList[i]);
i++;
}
}
// fill new array with items // count all items that are not null
for (int j = 0; j < count; j++) { int count = 0;
shortenedArray[j] = itemList[j]; for (String s : itemList) {
} if (s != null) {
count++;
}
}
// sort array alphabetically // create new array with just the size we need
Arrays.sort(shortenedArray); String[] shortenedArray = new String[count];
// put everything back in the inventory // fill new array with items
for (String s : shortenedArray) { for (int j = 0; j < count; j++) {
// System.out.println(s); shortenedArray[j] = itemList[j];
for (ItemStack item : items) { }
if (item != null && s != null) {
if (item.hashCode() == Integer.parseInt(s.split(",")[s.split(",").length-1])) { // sort array alphabetically
inv.addItem(item); Arrays.sort(shortenedArray);
item = null;
s = null; // put everything back in the inventory
} for (String s : shortenedArray) {
} // System.out.println(s);
} for (ItemStack item : items) {
} if (item != null && s != null) {
} if (item.hashCode() == Integer.parseInt(s.split(",")[s.split(",").length - 1])) {
inv.addItem(item);
item = null;
s = null;
}
}
}
}
}
} }

View File

@ -1,15 +1,20 @@
package de.jeffclan.JeffChestSort; package de.jeffclan.JeffChestSort;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import de.jeffclan.utils.Utils;
public class JeffChestSortPlugin extends JavaPlugin { public class JeffChestSortPlugin extends JavaPlugin {
Map<String, JeffChestSortPlayerSetting> PerPlayerSettings = new HashMap<String, JeffChestSortPlayerSetting>(); Map<String, JeffChestSortPlayerSetting> PerPlayerSettings = new HashMap<String, JeffChestSortPlayerSetting>();
@ -19,36 +24,43 @@ public class JeffChestSortPlugin extends JavaPlugin {
String sortingMethod; String sortingMethod;
int currentConfigVersion = 4; int currentConfigVersion = 4;
boolean debug = false; boolean debug = false;
long updateCheckInterval = 86400; // in seconds. We check on startup and every 24 hours (if you never restart your
// server)
@Override @Override
public void onEnable() { public void onEnable() {
createConfig(); createConfig();
saveDefaultCategories();
messages = new JeffChestSortMessages(this); messages = new JeffChestSortMessages(this);
organizer = new JeffChestSortOrganizer(this); organizer = new JeffChestSortOrganizer(this);
updateChecker = new JeffChestSortUpdateChecker(this); updateChecker = new JeffChestSortUpdateChecker(this);
sortingMethod = getConfig().getString("sorting-method","{itemsFirst},{name},{color}"); sortingMethod = getConfig().getString("sorting-method", "{itemsFirst},{name},{color}");
getServer().getPluginManager().registerEvents(new JeffChestSortListener(this), this); getServer().getPluginManager().registerEvents(new JeffChestSortListener(this), this);
JeffChestSortCommandExecutor commandExecutor = new JeffChestSortCommandExecutor(this); JeffChestSortCommandExecutor commandExecutor = new JeffChestSortCommandExecutor(this);
this.getCommand("chestsort").setExecutor(commandExecutor); this.getCommand("chestsort").setExecutor(commandExecutor);
if(getConfig().getBoolean("check-for-updates",true)) {
updateChecker.checkForUpdate();
}
@SuppressWarnings("unused") @SuppressWarnings("unused")
Metrics metrics = new Metrics(this); Metrics metrics = new Metrics(this);
//metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () -> getServer().getBukkitVersion())); // metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () ->
// getServer().getBukkitVersion()));
metrics.addCustomChart(new Metrics.SimplePie("sorting_method", () -> sortingMethod)); metrics.addCustomChart(new Metrics.SimplePie("sorting_method", () -> sortingMethod));
metrics.addCustomChart(new Metrics.SimplePie("config_version", () -> Integer.toString(getConfig().getInt("config-version",0)))); metrics.addCustomChart(new Metrics.SimplePie("config_version",
metrics.addCustomChart(new Metrics.SimplePie("check_for_updates", () -> Boolean.toString(getConfig().getBoolean("check-for-updates",true)))); () -> Integer.toString(getConfig().getInt("config-version", 0))));
metrics.addCustomChart(new Metrics.SimplePie("show_message_when_using_chest", () -> Boolean.toString(getConfig().getBoolean("show-message-when-using-chest")))); metrics.addCustomChart(new Metrics.SimplePie("check_for_updates",
metrics.addCustomChart(new Metrics.SimplePie("show_message_again_after_logout", () -> Boolean.toString(getConfig().getBoolean("show-message-again-after-logout")))); () -> Boolean.toString(getConfig().getBoolean("check-for-updates", true))));
metrics.addCustomChart(new Metrics.SimplePie("sorting_enabled_by_default", () -> Boolean.toString(getConfig().getBoolean("sorting-enabled-by-default")))); metrics.addCustomChart(new Metrics.SimplePie("show_message_when_using_chest",
() -> Boolean.toString(getConfig().getBoolean("show-message-when-using-chest"))));
getLogger().info("Current sorting method: "+sortingMethod); metrics.addCustomChart(new Metrics.SimplePie("show_message_again_after_logout",
() -> Boolean.toString(getConfig().getBoolean("show-message-again-after-logout"))));
if(getConfig().getInt("config-version",0) != currentConfigVersion) { metrics.addCustomChart(new Metrics.SimplePie("sorting_enabled_by_default",
() -> Boolean.toString(getConfig().getBoolean("sorting-enabled-by-default"))));
getLogger().info("Current sorting method: " + sortingMethod);
if (getConfig().getInt("config-version", 0) != currentConfigVersion) {
getLogger().warning("========================================================"); getLogger().warning("========================================================");
getLogger().warning("YOU ARE USING AN OLD CONFIG FILE!"); getLogger().warning("YOU ARE USING AN OLD CONFIG FILE!");
getLogger().warning("This is not a problem, as ChestSort will just use the"); getLogger().warning("This is not a problem, as ChestSort will just use the");
@ -59,10 +71,63 @@ public class JeffChestSortPlugin extends JavaPlugin {
getLogger().warning("then insert your old changes into the new file."); getLogger().warning("then insert your old changes into the new file.");
getLogger().warning("========================================================"); getLogger().warning("========================================================");
} }
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
if (getConfig().getBoolean("check-for-updates", true)) {
updateChecker.checkForUpdate();
}
}
}, 0L, updateCheckInterval * 20);
} }
private void saveDefaultCategories() {
String[] defaultCategories = { "900-valuables","905-tools","910-food" };
for (String category : defaultCategories) {
getLogger().info("Trying to save default category file: " + category);
FileOutputStream fopDefault = null;
File fileDefault;
// String content = "This is the text content";
try {
InputStream in = getClass().getResourceAsStream("/de/jeffclan/utils/categories/" + category + ".default.txt");
// Reader fr = new InputStreamReader(in, "utf-8");
fileDefault = new File(getDataFolder().getAbsolutePath() + File.separator + "categories" + File.separator + category + ".txt");
fopDefault = new FileOutputStream(fileDefault);
// if file doesnt exists, then create it
//if (!fileDefault.getAbsoluteFile().exists()) {
fileDefault.createNewFile();
//}
// get the content in bytes
byte[] contentInBytes = Utils.getBytes(in);
fopDefault.write(contentInBytes);
fopDefault.flush();
fopDefault.close();
// System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fopDefault != null) {
fopDefault.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override @Override
public void onDisable() { public void onDisable() {
for (Player p : getServer().getOnlinePlayers()) { for (Player p : getServer().getOnlinePlayers()) {
@ -77,9 +142,14 @@ public class JeffChestSortPlugin extends JavaPlugin {
void createConfig() { void createConfig() {
this.saveDefaultConfig(); this.saveDefaultConfig();
File playerDataFolder = new File(getDataFolder().getPath() + File.separator + "playerdata"); File playerDataFolder = new File(getDataFolder().getPath() + File.separator + "playerdata");
if (!playerDataFolder.exists()) if (!playerDataFolder.exists()) {
playerDataFolder.mkdir(); playerDataFolder.mkdir();
}
File categoriesFolder = new File(getDataFolder().getPath() + File.separator + "categories");
if (!categoriesFolder.exists()) {
categoriesFolder.mkdir();
}
getConfig().addDefault("sorting-enabled-by-default", false); getConfig().addDefault("sorting-enabled-by-default", false);
getConfig().addDefault("show-message-when-using-chest", true); getConfig().addDefault("show-message-when-using-chest", true);
getConfig().addDefault("show-message-when-using-chest-and-sorting-is-enabled", false); getConfig().addDefault("show-message-when-using-chest-and-sorting-is-enabled", false);
@ -87,12 +157,11 @@ public class JeffChestSortPlugin extends JavaPlugin {
getConfig().addDefault("sorting-method", "{itemsFirst},{name},{color}"); getConfig().addDefault("sorting-method", "{itemsFirst},{name},{color}");
getConfig().addDefault("check-for-updates", true); getConfig().addDefault("check-for-updates", true);
} }
void unregisterPlayer(Player p) { void unregisterPlayer(Player p) {
UUID uniqueId = p.getUniqueId(); UUID uniqueId = p.getUniqueId();
if (PerPlayerSettings.containsKey(uniqueId.toString())) { if (PerPlayerSettings.containsKey(uniqueId.toString())) {
JeffChestSortPlayerSetting setting = PerPlayerSettings JeffChestSortPlayerSetting setting = PerPlayerSettings.get(p.getUniqueId().toString());
.get(p.getUniqueId().toString());
File playerFile = new File(getDataFolder() + File.separator + "playerdata", File playerFile = new File(getDataFolder() + File.separator + "playerdata",
p.getUniqueId().toString() + ".yml"); p.getUniqueId().toString() + ".yml");
YamlConfiguration playerConfig = YamlConfiguration.loadConfiguration(playerFile); YamlConfiguration playerConfig = YamlConfiguration.loadConfiguration(playerFile);

View File

@ -0,0 +1,30 @@
package de.jeffclan.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Utils {
public static byte[] getBytes(InputStream is) throws IOException {
int len;
int size = 1024;
byte[] buf;
if (is instanceof ByteArrayInputStream) {
size = is.available();
buf = new byte[size];
len = is.read(buf, 0, size);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buf = new byte[size];
while ((len = is.read(buf, 0, size)) != -1)
bos.write(buf, 0, len);
buf = bos.toByteArray();
}
return buf;
}
}

View File

@ -0,0 +1,8 @@
diamond
emerald
diamond_ore
emerald_ore
iron_ingot
iron_ore
gold_ingot
gold_ore

View File

@ -0,0 +1,26 @@
diamond_pickaxe
diamond_shovel
diamond_axe
diamond_hoe
iron_pickaxe
iron_shovel
iron_axe
iron_hoe
gold_pickaxe
gold_shovel
gold_axe
gold_hoe
stone_pickaxe
stone_shovel
stone_axe
stone_hoe
wooden_pickaxe
wooden_shovel
wooden_axe
wooden_hoe
flint_and_steel
fishing_rod
compass
clock
shears
lead

View File

@ -0,0 +1,28 @@
apple
baked_potato
beef
beetroot
beetroot_soup
bread
mushroom_stew
porkchop
cooked_porkchop
cod
salmon
cooked_cod
cooked_salmon
cake
cookie
melon_slice
dried_kelp
cooked_beef
chicken
cooked_chicken
carrot
potato
pumpkin_pie
rabbit
cooked_rabbit
rabbit_stew
mutton
cooked_mutton