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:
chestsort.use:
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.entity.Player;
import net.md_5.bungee.api.ChatColor;
public class JeffChestSortCommandExecutor implements CommandExecutor {
JeffChestSortPlugin plugin;
@ -17,6 +19,19 @@ public class JeffChestSortCommandExecutor implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] arg3) {
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)) {
sender.sendMessage(plugin.messages.MSG_PLAYERSONLY);
return true;

View File

@ -1,148 +1,195 @@
package de.jeffclan.JeffChestSort;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class JeffChestSortOrganizer {
JeffChestSortPlugin plugin;
String[] colors = {"white","orange","magenta","light_blue","light_gray","yellow","lime","pink","gray","cyan","purple","blue","brown","green","red","black"};
String[] tools = {"pickaxe","axe","shovel","hoe","flint_and_steel"};
String[] loot = {"rotten_flesh","string","spider_eye"};
String[] colors = { "white", "orange", "magenta", "light_blue", "light_gray", "yellow", "lime", "pink", "gray",
"cyan", "purple", "blue", "brown", "green", "red", "black" };
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) {
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 myColor = "<none>";
typeName = typeName.toLowerCase();
for(String color : colors) {
if(typeName.startsWith(color)) {
for (String color : colors) {
if (typeName.startsWith(color)) {
typeName = typeName.replaceFirst(color + "_", "");
myColor = color;
}
}
// Wool (sort by color)
/*if(typeName.endsWith("_wool")) {
typeName = typeName.replaceFirst("_wool", "");
return "wool_" + typeName;
}
}*/
/*
* if(typeName.endsWith("_wool")) {
*
* typeName = typeName.replaceFirst("_wool", ""); return "wool_" + typeName; } }
*/
String[] typeAndColor = new String[2];
typeAndColor[0] = typeName;
typeAndColor[1] = myColor;
return typeAndColor;
}
String getCategory(String typeName) {
typeName = typeName.toLowerCase();
for (String pattern : tools) {
if(typeName.contains(pattern)) {
return "tools";
}
}
for(String pattern : loot) {
if(typeName.contains(pattern)) {
return "loot";
for (JeffChestSortCategory cat : categories) {
if (cat.matches(typeName)) {
return cat.name;
}
}
return "<none>";
}
String getSortableString(ItemStack item) {
char blocksFirst;
char itemsFirst;
if(item.getType().isBlock()) {
blocksFirst='!';
itemsFirst='#';
if(plugin.debug) System.out.println(item.getType().name() + " is a block.");
} else {
blocksFirst='#';
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 getSortableString(ItemStack item) {
char blocksFirst;
char itemsFirst;
if (item.getType().isBlock()) {
blocksFirst = '!';
itemsFirst = '#';
if (plugin.debug)
System.out.println(item.getType().name() + " is a block.");
} else {
blocksFirst = '#';
itemsFirst = '!';
if (plugin.debug)
System.out.println(item.getType().name() + " is an item.");
}
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;
String[] typeAndColor = getTypeAndColor(item.getType().name());
String typeName = typeAndColor[0];
String color = typeAndColor[1];
String category = getCategory(item.getType().name());
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) {
ItemStack[] items = inv.getContents();
inv.clear();
String[] itemList = new String[inv.getSize()];
return sortableString;
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
int count = 0;
for (String s : itemList) {
if (s != null) {
count++;
}
}
void sortInventory(Inventory inv) {
ItemStack[] items = inv.getContents();
inv.clear();
String[] itemList = new String[inv.getSize()];
// create new array with just the size we need
String[] shortenedArray = new String[count];
int i = 0;
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
for (int j = 0; j < count; j++) {
shortenedArray[j] = itemList[j];
}
// count all items that are not null
int count = 0;
for (String s : itemList) {
if (s != null) {
count++;
}
}
// sort array alphabetically
Arrays.sort(shortenedArray);
// create new array with just the size we need
String[] shortenedArray = new String[count];
// 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;
}
}
}
}
}
// fill new array with items
for (int j = 0; j < count; j++) {
shortenedArray[j] = itemList[j];
}
// sort array alphabetically
Arrays.sort(shortenedArray);
// 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;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import de.jeffclan.utils.Utils;
public class JeffChestSortPlugin extends JavaPlugin {
Map<String, JeffChestSortPlayerSetting> PerPlayerSettings = new HashMap<String, JeffChestSortPlayerSetting>();
@ -19,36 +24,43 @@ public class JeffChestSortPlugin extends JavaPlugin {
String sortingMethod;
int currentConfigVersion = 4;
boolean debug = false;
long updateCheckInterval = 86400; // in seconds. We check on startup and every 24 hours (if you never restart your
// server)
@Override
public void onEnable() {
createConfig();
saveDefaultCategories();
messages = new JeffChestSortMessages(this);
organizer = new JeffChestSortOrganizer(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);
JeffChestSortCommandExecutor commandExecutor = new JeffChestSortCommandExecutor(this);
this.getCommand("chestsort").setExecutor(commandExecutor);
if(getConfig().getBoolean("check-for-updates",true)) {
updateChecker.checkForUpdate();
}
@SuppressWarnings("unused")
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("config_version", () -> Integer.toString(getConfig().getInt("config-version",0))));
metrics.addCustomChart(new Metrics.SimplePie("check_for_updates", () -> Boolean.toString(getConfig().getBoolean("check-for-updates",true))));
metrics.addCustomChart(new Metrics.SimplePie("show_message_when_using_chest", () -> Boolean.toString(getConfig().getBoolean("show-message-when-using-chest"))));
metrics.addCustomChart(new Metrics.SimplePie("show_message_again_after_logout", () -> Boolean.toString(getConfig().getBoolean("show-message-again-after-logout"))));
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) {
metrics.addCustomChart(new Metrics.SimplePie("config_version",
() -> Integer.toString(getConfig().getInt("config-version", 0))));
metrics.addCustomChart(new Metrics.SimplePie("check_for_updates",
() -> Boolean.toString(getConfig().getBoolean("check-for-updates", true))));
metrics.addCustomChart(new Metrics.SimplePie("show_message_when_using_chest",
() -> Boolean.toString(getConfig().getBoolean("show-message-when-using-chest"))));
metrics.addCustomChart(new Metrics.SimplePie("show_message_again_after_logout",
() -> Boolean.toString(getConfig().getBoolean("show-message-again-after-logout"))));
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("YOU ARE USING AN OLD CONFIG FILE!");
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("========================================================");
}
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
public void onDisable() {
for (Player p : getServer().getOnlinePlayers()) {
@ -77,9 +142,14 @@ public class JeffChestSortPlugin extends JavaPlugin {
void createConfig() {
this.saveDefaultConfig();
File playerDataFolder = new File(getDataFolder().getPath() + File.separator + "playerdata");
if (!playerDataFolder.exists())
if (!playerDataFolder.exists()) {
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("show-message-when-using-chest", true);
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("check-for-updates", true);
}
void unregisterPlayer(Player p) {
UUID uniqueId = p.getUniqueId();
if (PerPlayerSettings.containsKey(uniqueId.toString())) {
JeffChestSortPlayerSetting setting = PerPlayerSettings
.get(p.getUniqueId().toString());
JeffChestSortPlayerSetting setting = PerPlayerSettings.get(p.getUniqueId().toString());
File playerFile = new File(getDataFolder() + File.separator + "playerdata",
p.getUniqueId().toString() + ".yml");
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