Rewrote most of the plugin.

Added back settings manager.
Added back settings editor.
Updated storage handler.
Updated GUI system.
Added support for player points.
Removed useless and complicated.
Redid and optimized hologram handling.
This commit is contained in:
Brianna 2019-06-13 06:40:38 -04:00
parent e86c93d9e5
commit c366efb4af
89 changed files with 4806 additions and 4592 deletions

View File

@ -4,7 +4,7 @@ stages:
variables:
name: "EpicFurnaces"
path: "/builds/$CI_PROJECT_PATH"
version: "4.2.5"
version: "4.3"
build:
stage: build

View File

@ -1,140 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>EpicFurnaces-Parent</artifactId>
<groupId>com.songoda</groupId>
<version>maven-version-number</version>
</parent>
<artifactId>EpicFurnaces</artifactId>
<packaging>jar</packaging>
<name>EpicFurnaces</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<url>https://songoda.com/</url>
<build>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.songoda.epicfurnaces</shadedPattern>
</relocation>
</relocations>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>shaded</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
<artifactSet>
<includes>
<include>com.songoda:songodaupdater</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>CodeMC</id>
<url>https://repo.codemc.org/repository/maven-public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.14-pre5-2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>songodaupdater</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.gmail.filoghost.holographicdisplays</groupId>
<artifactId>holographicdisplays-api</artifactId>
<version>2.3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.milkbowl</groupId>
<artifactId>vault</artifactId>
<version>1.7.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,300 +0,0 @@
package com.songoda.epicfurnaces;
import com.songoda.epicfurnaces.command.CommandManager;
import com.songoda.epicfurnaces.handlers.BlacklistHandler;
import com.songoda.epicfurnaces.listeners.BlockListeners;
import com.songoda.epicfurnaces.listeners.FurnaceListeners;
import com.songoda.epicfurnaces.listeners.InteractListeners;
import com.songoda.epicfurnaces.listeners.InventoryListeners;
import com.songoda.epicfurnaces.managers.BoostManager;
import com.songoda.epicfurnaces.managers.FurnaceManager;
import com.songoda.epicfurnaces.managers.HologramManager;
import com.songoda.epicfurnaces.managers.LevelManager;
import com.songoda.epicfurnaces.storage.Storage;
import com.songoda.epicfurnaces.storage.types.StorageMysql;
import com.songoda.epicfurnaces.storage.types.StorageYaml;
import com.songoda.epicfurnaces.tasks.FurnaceTask;
import com.songoda.epicfurnaces.tasks.HologramTask;
import com.songoda.epicfurnaces.utils.BukkitEnums;
import com.songoda.epicfurnaces.utils.Methods;
import com.songoda.epicfurnaces.utils.StringUtils;
import com.songoda.epicfurnaces.utils.gui.FastInv;
import com.songoda.epicfurnaces.utils.updateModules.LocaleModule;
import com.songoda.update.Plugin;
import com.songoda.update.SongodaUpdate;
import net.milkbowl.vault.economy.Economy;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import static com.songoda.epicfurnaces.utils.StringUtils.formatText;
import static java.util.Arrays.asList;
public class EpicFurnaces extends JavaPlugin {
private static Map<String, FileConfiguration> configurations = new HashMap<>();
private BlacklistHandler blacklistHandler;
private BoostManager boostManager;
private BukkitEnums bukkitEnums;
private CommandManager commandManager;
private FurnaceManager furnaceManager;
private LevelManager levelManager;
private Locale locale;
private Storage storage;
private HologramManager hologramManager;
private Economy economy;
private int currentVersion;
@Override
public void onEnable() {
Bukkit.getConsoleSender().sendMessage(formatText("&a============================="));
Bukkit.getConsoleSender().sendMessage(formatText("&7EpicFurnaces " + this.getDescription().getVersion() + " by &5Songoda <3&7!"));
Bukkit.getConsoleSender().sendMessage(formatText("&7Action: &aEnabling&7..."));
if (!checkVersion()) {
getPluginLoader().disablePlugin(this);
return;
}
for (String name : asList("config", "data", "hooks", "blacklist", "Furnace Recipes")) {
File file = new File(getDataFolder(), name + ".yml");
if (!file.exists()) {
file.getParentFile().mkdirs();
saveResource(file.getName(), false);
}
FileConfiguration configuration = new YamlConfiguration();
try {
configuration.load(file);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
configurations.put(name, configuration);
}
String langMode = getConfig().getString("System.Language Mode");
Locale.init(this);
Locale.saveDefaultLocale("en_US");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode", langMode));
//Running Songoda Updater
Plugin plugin = new Plugin(this, 22);
plugin.addModule(new LocaleModule());
SongodaUpdate.load(plugin);
FastInv.init(this);
Methods.init(this);
StringUtils.init(this);
this.furnaceManager = new FurnaceManager(this);
this.commandManager = new CommandManager(this);
this.boostManager = new BoostManager(this);
this.blacklistHandler = new BlacklistHandler(this);
this.bukkitEnums = new BukkitEnums(this);
this.levelManager = new LevelManager(this);
if (!setupEconomy()) {
getLogger().severe("Economy provider not found/not supported, disabling...");
Bukkit.getPluginManager().disablePlugin(this);
Bukkit.getConsoleSender().sendMessage(formatText("&a============================="));
return;
}
if (Bukkit.getPluginManager().isPluginEnabled("HolographicDisplays") && getConfig().getBoolean("Main.Furnaces Have Holograms")) {
this.hologramManager = new HologramManager(this);
}
checkStorage();
levelManager.loadLevelManager();
setupRecipes();
int timeout = getConfig().getInt("Main.Auto Save Interval In Seconds") * 60 * 20;
Bukkit.getScheduler().runTaskLater(this, furnaceManager::loadFurnaces, 10);
Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> storage.doSave(), timeout, timeout);
// Start Tasks
HologramTask.startTask(this);
FurnaceTask.startTask(this);
// Register Listeners
PluginManager pluginManager = Bukkit.getPluginManager();
new HashSet<>(asList(
new BlockListeners(this),
new FurnaceListeners(this),
new InteractListeners(this),
new InventoryListeners(this))).forEach(listener -> pluginManager.registerEvents(listener, this));
new Metrics(this);
Bukkit.getConsoleSender().sendMessage(formatText("&a============================="));
}
@Override
public void onDisable() {
Bukkit.getConsoleSender().sendMessage(formatText("&a============================="));
Bukkit.getConsoleSender().sendMessage(formatText("&7EpicFurnaces " + this.getDescription().getVersion() + " by &5Songoda <3&7!"));
Bukkit.getConsoleSender().sendMessage(formatText("&7Action: &cDisabling&7..."));
Bukkit.getConsoleSender().sendMessage(formatText("&a============================="));
getHologramManager().ifPresent(HologramManager::clearAll);
this.hologramManager = null;
storage.doSave();
storage.closeConnection();
Map<Inventory, Location> loadedFurnaceInventories = this.furnaceManager.getLoadedFurnaceInventories();
for (Inventory inventory : loadedFurnaceInventories.keySet())
loadedFurnaceInventories.get(inventory).getChunk().load();
loadedFurnaceInventories.clear();
}
private void checkStorage() {
if (getConfig().getBoolean("Database.Activate Mysql Support")) {
this.storage = new StorageMysql(this);
} else {
this.storage = new StorageYaml(this);
}
}
public void reload() {
Bukkit.getScheduler().cancelTasks(this);
reloadConfig();
saveConfig();
onDisable();
onEnable();
}
private void setupRecipes() {
if (!getConfig().getBoolean("Main.Use Custom Recipes")) {
return;
}
ConfigurationSection cs = getConfiguration("Furnace Recipes").getConfigurationSection("Recipes");
for (String key : cs.getKeys(false)) {
Material item = Material.matchMaterial(key.toUpperCase());
if (item == null) {
getLogger().info("Invalid material from recipes files: " + key.toUpperCase());
continue;
}
Material result = Material.matchMaterial(cs.getString(key.toUpperCase() + ".result"));
if (result == null) {
getLogger().info("Invalid material from recipes files: " + cs.getString(key.toUpperCase() + ".result"));
continue;
}
int amount = cs.getInt(key.toUpperCase() + ".amount");
getServer().addRecipe(new FurnaceRecipe(new ItemStack(result, amount), item));
}
}
public void save(String configuration) {
try {
File configurationFile = new File(getDataFolder(), configuration + ".yml");
getConfiguration(configuration).save(configurationFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean checkVersion() {
String version = getServer().getClass().getPackage().getName().split("\\.")[3];
currentVersion = Integer.parseInt(version.split("_")[1]);
int workingVersion = 8;
if (currentVersion < workingVersion) {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
Bukkit.getConsoleSender().sendMessage("");
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "You installed the 1." + workingVersion + "+ version of " +
this.getDescription().getName() + " on a 1." + currentVersion + " server. " +
"We currently do not support " + currentVersion + " and below.");
Bukkit.getConsoleSender().sendMessage("");
});
return false;
}
return true;
}
private boolean setupEconomy() {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
economy = rsp.getProvider();
return economy != null;
}
public FileConfiguration getConfiguration(String name) {
return configurations.get(name);
}
public BlacklistHandler getBlacklistHandler() {
return blacklistHandler;
}
public BoostManager getBoostManager() {
return boostManager;
}
public CommandManager getCommandManager() {
return commandManager;
}
public FurnaceManager getFurnaceManager() {
return furnaceManager;
}
public LevelManager getLevelManager() {
return levelManager;
}
public Locale getLocale() {
return locale;
}
public BukkitEnums getBukkitEnums() {
return bukkitEnums;
}
public Optional<HologramManager> getHologramManager() {
return Optional.ofNullable(hologramManager);
}
public Storage getStorage() {
return storage;
}
public Economy getEconomy() {
return economy;
}
public int getCurrentVersion() {
return currentVersion;
}
}

View File

@ -1,86 +0,0 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.command.AbstractCommand;
import com.songoda.epicfurnaces.objects.BoostData;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.Calendar;
import java.util.Date;
public class CommandBoost extends AbstractCommand {
private final EpicFurnaces instance;
public CommandBoost(EpicFurnaces instance, AbstractCommand parent) {
super("boost", parent, false);
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length < 3) {
return ReturnType.SYNTAX_ERROR;
}
if (Bukkit.getPlayer(args[1]) == null) {
sender.sendMessage(com.songoda.epicfurnaces.utils.StringUtils.formatText(instance.getLocale().getPrefix() + "&cThat player does not exist..."));
return ReturnType.FAILURE;
} else if (!StringUtils.isNumeric(args[2])) {
sender.sendMessage(com.songoda.epicfurnaces.utils.StringUtils.formatText(instance.getLocale().getPrefix() + "&6" + args[2] + " &7is not a number..."));
return ReturnType.FAILURE;
} else {
Calendar c = Calendar.getInstance();
Date currentDate = new Date();
c.setTime(currentDate);
String time = "&7.";
if (args.length > 3) {
if (args[3].contains("m:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.MINUTE, Integer.parseInt(arr2[1]));
time = " &7for &6" + arr2[1] + " minutes&7.";
} else if (args[3].contains("h:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.HOUR, Integer.parseInt(arr2[1]));
time = " &7for &6" + arr2[1] + " hours&7.";
} else if (args[3].contains("d:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.HOUR, Integer.parseInt(arr2[1]) * 24);
time = " &7for &6" + arr2[1] + " days&7.";
} else if (args[3].contains("y:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.YEAR, Integer.parseInt(arr2[1]));
time = " &7for &6" + arr2[1] + " years&7.";
} else {
sender.sendMessage(com.songoda.epicfurnaces.utils.StringUtils.formatText(instance.getLocale().getPrefix() + "&7" + args[3] + " &7is invalid."));
return ReturnType.SUCCESS;
}
} else {
c.add(Calendar.YEAR, 10);
}
BoostData boostData = new BoostData(Integer.parseInt(args[2]), c.getTime().getTime(), Bukkit.getPlayer(args[1]).getUniqueId());
instance.getBoostManager().addBoostToPlayer(boostData);
sender.sendMessage(com.songoda.epicfurnaces.utils.StringUtils.formatText(instance.getLocale().getPrefix() + "&7Successfully boosted &6" + Bukkit.getPlayer(args[1]).getName() + "'s &7furnaces reward amounts by &6" + args[2] + "x" + time));
}
return ReturnType.FAILURE;
}
@Override
public String getPermissionNode() {
return "epicfurnaces.admin";
}
@Override
public String getSyntax() {
return "/ef boost <player> <multiplier> [m:minute, h:hour, d:day, y:year]";
}
@Override
public String getDescription() {
return "This allows you to boost a players objects reward amounts by a multiplier (Put 2 for double, 3 for triple and so on).";
}
}

View File

@ -1,69 +0,0 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.command.AbstractCommand;
import com.songoda.epicfurnaces.objects.Level;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGive extends AbstractCommand {
private final EpicFurnaces instance;
public CommandGive(EpicFurnaces instance, AbstractCommand parent) {
super("give", parent, false);
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length == 2) {
return ReturnType.SYNTAX_ERROR;
}
Level level = instance.getLevelManager().getLowestLevel();
Player player;
if (args.length != 1 && Bukkit.getPlayer(args[1]) == null) {
sender.sendMessage(instance.getLocale().getPrefix() + StringUtils.formatText("&cThat player does not exist or is currently offline."));
return ReturnType.FAILURE;
} else if (args.length == 1) {
if (!(sender instanceof Player)) {
sender.sendMessage(instance.getLocale().getPrefix() + StringUtils.formatText("&cYou need to be a player to give a farm item to yourself."));
return ReturnType.FAILURE;
}
player = (Player) sender;
} else {
player = Bukkit.getPlayer(args[1]);
}
if (args.length >= 3 && !instance.getLevelManager().isLevel(Integer.parseInt(args[2]))) {
sender.sendMessage(instance.getLocale().getPrefix() + StringUtils.formatText("&cNot a valid level... The current valid levels are: &4" + instance.getLevelManager().getLowestLevel().getLevel() + "-" + instance.getLevelManager().getHighestLevel().getLevel() + "&c."));
return ReturnType.FAILURE;
} else if (args.length != 1) {
level = instance.getLevelManager().getLevel(Integer.parseInt(args[2]));
}
player.getInventory().addItem(instance.getFurnaceManager().createLeveledFurnace(level.getLevel(), 0, instance));
player.sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("command.give.success", level.getLevel()));
return ReturnType.SUCCESS;
}
@Override
public String getPermissionNode() {
return "epicfurnaces.admin";
}
@Override
public String getSyntax() {
return "/ef give [player] <level>";
}
@Override
public String getDescription() {
return "Give a leveled objects to a player.";
}
}

View File

@ -1,46 +0,0 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.command.AbstractCommand;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.command.CommandSender;
public class CommandHelp extends AbstractCommand {
private final EpicFurnaces instance;
public CommandHelp(EpicFurnaces instance, AbstractCommand parent) {
super("help", parent, false);
this.instance = instance;
}
@Override
protected AbstractCommand.ReturnType runCommand(CommandSender sender, String... args) {
sender.sendMessage("");
sender.sendMessage(StringUtils.formatText(instance.getLocale().getPrefix() + "&7Version " + instance.getDescription().getVersion() + " Created with <3 by &5&l&oSongoda"));
for (AbstractCommand command : instance.getCommandManager().getCommands()) {
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
sender.sendMessage(StringUtils.formatText("&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
}
}
sender.sendMessage("");
return ReturnType.SUCCESS;
}
@Override
public String getDescription() {
return "Displays the help page.";
}
@Override
public String getPermissionNode() {
return null;
}
@Override
public String getSyntax() {
return "/ef help";
}
}

View File

@ -1,82 +0,0 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.command.AbstractCommand;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import org.bukkit.block.Furnace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.UUID;
public class CommandRemote extends AbstractCommand {
private final EpicFurnaces instance;
public CommandRemote(EpicFurnaces instance, AbstractCommand abstractCommand) {
super("remote", abstractCommand, true);
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (!instance.getConfig().getBoolean("Main.Access Furnaces Remotely") || !sender.hasPermission("EpicFurnaces.Remote")) {
sender.sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.general.nopermission"));
return ReturnType.FAILURE;
}
/*if (!instance.getConfiguration("data").contains("data.charged")) {
return ReturnType.FAILURE;
}*/
if (args.length < 2) {
return ReturnType.SYNTAX_ERROR;
}
String furnaceName = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
for (FurnaceObject furnace : instance.getFurnaceManager().getAllFurnaces().values()) {
if (furnace.getNickname() == null) {
continue;
}
if (!furnace.getNickname().equalsIgnoreCase(furnaceName)) {
continue;
}
for (UUID uuid : furnace.getAccessList()) {
if (!uuid.equals(((Player) sender).getUniqueId())) {
continue;
}
Furnace furnaceBlock = (Furnace) furnace.getLocation().getBlock().getState();
this.instance.getFurnaceManager().getLoadedFurnaceInventories().put(furnaceBlock.getInventory(), furnaceBlock.getLocation());
furnaceBlock.getChunk().load();
((Player) sender).openInventory(furnaceBlock.getInventory());
return ReturnType.SUCCESS;
}
sender.sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.general.nopermission"));
return ReturnType.SUCCESS;
}
sender.sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.remote.notfound"));
return ReturnType.FAILURE;
}
@Override
public String getPermissionNode() {
return null;
}
@Override
public String getSyntax() {
return "/ef remote [nickname]";
}
@Override
public String getDescription() {
return "Remote control your objects.";
}
}

View File

@ -1,38 +0,0 @@
package com.songoda.epicfurnaces.handlers;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.util.List;
/**
* Created by songoda on 2/25/2017.
*/
public class BlacklistHandler {
private final EpicFurnaces instance;
private FileConfiguration blackFile;
public BlacklistHandler(EpicFurnaces instance) {
this.instance = instance;
this.blackFile = instance.getConfiguration("blacklist");
}
public boolean isBlacklisted(Player player) {
boolean blacklisted = false;
List<String> list = blackFile.getStringList("settings.blacklist");
String cWorld = player.getWorld().getName();
for (String world : list) {
if (cWorld.equalsIgnoreCase(world)) {
blacklisted = true;
}
}
return blacklisted;
}
public void reload() {
instance.save("blacklist");
blackFile = instance.getConfiguration("blacklist");
}
}

View File

@ -1,120 +0,0 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Furnace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static com.songoda.epicfurnaces.objects.FurnaceObject.BoostType.OVERHEAT;
/**
* Created by songoda on 2/26/2017.
*/
public class BlockListeners implements Listener {
private final EpicFurnaces instance;
public BlockListeners(EpicFurnaces instance) {
this.instance = instance;
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onSnowLand(BlockFormEvent event) {
if (event.getNewState().getType() != Material.SNOW && event.getNewState().getType() != Material.ICE) {
return;
}
for (FurnaceObject furnace : instance.getFurnaceManager().getFurnaces().values()) {
if (furnace.getRadius(OVERHEAT) == null || ((Furnace) furnace.getLocation().getBlock().getState()).getBurnTime() == 0) {
continue;
}
for (Location location : furnace.getRadius(OVERHEAT)) {
if (location.getX() != event.getNewState().getX() || location.getY() != event.getNewState().getY() || location.getZ() != event.getNewState().getZ()) {
continue;
}
event.setCancelled(true);
return;
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
if (event.getBlock().getType() != Material.FURNACE) {
return;
}
ItemStack item = event.getItemInHand();
Location location = event.getBlock().getLocation();
if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) {
event.setCancelled(true);
return;
}
FurnaceObject furnaceObject = new FurnaceObject(instance,
location,
instance.getLevelManager().getLevel(instance.getFurnaceManager().getFurnaceLevel(item)),
null,
instance.getFurnaceManager().getFurnaceUses(item),
0,
new ArrayList<>(),
event.getPlayer().getUniqueId());
instance.getFurnaceManager().addFurnace(location, furnaceObject);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (!event.getPlayer().hasPermission("epicfurnaces.overview") && !event.getPlayer().hasPermission("epicfurnaces.*")) {
return;
}
if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) {
return;
}
if (event.getBlock().getType() != Material.FURNACE && !event.getBlock().getType().name().equals("BURNING_FURNACE")) {
return;
}
instance.getFurnaceManager().getFurnace(event.getBlock().getLocation()).ifPresent(this::handleBreak);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onBlockExplode(EntityExplodeEvent event) {
Set<FurnaceObject> furnaces = event.blockList().parallelStream()
.map(block -> instance.getFurnaceManager().getFurnace(block.getLocation()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
furnaces.forEach(this::handleBreak);
}
private void handleBreak(FurnaceObject furnaceObject) {
ItemStack item = instance.getFurnaceManager().createLeveledFurnace(furnaceObject.getLevel().getLevel(), furnaceObject.getUses(), instance);
furnaceObject.getLocation().getBlock().setType(Material.AIR);
furnaceObject.getLocation().getWorld().dropItemNaturally(furnaceObject.getLocation().getBlock().getLocation(), item);
instance.getFurnaceManager().removeFurnace(furnaceObject);
}
}

View File

@ -1,55 +0,0 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import com.songoda.epicfurnaces.objects.Level;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import java.util.Optional;
/**
* Created by songoda on 2/26/2017.
*/
public class FurnaceListeners implements Listener {
private final EpicFurnaces instance;
public FurnaceListeners(EpicFurnaces instance) {
this.instance = instance;
}
@EventHandler
public void onCook(FurnaceSmeltEvent event) {
if ((event.getBlock().isBlockPowered() && instance.getConfig().getBoolean("Main.Redstone Deactivates Furnaces"))) {
event.setCancelled(true);
return;
}
Optional<FurnaceObject> furnace = instance.getFurnaceManager().getFurnace(event.getBlock().getLocation());
if (furnace.isPresent() && event.getSource().getType() != instance.getBukkitEnums().getMaterial("WET_SPONGE").getType()) {
furnace.get().plus(event);
}
}
@EventHandler
public void onFuel(FurnaceBurnEvent event) {
if (event.getFuel() == null) {
return;
}
Optional<FurnaceObject> furnace = instance.getFurnaceManager().getFurnace(event.getBlock().getLocation());
Level level = furnace.isPresent() ? furnace.get().getLevel() : instance.getLevelManager().getLowestLevel();
if (level.getFuelDuration() != 0) {
return;
}
int num = level.getFuelDuration();
int per = (event.getBurnTime() / 100) * num;
event.setBurnTime(event.getBurnTime() + per);
}
}

View File

@ -1,44 +0,0 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class InteractListeners implements Listener {
private final EpicFurnaces instance;
public InteractListeners(EpicFurnaces instance) {
this.instance = instance;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onClick(PlayerInteractEvent event) {
if (event.getClickedBlock() == null
&& instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) {
return;
}
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (!player.hasPermission("EpicFurnaces.overview")
|| event.getAction() != Action.LEFT_CLICK_BLOCK
|| player.isSneaking()
|| (block.getType() != Material.FURNACE && !block.getType().name().equals("BURNING_FURNACE"))
|| player.getInventory().getItemInHand().getType().name().contains("PICKAXE")) {
return;
}
event.setCancelled(true);
instance.getFurnaceManager().getFurnace(block.getLocation()).orElseGet(() -> instance.getFurnaceManager().createFurnace(block.getLocation())).openOverview(player);
}
}

View File

@ -1,83 +0,0 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Furnace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
import static org.bukkit.event.inventory.InventoryAction.NOTHING;
import static org.bukkit.event.inventory.InventoryType.*;
import static org.bukkit.event.inventory.InventoryType.SlotType.CRAFTING;
/**
* Created by songoda on 2/26/2017.
*/
public class InventoryListeners implements Listener {
private final EpicFurnaces instance;
public InventoryListeners(EpicFurnaces instance) {
this.instance = instance;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
Inventory inventory = event.getInventory();
Map<Inventory, Location> loadedFurnaceInventories = this.instance.getFurnaceManager().getLoadedFurnaceInventories();
Location location = loadedFurnaceInventories.get(inventory);
if (location == null)
return;
location.getChunk().unload();
loadedFurnaceInventories.remove(inventory);
}
@EventHandler
public void onInventoryMove(InventoryMoveItemEvent event) {
if (!event.getDestination().getType().equals(FURNACE)
|| event.getDestination().getItem(0) == null
|| event.getDestination().getItem(0).getType() != event.getItem().getType()
|| event.getDestination().getItem(0).getAmount() != 1) {
return;
}
instance.getFurnaceManager().getFurnace(((Furnace) event.getDestination().getHolder()).getLocation()).ifPresent(FurnaceObject::updateCook);
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (event.getInventory().getType().equals(FURNACE)
&& event.getInventory().getHolder() != null
&& event.getSlotType() == CRAFTING) {
Block block = ((Furnace) event.getInventory().getHolder()).getLocation().getBlock();
instance.getFurnaceManager().getFurnace(block.getLocation()).ifPresent(FurnaceObject::updateCook);
}
if (event.getSlot() == 64537 || event.getInventory().getType() != ANVIL || event.getAction() == NOTHING) {
return;
}
if (event.getCurrentItem().getType() == Material.AIR) {
return;
}
ItemStack item = event.getCurrentItem();
if (item.getType() == Material.FURNACE) {
event.setCancelled(true);
}
}
}

View File

@ -1,157 +0,0 @@
package com.songoda.epicfurnaces.managers;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.BoostData;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import com.songoda.epicfurnaces.storage.Storage;
import com.songoda.epicfurnaces.storage.StorageItem;
import com.songoda.epicfurnaces.storage.StorageRow;
import com.songoda.epicfurnaces.utils.Methods;
import com.songoda.epicfurnaces.utils.gui.ItemBuilder;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Location;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import static org.bukkit.Material.FURNACE;
public class FurnaceManager {
private final Map<Location, FurnaceObject> registeredFurnaces = new HashMap<>();
private final Map<Inventory, Location> loadedFurnaceInventories = new HashMap<>();
private final EpicFurnaces instance;
public FurnaceManager(EpicFurnaces instance) {
this.instance = instance;
}
public FurnaceObject addFurnace(Location location, FurnaceObject furnace) {
instance.getHologramManager().ifPresent(manager -> manager.updateHologram(furnace));
registeredFurnaces.put(roundLocation(location), furnace);
return furnace;
}
public FurnaceObject createFurnace(Location location) {
return addFurnace(location, new FurnaceObject(instance, location, instance.getLevelManager().getLowestLevel(), null, 0, 0, new ArrayList<>(), null));
}
public void removeFurnace(FurnaceObject furnaceObject) {
removeFurnace(furnaceObject.getLocation());
}
public void removeFurnace(Location location) {
instance.getHologramManager().ifPresent(manager -> manager.remove(registeredFurnaces.remove(location)));
}
public Optional<FurnaceObject> getFurnace(Location location) {
return Optional.ofNullable(registeredFurnaces.get(location));
}
public int getFurnaceLevel(ItemStack item) {
if (!item.hasItemMeta() || !item.getItemMeta().hasDisplayName()) {
return 1;
}
if (item.getItemMeta().getDisplayName().contains(":")) {
String[] arr = (item.getItemMeta().getDisplayName().replace("§", "")).split(":");
return StringUtils.isNumeric(arr[0]) ? Integer.parseInt(arr[0]) : 1;
}
return 1;
}
public int getFurnaceUses(ItemStack item) {
if (!item.hasItemMeta() || !item.getItemMeta().hasDisplayName()) {
return 0;
}
if (item.getItemMeta().getDisplayName().contains(":")) {
String[] arr = (item.getItemMeta().getDisplayName().replace("§", "")).split(":");
return StringUtils.isNumeric(arr[1]) ? Integer.parseInt(arr[1]) : 0;
} else {
return 0;
}
}
private Location roundLocation(Location location) {
return location.getBlock().getLocation().clone();
}
public ItemStack createLeveledFurnace(int level, int uses, EpicFurnaces epicFurnaces) {
ItemBuilder itemBuilder = new ItemBuilder(FURNACE);
if (epicFurnaces.getConfig().getBoolean("Main.Remember Furnace Item Levels")) {
itemBuilder.name(com.songoda.epicfurnaces.utils.StringUtils.formatText(com.songoda.epicfurnaces.utils.StringUtils.formatName(level, uses, true)));
}
return itemBuilder.build();
}
public void loadFurnaces() {
Storage storage = instance.getStorage();
if (storage.containsGroup("charged")) {
for (StorageRow row : storage.getRowsByGroup("charged")) {
Location location = Methods.deserializeLocation(row.getKey());
if (location == null || location.getWorld() == null) {
continue;
}
int level = row.get("level").asInt();
int uses = row.get("uses").asInt();
int toLevel = row.get("level").asInt();
String nickname = row.get("nickname").asString();
List<String> accessList = row.get("accesslist").asStringList();
String placedByStr = row.get("placedBy").asString();
UUID placedBy = placedByStr == null ? null : UUID.fromString(placedByStr);
FurnaceObject furnace = new FurnaceObject(instance, location, instance.getLevelManager().getLevel(level), nickname, uses, toLevel, accessList, placedBy);
addFurnace(location, furnace);
}
}
if (storage.containsGroup("boosts")) {
for (StorageRow row : storage.getRowsByGroup("boosts")) {
if (row.getItems().get("uuid").asObject() != null) {
continue;
}
BoostData boostData = new BoostData(row.get("amount").asInt(), Long.parseLong(row.getKey()), UUID.fromString(row.get("uuid").asString()));
instance.getBoostManager().addBoostToPlayer(boostData);
}
}
if (!instance.getConfig().getBoolean("Main.Furnaces Have Holograms")) {
return;
}
getFurnaces().values().forEach(furnace -> instance.getHologramManager().ifPresent(manager -> manager.updateHologram(furnace)));
}
public Map<Inventory, Location> getLoadedFurnaceInventories() {
return this.loadedFurnaceInventories;
}
/**
* Gets a Map of all furnaces that are in loaded chunks
*
* @return All furnaces in memory that are in loaded chunks
*/
public Map<Location, FurnaceObject> getFurnaces() {
Map<Location, FurnaceObject> furnaces = new HashMap<>();
for (Location location : this.registeredFurnaces.keySet())
if (location.getWorld() != null && location.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4))
furnaces.put(location, this.registeredFurnaces.get(location));
return furnaces;
}
/**
* Gets a Map of all furnaces, regardless if they are in loaded chunks or not.
* Getting the furnace's block in an unloaded chunk will load the chunk.
*
* @return All furnaces in memory
*/
public Map<Location, FurnaceObject> getAllFurnaces() {
return Collections.unmodifiableMap(this.registeredFurnaces);
}
}

View File

@ -1,106 +0,0 @@
package com.songoda.epicfurnaces.managers;
import com.gmail.filoghost.holographicdisplays.api.Hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import com.gmail.filoghost.holographicdisplays.api.line.TextLine;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Furnace;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class HologramManager {
private final Map<FurnaceObject, Hologram> hologramMap;
private final EpicFurnaces instance;
public HologramManager(EpicFurnaces instance) {
this.hologramMap = new HashMap<>();
this.instance = instance;
}
public void updateHologram(FurnaceObject furnaceObject) {
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> {
if (furnaceObject.getLocation().getBlock().getType() != Material.FURNACE &&
!furnaceObject.getLocation().getBlock().getType().name().equals("BURNING_FURNACE")) {
if (hologramMap.containsKey(furnaceObject)) {
hologramMap.remove(furnaceObject).delete();
}
return;
}
Furnace furnaceBlock = (Furnace) furnaceObject.getLocation().getBlock().getState();
int performance = (furnaceBlock.getCookTime() - furnaceObject.getPerformanceTotal()) <= 0 ? 0 : furnaceObject.getPerformanceTotal();
float percent = (float) (furnaceBlock.getCookTime() - performance) / (200 - performance);
int progressBars = (int) (6 * percent) + (percent == 0 ? 0 : 1);
int leftOver = (6 - progressBars);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < progressBars; i++) {
sb.append("&a=");
}
for (int i = 0; i < leftOver; i++) {
sb.append("&c=");
}
String progress = StringUtils.formatText(sb.toString());
if (furnaceBlock.getInventory().getFuel() == null) {
progress = instance.getLocale().getMessage("general.hologram.outoffuel");
}
int inAmt = 0;
int outAmt = 0;
if (furnaceBlock.getInventory().getSmelting() != null) {
inAmt = furnaceBlock.getInventory().getSmelting().getAmount();
}
if (furnaceBlock.getInventory().getResult() != null) {
outAmt = furnaceBlock.getInventory().getResult().getAmount();
}
String stats = instance.getLocale().getMessage("general.hologram.stats", inAmt, outAmt > 64 ? 64 : outAmt);
Hologram hologram;
if (!hologramMap.containsKey(furnaceObject)) {
BlockFace direction = ((org.bukkit.material.Furnace) furnaceBlock.getData()).getFacing();
Location location = instance.getConfig().getBoolean("Main.Hologram in front") ?
furnaceObject.getLocation().getBlock().getRelative(direction).getLocation().add(0.5, 0.8, 0.5) :
furnaceBlock.getLocation().add(0.5, 1.8, 0.5);
hologram = HologramsAPI.createHologram(instance, location);
} else {
hologram = hologramMap.get(furnaceObject);
}
if (hologram.size() == 0) {
hologram.clearLines();
hologram.insertTextLine(0, progress);
hologram.insertTextLine(1, stats);
} else {
((TextLine) hologram.getLine(0)).setText(progress);
((TextLine) hologram.getLine(1)).setText(stats);
}
hologramMap.put(furnaceObject, hologram);
});
}
public void remove(FurnaceObject furnaceObject) {
Optional.ofNullable(hologramMap.remove(furnaceObject)).ifPresent(Hologram::delete);
}
public void clearAll() {
hologramMap.values().forEach(Hologram::delete);
hologramMap.clear();
}
}

View File

@ -1,73 +0,0 @@
package com.songoda.epicfurnaces.managers;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.Level;
import java.util.*;
public class LevelManager {
private final NavigableMap<Integer, Level> registeredLevels = new TreeMap<>();
private final EpicFurnaces instance;
public LevelManager(EpicFurnaces instance) {
this.instance = instance;
}
public void addLevel(int level, int costExperience, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare) {
registeredLevels.put(level, new Level(instance, level, costExperience, costEconomy, performance, reward, fuelDuration, overheat, fuelShare));
}
public void loadLevelManager() {
clear();
for (String levelName : instance.getConfig().getConfigurationSection("settings.levels").getKeys(false)) {
int level = Integer.valueOf(levelName.split("-")[1]);
int costExperience = instance.getConfig().getInt("settings.levels." + levelName + ".Cost-xp");
int costEconomy = instance.getConfig().getInt("settings.levels." + levelName + ".Cost-eco");
String performanceStr = instance.getConfig().getString("settings.levels." + levelName + ".Performance");
int performance = performanceStr == null ? 0 : Integer.parseInt(performanceStr.substring(0, performanceStr.length() - 1));
String reward = instance.getConfig().getString("settings.levels." + levelName + ".Reward");
String fuelDurationStr = instance.getConfig().getString("settings.levels." + levelName + ".Fuel-duration");
int fuelDuration = fuelDurationStr == null ? 0 : Integer.parseInt(fuelDurationStr.substring(0, fuelDurationStr.length() - 1));
int overheat = instance.getConfig().getInt("settings.levels." + levelName + ".Overheat");
int fuelShare = instance.getConfig().getInt("settings.levels." + levelName + ".Fuel-share");
addLevel(level, costExperience, costEconomy, performance, reward, fuelDuration, overheat, fuelShare);
}
}
public Level getLevel(int level) {
return registeredLevels.get(level);
}
public Level getLowestLevel() {
return registeredLevels.firstEntry().getValue();
}
public Level getHighestLevel() {
return registeredLevels.lastEntry().getValue();
}
public boolean isLevel(int level) {
return registeredLevels.containsKey(level);
}
public Map<Integer, Level> getLevels() {
return Collections.unmodifiableMap(registeredLevels);
}
public void clear() {
registeredLevels.clear();
}
}

View File

@ -1,213 +0,0 @@
package com.songoda.epicfurnaces.menus;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.BoostData;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import com.songoda.epicfurnaces.objects.Level;
import com.songoda.epicfurnaces.utils.Methods;
import com.songoda.epicfurnaces.utils.StringUtils;
import com.songoda.epicfurnaces.utils.gui.AbstractAnvilGUI;
import com.songoda.epicfurnaces.utils.gui.FastInv;
import com.songoda.epicfurnaces.utils.gui.ItemBuilder;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static com.songoda.epicfurnaces.utils.gui.AbstractAnvilGUI.AnvilSlot.INPUT_LEFT;
import static org.bukkit.Material.*;
public class OverviewMenu extends FastInv {
public OverviewMenu(EpicFurnaces instance, FurnaceObject furnace, Player accessor) {
super(27, StringUtils.formatName(furnace.getLevel().getLevel(), 0, false));
Level nextLevel = instance.getLevelManager().getHighestLevel().getLevel() > furnace.getLevel().getLevel() ? instance.getLevelManager().getLevel(furnace.getLevel().getLevel() + 1) : null;
int multi = instance.getConfig().getInt("Main.Level Cost Multiplier");
int needed = (multi * furnace.getLevel().getLevel()) - furnace.getToLevel();
ItemBuilder currentLevel = new ItemBuilder(FURNACE);
currentLevel.name(instance.getLocale().getMessage("interface.furnace.currentlevel", furnace.getLevel().getLevel()));
currentLevel.lore(instance.getLocale().getMessage("interface.furnace.smeltedx", furnace.getUses()));
currentLevel.addLore(furnace.getLevel().getDescription());
currentLevel.addLore("");
if (nextLevel == null)
currentLevel.addLore(instance.getLocale().getMessage("interface.furnace.alreadymaxed"));
else {
currentLevel.addLore(instance.getLocale().getMessage("interface.furnace.level", nextLevel.getLevel()));
currentLevel.addLore(nextLevel.getDescription());
if (instance.getConfig().getBoolean("Main.Upgrade By Smelting Materials")) {
currentLevel.addLore(instance.getLocale().getMessage("interface.furnace.tolevel", needed, StringUtils.cleanString(instance.getConfig().getString("Main.Furnace Upgrade Cost"))));
}
}
BoostData boostData = instance.getBoostManager().getBoost(furnace.getPlacedBy());
if (boostData != null) {
String[] parts = instance.getLocale().getMessage("interface.button.boostedstats", "" + boostData.getMultiplier(), StringUtils.msToString(boostData.getEndTime() - System.currentTimeMillis())).split("\\|");
currentLevel.addLore("");
for (String line : parts) {
currentLevel.addLore(StringUtils.formatText(line));
}
}
fill(Methods.getGlass());
ItemBuilder performance = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.Performance Icon")));
performance.name(instance.getLocale().getMessage("interface.furnace.performancetitle"));
String[] parts = instance.getLocale().getMessage("interface.furnace.performanceinfo", furnace.getLevel().getPerformance()).split("\\|");
performance.lore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
ItemBuilder reward = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.Reward Icon")));
reward.name(instance.getLocale().getMessage("interface.furnace.rewardtitle"));
parts = instance.getLocale().getMessage("interface.furnace.rewardinfo", furnace.getLevel().getReward().split(":")[0].replace("%", "")).split("\\|");
reward.lore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
ItemBuilder duration = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.FuelDuration Icon")));
duration.name(instance.getLocale().getMessage("interface.furnace.fueldurationtitle"));
parts = instance.getLocale().getMessage("interface.furnace.fueldurationinfo", furnace.getLevel().getFuelDuration()).split("\\|");
duration.lore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
ItemBuilder overheat = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.Overheat Icon")));
overheat.name(instance.getLocale().getMessage("interface.furnace.overheattitle"));
parts = instance.getLocale().getMessage("interface.furnace.overheatinfo", furnace.getLevel().getOverheat() * 3).split("\\|");
overheat.lore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
ItemBuilder fuelShare = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.FuelShare Icon")));
fuelShare.name(instance.getLocale().getMessage("interface.furnace.fuelsharetitle"));
parts = instance.getLocale().getMessage("interface.furnace.fuelshareinfo", furnace.getLevel().getFuelShare() * 3).split("\\|");
fuelShare.lore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
ItemBuilder xp = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.XP Icon")));
xp.name(instance.getLocale().getMessage("interface.furnace.upgradewithxp"));
xp.lore(nextLevel == null ? instance.getLocale().getMessage("interface.furnace.alreadymaxed") :
instance.getLocale().getMessage("interface.furnace.upgradewithxplore", furnace.getLevel().getCostExperience()));
ItemBuilder eco = new ItemBuilder(instance.getBukkitEnums().getMaterial(instance.getConfig().getString("Interfaces.Economy Icon")));
eco.name(instance.getLocale().getMessage("interface.furnace.upgradewitheconomy"));
eco.lore(nextLevel == null ? instance.getLocale().getMessage("interface.furnace.alreadymaxed") :
instance.getLocale().getMessage("interface.furnace.upgradewitheconomylore", StringUtils.formatEconomy(furnace.getLevel().getCostEconomy())));
ItemBuilder remote = new ItemBuilder(TRIPWIRE_HOOK);
remote.name(instance.getLocale().getMessage("interface.furnace.remotefurnace"));
parts = instance.getLocale().getMessage("interface.furnace.remotefurnacelore", furnace.getNickname() == null ? "Unset" : furnace.getNickname()).split("\\|");
remote.lore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
if (furnace.getNickname() != null) {
parts = instance.getLocale().getMessage("interface.furnace.utilize", furnace.getNickname()).split("\\|");
remote.addLore(Arrays.stream(parts).map(StringUtils::formatText).collect(Collectors.toList()));
}
if (!furnace.getOriginalAccessList().isEmpty()) {
remote.addLore("");
remote.addLore(instance.getLocale().getMessage("interface.furnace.remotelist"));
}
for (String line : furnace.getOriginalAccessList()) {
String[] halfs = line.split(":");
String name = halfs[1];
Player player = Bukkit.getPlayer(halfs[0]);
if (player != null) {
name = player.getDisplayName();
}
remote.addLore(StringUtils.formatText("&6" + name));
}
addItem(new int[]{0, 1, 7, 8, 9, 17, 18, 19, 25, 26}, Methods.getBackgroundGlass(true));
addItem(new int[]{2, 6, 10, 16, 20, 24}, Methods.getBackgroundGlass(false));
int num = -1;
Map<Integer, int[]> spots = new HashMap<Integer, int[]>() {{
put(0, new int[]{22});
put(1, new int[]{21, 23});
put(2, new int[]{21, 22, 23});
put(3, new int[]{20, 21, 23, 24});
put(4, new int[]{20, 21, 22, 23, 24});
}};
num += furnace.getLevel().getPerformance() == 0 ? 0 : 1;
num += (furnace.getLevel().getReward() == null ? 0 : 1);
num += furnace.getLevel().getFuelDuration() == 0 ? 0 : 1;
num += furnace.getLevel().getFuelShare() == 0 ? 0 : 1;
num += furnace.getLevel().getOverheat() == 0 ? 0 : 1;
int[] order = spots.get(num);
int current = 0;
if (furnace.getLevel().getPerformance() != 0) {
addItem(order[current], performance.build());
current++;
}
if (furnace.getLevel().getReward() != null) {
addItem(order[current], reward.build());
current++;
}
if (furnace.getLevel().getFuelDuration() != 0) {
addItem(order[current], duration.build());
current++;
}
if (furnace.getLevel().getFuelShare() != 0) {
addItem(order[current], fuelShare.build());
current++;
}
if (furnace.getLevel().getOverheat() != 0) {
addItem(order[current], overheat.build());
}
if (instance.getConfig().getBoolean("Main.Access Furnaces Remotely") && accessor.hasPermission("EpicFurnaces.Remote")) {
addItem(4, remote.build(), event -> {
if (event.getClickType().isLeftClick()) {
event.getPlayer().sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.remote.enter"));
AbstractAnvilGUI anvilGUI = new AbstractAnvilGUI(instance, event.getPlayer(), anvilEvent -> {
for (FurnaceObject other : instance.getFurnaceManager().getAllFurnaces().values()) {
if (other.getNickname() == null) {
continue;
}
if (other.getNickname().equalsIgnoreCase(anvilEvent.getName())) {
event.getPlayer().sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.remote.nicknameinuse"));
furnace.openOverview(event.getPlayer());
return;
}
}
furnace.setNickname(anvilEvent.getName());
furnace.openOverview(event.getPlayer());
event.getPlayer().sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.remote.nicknamesuccess"));
});
anvilGUI.setOnClose((closer, inv) -> furnace.openOverview(closer));
anvilGUI.setSlot(INPUT_LEFT, new ItemBuilder(PAPER).name("Enter a nickname").build());
anvilGUI.open();
} else if (event.getClickType().isRightClick()) {
if (!furnace.getAccessList().contains(event.getPlayer().getUniqueId())) {
furnace.addToAccessList(event.getPlayer().getUniqueId().toString() + ":" + event.getPlayer().getName());
furnace.openOverview(event.getPlayer());
}
}
});
}
if (instance.getConfig().getBoolean("Main.Upgrade With XP") && accessor.hasPermission("EpicFurnaces.Upgrade.XP")) {
addItem(11, xp.build(), event -> {
furnace.upgrade("XP", event.getPlayer());
furnace.openOverview(event.getPlayer());
});
}
if (instance.getConfig().getBoolean("Main.Upgrade With Economy") && accessor.hasPermission("EpicFurnaces.Upgrade.ECO")) {
addItem(15, eco.build(), event -> {
furnace.upgrade("ECO", event.getPlayer());
furnace.openOverview(event.getPlayer());
});
}
addItem(13, currentLevel.build());
}
}

View File

@ -1,339 +0,0 @@
package com.songoda.epicfurnaces.objects;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.menus.OverviewMenu;
import com.songoda.epicfurnaces.utils.NMSUtil;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Furnace;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.InventoryHolder;
import java.lang.reflect.Method;
import java.util.*;
import static com.songoda.epicfurnaces.objects.FurnaceObject.BoostType.*;
/**
* Created by songoda on 3/7/2017.
*/
public class FurnaceObject {
private final EpicFurnaces instance;
private Location location;
private Level level;
private String nickname;
private UUID placedBy;
private int uses, toLevel, radiusOverheatLast, radiusFuelShareLast;
private List<Location> radiusOverheat = new ArrayList<>();
private List<Location> radiusFuelShare = new ArrayList<>();
private List<String> accessList;
public FurnaceObject(EpicFurnaces instance, Location location, Level level, String nickname, int uses, int toLevel, List<String> accessList, UUID placedBy) {
this.instance = instance;
this.location = location;
this.level = level;
this.uses = uses;
this.toLevel = toLevel;
this.nickname = nickname;
this.placedBy = placedBy;
this.accessList = accessList;
this.syncName();
}
public void openOverview(Player player) {
if (!player.hasPermission("epicfurnaces.overview")) {
return;
}
new OverviewMenu(instance, this, player).open(player);
}
public void plus(FurnaceSmeltEvent e) {
Block block = location.getBlock();
if (block.getType() != Material.FURNACE && !block.getType().name().equals("BURNING_FURNACE")) {
return;
}
this.uses++;
this.toLevel++;
int multi = instance.getConfig().getInt("Main.Level Cost Multiplier");
if (level.getReward() == null) return;
String reward = level.getReward();
String[] amt = {"1", "1"};
if (reward.contains(":")) {
String[] rewardSplit = reward.split(":");
reward = rewardSplit[0].substring(0, rewardSplit[0].length() - 1);
if (rewardSplit[1].contains("-"))
amt = rewardSplit[1].split("-");
else {
amt[0] = rewardSplit[1];
amt[1] = rewardSplit[0];
}
}
int needed = ((multi * level.getLevel()) - toLevel) - 1;
if (instance.getConfig().getBoolean("Main.Upgrade By Smelting Materials")
&& needed <= 0
&& instance.getConfig().contains("settings.levels.Level-" + (level.getLevel() + 1))) {
toLevel = 0;
level = instance.getLevelManager().getLevel(this.level.getLevel() + 1);
}
updateCook();
FurnaceInventory inventory = (FurnaceInventory) ((InventoryHolder) block.getState()).getInventory();
int num = Integer.parseInt(reward);
double rand = Math.random() * 100;
if (rand >= num
|| e.getResult().getType().equals(Material.SPONGE)
|| instance.getConfig().getBoolean("Main.No Rewards From Custom Recipes")
&& instance.getConfiguration("Furnace Recipes").contains("Recipes." + inventory.getSmelting().getType().toString())) {
return;
}
int r = Integer.parseInt(amt[0]);
if (Integer.parseInt(amt[0]) !=
Integer.parseInt(amt[1].replace("%", "")))
r = (int) (Math.random() * ((Integer.parseInt(amt[1].replace("%", "")) - Integer.parseInt(amt[0])))) + Integer.parseInt(amt[0]);
BoostData boostData = instance.getBoostManager().getBoost(placedBy);
r = r * (boostData == null ? 1 : boostData.getMultiplier());
e.getResult().setAmount(e.getResult().getAmount() + r);
}
public void upgrade(String type, Player player) {
if (!instance.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1))
return;
int cost = type.equals("XP") ? level.getCostExperience() : level.getCostEconomy();
Level level = instance.getLevelManager().getLevel(this.level.getLevel() + 1);
if (type.equals("ECO")) {
if (instance.getEconomy().has(player, cost)) {
instance.getEconomy().withdrawPlayer(player, cost);
upgradeFinal(level, player);
return;
}
player.sendMessage(instance.getLocale().getMessage("event.upgrade.cannotafford"));
return;
}
if (player.getLevel() >= cost || player.getGameMode() == GameMode.CREATIVE) {
if (player.getGameMode() != GameMode.CREATIVE) {
player.setLevel(player.getLevel() - cost);
}
upgradeFinal(level, player);
return;
}
player.sendMessage(instance.getLocale().getMessage("event.upgrade.cannotafford"));
}
private void upgradeFinal(Level level, Player player) {
this.level = level;
syncName();
if (instance.getLevelManager().getHighestLevel() != level) {
player.sendMessage(instance.getLocale().getMessage("event.upgrade.success", level.getLevel()));
} else {
player.sendMessage(instance.getLocale().getMessage("event.upgrade.maxed", level.getLevel()));
}
Location loc = location.clone().add(.5, .5, .5);
if (instance.getCurrentVersion() > 8)
location.getWorld().spawnParticle(Particle.valueOf(instance.getConfig().getString("Main.Upgrade Particle Type")), loc.getX(), loc.getY(), loc.getZ(), 200, .5, .5, .5);
if (instance.getConfig().getBoolean("Main.Sounds Enabled")) {
if (instance.getLevelManager().getHighestLevel() != level) {
player.playSound(player.getLocation(), instance.getBukkitEnums().getSound("ENTITY_PLAYER_LEVELUP"), 0.6F, 15.0F);
} else {
player.playSound(player.getLocation(), instance.getBukkitEnums().getSound("ENTITY_PLAYER_LEVELUP"), 2F, 25.0F);
player.playSound(player.getLocation(), instance.getBukkitEnums().getSound("BLOCK_NOTE_BLOCK_CHIME"), 2F, 25.0F);
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> player.playSound(player.getLocation(), instance.getBukkitEnums().getSound("BLOCK_NOTE_BLOCK_CHIME"), 1.2F, 35.0F), 5L);
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> player.playSound(player.getLocation(), instance.getBukkitEnums().getSound("BLOCK_NOTE_BLOCK_CHIME"), 1.8F, 35.0F), 10L);
}
}
}
private void syncName() {
if (location.getBlock().getType() != Material.FURNACE && !location.getBlock().getType().name().equals("BURNING_FURNACE")) {
return;
}
String name = StringUtils.formatName(level.getLevel(), uses, false);
try {
Furnace craftFurnace = (Furnace) location.getBlock().getState();
craftFurnace.setCustomName(name);
craftFurnace.update(true);
} catch (Exception | Error e) {
try {
Object craftFurnace = NMSUtil.getCraftClass("block.CraftFurnace").cast(location.getBlock().getState());
Method getTileEntity = craftFurnace.getClass().getDeclaredMethod("getTileEntity");
Object tileEntity = getTileEntity.invoke(craftFurnace);
Method a = tileEntity.getClass().getDeclaredMethod("a", String.class);
a.invoke(tileEntity, name);
} catch (Exception | Error ignore) {
}
} finally {
location.getBlock().getState().update(true);
}
}
public void updateCook() {
Block block = location.getBlock();
if (block == null || (block.getType() != Material.FURNACE && !block.getType().name().equals("BURNING_FURNACE"))) {
return;
}
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(instance, () -> {
int num = getPerformanceTotal();
if (num > 200) {
num = 200;
}
if (num != 0) {
BlockState bs = (block.getState()); // max is 200
((Furnace) bs).setCookTime(Short.parseShort(Integer.toString(num)));
bs.update();
}
}, 1L);
}
public boolean addToAccessList(String string) {
return accessList.add(string);
}
public boolean removeFromAccessList(String string) {
return accessList.remove(string);
}
public void clearAccessList() {
accessList.clear();
}
public List<Location> getRadius(BoostType boostType) {
if (boostType == OVERHEAT) {
return radiusOverheat.isEmpty() ? null : Collections.unmodifiableList(radiusOverheat);
} else if (boostType == FUEL_SHARE) {
return radiusFuelShare.isEmpty() ? null : Collections.unmodifiableList(radiusFuelShare);
}
return null;
}
public void addToRadius(Location location, BoostType boostType) {
if (boostType == OVERHEAT) {
radiusOverheat.add(location);
} else if (boostType == FUEL_SHARE) {
radiusFuelShare.add(location);
}
}
public void clearRadius(BoostType boostType) {
if (boostType == OVERHEAT) {
radiusOverheat.clear();
} else if (boostType == FUEL_SHARE) {
radiusFuelShare.clear();
}
}
public int getRadiusLast(BoostType boostType) {
if (boostType == OVERHEAT) {
return radiusOverheatLast;
} else if (boostType == FUEL_SHARE) {
return radiusFuelShareLast;
}
return 0;
}
public void setRadiusLast(int radiusLast, BoostType boostType) {
if (boostType == OVERHEAT) {
this.radiusOverheatLast = radiusLast;
} else if (boostType == FUEL_SHARE) {
this.radiusFuelShareLast = radiusLast;
}
}
public List<UUID> getAccessList() {
List<UUID> list = new ArrayList<>();
for (String line : accessList) {
String[] halfs = line.split(":");
list.add(UUID.fromString(halfs[0]));
}
return list;
}
public Level getLevel() {
return level;
}
public Location getLocation() {
return location.clone();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public List<String> getOriginalAccessList() {
return Collections.unmodifiableList(accessList);
}
public int getPerformanceTotal() {
return (int) Math.round((level.getPerformance() / 100.0) * 200);
}
public UUID getPlacedBy() {
return placedBy;
}
public int getToLevel() {
return toLevel;
}
public int getUses() {
return uses;
}
public enum BoostType {
OVERHEAT, FUEL_SHARE
}
}

View File

@ -1,164 +0,0 @@
package com.songoda.epicfurnaces.tasks;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import com.songoda.epicfurnaces.objects.FurnaceObject.BoostType;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Furnace;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.concurrent.ThreadLocalRandom;
import static com.songoda.epicfurnaces.objects.FurnaceObject.BoostType.*;
public class FurnaceTask extends BukkitRunnable {
private static FurnaceTask plugin;
private final EpicFurnaces instance;
private FurnaceTask(EpicFurnaces plugin) {
this.instance = plugin;
}
public static void startTask(EpicFurnaces plugin) {
if (FurnaceTask.plugin == null) {
FurnaceTask.plugin = new FurnaceTask(plugin);
FurnaceTask.plugin.runTaskTimer(plugin, 0, plugin.getConfig().getInt("Main.Furnace Tick Speed"));
}
}
@Override
public void run() {
for (FurnaceObject furnace : instance.getFurnaceManager().getFurnaces().values()) {
Location furnaceLocation = furnace.getLocation();
if (furnaceLocation == null) {
continue;
}
if (furnaceLocation.getWorld() == null) {
instance.getFurnaceManager().removeFurnace(furnaceLocation);
continue;
}
if (furnace.getLocation().getBlock().getType() != Material.FURNACE &&
!furnace.getLocation().getBlock().getType().name().equals("BURNING_FURNACE")) {
continue;
}
if (((Furnace) furnaceLocation.getBlock().getState()).getBurnTime() == 0) {
continue;
}
if (furnace.getLevel().getOverheat() != 0) {
overheat(furnace);
}
if (furnace.getLevel().getFuelShare() != 0) {
fuelShare(furnace);
}
}
}
private void overheat(FurnaceObject furnace) {
if (furnace.getRadius(OVERHEAT) == null || furnace.getRadiusLast(OVERHEAT) != furnace.getLevel().getOverheat()) {
furnace.setRadiusLast(furnace.getLevel().getOverheat(), OVERHEAT);
cache(furnace, OVERHEAT);
}
for (Location location : furnace.getRadius(OVERHEAT)) {
int random = ThreadLocalRandom.current().nextInt(0, 10);
if (random != 1) {
continue;
}
Block block = location.getBlock();
if (block.getType() == Material.AIR || block.getRelative(BlockFace.UP).getType() != Material.AIR) {
continue;
}
broadcastParticles(location);
if (block.getType() == Material.SNOW) {
block.setType(Material.AIR);
continue;
}
if (block.getType() == Material.ICE || block.getType() == Material.PACKED_ICE) {
block.setType(Material.WATER);
}
}
}
private void fuelShare(FurnaceObject furnace) {
if (furnace.getRadius(FUEL_SHARE) == null || furnace.getRadiusLast(FUEL_SHARE) != furnace.getLevel().getFuelShare()) {
furnace.setRadiusLast(furnace.getLevel().getFuelShare(), FUEL_SHARE);
cache(furnace, FUEL_SHARE);
}
for (Location location : furnace.getRadius(FUEL_SHARE)) {
int random = ThreadLocalRandom.current().nextInt(0, 10);
if (random != 1) {
continue;
}
Block block = location.getBlock();
if (block.getType() != Material.FURNACE && !block.getType().name().equals("BURNING_FURNACE")) {
continue;
}
FurnaceObject other = instance.getFurnaceManager().getFurnace(block.getLocation()).orElseGet(() -> instance.getFurnaceManager().createFurnace(block.getLocation()));
if (furnace.equals(other)) {
continue;
}
if (((Furnace) furnace.getLocation().getBlock().getState()).getInventory().getFuel() == null) {
continue;
}
Furnace furnaceBlock = ((Furnace) block.getState());
if (furnaceBlock.getBurnTime() == 0) {
furnaceBlock.setBurnTime((short) 205);
furnaceBlock.update();
broadcastParticles(location);
}
}
}
private void cache(FurnaceObject furnace, BoostType boostType) {
Block block = furnace.getLocation().getBlock();
int radius = 3 * (boostType == OVERHEAT ? furnace.getLevel().getOverheat() : furnace.getLevel().getFuelShare());
int rSquared = radius * radius;
int bx = block.getX();
int by = block.getY();
int bz = block.getZ();
for (int fx = -radius; fx <= radius; fx++) {
for (int fy = -2; fy <= 1; fy++) {
for (int fz = -radius; fz <= radius; fz++) {
if ((fx * fx) + (fz * fz) <= rSquared) {
Location location = new Location(block.getWorld(), bx + fx, by + fy, bz + fz);
furnace.addToRadius(location, boostType);
}
}
}
}
}
private void broadcastParticles(Location location) {
if (instance.getConfig().getBoolean("Main.Overheat Particles")) {
if (instance.getCurrentVersion() > 8)
location.getWorld().spawnParticle(Particle.SMOKE_NORMAL, location.getX(), location.getY(), location.getZ(), 25, 0, 0, 0, 0);
}
}
}

View File

@ -1,36 +0,0 @@
package com.songoda.epicfurnaces.tasks;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.scheduler.BukkitRunnable;
public class HologramTask extends BukkitRunnable {
private static HologramTask task;
private final EpicFurnaces instance;
private HologramTask(EpicFurnaces instance) {
this.instance = instance;
}
public static void startTask(EpicFurnaces plugin) {
if (task == null) {
task = new HologramTask(plugin);
task.runTaskTimer(plugin, 0, 20L);
}
}
@Override
public void run() {
if (!instance.getConfig().getBoolean("Main.Furnaces Have Holograms")) {
return;
}
if (instance.getFurnaceManager() == null) {
return;
}
instance.getFurnaceManager().getFurnaces().values().stream()
.filter(furnace -> furnace.getLocation().getBlock() != null)
.forEach(furnace -> instance.getHologramManager().ifPresent(manager -> manager.updateHologram(furnace)));
}
}

View File

@ -1,922 +0,0 @@
package com.songoda.epicfurnaces.utils;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class BukkitEnums {
private final EpicFurnaces instance;
private final Map<String, String> soundMap = new HashMap<String, String>() {{
put("ENTITY_PLAYER_LEVELUP", "LEVEL_UP");
put("BLOCK_NOTE_BLOCK_CHIME", "NOTE_PLING");
put("NAN", "NAN");
}};
public BukkitEnums(EpicFurnaces instance) {
this.instance = instance;
}
public Sound getSound(String name) {
if (Arrays.stream(Sound.values()).anyMatch(s -> s.toString().equalsIgnoreCase(name))) {
return Sound.valueOf(name.toUpperCase());
}
if (Arrays.stream(Sound.values()).anyMatch(s -> s.toString().equalsIgnoreCase(soundMap.getOrDefault(name, "NAN")))) {
return Sound.valueOf(soundMap.get(name.toUpperCase()));
}
return null;
}
public ItemStack getMaterial(String string) {
Material material = Material.matchMaterial(string);
if (material != null) {
return new ItemStack(material);
}
return VersionEnum.requestMaterial(string);
}
private enum VersionEnum {
ACACIA_BOAT(0, "BOAT_ACACIA"),
ACACIA_BUTTON(0, "WOOD_BUTTON"),
ACACIA_DOOR(0, "ACACIA_DOOR", "ACACIA_DOOR_ITEM"),
ACACIA_FENCE(0, "ACACIA_FENCE"),
ACACIA_FENCE_GATE(0, "ACACIA_FENCE_GATE"),
ACACIA_LEAVES(0, "LEAVES_2"),
ACACIA_LOG(0, "LOG_2"),
ACACIA_PLANKS(4, "WOOD"),
ACACIA_PRESSURE_PLATE(0, "WOOD_PLATE"),
ACACIA_SAPLING(4, "SAPLING"),
ACACIA_SLAB(4, "WOODEN_SLAB", "WOOD_STEP", "WOOD_DOUBLE_STEP"),
ACACIA_STAIRS(4, "ACACIA_STAIRS"),
ACACIA_TRAPDOOR(0, "TRAP_DOOR"),
ACACIA_WOOD(0, "LOG_2"),
ACTIVATOR_RAIL(0, "ACTIVATOR_RAIL"),
AIR(0, "AIR"),
ALLIUM(2, "RED_ROSE"),
ANDESITE(5, "STONE"),
ANVIL(0, "ANVIL"),
APPLE(0, "APPLE"),
ARMOR_STAND(0, "ARMOR_STAND"),
ARROW(0, "ARROW"),
ATTACHED_MELON_STEM(7, "MELON_STEM"),
ATTACHED_PUMPKIN_STEM(7, "PUMPKIN_STEM"),
AZURE_BLUET(3, "RED_ROSE"),
BAKED_POTATO(0, "BAKED_POTATO"),
BARRIER(0, "BARRIER"),
BAT_SPAWN_EGG(0, "MONSTER_EGG"),
BEACON(0, "BEACON"),
BEDROCK(0, "BEDROCK"),
BEEF(0, "RAW_BEEF"),
BEETROOT(0, "BEETROOT"),
BEETROOTS(0, "BEETROOT", "BEETROOT_BLOCK"),
BEETROOT_SEEDS(0, "BEETROOT_SEEDS"),
BEETROOT_SOUP(0, "BEETROOT_SOUP"),
BIRCH_BOAT(0, "BOAT_BIRCH"),
BIRCH_BUTTON(0, "WOOD_BUTTON"),
BIRCH_DOOR(0, "BIRCH_DOOR", "BIRCH_DOOR_ITEM"),
BIRCH_FENCE(0, "BIRCH_FENCE"),
BIRCH_FENCE_GATE(0, "BIRCH_FENCE_GATE"),
BIRCH_LEAVES(2, "LEAVES"),
BIRCH_LOG(2, "LOG"),
BIRCH_PLANKS(2, "WOOD"),
BIRCH_PRESSURE_PLATE(0, "WOOD_PLATE"),
BIRCH_SAPLING(2, "SAPLING"),
BIRCH_SLAB(2, "WOODEN_SLAB", "WOOD_STEP", "WOOD_DOUBLE_STEP"),
BIRCH_STAIRS(0, "BIRCH_WOOD_STAIRS"),
BIRCH_TRAPDOOR(0, "TRAP_DOOR"),
BIRCH_WOOD(2, "LOG"),
BLACK_BANNER(0, "BANNER", "STANDING_BANNER"),
BLACK_BED(15, "BED", "BED_BLOCK"),
BLACK_CARPET(15, "CARPET"),
BLACK_CONCRETE(15, "CONCRETE"),
BLACK_CONCRETE_POWDER(15, "CONCRETE_POWDER"),
BLACK_GLAZED_TERRACOTTA(0, "BLACK_GLAZED_TERRACOTTA"),
BLACK_SHULKER_BOX(0, "BLACK_SHULKER_BOX"),
BLACK_STAINED_GLASS(15, "STAINED_GLASS"),
BLACK_STAINED_GLASS_PANE(15, "STAINED_GLASS_PANE"),
BLACK_TERRACOTTA(15, "STAINED_CLAY"),
BLACK_WALL_BANNER(0, "WALL_BANNER"),
BLACK_WOOL(15, "WOOL"),
BLAZE_POWDER(0, "BLAZE_POWDER"),
BLAZE_ROD(0, "BLAZE_ROD"),
BLAZE_SPAWN_EGG(0, "MONSTER_EGG"),
BLUE_BANNER(11, "BANNER", "STANDING_BANNER"),
BLUE_BED(4, "BED", "BED_BLOCK"),
BLUE_CARPET(11, "CARPET"),
BLUE_CONCRETE(11, "CONCRETE"),
BLUE_CONCRETE_POWDER(11, "CONCRETE_POWDER"),
BLUE_GLAZED_TERRACOTTA(0, "BLUE_GLAZED_TERRACOTTA"),
BLUE_ICE(0, "PACKED_ICE"),
BLUE_ORCHID(1, "RED_ROSE"),
BLUE_SHULKER_BOX(0, "BLUE_SHULKER_BOX"),
BLUE_STAINED_GLASS(11, "STAINED_GLASS"),
BLUE_STAINED_GLASS_PANE(11, "STAINED_GLASS_PANE"),
BLUE_TERRACOTTA(11, "STAINED_CLAY"),
BLUE_WALL_BANNER(11, "WALL_BANNER"),
BLUE_WOOL(11, "WOOL"),
BONE(0, "BONE"),
BONE_BLOCK(0, "BONE_BLOCK"),
BONE_MEAL(15, "INK_SACK"),
BOOK(0, "BOOK"),
BOOKSHELF(0, "BOOKSHELF"),
BOW(0, "BOW"),
BOWL(0, "BOWL"),
BRAIN_CORAL(0, "STONE"),
BRAIN_CORAL_BLOCK(0, "STONE"),
BRAIN_CORAL_FAN(0, "STONE"),
BREAD(0, "BREAD"),
BREWING_STAND(0, "BREWING_STAND", "BREWING_STAND_ITEM"),
BRICK(0, "CLAY_BRICK"),
BRICKS(0, "BRICK"),
BRICK_SLAB(4, "STEP"),
BRICK_STAIRS(0, "BRICK_STAIRS"),
BROWN_BANNER(3, "BANNER", "STANDING_BANNER"),
BROWN_BED(12, "BED", "BED_BLOCK"),
BROWN_CARPET(12, "CARPET"),
BROWN_CONCRETE(12, "CONCRETE"),
BROWN_CONCRETE_POWDER(12, "CONCRETE_POWDER"),
BROWN_GLAZED_TERRACOTTA(0, "BROWN_GLAZED_TERRACOTTA"),
BROWN_MUSHROOM(0, "BROWN_MUSHROOM"),
BROWN_MUSHROOM_BLOCK(0, "BROWN_MUSHROOM", "HUGE_MUSHROOM_1"),
BROWN_SHULKER_BOX(0, "BROWN_SHULKER_BOX"),
BROWN_STAINED_GLASS(12, "STAINED_GLASS"),
BROWN_STAINED_GLASS_PANE(12, "STAINED_GLASS_PANE"),
BROWN_TERRACOTTA(12, "STAINED_CLAY"),
BROWN_WALL_BANNER(3, "WALL_BANNER"),
BROWN_WOOL(12, "WOOL"),
BUBBLE_COLUMN(0, "STONE"),
BUBBLE_CORAL(0, "STONE"),
BUBBLE_CORAL_BLOCK(0, "STONE"),
BUBBLE_CORAL_FAN(0, "STONE"),
BUCKET(0, "BUCKET"),
CACTUS(0, "CACTUS"),
CACTUS_GREEN(2, "INK_SACK"),
CAKE(0, "CAKE", "CAKE_BLOCK"),
CARROT(0, "CARROT_ITEM"),
CARROTS(0, "CARROT"),
CARROT_ON_A_STICK(0, "CARROT_STICK"),
CARVED_PUMPKIN(0, "PUMPKIN"),
CAULDRON(0, "CAULDRON", "CAULDRON_ITEM"),
CAVE_AIR(0, "AIR"),
CAVE_SPIDER_SPAWN_EGG(0, "MONSTER_EGG"),
CHAINMAIL_BOOTS(0, "CHAINMAIL_BOOTS"),
CHAINMAIL_CHESTPLATE(0, "CHAINMAIL_CHESTPLATE"),
CHAINMAIL_HELMET(0, "CHAINMAIL_HELMET"),
CHAINMAIL_LEGGINGS(0, "CHAINMAIL_LEGGINGS"),
CHAIN_COMMAND_BLOCK(0, "COMMAND_CHAIN"),
CHARCOAL(1, "COAL"),
CHEST(0, "CHEST", "LOCKED_CHEST"),
CHEST_MINECART(0, "STORAGE_MINECART"),
CHICKEN(0, "RAW_CHICKEN"),
CHICKEN_SPAWN_EGG(0, "MONSTER_EGG"),
CHIPPED_ANVIL(1, "ANVIL"),
CHISELED_QUARTZ_BLOCK(1, "QUARTZ_BLOCK"),
CHISELED_RED_SANDSTONE(1, "RED_SANDSTONE"),
CHISELED_SANDSTONE(1, "SANDSTONE"),
CHISELED_STONE_BRICKS(3, "SMOOTH_BRICK"),
CHORUS_FLOWER(0, "CHORUS_FLOWER"),
CHORUS_FRUIT(0, "CHORUS_FRUIT"),
CHORUS_PLANT(0, "CHORUS_PLANT"),
CLAY(0, "CLAY"),
CLAY_BALL(0, "CLAY_BALL"),
CLOCK(0, "WATCH"),
COAL(0, "COAL"),
COAL_BLOCK(0, "COAL_BLOCK"),
COAL_ORE(0, "COAL_ORE"),
COARSE_DIRT(1, "DIRT"),
COBBLESTONE(0, "COBBLESTONE"),
COBBLESTONE_SLAB(3, "STEP"),
COBBLESTONE_STAIRS(0, "COBBLESTONE_STAIRS"),
COBBLESTONE_WALL(0, "COBBLE_WALL"),
COBWEB(0, "WEB"),
COCOA(0, "COCOA"),
COCOA_BEANS(3, "INK_SACK"),
COD(0, "RAW_FISH"),
COD_BUCKET(0, "BUCKET"),
COD_SPAWN_EGG(0, "MONSTER_EGG"),
COMMAND_BLOCK(0, "COMMAND"),
COMMAND_BLOCK_MINECART(0, "COMMAND_MINECART"),
COMPARATOR(0, "REDSTONE_COMPARATOR", "REDSTONE_COMPARATOR_ON", "REDSTONE_COMPARATOR_OFF"),
COMPASS(0, "COMPASS"),
CONDUIT(0, "STONE"),
COOKED_BEEF(0, "COOKED_BEEF"),
COOKED_CHICKEN(0, "COOKED_CHICKEN"),
COOKED_COD(0, "COOKED_FISH"),
COOKED_MUTTON(0, "COOKED_MUTTON"),
COOKED_PORKCHOP(0, "GRILLED_PORK"),
COOKED_RABBIT(0, "COOKED_RABBIT"),
COOKED_SALMON(1, "COOKED_FISH"),
COOKIE(0, "COOKIE"),
COW_SPAWN_EGG(0, "MONSTER_EGG"),
CRACKED_STONE_BRICKS(2, "SMOOTH_BRICK"),
CRAFTING_TABLE(0, "WORKBENCH"),
CREEPER_HEAD(0, "SKULL", "SKULL_ITEM"),
CREEPER_SPAWN_EGG(0, "MONSTER_EGG"),
CREEPER_WALL_HEAD(0, "SKULL", "SKULL_ITEM"),
CUT_RED_SANDSTONE(0, "STONE"),
CUT_SANDSTONE(0, "STONE"),
CYAN_BANNER(6, "BANNER", "STANDING_BANNER"),
CYAN_BED(9, "BED", "BED_BLOCK"),
CYAN_CARPET(9, "CARPET"),
CYAN_CONCRETE(9, "CONCRETE"),
CYAN_CONCRETE_POWDER(9, "CONCRETE_POWDER"),
CYAN_DYE(6, "INK_SACK"),
CYAN_GLAZED_TERRACOTTA(0, "CYAN_GLAZED_TERRACOTTA"),
CYAN_SHULKER_BOX(0, "CYAN_SHULKER_BOX"),
CYAN_STAINED_GLASS(9, "STAINED_GLASS"),
CYAN_STAINED_GLASS_PANE(9, "STAINED_GLASS_PANE"),
CYAN_TERRACOTTA(9, "STAINED_CLAY"),
CYAN_WALL_BANNER(0, "WALL_BANNER"),
CYAN_WOOL(9, "WOOL"),
DAMAGED_ANVIL(2, "ANVIL"),
DANDELION(0, "YELLOW_FLOWER"),
DANDELION_YELLOW(11, "INK_SACK"),
DARK_OAK_BOAT(0, "BOAT_DARK_OAK"),
DARK_OAK_BUTTON(0, "WOOD_BUTTON"),
DARK_OAK_DOOR(0, "DARK_OAK_DOOR", "DARK_OAK_DOOR_ITEM"),
DARK_OAK_FENCE(0, "DARK_OAK_FENCE"),
DARK_OAK_FENCE_GATE(0, "DARK_OAK_FENCE_GATE"),
DARK_OAK_LEAVES(1, "LEAVES_2"),
DARK_OAK_LOG(1, "LOG_2"),
DARK_OAK_PLANKS(5, "WOOD"),
DARK_OAK_PRESSURE_PLATE(0, "WOOD_PLATE"),
DARK_OAK_SAPLING(5, "SAPLING"),
DARK_OAK_SLAB(0, "WOODEN_SLAB", "WOOD_STEP", "WOOD_DOUBLE_STEP"),
DARK_OAK_STAIRS(0, "DARK_OAK_STAIRS"),
DARK_OAK_TRAPDOOR(0, "TRAP_DOOR"),
DARK_OAK_WOOD(1, "LOG_2"),
DARK_PRISMARINE(2, "PRISMARINE"),
DARK_PRISMARINE_SLAB(0, "STONE"),
DARK_PRISMARINE_STAIRS(0, "STONE"),
DAYLIGHT_DETECTOR(0, "DAYLIGHT_DETECTOR", "DAYLIGHT_DETECTOR_INVERTED"),
DEAD_BRAIN_CORAL_BLOCK(0, "STONE"),
DEAD_BUBBLE_CORAL_BLOCK(0, "STONE"),
DEAD_BUSH(0, "DEAD_BUSH"),
DEAD_FIRE_CORAL_BLOCK(0, "STONE"),
DEAD_HORN_CORAL_BLOCK(0, "STONE"),
DEAD_TUBE_CORAL_BLOCK(0, "STONE"),
DEBUG_STICK(0, "STICK"),
DETECTOR_RAIL(0, "DETECTOR_RAIL"),
DIAMOND(0, "DIAMOND"),
DIAMOND_AXE(0, "DIAMOND_AXE"),
DIAMOND_BLOCK(0, "DIAMOND_BLOCK"),
DIAMOND_BOOTS(0, "DIAMOND_BOOTS"),
DIAMOND_CHESTPLATE(0, "DIAMOND_CHESTPLATE"),
DIAMOND_HELMET(0, "DIAMOND_HELMET"),
DIAMOND_HOE(0, "DIAMOND_HOE"),
DIAMOND_HORSE_ARMOR(0, "DIAMOND_BARDING"),
DIAMOND_LEGGINGS(0, "DIAMOND_LEGGINGS"),
DIAMOND_ORE(0, "DIAMOND_ORE"),
DIAMOND_PICKAXE(0, "DIAMOND_PICKAXE"),
DIAMOND_SHOVEL(0, "DIAMOND_SPADE"),
DIAMOND_SWORD(0, "DIAMOND_SWORD"),
DIORITE(3, "STONE"),
DIRT(0, "DIRT"),
DISPENSER(0, "DISPENSER"),
DOLPHIN_SPAWN_EGG(0, "MONSTER_EGG"),
DONKEY_SPAWN_EGG(0, "MONSTER_EGG"),
DRAGON_BREATH(0, "DRAGONS_BREATH"),
DRAGON_EGG(0, "DRAGON_EGG"),
DRAGON_HEAD(5, "SKULL", "SKULL_ITEM"),
DRAGON_WALL_HEAD(0, "SKULL", "SKULL_ITEM"),
DRIED_KELP(0, "STONE"),
DRIED_KELP_BLOCK(0, "STONE"),
DROPPER(0, "DROPPER"),
DROWNED_SPAWN_EGG(0, "MONSTER_EGG"),
EGG(0, "EGG"),
ELDER_GUARDIAN_SPAWN_EGG(0, "MONSTER_EGG"),
ELYTRA(0, "ELYTRA"),
EMERALD(0, "EMERALD"),
EMERALD_BLOCK(0, "EMERALD_BLOCK"),
EMERALD_ORE(0, "EMERALD_ORE"),
ENCHANTED_BOOK(0, "ENCHANTED_BOOK"),
ENCHANTED_GOLDEN_APPLE(1, "GOLDEN_APPLE"),
ENCHANTING_TABLE(0, "ENCHANTMENT_TABLE"),
ENDERMAN_SPAWN_EGG(0, "MONSTER_EGG"),
ENDERMITE_SPAWN_EGG(0, "MONSTER_EGG"),
ENDER_CHEST(0, "ENDER_CHEST"),
ENDER_EYE(0, "EYE_OF_ENDER"),
ENDER_PEARL(0, "ENDER_PEARL"),
END_CRYSTAL(0, "END_CRYSTAL"),
END_GATEWAY(0, "END_GATEWAY"),
END_PORTAL(0, "ENDER_PORTAL"),
END_PORTAL_FRAME(0, "ENDER_PORTAL_FRAME"),
END_ROD(0, "END_ROD"),
END_STONE(0, "ENDER_STONE"),
END_STONE_BRICKS(0, "END_BRICKS"),
EVOKER_SPAWN_EGG(0, "MONSTER_EGG"),
EXPERIENCE_BOTTLE(0, "EXP_BOTTLE"),
FARMLAND(0, "SOIL"),
FEATHER(0, "FEATHER"),
FERMENTED_SPIDER_EYE(0, "FERMENTED_SPIDER_EYE"),
FERN(2, "LONG_GRASS"),
FILLED_MAP(0, "MAP"),
FIRE(0, "FIRE"),
FIREWORK_ROCKET(0, "FIREWORK"),
FIREWORK_STAR(0, "FIREWORK_CHARGE"),
FIRE_CHARGE(0, "FIREBALL"),
FIRE_CORAL(0, "STONE"),
FIRE_CORAL_BLOCK(0, "STONE"),
FIRE_CORAL_FAN(0, "STONE"),
FISHING_ROD(0, "FISHING_ROD"),
FLINT(0, "FLINT"),
FLINT_AND_STEEL(0, "FLINT_AND_STEEL"),
FLOWER_POT(0, "FLOWER_POT", "FLOWER_POT_ITEM"),
FROSTED_ICE(0, "FROSTED_ICE"),
FURNACE(0, "FURNACE", "BURNING_FURNACE"),
FURNACE_MINECART(0, "POWERED_MINECART"),
GHAST_SPAWN_EGG(0, "MONSTER_EGG"),
GHAST_TEAR(0, "GHAST_TEAR"),
GLASS(0, "GLASS"),
GLASS_BOTTLE(0, "GLASS_BOTTLE"),
GLASS_PANE(0, "THIN_GLASS"),
GLISTERING_MELON_SLICE(0, "SPECKLED_MELON"),
GLOWSTONE(0, "GLOWSTONE"),
GLOWSTONE_DUST(0, "GLOWSTONE_DUST"),
GOLDEN_APPLE(0, "GOLDEN_APPLE"),
GOLDEN_AXE(0, "GOLD_AXE"),
GOLDEN_BOOTS(0, "GOLD_BOOTS"),
GOLDEN_CARROT(0, "GOLDEN_CARROT"),
GOLDEN_CHESTPLATE(0, "GOLD_CHESTPLATE"),
GOLDEN_HELMET(0, "GOLD_HELMET"),
GOLDEN_HOE(0, "GOLD_HOE"),
GOLDEN_HORSE_ARMOR(0, "GOLD_BARDING"),
GOLDEN_LEGGINGS(0, "GOLD_LEGGINGS"),
GOLDEN_PICKAXE(0, "GOLD_PICKAXE"),
GOLDEN_SHOVEL(0, "GOLD_SPADE"),
GOLDEN_SWORD(0, "GOLD_SWORD"),
GOLD_BLOCK(0, "GOLD_BLOCK"),
GOLD_INGOT(0, "GOLD_INGOT"),
GOLD_NUGGET(0, "GOLD_NUGGET"),
GOLD_ORE(0, "GOLD_ORE"),
GRANITE(1, "STONE"),
GRASS(0, "GRASS"),
GRASS_BLOCK(0, "GRASS"),
GRASS_PATH(0, "GRASS_PATH"),
GRAVEL(0, "GRAVEL"),
GRAY_BANNER(8, "BANNER", "STANDING_BANNER"),
GRAY_BED(7, "BED", "BED_BLOCK"),
GRAY_CARPET(7, "CARPET"),
GRAY_CONCRETE(7, "CONCRETE"),
GRAY_CONCRETE_POWDER(7, "CONCRETE_POWDER"),
GRAY_DYE(8, "INK_SACK"),
GRAY_GLAZED_TERRACOTTA(0, "GRAY_GLAZED_TERRACOTTA"),
GRAY_SHULKER_BOX(0, "GRAY_SHULKER_BOX"),
GRAY_STAINED_GLASS(7, "STAINED_GLASS"),
GRAY_STAINED_GLASS_PANE(7, "STAINED_GLASS_PANE"),
GRAY_TERRACOTTA(7, "STAINED_CLAY"),
GRAY_WALL_BANNER(0, "WALL_BANNER"),
GRAY_WOOL(7, "WOOL"),
GREEN_BANNER(2, "BANNER", "STANDING_BANNER"),
GREEN_BED(13, "BED", "BED_BLOCK"),
GREEN_CARPET(13, "CARPET"),
GREEN_CONCRETE(13, "CONCRETE"),
GREEN_CONCRETE_POWDER(13, "CONCRETE_POWDER"),
GREEN_GLAZED_TERRACOTTA(0, "GREEN_GLAZED_TERRACOTTA"),
GREEN_SHULKER_BOX(0, "GREEN_SHULKER_BOX"),
GREEN_STAINED_GLASS(13, "STAINED_GLASS"),
GREEN_STAINED_GLASS_PANE(13, "STAINED_GLASS_PANE"),
GREEN_TERRACOTTA(13, "STAINED_CLAY"),
GREEN_WALL_BANNER(0, "WALL_BANNER"),
GREEN_WOOL(13, "WOOL"),
GUARDIAN_SPAWN_EGG(0, "MONSTER_EGG"),
GUNPOWDER(0, "SULPHUR"),
HAY_BLOCK(0, "HAY_BLOCK"),
HEART_OF_THE_SEA(0, "STONE"),
HEAVY_WEIGHTED_PRESSURE_PLATE(0, "IRON_PLATE"),
HOPPER(0, "HOPPER"),
HOPPER_MINECART(0, "HOPPER_MINECART"),
HORN_CORAL(0, "STONE"),
HORN_CORAL_BLOCK(0, "STONE"),
HORN_CORAL_FAN(0, "STONE"),
HORSE_SPAWN_EGG(0, "MONSTER_EGG"),
HUSK_SPAWN_EGG(0, "MONSTER_EGG"),
ICE(0, "ICE"),
INFESTED_CHISELED_STONE_BRICKS(5, "MONSTER_EGGS"),
INFESTED_COBBLESTONE(1, "MONSTER_EGGS"),
INFESTED_CRACKED_STONE_BRICKS(4, "MONSTER_EGGS"),
INFESTED_MOSSY_STONE_BRICKS(3, "MONSTER_EGGS"),
INFESTED_STONE(0, "MONSTER_EGGS"),
INFESTED_STONE_BRICKS(2, "MONSTER_EGGS"),
INK_SAC(0, "INK_SACK"),
IRON_AXE(0, "IRON_AXE"),
IRON_BARS(0, "IRON_FENCE"),
IRON_BLOCK(0, "IRON_BLOCK"),
IRON_BOOTS(0, "IRON_BOOTS"),
IRON_CHESTPLATE(0, "IRON_CHESTPLATE"),
IRON_DOOR(0, "IRON_DOOR", "IRON_DOOR_BLOCK"),
IRON_HELMET(0, "IRON_HELMET"),
IRON_HOE(0, "IRON_HOE"),
IRON_HORSE_ARMOR(0, "IRON_BARDING"),
IRON_INGOT(0, "IRON_INGOT"),
IRON_LEGGINGS(0, "IRON_LEGGINGS"),
IRON_NUGGET(0, "IRON_NUGGET"),
IRON_ORE(0, "IRON_ORE"),
IRON_PICKAXE(0, "IRON_PICKAXE"),
IRON_SHOVEL(0, "IRON_SPADE"),
IRON_SWORD(0, "IRON_SWORD"),
IRON_TRAPDOOR(0, "IRON_TRAPDOOR"),
ITEM_FRAME(0, "ITEM_FRAME"),
JACK_O_LANTERN(0, "JACK_O_LANTERN"),
JUKEBOX(0, "JUKEBOX"),
JUNGLE_BOAT(0, "BOAT_JUNGLE"),
JUNGLE_BUTTON(0, "WOOD_BUTTON"),
JUNGLE_DOOR(0, "JUNGLE_DOOR", "JUNGLE_DOOR_ITEM"),
JUNGLE_FENCE(0, "JUNGLE_FENCE"),
JUNGLE_FENCE_GATE(0, "JUNGLE_FENCE_GATE"),
JUNGLE_LEAVES(3, "LEAVES"),
JUNGLE_LOG(3, "LOG"),
JUNGLE_PLANKS(3, "WOOD"),
JUNGLE_PRESSURE_PLATE(0, "WOOD_PLATE"),
JUNGLE_SAPLING(3, "SAPLING"),
JUNGLE_SLAB(3, "WOODEN_SLAB", "WOOD_STEP", "WOOD_DOUBLE_STEP"),
JUNGLE_STAIRS(0, "JUNGLE_WOOD_STAIRS"),
JUNGLE_TRAPDOOR(0, "TRAP_DOOR"),
JUNGLE_WOOD(3, "LOG"),
KELP(0, "STONE"),
KELP_PLANT(0, "STONE"),
KNOWLEDGE_BOOK(0, "KNOWLEDGE_BOOK"),
LADDER(0, "LADDER"),
LAPIS_BLOCK(0, "LAPIS_BLOCK"),
LAPIS_LAZULI(4, "INK_SACK"),
LAPIS_ORE(0, "LAPIS_ORE"),
LARGE_FERN(3, "DOUBLE_PLANT"),
LAVA(0, "LAVA", "STATIONARY_LAVA"),
LAVA_BUCKET(0, "LAVA_BUCKET"),
LEAD(0, "LEASH"),
LEATHER(0, "LEATHER"),
LEATHER_BOOTS(0, "LEATHER_BOOTS"),
LEATHER_CHESTPLATE(0, "LEATHER_CHESTPLATE"),
LEATHER_HELMET(0, "LEATHER_HELMET"),
LEATHER_LEGGINGS(0, "LEATHER_LEGGINGS"),
LEVER(0, "LEVER"),
LIGHT_BLUE_BANNER(12, "BANNER", "STANDING_BANNER"),
LIGHT_BLUE_BED(3, "BED", "BED_BLOCK"),
LIGHT_BLUE_CARPET(3, "CARPET"),
LIGHT_BLUE_CONCRETE(3, "CONCRETE"),
LIGHT_BLUE_CONCRETE_POWDER(3, "CONCRETE_POWDER"),
LIGHT_BLUE_DYE(12, "INK_SACK"),
LIGHT_BLUE_GLAZED_TERRACOTTA(0, "LIGHT_BLUE_GLAZED_TERRACOTTA"),
LIGHT_BLUE_SHULKER_BOX(0, "LIGHT_BLUE_SHULKER_BOX"),
LIGHT_BLUE_STAINED_GLASS(3, "STAINED_GLASS"),
LIGHT_BLUE_STAINED_GLASS_PANE(3, "STAINED_GLASS_PANE"),
LIGHT_BLUE_TERRACOTTA(3, "STAINED_CLAY"),
LIGHT_BLUE_WALL_BANNER(0, "BANNER", "STANDING_BANNER"),
LIGHT_BLUE_WOOL(3, "WOOL"),
LIGHT_GRAY_BANNER(7, "BANNER", "STANDING_BANNER"),
LIGHT_GRAY_BED(8, "BED", "BED_BLOCK"),
LIGHT_GRAY_CARPET(8, "CARPET"),
LIGHT_GRAY_CONCRETE(8, "CONCRETE"),
LIGHT_GRAY_CONCRETE_POWDER(8, "CONCRETE_POWDER"),
LIGHT_GRAY_DYE(7, "INK_SACK"),
LIGHT_GRAY_GLAZED_TERRACOTTA(0, "SILVER_GLAZED_TERRACOTTA"),
LIGHT_GRAY_SHULKER_BOX(0, "SILVER_SHULKER_BOX"),
LIGHT_GRAY_STAINED_GLASS(8, "STAINED_GLASS"),
LIGHT_GRAY_STAINED_GLASS_PANE(8, "STAINED_GLASS_PANE"),
LIGHT_GRAY_TERRACOTTA(8, "STAINED_CLAY"),
LIGHT_GRAY_WALL_BANNER(0, "WALL_BANNER"),
LIGHT_GRAY_WOOL(8, "WOOL"),
LIGHT_WEIGHTED_PRESSURE_PLATE(0, "GOLD_PLATE"),
LILAC(1, "DOUBLE_PLANT"),
LILY_PAD(0, "WATER_LILY"),
LIME_BANNER(10, "BANNER", "STANDING_BANNER"),
LIME_BED(5, "BED", "BED_BLOCK"),
LIME_CARPET(5, "CARPET"),
LIME_CONCRETE(5, "CONCRETE"),
LIME_CONCRETE_POWDER(5, "CONCRETE_POWDER"),
LIME_DYE(10, "INK_SACK"),
LIME_GLAZED_TERRACOTTA(0, "LIME_GLAZED_TERRACOTTA"),
LIME_SHULKER_BOX(0, "LIME_SHULKER_BOX"),
LIME_STAINED_GLASS(5, "STAINED_GLASS"),
LIME_STAINED_GLASS_PANE(5, "STAINED_GLASS_PANE"),
LIME_TERRACOTTA(5, "STAINED_CLAY"),
LIME_WALL_BANNER(0, "WALL_BANNER"),
LIME_WOOL(5, "WOOL"),
LINGERING_POTION(0, "LINGERING_POTION"),
LLAMA_SPAWN_EGG(0, "MONSTER_EGG"),
MAGENTA_BANNER(13, "BANNER", "STANDING_BANNER"),
MAGENTA_BED(2, "BED", "BED_BLOCK"),
MAGENTA_CARPET(2, "CARPET"),
MAGENTA_CONCRETE(2, "CONCRETE"),
MAGENTA_CONCRETE_POWDER(2, "CONCRETE_POWDER"),
MAGENTA_DYE(13, "INK_SACK"),
MAGENTA_GLAZED_TERRACOTTA(0, "MAGENTA_GLAZED_TERRACOTTA"),
MAGENTA_SHULKER_BOX(0, "MAGENTA_SHULKER_BOX"),
MAGENTA_STAINED_GLASS(2, "STAINED_GLASS"),
MAGENTA_STAINED_GLASS_PANE(2, "STAINED_GLASS_PANE"),
MAGENTA_TERRACOTTA(2, "STAINED_CLAY"),
MAGENTA_WALL_BANNER(0, "WALL_BANNER"),
MAGENTA_WOOL(2, "WOOL"),
MAGMA_BLOCK(0, "MAGMA"),
MAGMA_CREAM(0, "MAGMA_CREAM"),
MAGMA_CUBE_SPAWN_EGG(0, "MONSTER_EGG"),
MAP(0, "MAP", "EMPTY_MAP"),
MELON(0, "MELON_BLOCK"),
MELON_SEEDS(0, "MELON_SEEDS"),
MELON_SLICE(0, "MELON"),
MELON_STEM(0, "MELON_STEM"),
MILK_BUCKET(0, "MILK_BUCKET"),
MINECART(0, "MINECART"),
MOOSHROOM_SPAWN_EGG(0, "MONSTER_EGG"),
MOSSY_COBBLESTONE(0, "MOSSY_COBBLESTONE"),
MOSSY_COBBLESTONE_WALL(1, "COBBLE_WALL"),
MOSSY_STONE_BRICKS(1, "SMOOTH_BRICK"),
MOVING_PISTON(0, "PISTON_MOVING_PIECE"),
MULE_SPAWN_EGG(0, "MONSTER_EGG"),
MUSHROOM_STEM(0, "BROWN_MUSHROOM"),
MUSHROOM_STEW(0, "MUSHROOM_SOUP"),
MUSIC_DISC_11(0, "GOLD_RECORD"),
MUSIC_DISC_13(0, "GREEN_RECORD"),
MUSIC_DISC_BLOCKS(0, "RECORD_3"),
MUSIC_DISC_CAT(0, "RECORD_4"),
MUSIC_DISC_CHIRP(0, "RECORD_5"),
MUSIC_DISC_FAR(0, "RECORD_6"),
MUSIC_DISC_MALL(0, "RECORD_7"),
MUSIC_DISC_MELLOHI(0, "RECORD_8"),
MUSIC_DISC_STAL(0, "RECORD_9"),
MUSIC_DISC_STRAD(0, "RECORD_10"),
MUSIC_DISC_WAIT(0, "RECORD_11"),
MUSIC_DISC_WARD(0, "RECORD_12"),
MUTTON(0, "MUTTON"),
MYCELIUM(0, "MYCEL"),
NAME_TAG(0, "NAME_TAG"),
NAUTILUS_SHELL(0, "STONE"),
NETHERRACK(0, "NETHERRACK"),
NETHER_BRICK(0, "NETHER_BRICK"),
NETHER_BRICKS(0, "NETHER_BRICK"),
NETHER_BRICK_FENCE(0, "NETHER_FENCE"),
NETHER_BRICK_SLAB(6, "STEP"),
NETHER_BRICK_STAIRS(0, "NETHER_BRICK_STAIRS"),
NETHER_PORTAL(0, "PORTAL"),
NETHER_QUARTZ_ORE(0, "QUARTZ_ORE"),
NETHER_STAR(0, "NETHER_STAR"),
NETHER_WART(0, "NETHER_STALK"),
NETHER_WART_BLOCK(0, "NETHER_WART_BLOCK", "NETHER_WARTS"),
NOTE_BLOCK(0, "NOTE_BLOCK"),
OAK_BOAT(0, "BOAT"),
OAK_BUTTON(0, "WOOD_BUTTON"),
OAK_DOOR(0, "WOODEN_DOOR", "WOOD_DOOR"),
OAK_FENCE(0, "FENCE"),
OAK_FENCE_GATE(0, "FENCE_GATE"),
OAK_LEAVES(0, "LEAVES"),
OAK_LOG(0, "LOG"),
OAK_PLANKS(0, "WOOD"),
OAK_PRESSURE_PLATE(0, "WOOD_PLATE"),
OAK_SAPLING(0, "SAPLING"),
OAK_SLAB(0, "WOODEN_SLAB", "WOOD_STEP", "WOOD_DOUBLE_STEP"),
OAK_STAIRS(0, "WOOD_STAIRS"),
OAK_TRAPDOOR(0, "TRAP_DOOR"),
OAK_WOOD(0, "LOG"),
OBSERVER(0, "OBSERVER"),
OBSIDIAN(0, "OBSIDIAN"),
OCELOT_SPAWN_EGG(0, "RECORD_12"),
ORANGE_BANNER(14, "BANNER", "STANDING_BANNER"),
ORANGE_BED(1, "BED", "BED_BLOCK"),
ORANGE_CARPET(1, "CARPET"),
ORANGE_CONCRETE(1, "CONCRETE"),
ORANGE_CONCRETE_POWDER(1, "CONCRETE_POWDER"),
ORANGE_DYE(14, "INK_SACK"),
ORANGE_GLAZED_TERRACOTTA(0, "ORANGE_GLAZED_TERRACOTTA"),
ORANGE_SHULKER_BOX(0, "ORANGE_SHULKER_BOX"),
ORANGE_STAINED_GLASS(1, "STAINED_GLASS"),
ORANGE_STAINED_GLASS_PANE(1, "STAINED_GLASS_PANE"),
ORANGE_TERRACOTTA(1, "STAINED_CLAY"),
ORANGE_TULIP(5, "RED_ROSE"),
ORANGE_WALL_BANNER(0, "WALL_BANNER"),
ORANGE_WOOL(1, "WOOL"),
OXEYE_DAISY(8, "RED_ROSE"),
PACKED_ICE(0, "PACKED_ICE"),
PAINTING(0, "PAINTING"),
PAPER(0, "PAPER"),
PARROT_SPAWN_EGG(0, "MONSTER_EGG"),
PEONY(5, "DOUBLE_PLANT"),
PETRIFIED_OAK_SLAB(0, "STONE"),
PHANTOM_MEMBRANE(0, "STONE"),
PHANTOM_SPAWN_EGG(0, "MONSTER_EGG"),
PIG_SPAWN_EGG(0, "MONSTER_EGG"),
PINK_BANNER(9, "BANNER", "STANDING_BANNER"),
PINK_BED(6, "BED", "BED_BLOCK"),
PINK_CARPET(6, "CARPET"),
PINK_CONCRETE(6, "CONCRETE"),
PINK_CONCRETE_POWDER(6, "CONCRETE_POWDER"),
PINK_DYE(9, "INK_SACK"),
PINK_GLAZED_TERRACOTTA(0, "PINK_GLAZED_TERRACOTTA"),
PINK_SHULKER_BOX(0, "PINK_SHULKER_BOX"),
PINK_STAINED_GLASS(6, "STAINED_GLASS"),
PINK_STAINED_GLASS_PANE(6, "STAINED_GLASS_PANE"),
PINK_TERRACOTTA(6, "STAINED_CLAY"),
PINK_TULIP(7, "RED_ROSE"),
PINK_WALL_BANNER(0, "WALL_BANNER"),
PINK_WOOL(6, "WOOL"),
PISTON(0, "PISTON_BASE"),
PISTON_HEAD(0, "PISTON_EXTENSION"),
PLAYER_HEAD(0, "SKULL", "SKULL_ITEM"),
PLAYER_WALL_HEAD(0, "SKULL", "SKULL_ITEM"),
PODZOL(2, "DIRT"),
POISONOUS_POTATO(0, "POISONOUS_POTATO"),
POLAR_BEAR_SPAWN_EGG(0, "MONSTER_EGG"),
POLISHED_ANDESITE(6, "STONE"),
POLISHED_DIORITE(4, "STONE"),
POLISHED_GRANITE(2, "STONE"),
POPPED_CHORUS_FRUIT(0, "CHORUS_FRUIT_POPPED"),
POPPY(0, "RED_ROSE"),
PORKCHOP(0, "PORK"),
POTATO(0, "POTATO_ITEM"),
POTATOES(0, "POTATO"),
POTION(0, "POTION"),
POTTED_ACACIA_SAPLING(0, "FLOWER_POT"),
POTTED_ALLIUM(0, "FLOWER_POT"),
POTTED_AZURE_BLUET(0, "FLOWER_POT"),
POTTED_BIRCH_SAPLING(0, "FLOWER_POT"),
POTTED_BLUE_ORCHID(0, "FLOWER_POT"),
POTTED_BROWN_MUSHROOM(0, "FLOWER_POT"),
POTTED_CACTUS(0, "FLOWER_POT"),
POTTED_DANDELION(0, "FLOWER_POT"),
POTTED_DARK_OAK_SAPLING(0, "FLOWER_POT"),
POTTED_DEAD_BUSH(0, "FLOWER_POT"),
POTTED_FERN(0, "FLOWER_POT"),
POTTED_JUNGLE_SAPLING(0, "FLOWER_POT"),
POTTED_OAK_SAPLING(0, "FLOWER_POT"),
POTTED_ORANGE_TULIP(0, "FLOWER_POT"),
POTTED_OXEYE_DAISY(0, "FLOWER_POT"),
POTTED_PINK_TULIP(0, "FLOWER_POT"),
POTTED_POPPY(0, "FLOWER_POT"),
POTTED_RED_MUSHROOM(0, "FLOWER_POT"),
POTTED_RED_TULIP(0, "FLOWER_POT"),
POTTED_SPRUCE_SAPLING(0, "FLOWER_POT"),
POTTED_WHITE_TULIP(0, "FLOWER_POT"),
POWERED_RAIL(0, "POWERED_RAIL"),
PRISMARINE(0, "PRISMARINE"),
PRISMARINE_BRICKS(1, "PRISMARINE"),
PRISMARINE_BRICK_SLAB(0, "STONE"),
PRISMARINE_BRICK_STAIRS(0, "STONE"),
PRISMARINE_CRYSTALS(0, "PRISMARINE_CRYSTALS"),
PRISMARINE_SHARD(0, "PRISMARINE_SHARD"),
PRISMARINE_SLAB(0, "STONE"),
PRISMARINE_STAIRS(0, "STONE"),
PUFFERFISH(3, "RAW_FISH"),
PUFFERFISH_BUCKET(0, "STONE"),
PUFFERFISH_SPAWN_EGG(0, "MONSTER_EGG"),
PUMPKIN(0, "PUMPKIN"),
PUMPKIN_PIE(0, "PUMPKIN_PIE"),
PUMPKIN_SEEDS(0, "PUMPKIN_SEEDS"),
PUMPKIN_STEM(0, "PUMPKIN_STEM"),
PURPLE_BANNER(5, "BANNER", "STANDING_BANNER"),
PURPLE_BED(10, "BED", "BED_BLOCK"),
PURPLE_CARPET(10, "CARPET"),
PURPLE_CONCRETE(10, "CONCRETE"),
PURPLE_CONCRETE_POWDER(10, "CONCRETE_POWDER"),
PURPLE_DYE(5, "INK_SACK"),
PURPLE_GLAZED_TERRACOTTA(0, "PURPLE_GLAZED_TERRACOTTA"),
PURPLE_SHULKER_BOX(0, "PURPLE_SHULKER_BOX"),
PURPLE_STAINED_GLASS(10, "STAINED_GLASS"),
PURPLE_STAINED_GLASS_PANE(10, "STAINED_GLASS_PANE"),
PURPLE_TERRACOTTA(10, "STAINED_CLAY"),
PURPLE_WALL_BANNER(0, "WALL_BANNER"),
PURPLE_WOOL(10, "WOOL"),
PURPUR_BLOCK(0, "PURPUR_BLOCK"),
PURPUR_PILLAR(0, "PURPUR_PILLAR"),
PURPUR_SLAB(0, "PURPUR_SLAB", "PURPUR_DOUBLE_SLAB"),
PURPUR_STAIRS(0, "PURPUR_STAIRS"),
QUARTZ(0, "QUARTZ"),
QUARTZ_BLOCK(0, "QUARTZ_BLOCK"),
QUARTZ_PILLAR(2, "QUARTZ_BLOCK"),
QUARTZ_SLAB(7, "STEP"),
QUARTZ_STAIRS(0, "QUARTZ_STAIRS"),
RABBIT(0, "RABBIT"),
RABBIT_FOOT(0, "RABBIT_FOOT"),
RABBIT_HIDE(0, "RABBIT_HIDE"),
RABBIT_SPAWN_EGG(0, "MONSTER_EGG"),
RABBIT_STEW(0, "RABBIT_STEW"),
RAIL(0, "RAILS"),
REDSTONE(0, "REDSTONE"),
REDSTONE_BLOCK(0, "REDSTONE_BLOCK"),
REDSTONE_LAMP(0, "REDSTONE_LAMP_ON", "REDSTONE_LAMP_OFF"),
REDSTONE_ORE(0, "REDSTONE_ORE", "GLOWING_REDSTONE_ORE"),
REDSTONE_TORCH(0, "REDSTONE_TORCH_ON", "REDSTONE_TORCH_OFF"),
REDSTONE_WALL_TORCH(1, "REDSTONE_TORCH_ON", "REDSTONE_TORCH_OFF"),
REDSTONE_WIRE(0, "REDSTONE_WIRE"),
RED_BANNER(1, "BANNER", "STANDING_BANNER"),
RED_BED(14, "BED", "BED_BLOCK"),
RED_CARPET(14, "CARPET"),
RED_CONCRETE(14, "CONCRETE"),
RED_CONCRETE_POWDER(14, "CONCRETE_POWDER"),
RED_GLAZED_TERRACOTTA(0, "RED_GLAZED_TERRACOTTA"),
RED_MUSHROOM(0, "RED_MUSHROOM"),
RED_MUSHROOM_BLOCK(0, "RED_MUSHROOM", "HUGE_MUSHROOM_2"),
RED_NETHER_BRICKS(0, "RED_NETHER_BRICK"),
RED_SAND(1, "SAND"),
RED_SANDSTONE(0, "RED_SANDSTONE"),
RED_SANDSTONE_SLAB(0, "STONE_SLAB2", "DOUBLE_STONE_SLAB2"),
RED_SANDSTONE_STAIRS(0, "RED_SANDSTONE_STAIRS"),
RED_SHULKER_BOX(0, "RED_SHULKER_BOX"),
RED_STAINED_GLASS(14, "STAINED_GLASS"),
RED_STAINED_GLASS_PANE(14, "STAINED_GLASS_PANE"),
RED_TERRACOTTA(14, "STAINED_CLAY"),
RED_TULIP(4, "RED_ROSE"),
RED_WALL_BANNER(0, "WALL_BANNER"),
RED_WOOL(14, "WOOL"),
REPEATER(0, "DIODE", "DIODE_BLOCK_ON", "DIODE_BLOCK_OFF"),
REPEATING_COMMAND_BLOCK(0, "COMMAND_REPEATING"),
ROSE_BUSH(4, "DOUBLE_PLANT"),
ROSE_RED(1, "INK_SACK"),
ROTTEN_FLESH(0, "ROTTEN_FLESH"),
SADDLE(0, "SADDLE"),
SALMON(1, "RAW_FISH"),
SALMON_BUCKET(0, "BUCKET"),
SALMON_SPAWN_EGG(0, "MONSTER_EGG"),
SAND(0, "SAND"),
SANDSTONE(0, "SANDSTONE"),
SANDSTONE_SLAB(1, "STONE_SLAB", "STEP", "DOUBLE_STEP"),
SANDSTONE_STAIRS(0, "SANDSTONE_STAIRS"),
SCUTE(0, "STONE"),
SEAGRASS(0, "STONE"),
SEA_LANTERN(0, "SEA_LANTERN"),
SEA_PICKLE(0, "STONE"),
SHEARS(0, "SHEARS"),
SHEEP_SPAWN_EGG(0, "MONSTER_EGG"),
SHIELD(0, "SHIELD"),
SHULKER_BOX(0, "PURPLE_SHULKER_BOX"),
SHULKER_SHELL(0, "SHULKER_SHELL"),
SHULKER_SPAWN_EGG(0, "MONSTER_EGG"),
SIGN(0, "SIGN"),
SILVERFISH_SPAWN_EGG(0, "MONSTER_EGG"),
SKELETON_HORSE_SPAWN_EGG(0, "MONSTER_EGG"),
SKELETON_SKULL(0, "SKULL", "SKULL_ITEM"),
SKELETON_SPAWN_EGG(0, "MONSTER_EGG"),
SKELETON_WALL_SKULL(0, "SKULL", "SKULL_ITEM"),
SLIME_BALL(0, "SLIME_BALL"),
SLIME_BLOCK(0, "SLIME_BLOCK"),
SLIME_SPAWN_EGG(0, "MONSTER_EGG"),
SMOOTH_QUARTZ(0, "STONE"),
SMOOTH_RED_SANDSTONE(2, "RED_SANDSTONE"),
SMOOTH_SANDSTONE(2, "SANDSTONE"),
SMOOTH_STONE(0, "STEP"),
SNOW(0, "SNOW"),
SNOWBALL(0, "SNOW_BALL"),
SNOW_BLOCK(0, "SNOW_BLOCK"),
SOUL_SAND(0, "SOUL_SAND"),
SPAWNER(0, "MOB_SPAWNER"),
SPECTRAL_ARROW(0, "SPECTRAL_ARROW"),
SPIDER_EYE(0, "SPIDER_EYE"),
SPIDER_SPAWN_EGG(0, "MONSTER_EGG"),
SPLASH_POTION(0, "SPLASH_POTION"),
SPONGE(0, "SPONGE"),
SPRUCE_BOAT(0, "BOAT_SPRUCE"),
SPRUCE_BUTTON(0, "WOOD_BUTTON"),
SPRUCE_DOOR(0, "SPRUCE_DOOR", "SPRUCE_DOOR_ITEM"),
SPRUCE_FENCE(0, "SPRUCE_FENCE"),
SPRUCE_FENCE_GATE(0, "SPRUCE_FENCE_GATE"),
SPRUCE_LEAVES(1, "LEAVES"),
SPRUCE_LOG(1, "LOG"),
SPRUCE_PLANKS(1, "WOOD"),
SPRUCE_PRESSURE_PLATE(0, "WOOD_PLATE"),
SPRUCE_SAPLING(1, "SAPLING"),
SPRUCE_SLAB(1, "WOODEN_SLAB", "WOOD_STEP", "WOOD_DOUBLE_STEP"),
SPRUCE_STAIRS(0, "SPRUCE_WOOD_STAIRS"),
SPRUCE_TRAPDOOR(0, "TRAP_DOOR"),
SPRUCE_WOOD(1, "LOG"),
SQUID_SPAWN_EGG(0, "MONSTER_EGG"),
STICK(0, "STICK"),
STICKY_PISTON(0, "PISTON_STICKY_BASE"),
STONE(0, "STONE"),
STONE_AXE(0, "STONE_AXE"),
STONE_BRICKS(0, "SMOOTH_BRICK"),
STONE_BRICK_SLAB(5, "STONE_SLAB", "STEP", "DOUBLE_STEP"),
STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"),
STONE_BUTTON(0, "STONE_BUTTON"),
STONE_HOE(0, "STONE_HOE"),
STONE_PICKAXE(0, "STONE_PICKAXE"),
STONE_PRESSURE_PLATE(0, "STONE_PLATE"),
STONE_SHOVEL(0, "STONE_SPADE"),
STONE_SLAB(0, "STONE_SLAB", "STEP", "DOUBLE_STEP"),
STONE_SWORD(0, "STONE_SWORD"),
STRAY_SPAWN_EGG(0, "MONSTER_EGG"),
STRING(0, "STRING"),
STRIPPED_ACACIA_LOG(0, "STONE"),
STRIPPED_ACACIA_WOOD(0, "STONE"),
STRIPPED_BIRCH_LOG(0, "STONE"),
STRIPPED_BIRCH_WOOD(0, "STONE"),
STRIPPED_DARK_OAK_LOG(0, "STONE"),
STRIPPED_DARK_OAK_WOOD(0, "STONE"),
STRIPPED_JUNGLE_LOG(0, "STONE"),
STRIPPED_JUNGLE_WOOD(0, "STONE"),
STRIPPED_OAK_LOG(0, "STONE"),
STRIPPED_OAK_WOOD(0, "STONE"),
STRIPPED_SPRUCE_LOG(0, "STONE"),
STRIPPED_SPRUCE_WOOD(0, "STONE"),
STRUCTURE_BLOCK(0, "STRUCTURE_BLOCK"),
STRUCTURE_VOID(0, "STRUCTURE_VOID"),
SUGAR(0, "SUGAR"),
SUGAR_CANE(0, "SUGAR_CANE", "SUGAR_CANE_BLOCK"),
SUNFLOWER(0, "DOUBLE_PLANT"),
TALL_GRASS(2, "DOUBLE_PLANT"),
TALL_SEAGRASS(0, "STONE"),
TERRACOTTA(0, "HARD_CLAY"),
TIPPED_ARROW(0, "TIPPED_ARROW"),
TNT(0, "TNT"),
TNT_MINECART(0, "EXPLOSIVE_MINECART"),
TORCH(0, "TORCH"),
TOTEM_OF_UNDYING(0, "TOTEM"),
TRAPPED_CHEST(0, "TRAPPED_CHEST"),
TRIDENT(0, "STONE"),
TRIPWIRE(0, "TRIPWIRE"),
TRIPWIRE_HOOK(0, "TRIPWIRE_HOOK"),
TROPICAL_FISH(0, "RAW_FISH"),
TROPICAL_FISH_BUCKET(0, "BUCKET"),
TROPICAL_FISH_SPAWN_EGG(0, "MONSTER_EGG"),
TUBE_CORAL(0, "STONE"),
TUBE_CORAL_BLOCK(0, "STONE"),
TUBE_CORAL_FAN(0, "STONE"),
TURTLE_EGG(0, "MONSTER_EGG"),
TURTLE_HELMET(0, "STONE"),
TURTLE_SPAWN_EGG(0, "MONSTER_EGG"),
VEX_SPAWN_EGG(0, "MONSTER_EGG"),
VILLAGER_SPAWN_EGG(0, "MONSTER_EGG"),
VINDICATOR_SPAWN_EGG(0, "MONSTER_EGG"),
VINE(0, "VINE"),
VOID_AIR(0, "AIR"),
WALL_SIGN(0, "WALL_SIGN", "SIGN_POST"),
WALL_TORCH(1, "TORCH"),
WATER(0, "WATER", "STATIONARY_WATER"),
WATER_BUCKET(0, "WATER_BUCKET"),
WET_SPONGE(1, "SPONGE"),
WHEAT(0, "WHEAT", "CROPS"),
WHEAT_SEEDS(0, "WHEAT_SEEDS", "SEEDS"),
WHITE_BANNER(15, "BANNER", "STANDING_BANNER"),
WHITE_BED(0, "BED", "BED_BLOCK"),
WHITE_CARPET(0, "CARPET"),
WHITE_CONCRETE(0, "CONCRETE"),
WHITE_CONCRETE_POWDER(0, "CONCRETE_POWDER"),
WHITE_GLAZED_TERRACOTTA(0, "WHITE_GLAZED_TERRACOTTA"),
WHITE_SHULKER_BOX(0, "WHITE_SHULKER_BOX"),
WHITE_STAINED_GLASS(0, "STAINED_GLASS"),
WHITE_STAINED_GLASS_PANE(0, "STAINED_GLASS_PANE"),
WHITE_TERRACOTTA(0, "TERRACOTTA"),
WHITE_TULIP(6, "RED_ROSE"),
WHITE_WALL_BANNER(0, "WALL_BANNER"),
WHITE_WOOL(0, "WOOL"),
WITCH_SPAWN_EGG(0, "MONSTER_EGG"),
WITHER_SKELETON_SKULL(0, "SKULL", "SKULL_ITEM"),
WITHER_SKELETON_SPAWN_EGG(0, "MONSTER_EGG"),
WITHER_SKELETON_WALL_SKULL(0, "SKULL", "SKULL_ITEM"),
WOLF_SPAWN_EGG(0, "MONSTER_EGG"),
WOODEN_AXE(0, "WOOD_AXE"),
WOODEN_HOE(0, "WOOD_HOE"),
WOODEN_PICKAXE(0, "WOOD_PICKAXE"),
WOODEN_SHOVEL(0, "WOOD_SPADE"),
WOODEN_SWORD(0, "WOOD_SWORD"),
WRITABLE_BOOK(0, "BOOK_AND_QUILL"),
WRITTEN_BOOK(0, "WRITTEN_BOOK"),
YELLOW_BANNER(11, "BANNER", "STANDING_BANNER"),
YELLOW_BED(4, "BED", "BED_BLOCK"),
YELLOW_CARPET(4, "CARPET"),
YELLOW_CONCRETE(4, "CONCRETE"),
YELLOW_CONCRETE_POWDER(4, "CONCRETE_POWDER"),
YELLOW_GLAZED_TERRACOTTA(0, "YELLOW_GLAZED_TERRACOTTA"),
YELLOW_SHULKER_BOX(0, "YELLOW_SHULKER_BOX"),
YELLOW_STAINED_GLASS(4, "STAINED_GLASS"),
YELLOW_STAINED_GLASS_PANE(4, "STAINED_GLASS_PANE"),
YELLOW_TERRACOTTA(4, "STAINED_CLAY"),
YELLOW_WALL_BANNER(0, "WALL_BANNER"),
YELLOW_WOOL(4, "WOOL"),
ZOMBIE_HEAD(0, "SKULL", "SKULL_ITEM"),
ZOMBIE_HORSE_SPAWN_EGG(0, "MONSTER_EGG"),
ZOMBIE_PIGMAN_SPAWN_EGG(0, "MONSTER_EGG"),
ZOMBIE_SPAWN_EGG(0, "MONSTER_EGG"),
ZOMBIE_VILLAGER_SPAWN_EGG(0, "MONSTER_EGG"),
ZOMBIE_WALL_HEAD(0, "SKULL", "SKULL_ITEM");
private static HashMap<String, ItemStack> cachedSearch = new HashMap<>();
int data;
String[] m;
VersionEnum(int data, String... m) {
this.m = m;
this.data = data;
}
public static ItemStack requestMaterial(String name) {
if (cachedSearch.containsKey(name.toUpperCase())) {
return cachedSearch.get(name.toUpperCase());
}
for (VersionEnum value : VersionEnum.values()) {
if (name.toUpperCase().equals(value.toString())) {
ItemStack itemStack = new ItemStack(Material.valueOf(value.m[0]), 1, (short) value.data);
cachedSearch.put(name, itemStack);
return itemStack;
}
}
return null;
}
}
}

View File

@ -1,68 +0,0 @@
package com.songoda.epicfurnaces.utils;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
/**
* Created by songoda on 2/25/2017.
*/
public class Methods {
private static EpicFurnaces instance;
public static void init(EpicFurnaces main) {
instance = main;
}
public static ItemStack getGlass(Boolean rainbow, int type) {
int randomNum = 1 + (int) (Math.random() * 6.0D);
ItemStack glass;
if (rainbow) {
glass = new ItemStack(instance.getBukkitEnums().getMaterial("WHITE_STAINED_GLASS_PANE").getType(), 1, (short) randomNum);
} else {
glass = new ItemStack(instance.getBukkitEnums().getMaterial("WHITE_STAINED_GLASS_PANE").getType(), 1, (short) type);
}
ItemMeta glassMeta = glass.getItemMeta();
glassMeta.setDisplayName("§l");
glass.setItemMeta(glassMeta);
return glass;
}
public static ItemStack getBackgroundGlass(boolean type) {
if (type) {
return getGlass(false, instance.getConfig().getInt("Interfaces.Glass Type 2"));
}
return getGlass(false, instance.getConfig().getInt("Interfaces.Glass Type 3"));
}
public static String serializeLocation(Location location) {
if (location == null) {
return "";
}
return "w:" + location.getWorld().getName() + "x:" + location.getBlockX() + "y:" + location.getBlockY() + "z:" + location.getBlockZ();
}
public static Location deserializeLocation(String string) {
if (string == null || string.isEmpty()) {
return null;
}
string = string.replace("y:", ":").replace("z:", ":").replace("w:", "").replace("x:", ":").replace("/", ".");
String[] args = string.split(":");
World world = Bukkit.getWorld(args[0]);
int x = Integer.parseInt(args[1]);
int y = Integer.parseInt(args[2]);
int z = Integer.parseInt(args[3]);
return new Location(world, x, y, z, 0.0F, 0.0F);
}
public static ItemStack getGlass() {
return getGlass(instance.getConfig().getBoolean("Interfaces.Replace Glass Type 1 With Rainbow Glass"), instance.getConfig().getInt("Interfaces.Glass Type 1"));
}
}

View File

@ -1,49 +0,0 @@
package com.songoda.epicfurnaces.utils;
import com.songoda.epicfurnaces.EpicFurnaces;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLDatabase {
private final EpicFurnaces instance;
private Connection connection;
public MySQLDatabase(EpicFurnaces instance) {
this.instance = instance;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" + instance.getConfig().getString("Database.IP") + ":" + instance.getConfig().getString("Database.Port") + "/" + instance.getConfig().getString("Database.Database Name") + "?autoReconnect=true&useSSL=false";
this.connection = DriverManager.getConnection(url, instance.getConfig().getString("Database.Username"), instance.getConfig().getString("Database.Password"));
//ToDo: This is sloppy
connection.createStatement().execute(
"CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "charged` (\n" +
"\t`location` TEXT NULL,\n" +
"\t`level` INT NULL,\n" +
"\t`uses` INT NULL,\n" +
"\t`tolevel` INT NULL,\n" +
"\t`nickname` TEXT NULL,\n" +
"\t`accesslist` TEXT NULL,\n" +
"\t`placedby` TEXT NULL\n" +
")");
connection.createStatement().execute("CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "boosts` (\n" +
"\t`endtime` TEXT NULL,\n" +
"\t`amount` INT NULL,\n" +
"\t`uuid` TEXT NULL\n" +
")");
} catch (ClassNotFoundException | SQLException e) {
instance.getLogger().severe("Database connection failed.");
}
}
public Connection getConnection() {
return connection;
}
}

View File

@ -1,109 +0,0 @@
package com.songoda.epicfurnaces.utils;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.ChatColor;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class StringUtils {
private static final NavigableMap<Long, String> suffixes = new TreeMap<>();
private static EpicFurnaces instance;
static {
suffixes.put(1_000L, "k");
suffixes.put(1_000_000L, "M");
suffixes.put(1_000_000_000L, "B");
suffixes.put(1_000_000_000_000L, "T");
suffixes.put(1_000_000_000_000_000L, "P");
suffixes.put(1_000_000_000_000_000_000L, "E");
}
public static void init(EpicFurnaces main) {
instance = main;
}
public static String msToString(Long milli) {
milli -= 24 * 60 * 60 * 1000;
Date date = new Date(milli);
boolean days = MILLISECONDS.toDays(milli) != 0;
boolean hours = MILLISECONDS.toHours(milli) != 0;
boolean minutes = MILLISECONDS.toMinutes(milli) != 0;
DateFormat formatter = new SimpleDateFormat((days ? "D 'Days' " : "") + (hours ? "HH 'hours' " : "") + (minutes ? "mm 'minutes'" : "") + " ss's' ");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
return formatter.format(date);
}
public static String cleanString(String string) {
string = string.replaceAll("_", " ");
if (string.split(" ").length == 2) {
string = ChatColor.stripColor(string.substring(0, 1).toUpperCase() + string.toLowerCase().substring(1));
}
return string;
}
public static String formatName(int level, int uses, boolean full) {
String name = instance.getLocale().getMessage("general.nametag.nameformat", level);
String info = "";
if (full) {
info += encode(level + ":" + uses + ":");
}
return info + formatText(name);
}
public static String formatText(String string) {
return string != null && !string.equals("") ? formatText(string, false) : "";
}
public static String formatText(String string, boolean cap) {
if (string != null && !string.equals("")) {
if (cap) {
string = string.substring(0, 1).toUpperCase() + string.substring(1);
}
return ChatColor.translateAlternateColorCodes('&', string);
} else {
return "";
}
}
private static String encode(String toEncode) {
StringBuilder builder = new StringBuilder();
for (char c : toEncode.toCharArray()) {
builder.append(ChatColor.COLOR_CHAR).append(c);
}
return builder.toString();
}
private static int decode(String toDecode) {
String decoded = toDecode.replaceAll(String.valueOf(ChatColor.COLOR_CHAR), "");
return Integer.parseInt(decoded);
}
public static String formatEconomy(long value) {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return formatEconomy(Long.MIN_VALUE + 1);
if (value < 0) return "-" + formatEconomy(-value);
if (value < 1000) return Long.toString(value); //deal with easy case
Map.Entry<Long, String> e = suffixes.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();
long truncated = value / (divideBy / 10); //the number part of the output times 10
boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}
}

View File

@ -1,522 +0,0 @@
package com.songoda.epicfurnaces.utils.gui;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.*;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitTask;
import java.util.*;
/**
* A fast API to easily create advanced GUI.
* The project is on <a href="https://github.com/MrMicky-FR/FastInv">GitHub</a>
*
* @author MrMicky
* @version 2.0.3 - Now supports async operations
*/
public class FastInv implements InventoryHolder {
private static Plugin plugin = null;
private boolean cancelTasksOnClose = true;
private Set<FastInvCloseListener> closeListeners = new HashSet<>();
private Set<FastInvClickListener> clickListeners = new HashSet<>();
private Map<Integer, FastInvClickListener> itemListeners = new HashMap<>();
private Set<BukkitTask> tasks = new HashSet<>();
private Inventory inventory;
/**
* Create a new FastInv with a custom size.
*
* @param size The size of the menus.
*/
public FastInv(int size) {
this(size, InventoryType.CHEST.getDefaultTitle());
}
/**
* Create a new FastInv with a custom size and title.
*
* @param size The size of the menus.
* @param title The title (name) of the menus.
*/
public FastInv(int size, String title) {
this(size, InventoryType.CHEST, title);
}
/**
* Create a new FastInv with a custom type.
*
* @param type The type of the menus.
*/
public FastInv(InventoryType type) {
this(type, type.getDefaultTitle());
}
/**
* Create a new FastInv with a custom type and title.
*
* @param type The type of the menus.
* @param title The title of the menus.
* @throws IllegalStateException if FastInv is not init with FastInv.init(Plugin plugin)
*/
public FastInv(InventoryType type, String title) {
this(0, type, title);
}
private FastInv(int size, InventoryType type, String title) {
if (plugin == null) {
throw new IllegalStateException("FastInv is not initialised");
}
runSync(() -> {
if (type == InventoryType.CHEST && size > 0) {
inventory = Bukkit.createInventory(this, size, title);
} else {
inventory = Bukkit.createInventory(this, type, title);
}
});
}
/**
* Register your FastInv instance.
*
* @param plugin The plugin that uses FastInv.
*/
public static void init(Plugin plugin) {
if (FastInv.plugin == null) {
FastInv.plugin = plugin;
Bukkit.getPluginManager().registerEvents(getListener(), plugin);
}
}
/**
* Add an {@link ItemStack} to the menus.
*
* @param item The item to add
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(ItemStack item) {
return addItem(item, null);
}
/**
* Add an {@link ItemStack} to the menus with a {@link FastInvClickListener} to handle clicks.
*
* @param item The item to add.
* @param listener The {@link FastInvClickListener} for the item.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(ItemStack item, FastInvClickListener listener) {
runSync(() -> {
int slot = inventory.firstEmpty();
if (slot >= 0) {
addItem(slot, item, listener);
}
});
return this;
}
/**
* Add an {@link ItemStack} to the menus on a specific slot.
*
* @param slot The slot of the item.
* @param item The item to add.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(int slot, ItemStack item) {
return addItem(slot, item, null);
}
/**
* Add an {@link ItemStack} to the menus on specific slot with a {@link FastInvClickListener} to handle clicks.
*
* @param slot The slot of the item.
* @param item The item to add.
* @param listener The FastInvClickListener for the item.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(int slot, ItemStack item, FastInvClickListener listener) {
runSync(() -> {
inventory.setItem(slot, item);
if (listener != null) {
itemListeners.put(slot, listener);
} else {
itemListeners.remove(slot);
}
});
return this;
}
/**
* Add an {@link ItemStack} to the menus on a range of slots.
*
* @param slotFrom Starting slot to put the item in.
* @param slotTo Ending slot to put the item in.
* @param item The item to add.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(int slotFrom, int slotTo, ItemStack item) {
return addItem(slotFrom, slotTo, item, null);
}
/**
* Add an {@link ItemStack} to the menus on a range of slots with a {@link FastInvClickListener} to handle clicks.
*
* @param slotFrom Starting slot to put the item in.
* @param slotTo Ending slot to put the item in.
* @param item The item to add.
* @param listener The FastInvClickListener for the item.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(int slotFrom, int slotTo, ItemStack item, FastInvClickListener listener) {
for (int i = slotFrom; i <= slotTo; i++) {
addItem(i, item, listener);
}
return this;
}
/**
* Add an {@link ItemStack} to the menus on multiple slots.
*
* @param slots The slot of the item.
* @param item The item to add.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(int[] slots, ItemStack item) {
return addItem(slots, item, null);
}
/**
* Add an {@link ItemStack} to the menus on the edges.
*
* @param item The item to add.
* @return This FastInv instance, for chaining.
*/
public FastInv edge(ItemStack item) {
int height = inventory.getSize() / 9;
addItem(0, 9, item);
addItem(inventory.getSize() - 9, inventory.getSize() - 1, item);
for (int i = 0; i < height; i++) {
addItem(i * 9, item);
addItem(i * 9 + 8, item);
}
return this;
}
/**
* Add an {@link ItemStack} to the menus on multiples slots with a {@link FastInvClickListener} to handle click.
*
* @param slots The slots to place the item.
* @param item The item to add.
* @param listener The FastInvClickListener for the item.
* @return This FastInv instance, for chaining.
*/
public FastInv addItem(int[] slots, ItemStack item, FastInvClickListener listener) {
for (int slot : slots) {
addItem(slot, item, listener);
}
return this;
}
public FastInv fill(ItemStack itemStack) {
runSync(() -> {
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) == null) {
addItem(i, itemStack);
}
}
});
return this;
}
/**
* Add a {@link FastInvCloseListener} to listen on menus close.
*
* @param listener The {@link FastInvCloseListener} to add.
* @return This FastInv instance, for chaining.
*/
public FastInv onClose(FastInvCloseListener listener) {
closeListeners.add(listener);
return this;
}
/**
* Add a {@link FastInvClickListener} to listen on menus click.
*
* @param listener The {@link FastInvClickListener} to add.
* @return This FastInv instance, for chaining.
*/
public FastInv onClick(FastInvClickListener listener) {
clickListeners.add(listener);
return this;
}
/**
* Schedule a task to run.
*
* @param period Delay between each run.
* @param runnable The {@link Runnable} task to run.
* @return This FastInv instance, for chaining.
*/
public FastInv onUpdate(long period, Runnable runnable) {
return onUpdate(period, period, runnable);
}
/**
* Schedule a task to run with a delay before starting.
*
* @param delay Ticks to wait before starting the task.
* @param period Delay between each run.
* @param runnable The {@link Runnable} task to run.
* @return This FastInv instance, for chaining
*/
public FastInv onUpdate(long delay, long period, Runnable runnable) {
tasks.add(Bukkit.getScheduler().runTaskTimer(plugin, runnable, delay, period));
return this;
}
/**
* Open the menus to a player.
*
* @param player The player to open the menu.
*/
public void open(Player player) {
Bukkit.getScheduler().runTask(plugin, () -> player.openInventory(inventory));
}
/**
* Open the menus to players.
*
* @param players The players to open the menu.
*/
public void open(Player... players) {
Bukkit.getScheduler().runTask(plugin, () -> {
for (Player p : players) {
p.openInventory(inventory);
}
});
}
/**
* Cancel all tasks.
*/
public void cancelTasks() {
tasks.forEach(BukkitTask::cancel);
tasks.clear();
}
/**
* Run a task on the server primary thread.
*
* @param runnable The runnable to run on the main thread
*/
public void runSync(Runnable runnable) {
if (Bukkit.isPrimaryThread()) {
runnable.run();
} else {
Bukkit.getScheduler().runTask(plugin, runnable);
}
}
public interface FastInvClickListener {
void onClick(FastInvClickEvent event);
}
public interface FastInvCloseListener {
void onClose(FastInvCloseEvent event);
}
public static abstract class FastInvEvent {
private Player player;
private FastInv inventory;
private boolean cancelled;
FastInvEvent(Player player, FastInv inventory, boolean cancelled) {
this.player = player;
this.inventory = inventory;
this.cancelled = cancelled;
}
/**
* Get the FastInv menus.
*
* @return This associated FastInv instance.
*/
public FastInv getInventory() {
return inventory;
}
/**
* Get the {@link Player} who clicked.
*
* @return the player who clicked.
*/
public Player getPlayer() {
return player;
}
/**
* Get if the event is cancelled or not.
*
* @return Whether the event was cancelled.
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Set if the event will be cancel or not.
*
* @param cancel Whether the event should be cancelled.
*/
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
}
public static class FastInvClickEvent extends FastInvEvent {
private int slot;
private ItemStack item;
private InventoryAction action;
private ClickType clickType;
private FastInvClickEvent(Player player, FastInv inventory, int slot, ItemStack item,
boolean cancelled, InventoryAction action, ClickType clickType) {
super(player, inventory, cancelled);
this.slot = slot;
this.item = item;
this.action = action;
this.clickType = clickType;
}
/**
* @return The action of the event
*/
public InventoryAction getAction() {
return this.action;
}
/**
* @return The click type
*/
public ClickType getClickType() {
return this.clickType;
}
/**
* Get the clicked {@link ItemStack}
*
* @return The clicked item
*/
public ItemStack getItem() {
return this.item;
}
/**
* Get the number of the clicked slot
*
* @return The slot number
*/
public int getSlot() {
return this.slot;
}
}
public static class FastInvCloseEvent extends FastInvEvent {
private FastInvCloseEvent(Player player, FastInv inventory, boolean cancelled) {
super(player, inventory, cancelled);
}
}
/**
* Get the Bukkit menus associated with this FastInv instance.
*
* @return The Bukkit {@link Inventory}.
*/
@Override
public Inventory getInventory() {
return inventory;
}
private static Listener getListener() {
return new Listener() {
@EventHandler
public void onClick(InventoryClickEvent event) {
if (event.getInventory().getHolder() instanceof FastInv && event.getWhoClicked() instanceof Player) {
int slot = event.getRawSlot();
FastInv inv = (FastInv) event.getInventory().getHolder();
FastInvClickEvent clickEvent = new FastInvClickEvent((Player) event.getWhoClicked(), inv, slot,
event.getCurrentItem(), true, event.getAction(), event.getClick());
if (inv.itemListeners.containsKey(slot)) {
inv.itemListeners.get(slot).onClick(clickEvent);
}
inv.clickListeners.forEach(listener -> listener.onClick(clickEvent));
if (clickEvent.isCancelled()) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onClose(InventoryCloseEvent event) {
if (event.getInventory().getHolder() instanceof FastInv && event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
FastInv inv = (FastInv) event.getInventory().getHolder();
FastInvCloseEvent closeEvent = new FastInvCloseEvent(player, inv, false);
inv.closeListeners.forEach(listener -> listener.onClose(closeEvent));
Bukkit.getScheduler().runTask(plugin, () -> {
// Tiny delay to prevent errors.
if (closeEvent.isCancelled() && player.isOnline()) {
player.openInventory(inv.getInventory());
} else if (inv.getInventory().getViewers().isEmpty() && inv.cancelTasksOnClose) {
inv.cancelTasks();
}
});
}
}
@EventHandler
public void onDisable(PluginDisableEvent event) {
if (event.getPlugin().equals(plugin)) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getOpenInventory().getTopInventory().getHolder() instanceof FastInv) {
player.closeInventory();
}
}
}
}
};
}
/**
* Set if the tasks will be cancel on menus close.
*
* @param cancelTasksOnClose Set if the tasks will be cancel
* @return This FastInv instance, for chaining.
*/
public FastInv setCancelTasksOnClose(boolean cancelTasksOnClose) {
this.cancelTasksOnClose = cancelTasksOnClose;
return this;
}
}

View File

@ -1,294 +0,0 @@
package com.songoda.epicfurnaces.utils.gui;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.block.banner.Pattern;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A complete {@link ItemStack} builder for FastInv (only works on 1.8+).
* <p>
* The project is on <a href="https://github.com/MrMicky-FR/FastInv">GitHub</a>
*
* @author MrMicky
*/
public class ItemBuilder {
private final ItemStack item;
private ItemMeta meta;
/*
* Constructors:
*/
public ItemBuilder(Material material) {
this(new ItemStack(material));
}
public ItemBuilder(Material material, int amount) {
this(new ItemStack(material, amount));
}
public ItemBuilder(Material material, byte data) {
this(new ItemStack(material, 1, data));
}
public ItemBuilder(Material material, int amount, byte data) {
this(new ItemStack(material, amount, data));
}
public ItemBuilder(ItemStack item) {
this.item = item;
this.meta = item.getItemMeta();
}
/*
* Meta:
*/
public boolean hasMeta() {
return getMeta() != null;
}
public ItemMeta getMeta() {
return meta;
}
public ItemBuilder meta(ItemMeta meta) {
this.meta = meta;
return this;
}
/*
* Name:
*/
public boolean hasName() {
return meta.hasDisplayName();
}
public String getName() {
return meta.getDisplayName();
}
public ItemBuilder name(String name) {
meta.setDisplayName(name);
return this;
}
/*
* Lore:
*/
public boolean hasLore() {
return meta.hasLore();
}
public List<String> getLore() {
return meta.getLore();
}
public ItemBuilder lore(String... lore) {
return lore(Arrays.asList(lore));
}
public ItemBuilder lore(List<String> lore) {
meta.setLore(lore);
return this;
}
public ItemBuilder addLore(List<String> lore) {
if (!meta.hasLore()) {
meta.setLore(lore);
return this;
}
List<String> toAdd = meta.getLore();
toAdd.addAll(lore);
meta.setLore(toAdd);
return this;
}
public ItemBuilder addLore(String... lore) {
return addLore(Arrays.asList(lore));
}
/*
* Enchantments:
*/
public boolean hasEnchants() {
return meta.hasEnchants();
}
public boolean hasEnchant(Enchantment enchantment) {
return meta.hasEnchant(enchantment);
}
public boolean hasConflictingEnchant(Enchantment enchantment) {
return meta.hasConflictingEnchant(enchantment);
}
public Map<Enchantment, Integer> getEnchants() {
return meta.getEnchants();
}
public ItemBuilder enchant(Enchantment enchantment, int level) {
meta.addEnchant(enchantment, level, true);
return this;
}
public ItemBuilder removeEnchant(Enchantment enchantment) {
meta.removeEnchant(enchantment);
return this;
}
/*
* Flags:
*/
public boolean hasFlag(ItemFlag flag) {
return meta.hasItemFlag(flag);
}
public Set<ItemFlag> getFlags() {
return meta.getItemFlags();
}
public ItemBuilder addFlags(ItemFlag... flags) {
meta.addItemFlags(flags);
return this;
}
public ItemBuilder removeFlags(ItemFlag... flags) {
meta.removeItemFlags(flags);
return this;
}
/*
* Unbreakability:
*/
public boolean isUnbreakable() {
return meta.spigot().isUnbreakable();
}
public ItemBuilder unbreakable() {
return unbreakable(true);
}
public ItemBuilder unbreakable(boolean unbreakable) {
meta.spigot().setUnbreakable(unbreakable);
return this;
}
/*
* ==========================
*
* SPECIFIC META
*
* ==========================
*/
/*
* Banners:
*/
public DyeColor getBannerBaseColor() {
return ((BannerMeta) meta).getBaseColor();
}
public List<Pattern> getBannerPatterns() {
return ((BannerMeta) meta).getPatterns();
}
public ItemBuilder bannerBaseColor(DyeColor color) {
((BannerMeta) meta).setBaseColor(color);
return this;
}
public ItemBuilder bannerPatterns(List<Pattern> patterns) {
((BannerMeta) meta).setPatterns(patterns);
return this;
}
public ItemBuilder bannerPattern(int i, Pattern pattern) {
((BannerMeta) meta).setPattern(i, pattern);
return this;
}
public ItemBuilder addBannerPatterns(Pattern pattern) {
((BannerMeta) meta).addPattern(pattern);
return this;
}
public ItemBuilder removeBannerPattern(int i) {
((BannerMeta) meta).removePattern(i);
return this;
}
/*
* Leather armor:
*/
public Color getLeatherArmorColor() {
return ((LeatherArmorMeta) meta).getColor();
}
public ItemBuilder leatherArmorColor(Color color) {
((LeatherArmorMeta) meta).setColor(color);
return this;
}
/*
* Skulls:
*/
public boolean hasSkullOwner() {
return ((SkullMeta) meta).hasOwner();
}
public String getSkullOwner() {
return ((SkullMeta) meta).getOwner();
}
public ItemBuilder skullOwner(String owner) {
item.setDurability((short) 3);
((SkullMeta) meta).setOwner(owner);
return this;
}
public ItemBuilder durability(int durability) {
item.setDurability((short) durability);
return this;
}
/*
* Potions:
*/
public boolean hasPotionEffect(PotionEffectType type) {
return ((PotionMeta) meta).hasCustomEffect(type);
}
public boolean hasPotionEffects() {
return ((PotionMeta) meta).hasCustomEffects();
}
public List<PotionEffect> getPotionEffects() {
return ((PotionMeta) meta).getCustomEffects();
}
public ItemBuilder addPotionEffect(PotionEffect effect, boolean overwrite) {
((PotionMeta) meta).addCustomEffect(effect, overwrite);
return this;
}
/*
* Build the ItemStack.
*/
public ItemStack build() {
item.setItemMeta(meta);
return item;
}
}

View File

@ -1,160 +0,0 @@
Recipes:
DIAMOND_SWORD:
result: DIAMOND
amount: 2
DIAMOND_PICKAXE:
result: DIAMOND
amount: 3
DIAMOND_AXE:
result: DIAMOND
amount: 3
DIAMOND_SPADE:
result: DIAMOND
amount: 1
DIAMOND_HOE:
result: DIAMOND
amount: 2
DIAMOND_HELMET:
result: DIAMOND
amount: 5
DIAMOND_CHESTPLATE:
result: DIAMOND
amount: 8
DIAMOND_LEGGINGS:
result: DIAMOND
amount: 7
DIAMOND_BOOTS:
result: DIAMOND
amount: 4
IRON_SWORD:
result: IRON_INGOT
amount: 2
IRON_PICKAXE:
result: IRON_INGOT
amount: 3
IRON_AXE:
result: IRON_INGOT
amount: 3
IRON_SPADE:
result: IRON_INGOT
amount: 1
IRON_HOE:
result: IRON_INGOT
amount: 2
IRON_HELMET:
result: IRON_INGOT
amount: 5
IRON_CHESTPLATE:
result: IRON_INGOT
amount: 8
IRON_LEGGINGS:
result: IRON_INGOT
amount: 7
IRON_BOOTS:
result: IRON_INGOT
amount: 4
GOLD_SWORD:
result: GOLD_INGOT
amount: 2
GOLD_PICKAXE:
result: GOLD_INGOT
amount: 3
GOLD_AXE:
result: GOLD_INGOT
amount: 3
GOLD_SPADE:
result: GOLD_INGOT
amount: 1
GOLD_HOE:
result: GOLD_INGOT
amount: 2
GOLD_HELMET:
result: GOLD_INGOT
amount: 5
GOLD_CHESTPLATE:
result: GOLD_INGOT
amount: 8
GOLD_LEGGINGS:
result: GOLD_INGOT
amount: 7
GOLD_BOOTS:
result: GOLD_INGOT
amount: 4
CHAINMAIL_HELMET:
result: IRON_INGOT
amount: 3
CHAINMAIL_CHESTPLATE:
result: IRON_INGOT
amount: 5
CHAINMAIL_LEGGINGS:
result: IRON_INGOT
amount: 4
CHAINMAIL_BOOTS:
result: IRON_INGOT
amount: 2
LEATHER_HELMET:
result: LEATHER
amount: 5
LEATHER_CHESTPLATE:
result: LEATHER
amount: 8
LEATHER_LEGGINGS:
result: LEATHER
amount: 7
LEATHER_BOOTS:
result: LEATHER
amount: 4
STONE_SWORD:
result: COBBLESTONE
amount: 2
STONE_PICKAXE:
result: COBBLESTONE
amount: 3
STONE_AXE:
result: COBBLESTONE
amount: 3
STONE_SPADE:
result: COBBLESTONE
amount: 1
STONE_HOE:
result: COBBLESTONE
amount: 2
WOOD_SWORD:
result: COAL
amount: 2
WOOD_PICKAXE:
result: COAL
amount: 3
WOOD_AXE:
result: COAL
amount: 3
WOOD_SPADE:
result: COAL
amount: 1
WOOD_HOE:
result: COAL
amount: 2
BOW:
result: COAL
amount: 3
FISHING_ROD:
result: COAL
amount: 3
COMPASS:
result: IRON_INGOT
amount: 4
WATCH:
result: GOLD_INGOT
amount: 4
SHEARS:
result: IRON_INGOT
amount: 2
BUCKET:
result: IRON_INGOT
amount: 3
MINECART:
result: IRON_INGOT
amount: 5
FLINT_AND_STEEL:
result: IRON_INGOT
amount: 1

View File

@ -1,6 +0,0 @@
settings:
blacklist:
- world2
- world3
- world4
- world5

View File

@ -1,80 +0,0 @@
Main:
Sounds Enabled: true
Hologram in front: false
Upgrade By Smelting Materials: true
Upgrade With Economy: true
Upgrade With XP: true
Level Cost Multiplier: 50
Remember Furnace Item Levels: true
Furnaces Have Holograms: true
Redstone Deactivates Furnaces: true
Furnace Upgrade Cost: IRON_INGOT
Use Custom Recipes: true
No Rewards From Custom Recipes: true
Upgrade Particle Type: SPELL_WITCH
Access Furnaces Remotely: true
Furnace Tick Speed: 10
Auto Save Interval In Seconds: 15
Overheat Particles: true
Interfaces:
Reward Icon: GOLDEN_APPLE
Performance Icon: REDSTONE
FuelShare Icon: COAL_BLOCK
FuelDuration Icon: COAL
Overheat Icon: FIRE_CHARGE
Economy Icon: SUNFLOWER
XP Icon: EXPERIENCE_BOTTLE
Glass Type 1: 7
Glass Type 2: 11
Glass Type 3: 3
Replace Glass Type 1 With Rainbow Glass: false
Database:
Activate Mysql Support: false
IP: 127.0.0.1
Port: 3306
Database Name: EpicFurnaces
Prefix: EF-
Username: PUT_USERNAME_HERE
Password: PUT_PASSWORD_HERE
System:
Language Mode: en_US
Debugger Enabled: false
settings:
levels:
Level-1:
Performance: 10%
Reward: 10%:1
Cost-xp: 20
Cost-eco: 5000
Level-2:
Performance: 25%
Reward: 20%:1-2
Cost-xp: 25
Cost-eco: 7500
Level-3:
Performance: 40%
Reward: 35%:2-3
Fuel-duration: 10%
Cost-xp: 30
Cost-eco: 10000
Level-4:
Performance: 55%
Reward: 50%:2-4
Fuel-duration: 25%
Cost-xp: 35
Cost-eco: 12000
Level-5:
Performance: 75%
Reward: 70%:3-4
Fuel-duration: 45%
Overheat: 1
Cost-xp: 40
Cost-eco: 15000
Level-6:
Performance: 75%
Reward: 70%:3-4
Fuel-duration: 45%
Overheat: 2
Fuel-share: 1
Cost-xp: 40
Cost-eco: 15000

View File

@ -1,55 +0,0 @@
#General Messages
general.nametag.prefix= "&8[&6EpicFurnaces&8]"
general.nametag.next= "&9Next"
general.nametag.back= "&9Back"
general.nametag.nameformat= "&eLevel %level% &fFurnace"
general.hologram.outoffuel= "&cNo Fuel"
general.hologram.stats= "&a%in%&7/&c%out%";
#Interface Messages
interface.furnace.upgradewithxp= "&aUpgrade with XP"
interface.furnace.upgradewithxplore= "&7Cost: &a%cost% Levels"
interface.furnace.upgradewitheconomy= "&aUpgrade with ECO"
interface.furnace.upgradewitheconomylore= "&7Cost: &a$%cost%"
interface.furnace.currentlevel= "&6Furnace Level &7%level%"
interface.furnace.level= "&6Next Level &7%level%"
interface.furnace.performance= "&7Performance: &6%amount%"
interface.furnace.reward= "&7Reward: &6%amount%"
interface.furnace.performancetitle= "&a&lPerformance"
interface.furnace.rewardtitle= "&c&lReward"
interface.furnace.fueldurationtitle= "&7&lFuel Duration"
interface.furnace.fuelduration= "&7Fuel Duration: &6%amount%"
interface.furnace.fuelshare= "&7Fuel Share: &6%amount%&7."
interface.furnace.fuelsharetitle= "&6&lFuel Share"
interface.furnace.fuelshareinfo= "&7This furnace will power other|&7furnaces within a &6%amount%&7 block radius."
interface.furnace.overheat= "&7Overheat: &6%amount%&7."
interface.furnace.overheattitle= "&6&lOverheat"
interface.furnace.overheatinfo= "&7This furnace will melt snow |&7and ice within a &6%amount%&7 block radius."
interface.furnace.performanceinfo= "&7This furnaces performance is |&7currently boosted an extra &6%amount%%&7. | |&7Performance boosts the speed in |&7which a furnace processes |&7materials."
interface.furnace.rewardinfo= "&7This furnace currently |&7has a &6%amount%%&7 chance of |&7producing multiple resources."
interface.furnace.fueldurationinfo= "&7This furnaces fuel duration is |&7currently boosted by &6%amount%%&7. | |&7Fuel Duration boosts how long |&7fuel in the furnace lasts."
interface.furnace.smeltedx= "&7Smelted &6%amount% Materials&7."
interface.furnace.tolevel= "&6%amount% %type%s &7away from leveling up."
interface.furnace.remotefurnace= "&5&lRemote Control"
interface.furnace.remotefurnacelore= "&7Left-Click to assign a nickname.|&7Right-Click to give yourself |&7remote access.|&7Current nickname is: &6%nickname%&7."
interface.furnace.utilize= "|&7To utilize remote access|&7use the command:|&6/EF Remote %nickname%"
interface.furnace.remotelist= "&7Players with remote access:"
interface.furnace.alreadymaxed= "&7This furnace is already maxed out!"
interface.button.boostedstats= "&a&lCurrently boosted!|&7Reward multiplied by &6%amount%x&7.|&7Expires in &6%time%&7."
#Command Messages
command.give.success= "&7You have been given a &6level %level% &7Furnace."
#Event Messages
event.general.nopermission= "&cYou do not have permission to do that."
event.upgrade.cannotafford= "&cYou cannot afford this upgrade."
event.upgrade.success= "&7You successfully upgraded this furnace to &6level %level%&7!"
event.upgrade.maxed= "&7You maxed out this furnace at &6level %level%&7."
event.remote.enter= "&7Enter a unique nickname for the furnace."
event.remote.notfound= "&cRemote furnace not found."
event.remote.nicknamesuccess= "&aNickname set successfully."
event.remote.nicknameinuse= "&cThat nickname is already in use."

View File

@ -1,14 +0,0 @@
name: EpicFurnaces
version: maven-version-number
main: com.songoda.epicfurnaces.EpicFurnaces
author: Songoda
website: https://songoda.com/
depend: [Vault]
softdepend: [PlotSquared, GriefPrevention, USkyBlock, SkyBlock, WorldGuard, Factions, HolographicDisplays, FabledSkyBlock]
api-version: 1.13
commands:
epicfurnaces:
description: Default command for the EpicFurnaces plugin.
default: true
aliases: [ef]
usage: /<command> [reload]

77
pom.xml
View File

@ -1,18 +1,11 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<groupId>com.songoda</groupId>
<artifactId>EpicFurnaces-Parent</artifactId>
<packaging>pom</packaging>
<artifactId>EpicFurnaces</artifactId>
<modelVersion>4.0.0</modelVersion>
<version>maven-version-number</version>
<modules>
<module>core</module>
</modules>
<build>
<defaultGoal>clean install</defaultGoal>
<finalName>EpicFurnaces-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -23,6 +16,39 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>shaded</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
<artifactSet>
<includes>
<include>com.songoda:songodaupdater</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
@ -31,4 +57,33 @@
<url>http://repo.songoda.com/artifactory/private/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.14.1</version>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>songodaupdater</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>net.milkbowl</groupId>
<artifactId>vault</artifactId>
<version>1.7.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.black_ixx</groupId>
<artifactId>playerpoints</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.gmail.filoghost.holographicdisplays</groupId>
<artifactId>holographicdisplays-api</artifactId>
<version>2.3.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,384 @@
package com.songoda.epicfurnaces;
import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.boost.BoostManager;
import com.songoda.epicfurnaces.command.CommandManager;
import com.songoda.epicfurnaces.economy.Economy;
import com.songoda.epicfurnaces.economy.PlayerPointsEconomy;
import com.songoda.epicfurnaces.economy.VaultEconomy;
import com.songoda.epicfurnaces.furnace.Furnace;
import com.songoda.epicfurnaces.furnace.FurnaceManager;
import com.songoda.epicfurnaces.furnace.levels.LevelManager;
import com.songoda.epicfurnaces.handlers.BlacklistHandler;
import com.songoda.epicfurnaces.hologram.Hologram;
import com.songoda.epicfurnaces.hologram.HologramHolographicDisplays;
import com.songoda.epicfurnaces.listeners.*;
import com.songoda.epicfurnaces.storage.Storage;
import com.songoda.epicfurnaces.storage.StorageRow;
import com.songoda.epicfurnaces.storage.types.StorageMysql;
import com.songoda.epicfurnaces.storage.types.StorageYaml;
import com.songoda.epicfurnaces.tasks.FurnaceTask;
import com.songoda.epicfurnaces.utils.ConfigWrapper;
import com.songoda.epicfurnaces.utils.Methods;
import com.songoda.epicfurnaces.utils.Metrics;
import com.songoda.epicfurnaces.utils.ServerVersion;
import com.songoda.epicfurnaces.utils.settings.Setting;
import com.songoda.epicfurnaces.utils.settings.SettingsManager;
import com.songoda.epicfurnaces.utils.updateModules.LocaleModule;
import com.songoda.update.Plugin;
import com.songoda.update.SongodaUpdate;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.List;
import java.util.UUID;
public class EpicFurnaces extends JavaPlugin {
private static CommandSender console = Bukkit.getConsoleSender();
private static EpicFurnaces INSTANCE;
private References references = null;
private ServerVersion serverVersion = ServerVersion.fromPackageName(Bukkit.getServer().getClass().getPackage().getName());
private ConfigWrapper langFile = new ConfigWrapper(this, "", "lang.yml");
private ConfigWrapper dataFile = new ConfigWrapper(this, "", "data.yml");
private ConfigWrapper furnaceRecipeFile = new ConfigWrapper(this, "", "Furnace Recipes.yml");
private ConfigWrapper levelsFile = new ConfigWrapper(this, "", "levels.yml");
private SettingsManager settingsManager;
private LevelManager levelManager;
private FurnaceManager furnaceManager;
private CommandManager commandManager;
private BoostManager boostManager;
private Hologram hologram;
private Locale locale;
private Economy economy;
private BlacklistHandler blacklistHandler;
private Storage storage;
public static EpicFurnaces getInstance() {
return INSTANCE;
}
@Override
public void onEnable() {
INSTANCE = this;
console.sendMessage(Methods.formatText("&a============================="));
console.sendMessage(Methods.formatText("&7EpicFurnaces " + this.getDescription().getVersion() + " by &5Songoda <3&7!"));
console.sendMessage(Methods.formatText("&7Action: &aEnabling&7..."));
this.settingsManager = new SettingsManager(this);
this.settingsManager.setupConfig();
dataFile.createNewFile("Loading data file", "EpicFurnaces data file");
langFile.createNewFile("Loading language file", "EpicFurnaces language file");
loadDataFile();
String langMode = getConfig().getString("System.Language Mode");
Locale.init(this);
Locale.saveDefaultLocale("en_US");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode", langMode));
// Running Songoda Updater
Plugin plugin = new Plugin(this, 22);
plugin.addModule(new LocaleModule());
SongodaUpdate.load(plugin);
loadLevelManager();
this.furnaceManager = new FurnaceManager();
this.commandManager = new CommandManager(this);
this.boostManager = new BoostManager();
this.blacklistHandler = new BlacklistHandler();
// Setup Economy
if (Setting.VAULT_ECONOMY.getBoolean()
&& getServer().getPluginManager().getPlugin("Vault") != null)
this.economy = new VaultEconomy(this);
else if (Setting.PLAYER_POINTS_ECONOMY.getBoolean()
&& getServer().getPluginManager().getPlugin("PlayerPoints") != null)
this.economy = new PlayerPointsEconomy(this);
this.checkStorage();
// Load from file
loadFromFile();
setupRecipies();
references = new References();
// Start Tasks
FurnaceTask.startTask(this);
PluginManager pluginManager = Bukkit.getPluginManager();
// Register Hologram Plugin
if (Setting.HOLOGRAMS.getBoolean()
&& pluginManager.isPluginEnabled("HolographicDisplays"))
hologram = new HologramHolographicDisplays(this);
// Register Listeners
pluginManager.registerEvents(new BlockListeners(this), this);
pluginManager.registerEvents(new FurnaceListeners(this), this);
pluginManager.registerEvents(new InteractListeners(this), this);
pluginManager.registerEvents(new InventoryListeners(this), this);
// Start auto save
int saveInterval = Setting.AUTOSAVE.getInt() * 60 * 20;
Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::saveToFile, saveInterval, saveInterval);
// Start Metrics
new Metrics(this);
console.sendMessage(Methods.formatText("&a============================="));
}
public void onDisable() {
saveToFile();
this.storage.closeConnection();
console.sendMessage(Methods.formatText("&a============================="));
console.sendMessage(Methods.formatText("&7EpicFurnaces " + this.getDescription().getVersion() + " by &5Songoda <3&7!"));
console.sendMessage(Methods.formatText("&7Action: &cDisabling&7..."));
console.sendMessage(Methods.formatText("&a============================="));
}
private void loadFromFile() {
/*
* Register furnaces into FurnaceManger from configuration
*/
Bukkit.getScheduler().runTaskLater(this, () -> {
if (storage.containsGroup("charged")) {
for (StorageRow row : storage.getRowsByGroup("charged")) {
Location location = Methods.unserializeLocation(row.getKey());
if (location == null) return;
int level = row.get("level").asInt();
int uses = row.get("uses").asInt();
int tolevel = row.get("level").asInt();
String nickname = row.get("nickname").asString();
List<String> accessList = row.get("accesslist").asStringList();
String placedByStr = row.get("placedBy").asString();
UUID placedBy = placedByStr == null ? null : UUID.fromString(placedByStr);
Furnace furnace = new Furnace(location, levelManager.getLevel(level), nickname, uses, tolevel, accessList, placedBy);
furnaceManager.addFurnace(location, furnace);
}
}
// Adding in Boosts
if (storage.containsGroup("boosts")) {
for (StorageRow row : storage.getRowsByGroup("boosts")) {
if (row.getItems().get("uuid").asObject() != null)
continue;
BoostData boostData = new BoostData(
row.get("amount").asInt(),
Long.parseLong(row.getKey()),
UUID.fromString(row.get("uuid").asString()));
this.boostManager.addBoostToPlayer(boostData);
}
}
if (hologram != null)
hologram.loadHolograms();
// Save data initially so that if the person reloads again fast they don't lose all their data.
this.saveToFile();
}, 10);
}
private void loadLevelManager() {
if (!new File(this.getDataFolder(), "levels.yml").exists())
this.saveResource("levels.yml", false);
// Load an plugin of LevelManager
levelManager = new LevelManager();
/*
* Register Levels into LevelManager from configuration.
*/
levelManager.clear();
for (String levelName : levelsFile.getConfig().getKeys(false)) {
int level = Integer.valueOf(levelName.split("-")[1]);
ConfigurationSection levels = levelsFile.getConfig().getConfigurationSection(levelName);
int costExperiance = levels.getInt("Cost-xp");
int costEconomy = levels.getInt("Cost-eco");
String performanceStr = levels.getString("Performance");
int performance = performanceStr == null ? 0 : Integer.parseInt(performanceStr.substring(0, performanceStr.length() - 1));
String reward = levels.getString("Reward");
String fuelDurationStr = levels.getString("Fuel-duration");
int fuelDuration = fuelDurationStr == null ? 0 : Integer.parseInt(fuelDurationStr.substring(0, fuelDurationStr.length() - 1));
int overheat = levels.getInt("Overheat");
int fuelShare = levels.getInt("Fuel-share");
levelManager.addLevel(level, costExperiance, costEconomy, performance, reward, fuelDuration, overheat, fuelShare);
}
}
private void checkStorage() {
if (getConfig().getBoolean("Database.Activate Mysql Support")) {
this.storage = new StorageMysql(this);
} else {
this.storage = new StorageYaml(this);
}
}
/*
* Saves registered furnaces to file.
*/
private void saveToFile() {
checkStorage();
storage.doSave();
}
public void reload() {
String langMode = getConfig().getString("System.Language Mode");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode", langMode));
this.locale.reloadMessages();
this.settingsManager.reloadConfig();
this.blacklistHandler.reload();
references = new References();
}
private void loadDataFile() {
dataFile.getConfig().options().copyDefaults(true);
dataFile.saveConfig();
}
private void setupRecipies() {
File config = new File(getDataFolder(), "Furnace Recipes.yml");
if (!config.exists()) {
saveResource("Furnace Recipes.yml", false);
}
if (getConfig().getBoolean("Main.Use Custom Recipes")) {
ConfigurationSection cs = furnaceRecipeFile.getConfig().getConfigurationSection("Recipes");
for (String key : cs.getKeys(false)) {
Material item = Material.valueOf(key.toUpperCase());
Material result = Material.valueOf(furnaceRecipeFile.getConfig().getString("Recipes." + key.toUpperCase() + ".result"));
int amount = furnaceRecipeFile.getConfig().getInt("Recipes." + key.toUpperCase() + ".amount");
getServer().addRecipe(new FurnaceRecipe(new ItemStack(result, amount), item));
}
}
}
public ItemStack createLeveledFurnace(int level, int uses) {
ItemStack item = new ItemStack(Material.FURNACE, 1);
ItemMeta itemmeta = item.getItemMeta();
if (getConfig().getBoolean("Main.Remember Furnace Item Levels"))
itemmeta.setDisplayName(Methods.formatText(Methods.formatName(level, uses, true)));
item.setItemMeta(itemmeta);
return item;
}
public ConfigWrapper getDataFile() {
return dataFile;
}
public int getFurnceLevel(ItemStack item) {
if (item.getItemMeta().getDisplayName().contains(":")) {
String arr[] = (item.getItemMeta().getDisplayName().replace("§", "")).split(":");
return Integer.parseInt(arr[0]);
} else {
return 1;
}
}
public int getFurnaceUses(ItemStack item) {
if (item.getItemMeta().getDisplayName().contains(":")) {
String arr[] = (item.getItemMeta().getDisplayName().replace("§", "")).split(":");
return Integer.parseInt(arr[1]);
} else {
return 0;
}
}
public ServerVersion getServerVersion() {
return serverVersion;
}
public boolean isServerVersion(ServerVersion version) {
return serverVersion == version;
}
public boolean isServerVersion(ServerVersion... versions) {
return ArrayUtils.contains(versions, serverVersion);
}
public boolean isServerVersionAtLeast(ServerVersion version) {
return serverVersion.ordinal() >= version.ordinal();
}
public ConfigWrapper getFurnaceRecipeFile() {
return furnaceRecipeFile;
}
public CommandManager getCommandManager() {
return commandManager;
}
public BoostManager getBoostManager() {
return boostManager;
}
public BlacklistHandler getBlacklistHandler() {
return blacklistHandler;
}
public References getReferences() {
return references;
}
public FurnaceManager getFurnaceManager() {
return furnaceManager;
}
public LevelManager getLevelManager() {
return levelManager;
}
public Economy getEconomy() {
return economy;
}
public SettingsManager getSettingsManager() {
return settingsManager;
}
public Hologram getHologram() {
return hologram;
}
public Locale getLocale() {
return locale;
}
}

View File

@ -3,7 +3,6 @@ package com.songoda.epicfurnaces;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;
@ -24,7 +23,7 @@ import java.util.stream.Collectors;
public class Locale {
private static final List<Locale> LOCALES = Lists.newArrayList();
private static final Pattern NODE_PATTERN = Pattern.compile("(\\w+(?:\\.\\w+)*)\\s*=\\s*\"(.*)\"");
private static final Pattern NODE_PATTERN = Pattern.compile("(\\w+(?:\\.{1}\\w+)*)\\s*=\\s*\"(.*)\"");
private static final String FILE_EXTENSION = ".lang";
private static JavaPlugin plugin;
private static File localeFolder;
@ -48,7 +47,7 @@ public class Locale {
if (this.reloadMessages()) return;
Bukkit.getConsoleSender().sendMessage("Loaded locale " + fileName);
plugin.getLogger().info("Loaded locale " + fileName);
}
/**
@ -57,7 +56,7 @@ public class Locale {
* Note that this will also call {@link #searchForLocales()}, so there is no need to
* invoke it for yourself after the initialization
*
* @param plugin the plugin instance
* @param plugin the plugin plugin
*/
public static void init(JavaPlugin plugin) {
Locale.plugin = plugin;
@ -74,9 +73,7 @@ public class Locale {
* Find all .lang file locales under the "locales" folder
*/
public static void searchForLocales() {
if (!localeFolder.exists()) {
localeFolder.mkdirs();
}
if (!localeFolder.exists()) localeFolder.mkdirs();
for (File file : localeFolder.listFiles()) {
String name = file.getName();
@ -89,7 +86,7 @@ public class Locale {
if (localeExists(localeValues[0] + "_" + localeValues[1])) continue;
LOCALES.add(new Locale(localeValues[0], localeValues[1]));
Bukkit.getConsoleSender().sendMessage("Found and loaded locale \"" + fileName + "\"");
plugin.getLogger().info("Found and loaded locale \"" + fileName + "\"");
}
}
@ -317,7 +314,7 @@ public class Locale {
public String getMessage(String node, Object... args) {
String message = getMessage(node);
for (Object arg : args) {
message = message.replaceFirst("%.*?%", arg.toString());
message = message.replaceFirst("\\%.*?\\%", arg.toString());
}
return message;
}
@ -358,7 +355,7 @@ public class Locale {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
for (int lineNumber = 0; (line = reader.readLine()) != null; lineNumber++) {
if (line.trim().isEmpty() || line.startsWith("#") /* Comment */) continue;
if (line.isEmpty() || line.startsWith("#") /* Comment */) continue;
Matcher matcher = NODE_PATTERN.matcher(line);
if (!matcher.find()) {
@ -375,7 +372,4 @@ public class Locale {
return true;
}
public String getPrefix() {
return getMessage("general.nametag.prefix") + " ";
}
}

View File

@ -0,0 +1,14 @@
package com.songoda.epicfurnaces;
public class References {
private String prefix;
public References() {
prefix = EpicFurnaces.getInstance().getLocale().getMessage("general.nametag.prefix") + " ";
}
public String getPrefix() {
return this.prefix;
}
}

View File

@ -1,4 +1,4 @@
package com.songoda.epicfurnaces.objects;
package com.songoda.epicfurnaces.boost;
import java.util.Objects;
import java.util.UUID;

View File

@ -1,19 +1,13 @@
package com.songoda.epicfurnaces.managers;
package com.songoda.epicfurnaces.boost;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.BoostData;
import com.songoda.epicfurnaces.storage.StorageItem;
import java.util.*;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class BoostManager {
private final Set<BoostData> registeredBoosts = new HashSet<>();
private final EpicFurnaces instance;
public BoostManager(EpicFurnaces instance) {
this.instance = instance;
}
public void addBoostToPlayer(BoostData data) {
this.registeredBoosts.add(data);

View File

@ -1,5 +1,6 @@
package com.songoda.epicfurnaces.command;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import org.bukkit.command.CommandSender;
public abstract class AbstractCommand {
@ -26,7 +27,7 @@ public abstract class AbstractCommand {
return noConsole;
}
protected abstract ReturnType runCommand(CommandSender sender, String... args);
protected abstract ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args);
public abstract String getPermissionNode();

View File

@ -1,8 +1,8 @@
package com.songoda.epicfurnaces.command;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.arconix.api.methods.formatting.TextComponent;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.command.commands.*;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@ -12,26 +12,24 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.songoda.epicfurnaces.command.AbstractCommand.ReturnType.SYNTAX_ERROR;
public class CommandManager implements CommandExecutor {
private EpicFurnaces instance;
private EpicFurnacesPlugin instance;
private List<AbstractCommand> commands = new ArrayList<>();
public CommandManager(EpicFurnaces instance) {
public CommandManager(EpicFurnacesPlugin instance) {
this.instance = instance;
instance.getCommand("EpicFurnaces").setExecutor(this);
AbstractCommand commandEpicFurnaces = addCommand(new CommandEpicFurnaces(instance));
AbstractCommand commandEpicFurnaces = addCommand(new CommandEpicFurnaces());
addCommand(new CommandReload(instance, commandEpicFurnaces));
addCommand(new CommandRemote(instance, commandEpicFurnaces));
addCommand(new CommandGive(instance, commandEpicFurnaces));
addCommand(new CommandBoost(instance, commandEpicFurnaces));
addCommand(new CommandHelp(instance, commandEpicFurnaces));
addCommand(new CommandReload(commandEpicFurnaces));
addCommand(new CommandRemote(commandEpicFurnaces));
addCommand(new CommandSettings(commandEpicFurnaces));
addCommand(new CommandGive(commandEpicFurnaces));
addCommand(new CommandBoost(commandEpicFurnaces));
}
private AbstractCommand addCommand(AbstractCommand abstractCommand) {
@ -55,7 +53,7 @@ public class CommandManager implements CommandExecutor {
}
}
}
commandSender.sendMessage(instance.getLocale().getPrefix() + StringUtils.formatText("&7The command you entered does not exist or is spelt incorrectly."));
commandSender.sendMessage(instance.getReferences().getPrefix() + TextComponent.formatText("&7The command you entered does not exist or is spelt incorrectly."));
return true;
}
@ -65,14 +63,14 @@ public class CommandManager implements CommandExecutor {
return;
}
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
AbstractCommand.ReturnType returnType = command.runCommand(sender, strings);
if (returnType == SYNTAX_ERROR) {
sender.sendMessage(instance.getLocale().getPrefix() + StringUtils.formatText("&cInvalid Syntax!"));
sender.sendMessage(instance.getLocale().getPrefix() + StringUtils.formatText("&7The valid syntax is: &6" + command.getSyntax() + "&7."));
AbstractCommand.ReturnType returnType = command.runCommand(instance, sender, strings);
if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) {
sender.sendMessage(instance.getReferences().getPrefix() + TextComponent.formatText("&cInvalid Syntax!"));
sender.sendMessage(instance.getReferences().getPrefix() + TextComponent.formatText("&7The valid syntax is: &6" + command.getSyntax() + "&7."));
}
return;
}
sender.sendMessage(instance.getLocale().getPrefix() + instance.getLocale().getMessage("event.general.nopermission"));
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.general.nopermission"));
}
public List<AbstractCommand> getCommands() {

View File

@ -0,0 +1,84 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.arconix.api.methods.formatting.TextComponent;
import com.songoda.arconix.api.methods.math.AMath;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.command.AbstractCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.Calendar;
import java.util.Date;
public class CommandBoost extends AbstractCommand {
public CommandBoost(AbstractCommand parent) {
super("boost", parent, false);
}
@Override
protected ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args) {
if (args.length < 3) {
return ReturnType.SYNTAX_ERROR;
}
if (Bukkit.getPlayer(args[1]) == null) {
sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&cThat player does not exist..."));
return ReturnType.FAILURE;
} else if (!AMath.isInt(args[2])) {
sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&6" + args[2] + " &7is not a number..."));
return ReturnType.FAILURE;
} else {
Calendar c = Calendar.getInstance();
Date currentDate = new Date();
c.setTime(currentDate);
String time = "&7.";
if (args.length > 3) {
if (args[3].contains("m:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.MINUTE, Integer.parseInt(arr2[1]));
time = " &7for &6" + arr2[1] + " minutes&7.";
} else if (args[3].contains("h:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.HOUR, Integer.parseInt(arr2[1]));
time = " &7for &6" + arr2[1] + " hours&7.";
} else if (args[3].contains("d:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.HOUR, Integer.parseInt(arr2[1]) * 24);
time = " &7for &6" + arr2[1] + " days&7.";
} else if (args[3].contains("y:")) {
String[] arr2 = (args[3]).split(":");
c.add(Calendar.YEAR, Integer.parseInt(arr2[1]));
time = " &7for &6" + arr2[1] + " years&7.";
} else {
sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7" + args[3] + " &7is invalid."));
return ReturnType.SUCCESS;
}
} else {
c.add(Calendar.YEAR, 10);
}
BoostData boostData = new BoostData(Integer.parseInt(args[2]), c.getTime().getTime(), Bukkit.getPlayer(args[1]).getUniqueId());
instance.getBoostManager().addBoostToPlayer(boostData);
sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7Successfully boosted &6" + Bukkit.getPlayer(args[1]).getName() + "'s &7furnaces reward amounts by &6" + args[2] + "x" + time));
}
return ReturnType.FAILURE;
}
@Override
public String getPermissionNode() {
return "epicfurnaces.admin";
}
@Override
public String getSyntax() {
return "/ef boost <player> <multiplier> [m:minute, h:hour, d:day, y:year]";
}
@Override
public String getDescription() {
return "This allows you to boost a players furnace reward amounts by a multiplier (Put 2 for double, 3 for triple and so on).";
}
}

View File

@ -1,27 +1,24 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.arconix.api.methods.formatting.TextComponent;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.command.AbstractCommand;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.command.CommandSender;
public class CommandEpicFurnaces extends AbstractCommand {
private final EpicFurnaces instance;
public CommandEpicFurnaces(EpicFurnaces instance) {
public CommandEpicFurnaces() {
super("EpicFurnaces", null, false);
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
protected ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args) {
sender.sendMessage("");
sender.sendMessage(StringUtils.formatText(instance.getLocale().getPrefix() + "&7Version " + instance.getDescription().getVersion() + " Created with <3 by &5&l&oSongoda"));
sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7Version " + instance.getDescription().getVersion() + " Created with <3 by &5&l&oBrianna"));
for (AbstractCommand command : instance.getCommandManager().getCommands()) {
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
sender.sendMessage(StringUtils.formatText("&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
sender.sendMessage(TextComponent.formatText("&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
}
}
sender.sendMessage("");
@ -29,11 +26,6 @@ public class CommandEpicFurnaces extends AbstractCommand {
return ReturnType.SUCCESS;
}
@Override
public String getDescription() {
return "Displays this page.";
}
@Override
public String getPermissionNode() {
return null;
@ -41,6 +33,11 @@ public class CommandEpicFurnaces extends AbstractCommand {
@Override
public String getSyntax() {
return "/ef";
return "/EpicFurnaces";
}
@Override
public String getDescription() {
return "Displays this page.";
}
}

View File

@ -0,0 +1,64 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.arconix.plugin.Arconix;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.api.furnace.Level;
import com.songoda.epicfurnaces.command.AbstractCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGive extends AbstractCommand {
public CommandGive(AbstractCommand parent) {
super("give", parent, false);
}
@Override
protected ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args) {
if (args.length == 2) return ReturnType.SYNTAX_ERROR;
Level level = instance.getLevelManager().getLowestLevel();
Player player;
if (args.length != 1 && Bukkit.getPlayer(args[1]) == null) {
sender.sendMessage(instance.getReferences().getPrefix() + Arconix.pl().getApi().format().formatText("&cThat player does not exist or is currently offline."));
return ReturnType.FAILURE;
} else if (args.length == 1) {
if (!(sender instanceof Player)) {
sender.sendMessage(instance.getReferences().getPrefix() + Arconix.pl().getApi().format().formatText("&cYou need to be a player to give a farm item to yourself."));
return ReturnType.FAILURE;
}
player = (Player)sender;
} else {
player = Bukkit.getPlayer(args[1]);
}
if (args.length >= 3 && !instance.getLevelManager().isLevel(Integer.parseInt(args[2]))) {
sender.sendMessage(instance.getReferences().getPrefix() + Arconix.pl().getApi().format().formatText("&cNot a valid level... The current valid levels are: &4" + instance.getLevelManager().getLowestLevel().getLevel() + "-" + instance.getLevelManager().getHighestLevel().getLevel() + "&c."));
return ReturnType.FAILURE;
} else if (args.length != 1){
level = instance.getLevelManager().getLevel(Integer.parseInt(args[2]));
}
player.getInventory().addItem(instance.createLeveledFurnace(level.getLevel(), 0));
player.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.give.success", level.getLevel()));
return ReturnType.SUCCESS;
}
@Override
public String getPermissionNode() {
return "epicfurnaces.admin";
}
@Override
public String getSyntax() {
return "/ef give [player] <level>";
}
@Override
public String getDescription() {
return "Give a leveled furnace to a player.";
}
}

View File

@ -1,22 +1,20 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.arconix.api.methods.formatting.TextComponent;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.command.AbstractCommand;
import com.songoda.epicfurnaces.utils.StringUtils;
import org.bukkit.command.CommandSender;
public class CommandReload extends AbstractCommand {
private final EpicFurnaces instance;
public CommandReload(EpicFurnaces instance, AbstractCommand parent) {
public CommandReload(AbstractCommand parent) {
super("reload", parent, false);
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
protected ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args) {
instance.reload();
sender.sendMessage(StringUtils.formatText(instance.getLocale().getPrefix() + "&7Configuration and Language files reloaded."));
sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7Configuration and Language files reloaded."));
return ReturnType.SUCCESS;
}

View File

@ -0,0 +1,71 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.api.furnace.Furnace;
import com.songoda.epicfurnaces.command.AbstractCommand;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
public class CommandRemote extends AbstractCommand {
public CommandRemote(AbstractCommand abstractCommand) {
super("remote", abstractCommand, true);
}
@Override
protected ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args) {
if (!instance.getConfig().getBoolean("Main.Access Furnaces Remotely") || !sender.hasPermission("EpicFurnaces.Remote")) {
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.general.nopermission"));
return ReturnType.FAILURE;
}
if (!instance.getDataFile().getConfig().contains("data.charged")) {
return ReturnType.FAILURE;
}
if (args.length < 2) return ReturnType.SYNTAX_ERROR;
StringBuilder name = new StringBuilder();
for (int i = 1; i < args.length; i++) {
name.append(" ").append(args[i]);
}
name = new StringBuilder(name.toString().trim());
for (Furnace furnace : instance.getFurnaceManager().getFurnaces().values()) {
if (furnace.getNickname() == null) continue;
if (!furnace.getNickname().equalsIgnoreCase(name.toString())) {
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.general.nopermission"));
continue;
}
for (UUID uuid : furnace.getAccessList()) {
if (!uuid.equals(((Player) sender).getUniqueId())) {
continue;
}
Block b = furnace.getLocation().getBlock();
org.bukkit.block.Furnace furnaceBlock = (org.bukkit.block.Furnace) b.getState();
((Player) sender).openInventory(furnaceBlock.getInventory());
return ReturnType.SUCCESS;
}
}
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.remote.notfound"));
return ReturnType.FAILURE;
}
@Override
public String getPermissionNode() {
return null;
}
@Override
public String getSyntax() {
return "/ef remote [nickname]";
}
@Override
public String getDescription() {
return "Remote control your furnace.";
}
}

View File

@ -0,0 +1,34 @@
package com.songoda.epicfurnaces.command.commands;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.command.AbstractCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandSettings extends AbstractCommand {
public CommandSettings(AbstractCommand parent) {
super("settings", parent, true);
}
@Override
protected ReturnType runCommand(EpicFurnacesPlugin instance, CommandSender sender, String... args) {
instance.getSettingsManager().openSettingsManager((Player) sender);
return ReturnType.SUCCESS;
}
@Override
public String getPermissionNode() {
return "epicfurnaces.admin";
}
@Override
public String getSyntax() {
return "/ef settings";
}
@Override
public String getDescription() {
return "Edit the EpicFurnaces Settings.";
}
}

View File

@ -0,0 +1,12 @@
package com.songoda.epichoppers.economy;
import org.bukkit.OfflinePlayer;
public interface Economy {
boolean hasBalance(OfflinePlayer player, double cost);
boolean withdrawBalance(OfflinePlayer player, double cost);
boolean deposit(OfflinePlayer player, double amount);
}

View File

@ -0,0 +1,43 @@
package com.songoda.epichoppers.economy;
import com.songoda.epichoppers.EpicHoppers;
import org.black_ixx.playerpoints.PlayerPoints;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public class PlayerPointsEconomy implements Economy {
private final EpicHoppers plugin;
private final PlayerPoints playerPoints;
public PlayerPointsEconomy(EpicHoppers plugin) {
this.plugin = plugin;
this.playerPoints = (PlayerPoints) plugin.getServer().getPluginManager().getPlugin("PlayerPoints");
}
private int convertAmount(double amount) {
return (int) Math.ceil(amount);
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().look(player.getUniqueId()) >= amount;
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().take(player.getUniqueId(), amount);
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
int amt = convertAmount(amount);
return playerPoints.getAPI().give(player.getUniqueId(), amt);
}
}

View File

@ -0,0 +1,34 @@
package com.songoda.epichoppers.economy;
import com.songoda.epichoppers.EpicHoppers;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public class VaultEconomy implements Economy {
private final EpicHoppers plugin;
private final net.milkbowl.vault.economy.Economy vault;
public VaultEconomy(EpicHoppers plugin) {
this.plugin = plugin;
this.vault = plugin.getServer().getServicesManager().
getRegistration(net.milkbowl.vault.economy.Economy.class).getProvider();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return vault.has(player, cost);
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return vault.withdrawPlayer(player, cost).transactionSuccess();
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return vault.depositPlayer(player, amount).transactionSuccess();
}
}

View File

@ -0,0 +1,615 @@
package com.songoda.epicfurnaces.furnace;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.player.PlayerData;
import com.songoda.epicfurnaces.utils.Debugger;
import com.songoda.epicfurnaces.utils.Methods;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.RegisteredServiceProvider;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.*;
/**
* Created by songoda on 3/7/2017.
*/
public class EFurnace {
private final EpicFurnaces instance = EpicFurnaces.getInstance();
private Location location;
private Level level;
private String nickname;
private UUID placedBy;
private int uses, tolevel, radiusOverheatLast, radiusFuelshareLast;
private List<Location> radiusOverheat = new ArrayList<>();
private List<Location> radiusFuelshare = new ArrayList<>();
private List<String> accessList = new ArrayList<>();
private Map<String, Integer> cache = new HashMap<>();
public EFurnace(Location location, Level level, String nickname, int uses, int tolevel, List<String> accessList, UUID placedBy) {
this.location = location;
this.level = level;
this.uses = uses;
this.tolevel = tolevel;
this.nickname = nickname;
this.placedBy = placedBy;
this.accessList = accessList;
this.syncName();
}
public EFurnace(Block block, Level level, String nickname, int uses, int tolevel, List<String> accessList, UUID placedBy) {
this(block.getLocation(), level, nickname, uses, tolevel, accessList, placedBy);
}
public void openOverview(Player p) {
try {
PlayerData playerData = instance.getPlayerDataManager().getPlayerData(p);
if (!p.hasPermission("epicfurnaces.overview")) return;
playerData.setLastFurace(this);
Level nextLevel = instance.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? instance.getLevelManager().getLevel(level.getLevel() + 1) : null;
int multi = instance.getConfig().getInt("Main.Level Cost Multiplier");
int needed = (multi * level.getLevel()) - tolevel;
ItemStack item = new ItemStack(Material.FURNACE, 1);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(instance.getLocale().getMessage("interface.furnace.currentlevel", level.getLevel()));
ArrayList<String> lore = new ArrayList<>();
lore.add(instance.getLocale().getMessage("interface.furnace.smeltedx", uses));
lore.addAll(this.level.getDescription());
lore.add("");
if (nextLevel == null)
lore.add(instance.getLocale().getMessage("interface.furnace.alreadymaxed"));
else {
lore.add(instance.getLocale().getMessage("interface.furnace.level", nextLevel.getLevel()));
lore.addAll(nextLevel.getDescription());
if (instance.getConfig().getBoolean("Main.Upgrade By Smelting Materials")) {
lore.add(instance.getLocale().getMessage("interface.furnace.tolevel", needed, Methods.cleanString(instance.getConfig().getString("Main.Furnace Upgrade Cost"))));
}
}
BoostData boostData = instance.getBoostManager().getBoost(placedBy);
if (boostData != null) {
String[] parts = instance.getLocale().getMessage("interface.button.boostedstats", Integer.toString(boostData.getMultiplier()), TimeComponent.makeReadable(boostData.getEndTime() - System.currentTimeMillis())).split("\\|");
lore.add("");
for (String line : parts)
lore.add(TextComponent.formatText(line));
}
itemmeta.setLore(lore);
item.setItemMeta(itemmeta);
Inventory i = Bukkit.createInventory(null, 27, Arconix.pl().getApi().format().formatText(Methods.formatName(level.getLevel(), 0, false)));
int nu = 0;
while (nu != 27) {
i.setItem(nu, Methods.getGlass());
nu++;
}
ItemStack item2 = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.Performance Icon")), 1);
ItemMeta itemmeta2 = item2.getItemMeta();
itemmeta2.setDisplayName(instance.getLocale().getMessage("interface.furnace.performancetitle")); //greyed out until available
ArrayList<String> lore2 = new ArrayList<>();
String[] parts = instance.getLocale().getMessage("interface.furnace.performanceinfo", level.getPerformance()).split("\\|");
lore.add("");
for (String line : parts) {
lore2.add(Arconix.pl().getApi().format().formatText(line));
}
itemmeta2.setLore(lore2);
item2.setItemMeta(itemmeta2);
ItemStack item3 = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.Reward Icon")), 1);
ItemMeta itemmeta3 = item3.getItemMeta();
itemmeta3.setDisplayName(instance.getLocale().getMessage("interface.furnace.rewardtitle"));
ArrayList<String> lore3 = new ArrayList<>();
parts = instance.getLocale().getMessage("interface.furnace.rewardinfo", level.getReward().split(":")[0].replace("%", "")).split("\\|");
lore.add("");
for (String line : parts) {
lore3.add(Arconix.pl().getApi().format().formatText(line));
}
itemmeta3.setLore(lore3);
item3.setItemMeta(itemmeta3);
ItemStack item4 = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.FuelDuration Icon")), 1);
ItemMeta itemmeta4 = item4.getItemMeta();
itemmeta4.setDisplayName(instance.getLocale().getMessage("interface.furnace.fueldurationtitle"));
ArrayList<String> lore4 = new ArrayList<>();
parts = instance.getLocale().getMessage("interface.furnace.fueldurationinfo", level.getFuelDuration()).split("\\|");
lore.add("");
for (String line : parts) {
lore4.add(Arconix.pl().getApi().format().formatText(line));
}
itemmeta4.setLore(lore4);
item4.setItemMeta(itemmeta4);
ItemStack item5 = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.Overheat Icon")), 1);
ItemMeta itemmeta5 = item4.getItemMeta();
itemmeta5.setDisplayName(instance.getLocale().getMessage("interface.furnace.overheattitle"));
ArrayList<String> lore5 = new ArrayList<>();
parts = instance.getLocale().getMessage("interface.furnace.overheatinfo", level.getOverheat() * 3).split("\\|");
lore.add("");
for (String line : parts) {
lore5.add(Arconix.pl().getApi().format().formatText(line));
}
itemmeta5.setLore(lore5);
item5.setItemMeta(itemmeta5);
ItemStack item6 = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.FuelShare Icon")), 1);
ItemMeta itemmeta6 = item4.getItemMeta();
itemmeta6.setDisplayName(instance.getLocale().getMessage("interface.furnace.fuelsharetitle"));
ArrayList<String> lore6 = new ArrayList<>();
parts = instance.getLocale().getMessage("interface.furnace.fuelshareinfo", level.getOverheat() * 3).split("\\|");
lore.add("");
for (String line : parts) {
lore6.add(Arconix.pl().getApi().format().formatText(line));
}
itemmeta6.setLore(lore6);
item6.setItemMeta(itemmeta6);
ItemStack itemXP = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.XP Icon")), 1);
ItemMeta itemmetaXP = itemXP.getItemMeta();
itemmetaXP.setDisplayName(instance.getLocale().getMessage("interface.furnace.upgradewithxp"));
ArrayList<String> loreXP = new ArrayList<>();
if (nextLevel != null)
loreXP.add(instance.getLocale().getMessage("interface.furnace.upgradewithxplore", level.getCostExperiance()));
else
loreXP.add(instance.getLocale().getMessage("interface.furnace.alreadymaxed"));
itemmetaXP.setLore(loreXP);
itemXP.setItemMeta(itemmetaXP);
ItemStack itemECO = new ItemStack(Material.valueOf(instance.getConfig().getString("Interfaces.Economy Icon")), 1);
ItemMeta itemmetaECO = itemECO.getItemMeta();
itemmetaECO.setDisplayName(instance.getLocale().getMessage("interface.furnace.upgradewitheconomy"));
ArrayList<String> loreECO = new ArrayList<>();
if (nextLevel != null)
loreECO.add(instance.getLocale().getMessage("interface.furnace.upgradewitheconomylore", Arconix.pl().getApi().format().formatEconomy(level.getCostEconomy())));
else
loreECO.add(instance.getLocale().getMessage("interface.furnace.alreadymaxed"));
itemmetaECO.setLore(loreECO);
itemECO.setItemMeta(itemmetaECO);
i.setItem(13, item);
i.setItem(0, Methods.getBackgroundGlass(true));
i.setItem(1, Methods.getBackgroundGlass(true));
i.setItem(2, Methods.getBackgroundGlass(false));
i.setItem(6, Methods.getBackgroundGlass(false));
i.setItem(7, Methods.getBackgroundGlass(true));
i.setItem(8, Methods.getBackgroundGlass(true));
i.setItem(9, Methods.getBackgroundGlass(true));
i.setItem(10, Methods.getBackgroundGlass(false));
i.setItem(16, Methods.getBackgroundGlass(false));
i.setItem(17, Methods.getBackgroundGlass(true));
i.setItem(18, Methods.getBackgroundGlass(true));
i.setItem(19, Methods.getBackgroundGlass(true));
i.setItem(20, Methods.getBackgroundGlass(false));
i.setItem(24, Methods.getBackgroundGlass(false));
i.setItem(25, Methods.getBackgroundGlass(true));
i.setItem(26, Methods.getBackgroundGlass(true));
int num = -1;
Map<Integer, int[]> spots = new HashMap();
int[] s1 = {22};
spots.put(0, s1);
int[] s2 = {21, 23};
spots.put(1, s2);
int[] s3 = {21, 22, 23};
spots.put(2, s3);
int[] s4 = {20, 21, 23, 24};
spots.put(3, s4);
int[] s5 = {20, 21, 22, 23, 24};
spots.put(4, s5);
if (level.getPerformance() != 0) {
num ++;
}
if (level.getReward() != null) {
num ++;
}
if (level.getFuelDuration() != 0) {
num ++;
}
if (level.getFuelShare() != 0) {
num ++;
}
if (level.getOverheat() != 0) {
num ++;
}
int[] order = spots.get(num);
int current = 0;
if (level.getPerformance() != 0) {
i.setItem(order[current], item2);
current ++;
}
if (level.getReward() != null) {
i.setItem(order[current], item3);
current ++;
}
if (level.getFuelDuration() != 0) {
i.setItem(order[current], item4);
current ++;
}
if (level.getFuelShare() != 0) {
i.setItem(order[current], item6);
current ++;
}
if (level.getOverheat() != 0) {
i.setItem(order[current], item5);
}
ItemStack hook = new ItemStack(Material.TRIPWIRE_HOOK, 1);
ItemMeta hookmeta = hook.getItemMeta();
hookmeta.setDisplayName(instance.getLocale().getMessage("interface.furnace.remotefurnace"));
ArrayList<String> lorehook = new ArrayList<>();
parts = instance.getLocale().getMessage("interface.furnace.remotefurnacelore", nickname == null ? "Unset" : nickname).split("\\|");
for (String line : parts) {
lorehook.add(Arconix.pl().getApi().format().formatText(line));
}
if (nickname != null) {
parts = instance.getLocale().getMessage("interface.furnace.utilize", nickname).split("\\|");
for (String line : parts) {
lorehook.add(Arconix.pl().getApi().format().formatText(line));
}
}
for (String line : accessList) {
lorehook.add("");
lorehook.add(instance.getLocale().getMessage("interface.furnace.remotelist"));
String[] halfs = line.split(":");
String name = halfs[1];
Player player = Bukkit.getPlayer(halfs[0]);
if (player != null) {
name = player.getDisplayName();
}
lorehook.add(Arconix.pl().getApi().format().formatText("&6" + name));
}
hookmeta.setLore(lorehook);
hook.setItemMeta(hookmeta);
if (instance.getConfig().getBoolean("Main.Access Furnaces Remotely") && p.hasPermission("EpicFurnaces.Remote")) {
i.setItem(4, hook);
}
i.setItem(13, item);
if (instance.getConfig().getBoolean("Main.Upgrade With XP") && p.hasPermission("EpicFurnaces.Upgrade.XP")) {
i.setItem(11, itemXP);
}
if (instance.getConfig().getBoolean("Main.Upgrade With Economy") && p.hasPermission("EpicFurnaces.Upgrade.ECO")) {
i.setItem(15, itemECO);
}
p.openInventory(i);
playerData.setInOverview(true);
} catch (Exception e) {
Debugger.runReport(e);
}
}
public void plus(FurnaceSmeltEvent e) {
try {
Block block = location.getBlock();
if (block.getType() != Material.FURNACE) return;
this.uses ++;
this.tolevel ++;
int multi = instance.getConfig().getInt("Main.Level Cost Multiplier");
if (level.getReward() == null) return;
String reward = level.getReward();
String amt[] = {"1", "1"};
if (reward.contains(":")) {
String[] rewardSplit = reward.split(":");
reward = rewardSplit[0].substring(0, rewardSplit[0].length() - 1);
if (rewardSplit[1].contains("-"))
amt = rewardSplit[1].split("-");
else {
amt[0] = rewardSplit[1];
amt[1] = rewardSplit[0];
}
}
int needed = ((multi * level.getLevel()) - tolevel) - 1;
if (instance.getConfig().getBoolean("Main.Upgrade By Smelting Materials")
&& needed <= 0
&& instance.getConfig().contains("settings.levels.Level-" + (level.getLevel() + 1))) {
tolevel = 0;
level = instance.getLevelManager().getLevel(this.level.getLevel() + 1);
}
this.updateCook();
FurnaceInventory i = (FurnaceInventory) ((InventoryHolder) block.getState()).getInventory();
int num = Integer.parseInt(reward);
double rand = Math.random() * 100;
if (rand >= num
|| e.getResult().equals(Material.SPONGE)
|| instance.getConfig().getBoolean("Main.No Rewards From Custom Recipes")
&& instance.getFurnaceRecipeFile().getConfig().contains("Recipes." + i.getSmelting().getType().toString())) {
return;
}
int r = Integer.parseInt(amt[0]);
if (Integer.parseInt(amt[0]) !=
Integer.parseInt(amt[1].replace("%", "")))
r = (int) (Math.random() * ((Integer.parseInt(amt[1].replace("%", "")) - Integer.parseInt(amt[0])))) + Integer.parseInt(amt[0]);
BoostData boostData = instance.getBoostManager().getBoost(placedBy);
r = r * (boostData == null ? 1 : boostData.getMultiplier());
if (e.getResult() != null) {
e.getResult().setAmount(e.getResult().getAmount() + r);
return;
}
e.setResult(new ItemStack(e.getResult().getType(), r));
} catch (Exception ex) {
Debugger.runReport(ex);
}
}
public void upgrade(String type, Player player) {
try {
if (!instance.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1))
return;
int cost;
if (type.equals("XP")) {
cost = level.getCostExperiance();
} else {
cost = level.getCostEconomy();
}
Level level = instance.getLevelManager().getLevel(this.level.getLevel() + 1);
if (type.equals("ECO")) {
if (instance.getServer().getPluginManager().getPlugin("Vault") != null) {
RegisteredServiceProvider<Economy> rsp = instance.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
net.milkbowl.vault.economy.Economy econ = rsp.getProvider();
if (econ.has(player, cost)) {
econ.withdrawPlayer(player, cost);
upgradeFinal(level, player);
} else {
player.sendMessage(instance.getLocale().getMessage("event.upgrade.cannotafford"));
}
} else {
player.sendMessage("Vault is not installed.");
}
} else if (type.equals("XP")) {
if (player.getLevel() >= cost || player.getGameMode() == GameMode.CREATIVE) {
if (player.getGameMode() != GameMode.CREATIVE) {
player.setLevel(player.getLevel() - cost);
}
upgradeFinal(level, player);
} else {
player.sendMessage(instance.getLocale().getMessage("event.upgrade.cannotafford"));
}
}
} catch (Exception ex) {
Debugger.runReport(ex);
}
}
private void upgradeFinal(Level level, Player player) {
try {
this.level = level;
syncName();
if (instance.getLevelManager().getHighestLevel() != level) {
player.sendMessage(instance.getLocale().getMessage("event.upgrade.success", level.getLevel()));
} else {
player.sendMessage(instance.getLocale().getMessage("event.upgrade.maxed", level.getLevel()));
}
Location loc = location.clone().add(.5, .5, .5);
player.getWorld().spawnParticle(org.bukkit.Particle.valueOf(instance.getConfig().getString("Main.Upgrade Particle Type")), loc, 200, .5, .5, .5);
if (instance.getConfig().getBoolean("Main.Use Sounds")) {
if (instance.getLevelManager().getHighestLevel() == level) {
player.playSound(player.getLocation(), org.bukkit.Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 15.0F);
} else {
player.playSound(player.getLocation(), org.bukkit.Sound.ENTITY_PLAYER_LEVELUP, 2F, 25.0F);
player.playSound(player.getLocation(), org.bukkit.Sound.BLOCK_NOTE_BLOCK_CHIME, 2F, 25.0F);
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> player.playSound(player.getLocation(), org.bukkit.Sound.BLOCK_NOTE_BLOCK_CHIME, 1.2F, 35.0F), 5L);
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> player.playSound(player.getLocation(), org.bukkit.Sound.BLOCK_NOTE_BLOCK_CHIME, 1.8F, 35.0F), 10L);
}
}
} catch (Exception ex) {
Debugger.runReport(ex);
}
}
private void syncName() {
if (!(location.getBlock() instanceof Furnace)) return;
org.bukkit.block.Furnace furnace = (org.bukkit.block.Furnace) location.getBlock().getState();
furnace.setCustomName(Methods.formatName(level.getLevel(), uses, false));
furnace.update(true);
}
public void updateCook() {
try {
Block block = location.getBlock();
if (block == null || block.getType() != Material.FURNACE) return;
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(instance, () -> {
int num = getPerformanceTotal();
if (num > 200) {
num = 200;
}
if (num != 0) {
BlockState bs = (block.getState()); // max is 200
((org.bukkit.block.Furnace) bs).setCookTime(Short.parseShort(Integer.toString(num)));
bs.update();
}
}, 1L);
} catch (Exception e) {
Debugger.runReport(e);
}
}
public Level getLevel() {
return level;
}
public List<UUID> getAccessList() {
List<UUID> list = new ArrayList<>();
for (String line : accessList) {
String[] halfs = line.split(":");
list.add(UUID.fromString(halfs[0]));
}
return list;
}
public int getPerformanceTotal() {
String equation = "(" + level.getPerformance() + " / 100) * 200";
try {
if (!cache.containsKey(equation)) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
int num = (int) Math.round(Double.parseDouble(engine.eval("(" + level.getPerformance() + " / 100) * 200").toString()));
cache.put(equation, num);
return num;
} else {
return cache.get(equation);
}
} catch (ScriptException e) {
Debugger.runReport(e);
}
return 0;
}
public List<String> getOriginalAccessList() {
return Collections.unmodifiableList(accessList);
}
public boolean addToAccessList(String string) {
return accessList.add(string);
}
public boolean removeFromAccessList(String string) {
return accessList.remove(string);
}
public void clearAccessList() {
accessList.clear();
}
public Location getLocation() {
return location.clone();
}
public String getNickname() {
return nickname;
}
public UUID getPlacedBy() {
return placedBy;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public List<Location> getRadius(boolean overHeat) {
if (overHeat)
return radiusOverheat.isEmpty() ? null : Collections.unmodifiableList(radiusOverheat);
else
return radiusFuelshare.isEmpty() ? null : Collections.unmodifiableList(radiusFuelshare);
}
public void addToRadius(Location location, boolean overHeat) {
if (overHeat)
radiusOverheat.add(location);
else
radiusFuelshare.add(location);
}
public void clearRadius(boolean overHeat) {
if (overHeat)
radiusOverheat.clear();
else
radiusFuelshare.clear();
}
public int getRadiusLast(boolean overHeat) {
if (overHeat)
return radiusOverheatLast;
else
return radiusFuelshareLast;
}
public void setRadiusLast(int radiusLast, boolean overHeat) {
if (overHeat)
this.radiusOverheatLast = radiusLast;
else
this.radiusFuelshareLast = radiusLast;
}
public int getUses() {
return uses;
}
public int getTolevel() {
return tolevel;
}
}

View File

@ -0,0 +1,53 @@
package com.songoda.epicfurnaces.furnace;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.api.furnace.Furnace;
import com.songoda.epicfurnaces.api.furnace.FurnaceManager;
import org.bukkit.Location;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class EFurnaceManager implements FurnaceManager {
private final Map<Location, Furnace> registeredFurnaces = new HashMap<>();
@Override
public void addFurnace(Location location, Furnace furnace) {
registeredFurnaces.put(roundLocation(location), furnace);
}
@Override
public Furnace removeFurnace(Location location) {
return registeredFurnaces.remove(location);
}
@Override
public Furnace getFurnace(Location location) {
if (!registeredFurnaces.containsKey(location)) {
addFurnace(location, new EFurnace(location, EpicFurnaces.getInstance().getLevelManager().getLowestLevel(), null, 0, 0, new ArrayList<>(), null));
}
return registeredFurnaces.get(location);
}
@Override
public Furnace getFurnace(Block block) {
return getFurnace(block.getLocation());
}
@Override
public Map<Location, Furnace> getFurnaces() {
return Collections.unmodifiableMap(registeredFurnaces);
}
private Location roundLocation(Location location) {
location = location.clone();
location.setX(location.getBlockX());
location.setY(location.getBlockY());
location.setZ(location.getBlockZ());
return location;
}
}

View File

@ -1,20 +1,22 @@
package com.songoda.epicfurnaces.objects;
package com.songoda.epicfurnaces.furnace;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.api.furnace.Level;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Level {
public class Level implements Level {
private int level, costExperiance, costEconomy, performance, fuelDuration, overheat, fuelShare;
private List<String> description = new ArrayList<>();
private int level, costExperience, costEconomy, performance, fuelDuration, overheat, fuelShare;
private String reward;
public Level(EpicFurnaces instance, int level, int costExperience, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare) {
private List<String> description = new ArrayList<>();
Level(int level, int costExperiance, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare) {
this.level = level;
this.costExperience = costExperience;
this.costExperiance = costExperiance;
this.costEconomy = costEconomy;
this.performance = performance;
this.reward = reward;
@ -22,6 +24,8 @@ public class Level {
this.overheat = overheat;
this.fuelShare = fuelShare;
EpicFurnaces instance = EpicFurnaces.getInstance();
if (performance != 0)
description.add(instance.getLocale().getMessage("interface.furnace.performance", performance + "%"));
@ -38,47 +42,47 @@ public class Level {
description.add(instance.getLocale().getMessage("interface.furnace.overheat", overheat));
}
@Override
public List<String> getDescription() {
return Collections.unmodifiableList(description);
return new ArrayList<>(description);
}
@Override
public int getLevel() {
return level;
}
@Override
public int getPerformance() {
return performance;
}
@Override
public String getReward() {
return reward;
}
@Override
public int getOverheat() {
return overheat;
}
@Override
public int getFuelShare() {
return fuelShare;
}
@Override
public int getFuelDuration() {
return fuelDuration;
}
public int getCostExperience() {
return costExperience;
@Override
public int getCostExperiance() {
return costExperiance;
}
@Override
public int getCostEconomy() {
return costEconomy;
}

View File

@ -0,0 +1,49 @@
package com.songoda.epicfurnaces.furnace;
import com.songoda.epicfurnaces.api.furnace.Level;
import com.songoda.epicfurnaces.api.furnace.LevelManager;
import java.util.Collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
public class LevelManager implements LevelManager {
private final NavigableMap<Integer, Level> registeredLevels = new TreeMap<>();
@Override
public void addLevel(int level, int costExperiance, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare) {
registeredLevels.put(level, new Level(level, costExperiance, costEconomy, performance, reward, fuelDuration, overheat, fuelShare));
}
@Override
public Level getLevel(int level) {
return registeredLevels.get(level);
}
@Override
public Level getLowestLevel() {
return registeredLevels.firstEntry().getValue();
}
@Override
public Level getHighestLevel() {
return registeredLevels.lastEntry().getValue();
}
@Override
public boolean isLevel(int level) {
return registeredLevels.containsKey(level);
}
@Override
public Map<Integer, Level> getLevels() {
return Collections.unmodifiableMap(registeredLevels);
}
@Override
public void clear() {
registeredLevels.clear();
}
}

View File

@ -0,0 +1,290 @@
package com.songoda.epichoppers.gui;
import com.songoda.epichoppers.EpicHoppers;
import com.songoda.epichoppers.boost.BoostData;
import com.songoda.epichoppers.hopper.Hopper;
import com.songoda.epichoppers.hopper.levels.Level;
import com.songoda.epichoppers.hopper.levels.modules.Module;
import com.songoda.epichoppers.player.SyncType;
import com.songoda.epichoppers.utils.CostType;
import com.songoda.epichoppers.utils.Methods;
import com.songoda.epichoppers.utils.ServerVersion;
import com.songoda.epichoppers.utils.TeleportTrigger;
import com.songoda.epichoppers.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GUIOverview extends AbstractGUI {
private final EpicHoppers plugin;
private final Hopper hopper;
private int task;
public GUIOverview(EpicHoppers plugin, Hopper hopper, Player player) {
super(player);
this.plugin = plugin;
this.hopper = hopper;
init(Methods.formatName(hopper.getLevel().getLevel(), false), 27);
runTask();
}
@Override
protected void constructGUI() {
inventory.clear();
resetClickables();
registerClickables();
plugin.getPlayerDataManager().getPlayerData(player).setLastHopper(hopper);
Level level = hopper.getLevel();
Level nextLevel = plugin.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? plugin.getLevelManager().getLevel(level.getLevel() + 1) : null;
ItemStack perl = new ItemStack(Material.ENDER_PEARL, 1);
ItemMeta perlmeta = perl.getItemMeta();
perlmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.perltitle"));
ArrayList<String> loreperl = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.hopper.perllore2", hopper.getTeleportTrigger() == TeleportTrigger.DISABLED ? plugin.getLocale().getMessage("general.word.disabled") : hopper.getTeleportTrigger().name()).split("\\|");
for (String line : parts) {
loreperl.add(Methods.formatText(line));
}
perlmeta.setLore(loreperl);
perl.setItemMeta(perlmeta);
ItemStack filter = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.COMPARATOR : Material.valueOf("REDSTONE_COMPARATOR"), 1);
ItemMeta filtermeta = filter.getItemMeta();
filtermeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.filtertitle"));
ArrayList<String> lorefilter = new ArrayList<>();
parts = plugin.getLocale().getMessage("interface.hopper.filterlore").split("\\|");
for (String line : parts) {
lorefilter.add(Methods.formatText(line));
}
filtermeta.setLore(lorefilter);
filter.setItemMeta(filtermeta);
ItemStack item = new ItemStack(Material.HOPPER, 1);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.currentlevel", level.getLevel()));
List<String> lore = level.getDescription();
if (plugin.getConfig().getBoolean("Main.Allow hopper Upgrading")) {
lore.add("");
if (nextLevel == null) lore.add(plugin.getLocale().getMessage("interface.hopper.alreadymaxed"));
else {
lore.add(plugin.getLocale().getMessage("interface.hopper.nextlevel", nextLevel.getLevel()));
lore.addAll(nextLevel.getDescription());
}
}
BoostData boostData = plugin.getBoostManager().getBoost(hopper.getPlacedBy());
if (boostData != null) {
parts = plugin.getLocale().getMessage("interface.hopper.boostedstats", Integer.toString(boostData.getMultiplier()), Methods.makeReadable(boostData.getEndTime() - System.currentTimeMillis())).split("\\|");
lore.add("");
for (String line : parts)
lore.add(Methods.formatText(line));
}
itemmeta.setLore(lore);
item.setItemMeta(itemmeta);
ItemStack hook = new ItemStack(Material.TRIPWIRE_HOOK, 1);
ItemMeta hookmeta = hook.getItemMeta();
hookmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.synchopper"));
ArrayList<String> lorehook = new ArrayList<>();
parts = plugin.getLocale().getMessage("interface.hopper.synclore", hopper.getLinkedBlocks().stream().distinct().count()).split("\\|");
for (String line : parts) {
lorehook.add(Methods.formatText(line));
}
hookmeta.setLore(lorehook);
hook.setItemMeta(hookmeta);
int nu = 0;
while (nu != 27) {
inventory.setItem(nu, Methods.getGlass());
nu++;
}
Map<Integer, Integer[]> layouts = new HashMap<>();
layouts.put(1, new Integer[]{22});
layouts.put(2, new Integer[]{22, 4});
layouts.put(3, new Integer[]{22, 3, 5});
layouts.put(4, new Integer[]{23, 3, 5, 21});
layouts.put(5, new Integer[]{23, 3, 5, 21, 22});
layouts.put(6, new Integer[]{23, 3, 4, 5, 21, 22});
layouts.put(7, new Integer[]{23, 3, 4, 5, 21, 22, 12});
layouts.put(8, new Integer[]{23, 3, 4, 5, 21, 22, 12, 14});
int amount = 1;
boolean canFilter = level.isFilter() || player.hasPermission("EpicHoppers.Filter");
boolean canTeleport = level.isTeleport() || player.hasPermission("EpicHoppers.Teleport");
if (canFilter) amount++;
if (canTeleport) amount++;
List<Module> modules = level.getRegisteredModules().stream().filter(module ->
module.getGUIButton(hopper) != null).collect(Collectors.toList());
amount += modules.size();
Integer[] layout = layouts.get(amount);
for (int ii = 0; ii < amount; ii++) {
int slot = layout[ii];
if (ii == 0) {
inventory.setItem(slot, hook);
} else if (canTeleport) {
inventory.setItem(slot, perl);
canTeleport = false;
} else if (canFilter) {
inventory.setItem(slot, filter);
canFilter = false;
} else {
if (modules.isEmpty()) break;
Module module = modules.get(0);
modules.remove(module);
inventory.setItem(slot, module.getGUIButton(hopper));
}
}
if (plugin.getConfig().getBoolean("Main.Allow hopper Upgrading")) {
ItemStack itemXP = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.XP Icon")), 1);
ItemMeta itemmetaXP = itemXP.getItemMeta();
itemmetaXP.setDisplayName(plugin.getLocale().getMessage("interface.hopper.upgradewithxp"));
ArrayList<String> loreXP = new ArrayList<>();
if (nextLevel != null)
loreXP.add(plugin.getLocale().getMessage("interface.hopper.upgradewithxplore", nextLevel.getCostExperience()));
else
loreXP.add(plugin.getLocale().getMessage("interface.hopper.alreadymaxed"));
itemmetaXP.setLore(loreXP);
itemXP.setItemMeta(itemmetaXP);
ItemStack itemECO = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Economy Icon")), 1);
ItemMeta itemmetaECO = itemECO.getItemMeta();
itemmetaECO.setDisplayName(plugin.getLocale().getMessage("interface.hopper.upgradewitheconomy"));
ArrayList<String> loreECO = new ArrayList<>();
if (nextLevel != null)
loreECO.add(plugin.getLocale().getMessage("interface.hopper.upgradewitheconomylore", Methods.formatEconomy(nextLevel.getCostEconomy())));
else
loreECO.add(plugin.getLocale().getMessage("interface.hopper.alreadymaxed"));
itemmetaECO.setLore(loreECO);
itemECO.setItemMeta(itemmetaECO);
if (plugin.getConfig().getBoolean("Main.Upgrade With XP")
&& player.hasPermission("EpicHoppers.Upgrade.XP")
&& level.getCostExperience() != -1) {
inventory.setItem(11, itemXP);
registerClickable(11, ((player, inventory, cursor, slot, type) -> {
hopper.upgrade(player, CostType.EXPERIENCE);
this.hopper.overview(player);
}));
}
if (plugin.getConfig().getBoolean("Main.Upgrade With Economy")
&& player.hasPermission("EpicHoppers.Upgrade.ECO")
&& level.getCostEconomy() != -1) {
inventory.setItem(15, itemECO);
registerClickable(15, ((player, inventory, cursor, slot, type) -> {
hopper.upgrade(player, CostType.ECONOMY);
this.hopper.overview(player);
}));
}
}
inventory.setItem(13, item);
inventory.setItem(0, Methods.getBackgroundGlass(true));
inventory.setItem(1, Methods.getBackgroundGlass(true));
inventory.setItem(2, Methods.getBackgroundGlass(false));
inventory.setItem(6, Methods.getBackgroundGlass(false));
inventory.setItem(7, Methods.getBackgroundGlass(true));
inventory.setItem(8, Methods.getBackgroundGlass(true));
inventory.setItem(9, Methods.getBackgroundGlass(true));
inventory.setItem(10, Methods.getBackgroundGlass(false));
inventory.setItem(16, Methods.getBackgroundGlass(false));
inventory.setItem(17, Methods.getBackgroundGlass(true));
inventory.setItem(18, Methods.getBackgroundGlass(true));
inventory.setItem(19, Methods.getBackgroundGlass(true));
inventory.setItem(20, Methods.getBackgroundGlass(false));
inventory.setItem(24, Methods.getBackgroundGlass(false));
inventory.setItem(25, Methods.getBackgroundGlass(true));
inventory.setItem(26, Methods.getBackgroundGlass(true));
hopper.setLastPlayer(player.getUniqueId());
}
private void runTask() {
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this::constructGUI, 5L, 5L);
}
@Override
protected void registerClickables() {
registerClickable(3, 23, ((player, inventory, cursor, slot, type) -> {
for (Module module : hopper.getLevel().getRegisteredModules()) {
if (module.getGUIButton(hopper) != null && !module.getGUIButton(hopper).getItemMeta()
.getDisplayName().equalsIgnoreCase(inventory.getItem(slot).getItemMeta().getDisplayName()))
continue;
module.runButtonPress(player, hopper);
}
if (inventory.getItem(slot).getItemMeta()
.getDisplayName().equals(plugin.getLocale().getMessage("interface.hopper.filtertitle"))) {
new GUIFilter(plugin, hopper, player);
} else if (inventory.getItem(slot).getItemMeta()
.getDisplayName().equals(plugin.getLocale().getMessage("interface.hopper.perltitle"))) {
if (type == ClickType.LEFT) {
if (hopper.getLinkedBlocks() != null) {
plugin.getTeleportHandler().tpEntity(player, hopper);
player.closeInventory();
}
} else {
if (hopper.getTeleportTrigger() == TeleportTrigger.DISABLED) {
hopper.setTeleportTrigger(TeleportTrigger.SNEAK);
} else if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) {
hopper.setTeleportTrigger(TeleportTrigger.WALK_ON);
} else if (hopper.getTeleportTrigger() == TeleportTrigger.WALK_ON) {
hopper.setTeleportTrigger(TeleportTrigger.DISABLED);
}
constructGUI();
}
} else if (inventory.getItem(slot).getItemMeta()
.getDisplayName().equals(plugin.getLocale().getMessage("interface.hopper.synchopper"))) {
if (type == ClickType.RIGHT) {
player.sendMessage(plugin.references.getPrefix() + plugin.getLocale().getMessage("event.hopper.desync"));
hopper.clearLinkedBlocks();
} else {
if (hopper.getLastPlayer() != null && !hopper.getLastPlayer().equals(player.getUniqueId())) {
player.sendMessage(plugin.references.getPrefix() + plugin.getLocale().getMessage("event.hopper.syncdidnotplace"));
return;
}
plugin.getPlayerDataManager().getPlayerData(player).setSyncType(SyncType.REGULAR);
hopper.clearLinkedBlocks();
player.sendMessage(plugin.references.getPrefix() + plugin.getLocale().getMessage("event.hopper.syncnext"));
hopper.timeout(player);
}
player.closeInventory();
}
}));
}
@Override
protected void registerOnCloses() {
registerOnClose(((player1, inventory1) -> Bukkit.getScheduler().cancelTask(task)));
}
}

View File

@ -0,0 +1,67 @@
package com.songoda.epicfurnaces.handlers;
import com.songoda.arconix.api.utils.ConfigWrapper;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.utils.Debugger;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
/**
* Created by songoda on 2/25/2017.
*/
public class BlacklistHandler {
private ConfigWrapper blackFile = new ConfigWrapper(EpicFurnacesPlugin.getInstance(), "", "blacklist.yml");
public BlacklistHandler() {
try {
blackFile.createNewFile("Loading language file", "EpicFurnaces blacklist file");
loadBlacklistFile();
} catch (Exception e) {
Debugger.runReport(e);
}
}
public boolean isBlacklisted(Player player) {
boolean blacklisted = false;
try {
List<String> list = blackFile.getConfig().getStringList("settings.blacklist");
String cWorld = player.getWorld().getName();
for (String world : list) {
if (cWorld.equalsIgnoreCase(world)) {
blacklisted = true;
}
}
} catch (Exception e) {
Debugger.runReport(e);
}
return blacklisted;
}
private void loadBlacklistFile() {
try {
List<String> list = new ArrayList<>();
list.add("world2");
list.add("world3");
list.add("world4");
list.add("world5");
blackFile.getConfig().addDefault("settings.blacklist", list);
blackFile.getConfig().options().copyDefaults(true);
blackFile.saveConfig();
} catch (Exception e) {
Debugger.runReport(e);
}
}
public void reload() {
try {
blackFile.createNewFile("Loading blacklist file", "EpicFurnaces blacklist file");
loadBlacklistFile();
} catch (Exception e) {
Debugger.runReport(e);
}
}
}

View File

@ -0,0 +1,166 @@
package com.songoda.ultimatekits.hologram;
import com.songoda.ultimatekits.UltimateKits;
import com.songoda.ultimatekits.kit.Kit;
import com.songoda.ultimatekits.kit.KitBlockData;
import com.songoda.ultimatekits.kit.KitType;
import com.songoda.ultimatekits.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public abstract class Hologram {
protected final UltimateKits instance;
Hologram(UltimateKits instance) {
this.instance = instance;
}
public void loadHolograms() {
Collection<KitBlockData> kitBlocks = instance.getKitManager().getKitLocations().values();
if (kitBlocks.size() == 0) return;
for (KitBlockData data : kitBlocks) {
if (data.getWorld() == null) continue;
add(data);
}
}
public void unloadHolograms() {
Collection<KitBlockData> kitBlocks = instance.getKitManager().getKitLocations().values();
if (kitBlocks.size() == 0) return;
for (KitBlockData data : kitBlocks) {
if (data.getWorld() == null) continue;
remove(data);
}
}
public void add(KitBlockData data) {
format(data, Action.ADD);
}
public void remove(KitBlockData data) {
format(data, Action.REMOVE);
}
public void remove(Kit kit) {
for (KitBlockData data : instance.getKitManager().getKitLocations().values()) {
if (data.getKit() != kit) continue;
remove(data);
}
}
public void update(KitBlockData data) {
format(data, Action.UPDATE);
}
public void update(Kit kit) {
for (KitBlockData data : instance.getKitManager().getKitLocations().values()) {
if (data.getKit() != kit) continue;
update(data);
}
}
private void format(KitBlockData data, Action action) {
if (data == null) return;
KitType kitType = data.getType();
ArrayList<String> lines = new ArrayList<>();
List<String> order = instance.getConfig().getStringList("Main.Hologram Layout");
Kit kit = data.getKit();
for (String o : order) {
switch (o.toUpperCase()) {
case "{TITLE}":
String title = kit.getTitle();
if (title == null) {
lines.add(Methods.formatText("&5" + Methods.formatText(kit.getName(), true)));
} else {
lines.add(Methods.formatText("&5" + Methods.formatText(title)));
}
break;
case "{RIGHT-CLICK}":
if (kitType == KitType.CRATE) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.crate")));
break;
}
if (kit.getLink() != null) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.buylink")));
break;
}
if (kit.getPrice() != 0) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.buyeco", kit.getPrice() != 0 ? Methods.formatEconomy(kit.getPrice()) : instance.getLocale().getMessage("general.type.free"))));
}
break;
case "{LEFT-CLICK}":
if (kitType == KitType.CLAIM) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.daily")));
break;
}
if (kit.getLink() == null && kit.getPrice() == 0) {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.previewonly")));
} else {
lines.add(Methods.formatText(instance.getLocale().getMessage("interface.hologram.preview")));
}
break;
default:
lines.add(Methods.formatText(o));
break;
}
}
double multi = .25 * lines.size();
Location location = data.getLocation();
Block b = location.getBlock();
if (data.isDisplayingItems()) multi += .40;
if (b.getType() == Material.TRAPPED_CHEST
|| b.getType() == Material.CHEST
|| b.getType().name().contains("SIGN")
|| b.getType() == Material.ENDER_CHEST) multi -= .15;
location.add(0, multi, 0);
if (!data.showHologram()) {
remove(location);
return;
}
switch (action) {
case UPDATE:
update(location, lines);
break;
case ADD:
add(location, lines);
break;
case REMOVE:
remove(location);
break;
}
}
protected abstract void add(Location location, ArrayList<String> lines);
protected abstract void remove(Location location);
protected abstract void update(Location location, ArrayList<String> lines);
public enum Action {
UPDATE, ADD, REMOVE
}
}

View File

@ -0,0 +1,56 @@
package com.songoda.ultimatekits.hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import com.songoda.ultimatekits.UltimateKits;
import org.bukkit.Location;
import java.util.ArrayList;
public class HologramHolographicDisplays extends Hologram {
public HologramHolographicDisplays(UltimateKits instance) {
super(instance);
}
@Override
public void add(Location location, ArrayList<String> lines) {
fixLocation(location);
com.gmail.filoghost.holographicdisplays.api.Hologram hologram = HologramsAPI.createHologram(instance, location);
for (String line : lines) {
hologram.appendTextLine(line);
}
}
@Override
public void remove(Location location) {
fixLocation(location);
for (com.gmail.filoghost.holographicdisplays.api.Hologram hologram : HologramsAPI.getHolograms(instance)) {
if (hologram.getX() != location.getX()
|| hologram.getY() != location.getY()
|| hologram.getZ() != location.getZ()) continue;
hologram.delete();
}
}
@Override
public void update(Location location, ArrayList<String> lines) {
for (com.gmail.filoghost.holographicdisplays.api.Hologram hologram : HologramsAPI.getHolograms(instance)) {
if (hologram.getX() != location.getX()
|| hologram.getY() != location.getY()
|| hologram.getZ() != location.getZ()) continue;
fixLocation(location);
hologram.clearLines();
for (String line : lines) {
hologram.appendTextLine(line);
}
return;
}
add(location, lines);
}
private void fixLocation(Location location) {
location.add(.5, 1.3, .5);
}
}

View File

@ -0,0 +1,108 @@
package com.songoda.epicfurnaces.listeners;
import com.mysql.jdbc.Buffer;
import com.songoda.arconix.api.methods.formatting.TextComponent;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.api.furnace.Furnace;
import com.songoda.epicfurnaces.furnace.EFurnace;
import com.songoda.epicfurnaces.utils.Debugger;
import com.songoda.epicfurnaces.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
/**
* Created by songoda on 2/26/2017.
*/
public class BlockListeners implements Listener {
private final EpicFurnacesPlugin instance;
public BlockListeners(EpicFurnacesPlugin instance) {
this.instance = instance;
}
@EventHandler
public void onSnowLand(BlockFormEvent event) {
Material material = event.getNewState().getType();
if (material != Material.SNOW && material != Material.ICE) return;
for (Furnace furnace : instance.getFurnaceManager().getFurnaces().values()) {
if (furnace.getRadius(false) == null || ((org.bukkit.block.Furnace)furnace.getLocation().getBlock().getState()).getBurnTime() == 0) continue;
for (Location location : furnace.getRadius(false)) {
if (location.getX() != event.getNewState().getX() || location.getY() != event.getNewState().getY() || location.getZ() != event.getNewState().getZ()) continue;
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
try {
if (event.getBlock().getType() != Material.FURNACE || !event.getItemInHand().getItemMeta().hasDisplayName()) return;
ItemStack item = event.getItemInHand();
Location location = event.getBlock().getLocation();
if (instance.getFurnceLevel(item) != 1) {
if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) {
event.setCancelled(true);
return;
}
instance.getFurnaceManager().addFurnace(location, new EFurnace(location, instance.getLevelManager().getLevel(instance.getFurnceLevel(item)), null, instance.getFurnaceUses(item), 0, new ArrayList<>(), event.getPlayer().getUniqueId()));
}
} catch (Exception ee) {
Debugger.runReport(ee);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
try {
if (!event.getPlayer().hasPermission("EpicFurnaces.overview") && !event.getPlayer().hasPermission("epicfurnaces.*")) {
return;
}
Block block = event.getBlock();
if (block.getType() != Material.FURNACE) {
return;
}
instance.getHologramTask().despawn(block);
if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) {
return;
}
Furnace furnace = instance.getFurnaceManager().getFurnace(block);
int level = instance.getFurnaceManager().getFurnace(block).getLevel().getLevel();
if (level != 0) {
event.setCancelled(true);
ItemStack item = instance.createLeveledFurnace(level, furnace.getUses());
event.getBlock().setType(Material.AIR);
event.getBlock().getLocation().getWorld().dropItemNaturally(event.getBlock().getLocation(), item);
}
instance.getFurnaceManager().removeFurnace(block.getLocation());
} catch (Exception ee) {
Debugger.runReport(ee);
}
}
}

View File

@ -0,0 +1,60 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.api.furnace.Furnace;
import com.songoda.epicfurnaces.api.furnace.Level;
import com.songoda.epicfurnaces.furnace.EFurnace;
import com.songoda.epicfurnaces.utils.Debugger;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class FurnaceListeners implements Listener {
private final EpicFurnacesPlugin instance;
public FurnaceListeners(EpicFurnacesPlugin instance) {
this.instance = instance;
}
@EventHandler
public void onCook(FurnaceSmeltEvent e) {
try {
Block b = e.getBlock();
if ((e.getBlock().isBlockPowered() && instance.getConfig().getBoolean("Main.Redstone Deactivates Furnaces")) || e.getResult() == null) {
e.setCancelled(true);
return;
}
Furnace furnace = instance.getFurnaceManager().getFurnace(b.getLocation());
if (furnace != null && e.getSource().getType() != Material.WET_SPONGE)
((EFurnace) furnace).plus(e);
} catch (Exception ee) {
Debugger.runReport(ee);
}
}
@EventHandler
public void onFuel(FurnaceBurnEvent e) {
try {
if (e.getFuel() == null) return;
Furnace furnace = instance.getFurnaceManager().getFurnace(e.getBlock().getLocation());
Level level = furnace != null ? furnace.getLevel() : instance.getLevelManager().getLowestLevel();
if (level.getFuelDuration() != 0) return;
int num = level.getFuelDuration();
int per = (e.getBurnTime() / 100) * num;
e.setBurnTime(e.getBurnTime() + per);
} catch (Exception ee) {
Debugger.runReport(ee);
}
}
}

View File

@ -0,0 +1,53 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.furnace.EFurnace;
import com.songoda.epicfurnaces.utils.Debugger;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class InteractListeners implements Listener {
private final EpicFurnacesPlugin instance;
public InteractListeners(EpicFurnacesPlugin instance) {
this.instance = instance;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onClick(PlayerInteractEvent event) {
try {
if (event.getClickedBlock() == null) return;
if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) {
return;
}
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (!player.hasPermission("EpicFurnaces.overview")
|| !instance.canBuild(player, event.getClickedBlock().getLocation())
|| event.getAction() != Action.LEFT_CLICK_BLOCK
|| player.isSneaking()
|| (block.getType() != Material.FURNACE)
|| player.getInventory().getItemInMainHand().getType().name().contains("PICKAXE")) {
return;
}
event.setCancelled(true);
((EFurnace) instance.getFurnaceManager().getFurnace(block.getLocation())).openOverview(player);
} catch (Exception ee) {
Debugger.runReport(ee);
}
}
}

View File

@ -0,0 +1,119 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.arconix.plugin.Arconix;
import com.songoda.epicfurnaces.EpicFurnacesPlugin;
import com.songoda.epicfurnaces.furnace.EFurnace;
import com.songoda.epicfurnaces.player.PlayerData;
import com.songoda.epicfurnaces.utils.Debugger;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
/**
* Created by songoda on 2/26/2017.
*/
public class InventoryListeners implements Listener {
private final EpicFurnacesPlugin instance;
public InventoryListeners(EpicFurnacesPlugin instance) {
this.instance = instance;
}
@EventHandler
public void onInventoryMove(InventoryMoveItemEvent e) {
if (!e.getDestination().getType().equals(InventoryType.FURNACE)
|| e.getDestination().getItem(0) == null
|| e.getDestination().getItem(0).getType() != e.getItem().getType()
|| e.getDestination().getItem(0).getAmount() != 1) {
return;
}
((EFurnace) instance.getFurnaceManager().getFurnace(e.getDestination().getLocation())).updateCook();
}
@SuppressWarnings("unchecked")
@EventHandler
public void onInventoryClick(InventoryClickEvent e) {
try {
Player p = (Player) e.getWhoClicked();
PlayerData playerData = instance.getPlayerDataManager().getPlayerData(p);
if (e.getInventory().getType().equals(InventoryType.FURNACE)
&& e.getInventory().getHolder() != null
&& e.getSlotType() == InventoryType.SlotType.CRAFTING) {
Block block;
block = e.getInventory().getLocation().getBlock();
((EFurnace) instance.getFurnaceManager().getFurnace(block)).updateCook();
} else if (playerData.isInOverview()) {
e.setCancelled(true);
EFurnace furnace = playerData.getLastFurace();
if (e.getSlot() == 11) {
if (!e.getCurrentItem().getItemMeta().getDisplayName().equals("§l")) {
furnace.upgrade("XP", p);
p.closeInventory();
}
} else if (e.getSlot() == 15) {
if (!e.getCurrentItem().getItemMeta().getDisplayName().equals("§l")) {
furnace.upgrade("ECO", p);
p.closeInventory();
}
} else if (e.getSlot() == 4) {
if (!e.getCurrentItem().getItemMeta().getDisplayName().equals("§l")) {
if (e.getClick().isLeftClick()) {
p.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.remote.enter"));
playerData.setSettingNickname(true);
p.closeInventory();
} else if (e.getClick().isRightClick()) {
List<String> list = new ArrayList<>();
String key = Arconix.pl().getApi().serialize().serializeLocation(furnace.getLocation());
String id = p.getUniqueId().toString() + ":" + p.getName();
if (instance.getDataFile().getConfig().contains("data.charged." + key + ".remoteAccessList")) {
list = (List<String>) instance.getDataFile().getConfig().getList("data.charged." + key + ".remoteAccessList");
for (String line : (List<String>) instance.getDataFile().getConfig().getList("data.charged." + key + ".remoteAccessList")) {
if (id.equals(line)) {
e.setCancelled(true);
return;
}
}
}
list.add(id);
instance.getDataFile().getConfig().set("data.charged." + key + ".remoteAccessList", list);
furnace.openOverview(p);
}
}
}
if (e.getSlot() != 64537) {
if (e.getInventory().getType() == InventoryType.ANVIL) {
if (e.getAction() != InventoryAction.NOTHING) {
if (e.getCurrentItem().getType() != Material.AIR) {
ItemStack item = e.getCurrentItem();
if (item.getType() == Material.FURNACE) {
e.setCancelled(true);
}
}
}
}
}
}
} catch (Exception ee) {
Debugger.runReport(ee);
}
}
@EventHandler
public void onClose(InventoryCloseEvent event) {
try {
instance.getPlayerDataManager().getPlayerData((Player) event.getPlayer()).setInOverview(false);
} catch (Exception e) {
Debugger.runReport(e);
}
}
}

View File

@ -1,8 +1,8 @@
package com.songoda.epicfurnaces.storage;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.objects.BoostData;
import com.songoda.epicfurnaces.objects.FurnaceObject;
import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.furnace.Furnace;
import com.songoda.epicfurnaces.utils.ConfigWrapper;
import com.songoda.epicfurnaces.utils.Methods;
@ -10,12 +10,12 @@ import java.util.List;
public abstract class Storage {
protected final EpicFurnaces instance;
protected final EpicFurnaces plugin;
protected final ConfigWrapper dataFile;
public Storage(EpicFurnaces instance) {
this.instance = instance;
this.dataFile = new ConfigWrapper(instance, "", "data.yml");
public Storage(EpicFurnaces plugin) {
this.plugin = plugin;
this.dataFile = new ConfigWrapper(plugin, "", "data.yml");
this.dataFile.createNewFile(null, "EpicFurnaces Data File");
this.dataFile.getConfig().options().copyDefaults(true);
this.dataFile.saveConfig();
@ -27,26 +27,28 @@ public abstract class Storage {
public abstract void prepareSaveItem(String group, StorageItem... items);
public void updateData(EpicFurnaces instance) {
// Save game data
for (FurnaceObject furnace : instance.getFurnaceManager().getAllFurnaces().values()) {
if (furnace == null || furnace.getLocation() == null || furnace.getLocation().getWorld() == null) {
continue;
}
public void updateData(EpicFurnaces plugin) {
/*
* Dump FurnaceManager to file.
*/
for (Furnace furnace : plugin.getFurnaceManager().getFurnaces().values()) {
if (furnace == null || furnace.getLocation() == null || furnace.getLocation().getWorld() == null) continue;
String locationStr = Methods.serializeLocation(furnace.getLocation());
instance.getStorage().prepareSaveItem("charged",
new StorageItem("location", locationStr),
prepareSaveItem("charged", new StorageItem("location", locationStr),
new StorageItem("level", furnace.getLevel().getLevel()),
new StorageItem("uses", furnace.getUses()),
new StorageItem("tolevel", furnace.getToLevel()),
new StorageItem("tolevel", furnace.getTolevel()),
new StorageItem("nickname", furnace.getNickname()),
new StorageItem("accesslist", furnace.getOriginalAccessList()),
new StorageItem("placedby", furnace.getPlacedBy() == null ? null : furnace.getPlacedBy().toString()));
}
for (BoostData boostData : instance.getBoostManager().getBoosts()) {
instance.getStorage().prepareSaveItem("boosts", new StorageItem("endtime", String.valueOf(boostData.getEndTime())),
/*
* Dump BoostManager to file.
*/
for (BoostData boostData : plugin.getBoostManager().getBoosts()) {
prepareSaveItem("boosts", new StorageItem("endtime", String.valueOf(boostData.getEndTime())),
new StorageItem("amount", boostData.getMultiplier()),
new StorageItem("uuid", boostData.getPlayer().toString()));
}

View File

@ -1,13 +1,18 @@
package com.songoda.epicfurnaces.storage;
import com.songoda.epicfurnaces.utils.Methods;
import com.songoda.epicfurnaces.utils.Serializers;
import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StorageItem {
private String key = null;
private final Object object;
private String key = null;
public StorageItem(Object object) {
this.object = object;
@ -27,6 +32,16 @@ public class StorageItem {
this.object = object.toString();
}
public StorageItem(String key, boolean type, List<Location> blocks) {
StringBuilder object = new StringBuilder();
for (Location location : blocks) {
object.append(Methods.serializeLocation(location));
object.append(";;");
}
this.key = key;
this.object = object.toString();
}
public String getKey() {
return key;
}
@ -38,6 +53,7 @@ public class StorageItem {
public boolean asBoolean() {
if (object == null) return false;
if (object instanceof Integer) return (Integer) object == 1;
return (boolean) object;
}
@ -47,9 +63,22 @@ public class StorageItem {
}
public Object asObject() {
if (object == null) return null;
if (object instanceof Boolean) return (Boolean) object ? 1 : 0;
return object;
}
public List<ItemStack> asItemStackList() {
List<ItemStack> list = new ArrayList<>();
if (object == null) return list;
String obj = (String) object;
if (obj.equals("[]")) return list;
List<String> sers = new ArrayList<>(Arrays.asList(obj.split(";;")));
for (String ser : sers) {
list.add(Serializers.deserialize(ser));
}
return list;
}
public List<String> asStringList() {
if (object instanceof ArrayList) return new ArrayList<>();
List<String> list = new ArrayList<>();
@ -61,4 +90,5 @@ public class StorageItem {
}
return list;
}
}

View File

@ -18,19 +18,19 @@ import java.util.Map;
public class StorageMysql extends Storage {
private static Map<String, StorageItem[]> toSave = new HashMap<>();
private static Map<String, StorageItem[]> lastSave = new HashMap<>();
private static Map<String, StorageItem[]> lastSave = null;
private MySQLDatabase database;
public StorageMysql(EpicFurnaces instance) {
super(instance);
this.database = new MySQLDatabase(instance);
public StorageMysql(EpicFurnaces plugin) {
super(plugin);
this.database = new MySQLDatabase(plugin);
}
@Override
public boolean containsGroup(String group) {
try {
DatabaseMetaData dbm = database.getConnection().getMetaData();
ResultSet rs = dbm.getTables(null, null, instance.getConfig().getString("Database.Prefix") + group, null);
ResultSet rs = dbm.getTables(null, null, plugin.getConfig().getString("Database.Prefix") + group, null);
if (rs.next()) {
return true;
}
@ -45,7 +45,7 @@ public class StorageMysql extends Storage {
public List<StorageRow> getRowsByGroup(String group) {
List<StorageRow> rows = new ArrayList<>();
try {
ResultSet set = database.getConnection().createStatement().executeQuery(String.format("SELECT * FROM `" + instance.getConfig().getString("Database.Prefix") + "%s`", group));
ResultSet set = database.getConnection().createStatement().executeQuery(String.format("SELECT * FROM `" + plugin.getConfig().getString("Database.Prefix") + "%s`", group));
while (set.next()) {
Map<String, StorageItem> items = new HashMap<>();
@ -71,13 +71,14 @@ public class StorageMysql extends Storage {
@Override
public void doSave() {
this.updateData(instance);
this.updateData(plugin);
if (lastSave == null)
lastSave = new HashMap<>(toSave);
if (toSave.isEmpty()) return;
Map<String, StorageItem[]> nextSave = new HashMap<>(toSave);
if (lastSave.isEmpty())
lastSave.putAll(toSave);
this.makeBackup();
this.save();
@ -102,14 +103,15 @@ public class StorageMysql extends Storage {
|| !to.getValue()[0].asObject().equals(lastValue)
|| to.getValue().length != last.getValue().length)
continue;
toSave.remove(toKey);
for (int i = 0; i < to.getValue().length - 1; i ++) {
if (to.getValue()[i].asObject() != null
&& !to.getValue()[i].asObject().toString()
.equals(last.getValue()[i].asObject().toString())) {
toSave.remove(to.getKey());
for (int i = 0; i < to.getValue().length; i ++) {
if ((to.getValue()[i].asObject() != null && last.getValue()[i].asObject() == null)
|| (last.getValue()[i].asObject() == null && to.getValue()[i].asObject() != null)
|| (last.getValue()[i].asObject() != null && to.getValue()[i].asObject() != null
&& !to.getValue()[i].asObject().toString().equals(last.getValue()[i].asObject().toString()))) {
//Update
StorageItem[] items = to.getValue();
StringBuilder sql = new StringBuilder(String.format("UPDATE `" + instance.getConfig().getString("Database.Prefix") + "%s`", toKey));
StringBuilder sql = new StringBuilder(String.format("UPDATE `" + plugin.getConfig().getString("Database.Prefix") + "%s`", toKey));
sql.append(" SET");
@ -133,7 +135,7 @@ public class StorageMysql extends Storage {
continue last;
}
//Was not found delete.
StringBuilder sql = new StringBuilder(String.format("DELETE FROM `" + instance.getConfig().getString("Database.Prefix") + "%s`", lastKey));
StringBuilder sql = new StringBuilder(String.format("DELETE FROM `" + plugin.getConfig().getString("Database.Prefix") + "%s`", lastKey));
sql.append(String.format(" WHERE `%s`='%s'", last.getValue()[0].getKey(), last.getValue()[0].asObject().toString()));
stmt.addBatch(sql.toString());
@ -143,7 +145,7 @@ public class StorageMysql extends Storage {
String toKey = to.getKey().split("]")[0];
//Add
StorageItem[] items = to.getValue();
StringBuilder sql = new StringBuilder(String.format("INSERT INTO `" + instance.getConfig().getString("Database.Prefix") + "%s`", toKey));
StringBuilder sql = new StringBuilder(String.format("INSERT INTO `" + plugin.getConfig().getString("Database.Prefix") + "%s`", toKey));
sql.append(" (");

View File

@ -13,10 +13,10 @@ import java.util.*;
public class StorageYaml extends Storage {
private static final Map<String, Object> toSave = new HashMap<>();
private static final Map<String, Object> lastSave = new HashMap<>();
private static Map<String, Object> lastSave = null;
public StorageYaml(EpicFurnaces instance) {
super(instance);
public StorageYaml(EpicFurnaces plugin) {
super(plugin);
}
@Override
@ -56,19 +56,20 @@ public class StorageYaml extends Storage {
public void prepareSaveItem(String group, StorageItem... items) {
for (StorageItem item : items) {
if (item == null || item.asObject() == null) continue;
toSave.put("data." + group + "." + items[0].asObject()+ "." + item.getKey(), item.asObject());
toSave.put("data." + group + "." + items[0].asString() + "." + item.getKey(), item.asObject());
}
}
@Override
public void doSave() {
this.updateData(instance);
this.updateData(plugin);
if (lastSave == null)
lastSave = new HashMap<>(toSave);
if (toSave.isEmpty()) return;
Map<String, Object> nextSave = new HashMap<>(toSave);
if (lastSave.isEmpty())
lastSave.putAll(toSave);
this.makeBackup();
this.save();
@ -84,9 +85,9 @@ public class StorageYaml extends Storage {
if (toSave.containsKey(entry.getKey())) {
Object newValue = toSave.get(entry.getKey());
if (!entry.getValue().equals(newValue)) {
dataFile.getConfig().set(entry.getKey(), entry.getValue());
dataFile.getConfig().set(entry.getKey(), newValue);
}
toSave.remove(newValue);
toSave.remove(entry.getKey());
} else {
dataFile.getConfig().set(entry.getKey(), null);
}
@ -104,15 +105,15 @@ public class StorageYaml extends Storage {
@Override
public void makeBackup() {
File data = new File(instance.getDataFolder(), "data.yml");
File dataClone = new File(instance.getDataFolder(), "data-backup-" + System.currentTimeMillis() + ".yml");
File data = new File(plugin.getDataFolder(), "data.yml");
File dataClone = new File(plugin.getDataFolder(), "data-backup-" + System.currentTimeMillis() + ".yml");
try {
copyFile(data, dataClone);
} catch (IOException e) {
e.printStackTrace();
}
Deque<File> backups = new ArrayDeque<>();
for (File file : Objects.requireNonNull(instance.getDataFolder().listFiles())) {
for (File file : Objects.requireNonNull(plugin.getDataFolder().listFiles())) {
if (file.getName().toLowerCase().contains("data-backup")) {
backups.add(file);
}
@ -127,7 +128,6 @@ public class StorageYaml extends Storage {
dataFile.saveConfig();
}
private static void copyFile(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;

View File

@ -0,0 +1,156 @@
package com.songoda.epicfurnaces.tasks;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.furnace.Furnace;
import com.songoda.epicfurnaces.utils.ServerVersion;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.concurrent.ThreadLocalRandom;
public class FurnaceTask extends BukkitRunnable {
private static FurnaceTask instance;
private final EpicFurnaces plugin;
private FurnaceTask(EpicFurnaces plugin) {
this.plugin = plugin;
}
public static FurnaceTask startTask(EpicFurnaces plugin) {
if (instance == null) {
instance = new FurnaceTask(plugin);
instance.runTaskTimer(plugin, 0, plugin.getConfig().getInt("Main.Furnace Tick Speed"));
}
return instance;
}
@Override
public void run() {
for (Furnace furnace : plugin.getFurnaceManager().getFurnaces().values()) {
Location furnaceLocation = furnace.getLocation();
if (furnaceLocation == null) continue;
if (furnaceLocation.getWorld() == null) {
plugin.getFurnaceManager().removeFurnace(furnaceLocation);
continue;
}
int x = furnaceLocation.getBlockX() >> 4;
int z = furnaceLocation.getBlockZ() >> 4;
if (!furnaceLocation.getWorld().isChunkLoaded(x, z)) {
continue;
}
if (furnace.getLocation().getBlock().getType() != Material.FURNACE)
continue;
if (((org.bukkit.block.Furnace) furnaceLocation.getBlock().getState()).getBurnTime() == 0) continue;
if (furnace.getLevel().getOverheat() != 0) {
overheat(furnace);
}
if (furnace.getLevel().getFuelShare() != 0) {
fuelshare(furnace);
}
}
}
private void overheat(Furnace furnace) {
if (furnace.getRadius(true) == null || furnace.getRadiusLast(true) != furnace.getLevel().getOverheat()) {
furnace.setRadiusLast(furnace.getLevel().getOverheat(), true);
cache(furnace, true);
}
for (Location location : furnace.getRadius(true)) {
int random = ThreadLocalRandom.current().nextInt(0, 10);
if (random != 1) continue;
Block block = location.getBlock();
if (block.getType() == Material.AIR || block.getRelative(BlockFace.UP).getType() != Material.AIR) continue;
if (plugin.getConfig().getBoolean("Main.Overheat Particles")) {
float xx = (float) (0 + (Math.random() * .75));
float yy = (float) (0 + (Math.random() * 1));
float zz = (float) (0 + (Math.random() * .75));
if (EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_9))
location.getWorld().spawnParticle(Particle.SMOKE_NORMAL, location, 25, xx, yy, zz, 1);
}
if (block.getType() == Material.SNOW) {
block.setType(Material.AIR);
} else if (block.getType() == Material.ICE || block.getType() == Material.PACKED_ICE) {
block.setType(Material.WATER);
}
}
}
private void fuelshare(Furnace furnace) {
if (furnace.getRadius(false) == null || furnace.getRadiusLast(false) != furnace.getLevel().getOverheat()) {
furnace.setRadiusLast(furnace.getLevel().getOverheat(), false);
cache(furnace, false);
}
for (Location location : furnace.getRadius(false)) {
int random = ThreadLocalRandom.current().nextInt(0, 10);
if (random != 1) continue;
Block block = location.getBlock();
if (block.getType() != Material.FURNACE) continue;
Furnace furnace1 = plugin.getFurnaceManager().getFurnace(block);
if (furnace == furnace1) continue;
org.bukkit.block.Furnace furnaceBlock = ((org.bukkit.block.Furnace) block.getState());
if (furnaceBlock.getBurnTime() == 0) {
furnaceBlock.setBurnTime((short) 100);
furnaceBlock.update();
if (plugin.getConfig().getBoolean("Main.Overheat Particles")) {
float xx = (float) (0 + (Math.random() * .75));
float yy = (float) (0 + (Math.random() * 1));
float zz = (float) (0 + (Math.random() * .75));
if (EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_9))
location.getWorld().spawnParticle(Particle.SMOKE_NORMAL, location, 25, xx, yy, zz, 1);
}
}
}
}
private void cache(Furnace furnace, boolean overheat) {
Block block = furnace.getLocation().getBlock();
int radius = 3 * (overheat ? furnace.getLevel().getOverheat() : furnace.getLevel().getFuelShare());
int rSquared = radius * radius;
int bx = block.getX();
int by = block.getY();
int bz = block.getZ();
for (int fx = -radius; fx <= radius; fx++) {
for (int fy = -2; fy <= 1; fy++) {
for (int fz = -radius; fz <= radius; fz++) {
if ((fx * fx) + (fz * fz) <= rSquared) {
Location location = new Location(block.getWorld(), bx + fx, by + fy, bz + fz);
furnace.addToRadius(location, overheat);
}
}
}
}
}
}

View File

@ -18,8 +18,8 @@ public class ConfigWrapper {
private FileConfiguration config;
private File configFile;
public ConfigWrapper(final JavaPlugin instance, final String folderName, final String fileName) {
this.plugin = instance;
public ConfigWrapper(final JavaPlugin plugin, final String folderName, final String fileName) {
this.plugin = plugin;
this.folderName = folderName;
this.fileName = fileName;
}

View File

@ -0,0 +1,18 @@
package com.songoda.epicfurnaces.utils;
/**
* Represents a cost type when making a purchase from EpicFurnaces
*/
public enum CostType {
/**
* A purchase made with an economy balance (generally an implementation of Vault)
*/
ECONOMY,
/**
* A purchase made with a player's experience levels
*/
EXPERIENCE
}

View File

@ -0,0 +1,225 @@
package com.songoda.epicfurnaces.utils;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Created by songoda on 2/25/2017.
*/
public class Methods {
public static ItemStack getGlass() {
EpicFurnaces plugin = EpicFurnaces.getInstance();
return Methods.getGlass(plugin.getConfig().getBoolean("Interfaces.Replace Glass Type 1 With Rainbow Glass"), plugin.getConfig().getInt("Interfaces.Glass Type 1"));
}
public static ItemStack getBackgroundGlass(boolean type) {
EpicFurnaces plugin = EpicFurnaces.getInstance();
if (type)
return getGlass(false, plugin.getConfig().getInt("Interfaces.Glass Type 2"));
else
return getGlass(false, plugin.getConfig().getInt("Interfaces.Glass Type 3"));
}
private static ItemStack getGlass(Boolean rainbow, int type) {
int randomNum = 1 + (int) (Math.random() * 6);
ItemStack glass;
if (rainbow) {
glass = new ItemStack(EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ?
Material.LEGACY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1, (short) randomNum);
} else {
glass = new ItemStack(EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ?
Material.LEGACY_STAINED_GLASS_PANE : Material.valueOf("STAINED_GLASS_PANE"), 1, (short) type);
}
ItemMeta glassmeta = glass.getItemMeta();
glassmeta.setDisplayName("§l");
glass.setItemMeta(glassmeta);
return glass;
}
public static String cleanString(String typ) {
String type = typ.replaceAll("_", " ");
type = ChatColor.stripColor(type.substring(0, 1).toUpperCase() + type.toLowerCase().substring(1));
return type;
}
public static String formatName(int level, int uses, boolean full) {
String name = EpicFurnaces.getInstance().getLocale().getMessage("general.nametag.nameformat", level);
String info = "";
if (full) {
info += convertToInvisibleString(level + ":" + uses + ":");
}
return info + formatText(name);
}
/**
* Serializes the location of the block specified.
*
* @param b The block whose location is to be saved.
* @return The serialized data.
*/
public static String serializeLocation(Block b) {
if (b == null)
return "";
return serializeLocation(b.getLocation());
}
/**
* Serializes the location specified.
*
* @param location The location that is to be saved.
* @return The serialized data.
*/
public static String serializeLocation(Location location) {
if (location == null)
return "";
String w = location.getWorld().getName();
double x = location.getX();
double y = location.getY();
double z = location.getZ();
String str = w + ":" + x + ":" + y + ":" + z;
str = str.replace(".0", "").replace(".", "/");
return str;
}
private static Map<String, Location> serializeCache = new HashMap<>();
/**
* Deserializes a location from the string.
*
* @param str The string to parse.
* @return The location that was serialized in the string.
*/
public static Location unserializeLocation(String str) {
if (str == null || str.equals(""))
return null;
if (serializeCache.containsKey(str)) {
return serializeCache.get(str).clone();
}
String cacheKey = str;
str = str.replace("y:", ":").replace("z:", ":").replace("w:", "").replace("x:", ":").replace("/", ".");
List<String> args = Arrays.asList(str.split("\\s*:\\s*"));
World world = Bukkit.getWorld(args.get(0));
double x = Double.parseDouble(args.get(1)), y = Double.parseDouble(args.get(2)), z = Double.parseDouble(args.get(3));
Location location = new Location(world, x, y, z, 0, 0);
serializeCache.put(cacheKey, location.clone());
return location;
}
public static String convertToInvisibleString(String s) {
if (s == null || s.equals(""))
return "";
StringBuilder hidden = new StringBuilder();
for (char c : s.toCharArray()) hidden.append(ChatColor.COLOR_CHAR + "").append(c);
return hidden.toString();
}
public static String formatText(String text) {
if (text == null || text.equals(""))
return "";
return formatText(text, false);
}
public static String formatText(String text, boolean cap) {
if (text == null || text.equals(""))
return "";
if (cap)
text = text.substring(0, 1).toUpperCase() + text.substring(1);
return ChatColor.translateAlternateColorCodes('&', text);
}
public static boolean isInt(String number) {
if (number == null || number.equals(""))
return false;
try {
Integer.parseInt(number);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public static String makeReadable(Long time) {
if (time == null)
return "";
StringBuilder sb = new StringBuilder();
long days = TimeUnit.MILLISECONDS.toDays(time);
long hours = TimeUnit.MILLISECONDS.toHours(time) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(time));
long minutes = TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time));
long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time));
if (days != 0L)
sb.append(" ").append(days).append("d");
if (hours != 0L)
sb.append(" ").append(hours).append("h");
if (minutes != 0L)
sb.append(" ").append(minutes).append("m");
if (seconds != 0L)
sb.append(" ").append(seconds).append("s");
return sb.toString().trim();
}
public static long parseTime(String input) {
long result = 0;
StringBuilder number = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
number.append(c);
} else if (Character.isLetter(c) && (number.length() > 0)) {
result += convert(Integer.parseInt(number.toString()), c);
number = new StringBuilder();
}
}
return result;
}
private static long convert(long value, char unit) {
switch (unit) {
case 'd':
return value * 1000 * 60 * 60 * 24;
case 'h':
return value * 1000 * 60 * 60;
case 'm':
return value * 1000 * 60;
case 's':
return value * 1000;
}
return 0;
}
public static String formatEconomy(double amt) {
DecimalFormat formatter = new DecimalFormat("#,###.00");
return formatter.format(amt);
}
public static String formatTitle(String text) {
if (text == null || text.equals(""))
return "";
if (!EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_9)) {
if (text.length() > 31)
text = text.substring(0, 29) + "...";
}
text = formatText(text);
return text;
}
}

View File

@ -0,0 +1,695 @@
package com.songoda.epicfurnaces.utils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly blacklist effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has blacklist effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger plugin.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JSONObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JSONObject value = new JSONObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.put(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.put(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
}

View File

@ -0,0 +1,49 @@
package com.songoda.epicfurnaces.utils;
import com.songoda.epicfurnaces.EpicFurnaces;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLDatabase {
private final EpicFurnaces plugin;
private Connection connection;
public MySQLDatabase(EpicFurnaces plugin) {
this.plugin = plugin;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" + plugin.getConfig().getString("Database.IP") + ":" + plugin.getConfig().getString("Database.Port") + "/" + plugin.getConfig().getString("Database.Database Name") + "?autoReconnect=true&useSSL=false";
this.connection = DriverManager.getConnection(url, plugin.getConfig().getString("Database.Username"), plugin.getConfig().getString("Database.Password"));
//ToDo: This is sloppy
connection.createStatement().execute(
"CREATE TABLE IF NOT EXISTS `" + plugin.getConfig().getString("Database.Prefix") + "charged` (\n" +
"\t`location` TEXT NULL,\n" +
"\t`level` INT NULL,\n" +
"\t`uses` INT NULL,\n" +
"\t`tolevel` INT NULL,\n" +
"\t`nickname` TEXT NULL,\n" +
"\t`accesslist` TEXT NULL,\n" +
"\t`placedby` TEXT NULL\n" +
")");
connection.createStatement().execute("CREATE TABLE IF NOT EXISTS `" + plugin.getConfig().getString("Database.Prefix") + "boosts` (\n" +
"\t`endtime` TEXT NULL,\n" +
"\t`amount` INT NULL,\n" +
"\t`uuid` TEXT NULL\n" +
")");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Database connection failed.");
}
}
public Connection getConnection() {
return connection;
}
}

View File

@ -0,0 +1,156 @@
package com.songoda.epicfurnaces.utils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Serializers {
public static String serialize(ItemStack item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getType().toString());
if (item.getDurability() != 0) builder.append(":" + item.getDurability());
builder.append(" " + item.getAmount());
for (Enchantment enchant : item.getEnchantments().keySet())
builder.append(" " + enchant.getName() + ":" + item.getEnchantments().get(enchant));
String name = getName(item);
if (name != null) builder.append(" name:" + name);
String lore = getLore(item);
if (lore != null) builder.append(" lore:" + lore);
Color color = getArmorColor(item);
if (color != null) builder.append(" rgb:" + color.getRed() + "|" + color.getGreen() + "|" + color.getBlue());
String owner = getOwner(item);
if (owner != null) builder.append(" owner:" + owner);
return builder.toString();
}
public static ItemStack deserialize(String serializedItem) {
String[] strings = serializedItem.split(" ");
Map<Enchantment, Integer> enchants = new HashMap<>();
String[] args;
ItemStack item = new ItemStack(Material.AIR);
for (String str : strings) {
args = str.split(":");
if (Material.matchMaterial(args[0]) != null && item.getType() == Material.AIR) {
item.setType(Material.matchMaterial(args[0]));
if (args.length == 2) item.setDurability(Short.parseShort(args[1]));
break;
}
}
if (item.getType() == Material.AIR) {
Bukkit.getLogger().info("Could not find a valid material for the item in \"" + serializedItem + "\"");
return null;
}
for (String str : strings) {
args = str.split(":", 2);
if (isNumber(args[0])) item.setAmount(Integer.parseInt(args[0]));
if (args.length == 1) continue;
if (args[0].equalsIgnoreCase("name")) {
setName(item, ChatColor.translateAlternateColorCodes('&', args[1]));
continue;
}
if (args[0].equalsIgnoreCase("lore")) {
setLore(item, ChatColor.translateAlternateColorCodes('&', args[1]));
continue;
}
if (args[0].equalsIgnoreCase("rgb")) {
setArmorColor(item, args[1]);
continue;
}
if (args[0].equalsIgnoreCase("owner")) {
setOwner(item, args[1]);
continue;
}
if (Enchantment.getByName(args[0].toUpperCase()) != null) {
enchants.put(Enchantment.getByName(args[0].toUpperCase()), Integer.parseInt(args[1]));
continue;
}
}
item.addUnsafeEnchantments(enchants);
return item.getType().equals(Material.AIR) ? null : item;
}
private static String getOwner(ItemStack item) {
if (!(item.getItemMeta() instanceof SkullMeta)) return null;
return ((SkullMeta) item.getItemMeta()).getOwner();
}
private static void setOwner(ItemStack item, String owner) {
try {
SkullMeta meta = (SkullMeta) item.getItemMeta();
meta.setOwner(owner);
item.setItemMeta(meta);
} catch (Exception exception) {
return;
}
}
private static String getName(ItemStack item) {
if (!item.hasItemMeta()) return null;
if (!item.getItemMeta().hasDisplayName()) return null;
return item.getItemMeta().getDisplayName().replace(" ", "_").replace(ChatColor.COLOR_CHAR, '&');
}
private static void setName(ItemStack item, String name) {
name = name.replace("_", " ").replace('&', ChatColor.COLOR_CHAR);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
}
private static String getLore(ItemStack item) {
if (!item.hasItemMeta()) return null;
if (!item.getItemMeta().hasLore()) return null;
StringBuilder builder = new StringBuilder();
List<String> lore = item.getItemMeta().getLore();
for (int ind = 0; ind < lore.size(); ind++) {
builder.append((ind > 0 ? "|" : "") + lore.get(ind).replace(" ", "_").replace(ChatColor.COLOR_CHAR, '&'));
}
return builder.toString();
}
private static void setLore(ItemStack item, String lore) {
lore = lore.replace("_", " ").replace('&', ChatColor.COLOR_CHAR);
ItemMeta meta = item.getItemMeta();
meta.setLore(Arrays.asList(lore.split("\\|")));
item.setItemMeta(meta);
}
private static Color getArmorColor(ItemStack item) {
if (!(item.getItemMeta() instanceof LeatherArmorMeta)) return null;
return ((LeatherArmorMeta) item.getItemMeta()).getColor();
}
private static void setArmorColor(ItemStack item, String str) {
try {
String[] colors = str.split("\\|");
int red = Integer.parseInt(colors[0]);
int green = Integer.parseInt(colors[1]);
int blue = Integer.parseInt(colors[2]);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setColor(Color.fromRGB(red, green, blue));
item.setItemMeta(meta);
} catch (Exception exception) {
return;
}
}
private static boolean isNumber(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException exception) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,27 @@
package com.songoda.epicfurnaces.utils;
public enum ServerVersion {
UNKNOWN("unknown_server_version"),
V1_7("org.bukkit.craftbukkit.v1_7"),
V1_8("org.bukkit.craftbukkit.v1_8"),
V1_9("org.bukkit.craftbukkit.v1_9"),
V1_10("org.bukkit.craftbukkit.v1_10"),
V1_11("org.bukkit.craftbukkit.v1_11"),
V1_12("org.bukkit.craftbukkit.v1_12"),
V1_13("org.bukkit.craftbukkit.v1_13"),
V1_14("org.bukkit.craftbukkit.v1_14");
private final String packagePrefix;
ServerVersion(String packagePrefix) {
this.packagePrefix = packagePrefix;
}
public static ServerVersion fromPackageName(String packageName) {
for (ServerVersion version : values())
if (packageName.startsWith(version.packagePrefix)) return version;
return ServerVersion.UNKNOWN;
}
}

View File

@ -1,7 +1,7 @@
package com.songoda.epicfurnaces.utils.gui;
package com.songoda.epicspawners.utils.gui;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.utils.NMSUtil;
import com.songoda.epicspawners.EpicSpawners;
import com.songoda.epicspawners.utils.version.NMSUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@ -62,7 +62,8 @@ public class AbstractAnvilGUI {
}
}
public AbstractAnvilGUI(EpicFurnaces instance, Player player, AnvilClickEventHandler handler) {
public AbstractAnvilGUI(Player player, AnvilClickEventHandler handler) {
EpicSpawners instance = EpicSpawners.getInstance();
this.player = player;
this.listener = new Listener() {

View File

@ -0,0 +1,226 @@
package com.songoda.epicspawners.utils.gui;
import com.songoda.epicspawners.EpicSpawners;
import com.songoda.epicspawners.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractGUI implements Listener {
private static boolean listenersInitialized = false;
protected Player player;
protected Inventory inventory = null;
protected String setTitle = null;
protected boolean cancelBottom = false;
private Map<Range, Clickable> clickables = new HashMap<>();
private List<OnClose> onCloses = new ArrayList<>();
private Map<Range, Boolean> draggableRanges = new HashMap<>();
public AbstractGUI(Player player) {
this.player = player;
}
public static void initializeListeners(JavaPlugin plugin) {
if (listenersInitialized) return;
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onClickGUI(InventoryClickEvent event) {
Inventory inventory = event.getClickedInventory();
if (inventory == null) return;
AbstractGUI gui = getGUIFromInventory(inventory);
Player player = (Player) event.getWhoClicked();
boolean bottom = false;
InventoryType type = event.getClickedInventory().getType();
if (type != InventoryType.CHEST && type != InventoryType.PLAYER) return;
if (gui == null && event.getWhoClicked().getOpenInventory().getTopInventory() != null) {
Inventory top = event.getWhoClicked().getOpenInventory().getTopInventory();
gui = getGUIFromInventory(top);
if (gui != null && gui.cancelBottom) event.setCancelled(true);
bottom = true;
}
if (gui == null) return;
if (!bottom) event.setCancelled(true);
if (!gui.draggableRanges.isEmpty() && !bottom) {
for (Map.Entry<Range, Boolean> entry : gui.draggableRanges.entrySet()) {
Range range = entry.getKey();
if (range.getMax() == range.getMin() && event.getSlot() == range.getMin()
|| event.getSlot() >= range.getMin() && event.getSlot() <= range.getMax()) {
event.setCancelled(!entry.getValue());
if (!entry.getValue()) break;
}
}
}
Map<Range, Clickable> entries = new HashMap<>(gui.clickables);
for (Map.Entry<Range, Clickable> entry : entries.entrySet()) {
Range range = entry.getKey();
if (range.isBottom() && !bottom || !range.isBottom() && bottom || range.getClickType() != null && range.getClickType() != event.getClick())
continue;
if (event.getSlot() >= range.getMin() && event.getSlot() <= range.getMax()) {
entry.getValue().Clickable(player, inventory, event.getCursor(), event.getSlot(), event.getClick());
player.playSound(player.getLocation(), entry.getKey().getOnClickSound(), 1F, 1F);
}
}
}
@EventHandler
public void onCloseGUI(InventoryCloseEvent event) {
Inventory inventory = event.getInventory();
AbstractGUI gui = getGUIFromInventory(inventory);
if (gui == null || gui.inventory == null) return;
for (OnClose onClose : gui.onCloses) {
onClose.onClose((Player) event.getPlayer(), inventory);
}
}
private AbstractGUI getGUIFromInventory(Inventory inventory) {
if (inventory.getHolder() == null) return null;
InventoryHolder holder = inventory.getHolder();
if (!(holder instanceof GUIHolder)) return null;
return ((AbstractGUI.GUIHolder) holder).getGUI();
}
}, plugin);
listenersInitialized = true;
}
public void init(String title, int slots) {
if (inventory == null
|| inventory.getSize() != slots
|| ChatColor.translateAlternateColorCodes('&', title) != player.getOpenInventory().getTitle()) {
this.inventory = Bukkit.getServer().createInventory(new GUIHolder(), slots, Methods.formatTitle(title));
this.setTitle = Methods.formatText(title);
if (this.clickables.size() == 0)
registerClickables();
if (this.onCloses.size() == 0)
registerOnCloses();
}
constructGUI();
initializeListeners(EpicSpawners.getInstance());
player.openInventory(inventory);
}
public abstract void constructGUI();
protected void addDraggable(Range range, boolean option) {
this.draggableRanges.put(range, option);
}
protected void removeDraggable() {
this.draggableRanges.clear();
}
protected abstract void registerClickables();
protected abstract void registerOnCloses();
protected ItemStack createButton(int slot, Inventory inventory, ItemStack item, String name, String... lore) {
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
if (lore != null && lore.length != 0) {
List<String> newLore = new ArrayList<>();
for (String line : lore) newLore.add(ChatColor.translateAlternateColorCodes('&', line));
meta.setLore(newLore);
}
item.setItemMeta(meta);
inventory.setItem(slot, item);
return item;
}
protected ItemStack createButton(int slot, ItemStack item, String name, String... lore) {
return createButton(slot, inventory, item, name, lore);
}
protected ItemStack createButton(int slot, Inventory inventory, Material material, String name, String... lore) {
return createButton(slot, inventory, new ItemStack(material), name, lore);
}
protected ItemStack createButton(int slot, Material material, String name, String... lore) {
return createButton(slot, inventory, new ItemStack(material), name, lore);
}
protected ItemStack createButton(int slot, Material material, String name, ArrayList<String> lore) {
return createButton(slot, material, name, lore.toArray(new String[0]));
}
protected void registerClickable(int min, int max, ClickType clickType, boolean bottom, Clickable clickable) {
clickables.put(new Range(min, max, clickType, bottom), clickable);
}
protected void registerClickable(int min, int max, ClickType clickType, Clickable clickable) {
registerClickable(min, max, clickType, false, clickable);
}
protected void registerClickable(int slot, ClickType clickType, Clickable clickable) {
registerClickable(slot, slot, clickType, false, clickable);
}
protected void registerClickable(int min, int max, Clickable clickable) {
registerClickable(min, max, null, false, clickable);
}
protected void registerClickable(int slot, boolean bottom, Clickable clickable) {
registerClickable(slot, slot, null, bottom, clickable);
}
protected void registerClickable(int slot, Clickable clickable) {
registerClickable(slot, slot, null, false, clickable);
}
protected void resetClickables() {
clickables.clear();
}
protected void registerOnClose(OnClose onClose) {
onCloses.add(onClose);
}
public Inventory getInventory() {
return inventory;
}
public class GUIHolder implements InventoryHolder {
@Override
public Inventory getInventory() {
return inventory;
}
public AbstractGUI getGUI() {
return AbstractGUI.this;
}
}
public String getSetTitle() {
return setTitle;
}
}

View File

@ -0,0 +1,11 @@
package com.songoda.epicspawners.utils.gui;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public interface Clickable {
void Clickable(Player player, Inventory inventory, ItemStack cursor, int slot, ClickType type);
}

View File

@ -1,4 +1,4 @@
package com.songoda.epicfurnaces.utils.gui;
package com.songoda.epicspawners.utils.gui;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;

View File

@ -0,0 +1,51 @@
package com.songoda.epicspawners.utils.gui;
import com.songoda.epicspawners.EpicSpawners;
import com.songoda.epicspawners.utils.ServerVersion;
import org.bukkit.Sound;
import org.bukkit.event.inventory.ClickType;
public class Range {
private int min;
private int max;
private ClickType clickType;
private boolean bottom;
private Sound onClickSound;
public Range(int min, int max, ClickType clickType, boolean bottom) {
this.min = min;
this.max = max;
this.clickType = clickType;
this.bottom = bottom;
if (EpicSpawners.getInstance().isServerVersionAtLeast(ServerVersion.V1_9)) onClickSound = Sound.UI_BUTTON_CLICK;
}
public Range(int min, int max, Sound onClickSound, ClickType clickType, boolean bottom) {
this.min = min;
this.max = max;
this.onClickSound = onClickSound;
this.clickType = clickType;
this.bottom = bottom;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
public ClickType getClickType() {
return clickType;
}
public boolean isBottom() {
return bottom;
}
public Sound getOnClickSound() {
return onClickSound;
}
}

View File

@ -0,0 +1,21 @@
package com.songoda.epicfurnaces.utils.settings;
public enum Category {
MAIN("General settings and options."),
INTERFACES("These settings allow you to alter the way interfaces look.",
"They are used in GUI's to make patterns, change them up then open up a",
"GUI to see how it works."),
SYSTEM("System related settings.");
private String[] comments;
Category(String... comments) {
this.comments = comments;
}
public String[] getComments() {
return comments;
}
}

View File

@ -0,0 +1,152 @@
package com.songoda.epicfurnaces.utils.settings;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.utils.ServerVersion;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public enum Setting {
o3("Main.Upgrade By Smelting Materials", true),
UPGRADE_WITH_ECONOMY("Main.Upgrade With Economy", true,
"Should you be able to upgrade furnaces with economy?"),
UPGRADE_WITH_XP("Main.Upgrade With XP", true,
"Should you be able to upgrade furnaces with experience?"),
AUTOSAVE("Main.Auto Save Interval In Seconds", 15,
"The amount of time in between saving to file.",
"This is purely a safety function to prevent against unplanned crashes or",
"restarts. With that said it is advised to keep this enabled.",
"If however you enjoy living on the edge, feel free to turn it off."),
o6("Main.Level Cost Multiplier", 50),
o102("Main.Remember Furnace Item Levels", true),
HOLOGRAMS("Main.Furnaces Have Holograms", true),
o324("Main.Redstone Deactivates Furnaces", true),
o11("Main.Furnace Upgrade Cost", "IRON_INGOT"),
o12("Main.Use Custom Recipes", true),
o13("Main.No Rewards From Custom Recipes", true),
PARTICLE_TYPE("Main.Upgrade Particle Type", "SPELL_WITCH",
"The type of particle shown when a furnace is upgraded."),
o18("Main.Access Furnaces Remotely", true),
o543("Main.Furnace Tick Speed", 10),
o5423("Main.Auto Save Interval In Seconds", 15),
o54("Main.Overheat Particles", true),
o14("Interfaces.Reward Icon", "GOLDEN_APPLE"),
o15("Interfaces.Performance Icon", "REDSTONE"),
o16("Interfaces.FuelShare Icon", "COAL_BLOCK"),
o316("Interfaces.FuelDuration Icon", "COAL"),
o162("Interfaces.Overheat Icon", "FIRE_CHARGE"),
VAULT_ECONOMY("Economy.Use Vault Economy", true,
"Should Vault be used?"),
PLAYER_POINTS_ECONOMY("Economy.Use Player Points Economy", false,
"Should PlayerPoints be used?"),
RAINBOW("Interfaces.Replace Glass Type 1 With Rainbow Glass", false),
ECO_ICON("Interfaces.Economy Icon", EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "SUNFLOWER" : "DOUBLE_PLANT"),
XP_ICON("Interfaces.XP Icon", EpicFurnaces.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "EXPERIENCE_BOTTLE" : "EXP_BOTTLE"),
GLASS_TYPE_1("Interfaces.Glass Type 1", 7),
GLASS_TYPE_2("Interfaces.Glass Type 2", 11),
GLASS_TYPE_3("Interfaces.Glass Type 3", 3),
DATABASE_SUPPORT("Database.Activate Mysql Support", false,
"Should MySQL be used for data storage?"),
DATABASE_IP("Database.IP", "127.0.0.1",
"MySQL IP"),
DATABASE_PORT("Database.Port", 3306,
"MySQL Port"),
DATABASE_NAME("Database.Database Name", "EpicFurnaces",
"The database you are inserting data into."),
DATABASE_PREFIX("Database.Prefix", "EH-",
"The prefix for tables inserted into the database."),
DATABASE_USERNAME("Database.Username", "PUT_USERNAME_HERE",
"MySQL Username"),
DATABASE_PASSWORD("Database.Password", "PUT_PASSWORD_HERE",
"MySQL Password"),
LANGUGE_MODE("System.Language Mode", "en_US",
"The enabled language file.",
"More language files (if available) can be found in the plugins data folder.");
private String setting;
private Object option;
private String[] comments;
Setting(String setting, Object option, String... comments) {
this.setting = setting;
this.option = option;
this.comments = comments;
}
Setting(String setting, Object option) {
this.setting = setting;
this.option = option;
this.comments = null;
}
public static Setting getSetting(String setting) {
List<Setting> settings = Arrays.stream(values()).filter(setting1 -> setting1.setting.equals(setting)).collect(Collectors.toList());
if (settings.isEmpty()) return null;
return settings.get(0);
}
public String getSetting() {
return setting;
}
public Object getOption() {
return option;
}
public String[] getComments() {
return comments;
}
public List<String> getStringList() {
return EpicFurnaces.getInstance().getConfig().getStringList(setting);
}
public boolean getBoolean() {
return EpicFurnaces.getInstance().getConfig().getBoolean(setting);
}
public int getInt() {
return EpicFurnaces.getInstance().getConfig().getInt(setting);
}
public long getLong() {
return EpicFurnaces.getInstance().getConfig().getLong(setting);
}
public String getString() {
return EpicFurnaces.getInstance().getConfig().getString(setting);
}
public char getChar() {
return EpicFurnaces.getInstance().getConfig().getString(setting).charAt(0);
}
public double getDouble() {
return EpicFurnaces.getInstance().getConfig().getDouble(setting);
}
}

View File

@ -0,0 +1,309 @@
package com.songoda.epicfurnaces.utils.settings;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.utils.Methods;
import com.songoda.epicfurnaces.utils.ServerVersion;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.*;
import java.util.*;
/**
* Created by songoda on 6/4/2017.
*/
public class SettingsManager implements Listener {
private final EpicFurnaces plugin;
private Map<Player, String> cat = new HashMap<>();
private Map<Player, String> current = new HashMap<>();
public SettingsManager(EpicFurnaces plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
ItemStack clickedItem = event.getCurrentItem();
if (event.getInventory() != event.getWhoClicked().getOpenInventory().getTopInventory()
|| clickedItem == null || !clickedItem.hasItemMeta()
|| !clickedItem.getItemMeta().hasDisplayName()) {
return;
}
if (event.getView().getTitle().equals(plugin.getName() + " Settings Manager")) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
String type = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
this.cat.put((Player) event.getWhoClicked(), type);
this.openEditor((Player) event.getWhoClicked());
} else if (event.getView().getTitle().equals(plugin.getName() + " Settings Editor")) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
Player player = (Player) event.getWhoClicked();
String key = cat.get(player) + "." + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
if (plugin.getConfig().get(key).getClass().getName().equals("java.lang.Boolean")) {
this.plugin.getConfig().set(key, !plugin.getConfig().getBoolean(key));
this.finishEditing(player);
} else {
this.editObject(player, key);
}
}
}
@EventHandler
public void onChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (!current.containsKey(player)) return;
String value = current.get(player);
FileConfiguration config = plugin.getConfig();
if (config.isLong(value)) {
config.set(value, Long.parseLong(event.getMessage()));
} else if (config.isInt(value)) {
config.set(value, Integer.parseInt(event.getMessage()));
} else if (config.isDouble(value)) {
config.set(value, Double.parseDouble(event.getMessage()));
} else if (config.isString(value)) {
config.set(value, event.getMessage());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(EpicFurnaces.getInstance(), () ->
this.finishEditing(player), 0L);
event.setCancelled(true);
}
private void finishEditing(Player player) {
this.current.remove(player);
this.saveConfig();
this.openEditor(player);
}
private void editObject(Player player, String current) {
this.current.put(player, ChatColor.stripColor(current));
player.closeInventory();
player.sendMessage("");
player.sendMessage(Methods.formatText("&7Please enter a value for &6" + current + "&7."));
if (plugin.getConfig().isInt(current) || plugin.getConfig().isDouble(current)) {
player.sendMessage(Methods.formatText("&cUse only numbers."));
}
player.sendMessage("");
}
public void openSettingsManager(Player player) {
Inventory inventory = Bukkit.createInventory(null, 27, plugin.getName() + " Settings Manager");
ItemStack glass = Methods.getGlass();
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, glass);
}
int slot = 10;
for (String key : plugin.getConfig().getDefaultSection().getKeys(false)) {
ItemStack item = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.LEGACY_WOOL : Material.valueOf("WOOL"), 1, (byte) (slot - 9));
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(Methods.formatText("&6Click To Edit This Category.")));
meta.setDisplayName(Methods.formatText("&f&l" + key));
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
private void openEditor(Player player) {
Inventory inventory = Bukkit.createInventory(null, 54, plugin.getName() + " Settings Editor");
FileConfiguration config = plugin.getConfig();
int slot = 0;
for (String key : config.getConfigurationSection(cat.get(player)).getKeys(true)) {
String fKey = cat.get(player) + "." + key;
ItemStack item = new ItemStack(Material.DIAMOND_HELMET);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Methods.formatText("&6" + key));
List<String> lore = new ArrayList<>();
if (config.isBoolean(fKey)) {
item.setType(Material.LEVER);
lore.add(Methods.formatText(config.getBoolean(fKey) ? "&atrue" : "&cfalse"));
} else if (config.isString(fKey)) {
item.setType(Material.PAPER);
lore.add(Methods.formatText("&7" + config.getString(fKey)));
} else if (config.isInt(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getInt(fKey)));
} else if (config.isLong(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getLong(fKey)));
} else if (config.isDouble(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getDouble(fKey)));
}
Setting setting = Setting.getSetting(fKey);
if (setting != null && setting.getComments() != null) {
lore.add("");
String comment = String.join(" ", setting.getComments());
int lastIndex = 0;
for (int n = 0; n < comment.length(); n++) {
if (n - lastIndex < 30)
continue;
if (comment.charAt(n) == ' ') {
lore.add(Methods.formatText("&8" + comment.substring(lastIndex, n).trim()));
lastIndex = n;
}
}
if (lastIndex - comment.length() < 30)
lore.add(Methods.formatText("&8" + comment.substring(lastIndex).trim()));
}
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
public void reloadConfig() {
plugin.reloadConfig();
this.setupConfig();
}
public void setupConfig() {
FileConfiguration config = plugin.getConfig();
for (Setting setting : Setting.values()) {
config.addDefault(setting.getSetting(), setting.getOption());
}
plugin.getConfig().options().copyDefaults(true);
saveConfig();
}
private void saveConfig() {
String dump = plugin.getConfig().saveToString();
StringBuilder config = new StringBuilder();
BufferedReader bufReader = new BufferedReader(new StringReader(dump));
try {
boolean first = true;
String line;
int currentTab = 0;
String category = "";
while ((line = bufReader.readLine()) != null) {
if (line.trim().startsWith("#")) continue;
int tabChange = line.length() - line.trim().length();
if (currentTab != tabChange) {
category = category.contains(".") && tabChange != 0 ? category.substring(0, category.indexOf(".")) : "";
currentTab = tabChange;
}
if (line.endsWith(":")) {
bufReader.mark(1000);
String found = bufReader.readLine();
bufReader.reset();
if (!found.trim().startsWith("-")) {
String newCategory = line.substring(0, line.length() - 1).trim();
if (category.equals(""))
category = newCategory;
else
category += "." + newCategory;
currentTab = tabChange + 2;
if (!first) {
config.append("\n\n");
} else {
first = false;
}
if (!category.contains("."))
config.append("#").append("\n");
try {
Category categoryObj = Category.valueOf(category.toUpperCase()
.replace(" ", "_")
.replace(".", "_"));
config.append(new String(new char[tabChange]).replace('\0', ' '));
for (String l : categoryObj.getComments())
config.append("# ").append(l).append("\n");
} catch (IllegalArgumentException e) {
config.append("# ").append(category).append("\n");
}
if (!category.contains("."))
config.append("#").append("\n");
config.append(line).append("\n");
continue;
}
}
if (line.trim().startsWith("-")) {
config.append(line).append("\n");
continue;
}
String key = category + "." + (line.split(":")[0].trim());
for (Setting setting : Setting.values()) {
if (!setting.getSetting().equals(key) || setting.getComments() == null) continue;
config.append(" ").append("\n");
for (String l : setting.getComments()) {
config.append(new String(new char[currentTab]).replace('\0', ' '));
config.append("# ").append(l).append("\n");
}
}
config.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (!plugin.getDataFolder().exists())
plugin.getDataFolder().mkdir();
BufferedWriter writer =
new BufferedWriter(new FileWriter(new File(plugin.getDataFolder() + File.separator + "config.yml")));
writer.write(config.toString());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,6 +1,6 @@
package com.songoda.epicfurnaces.utils.updateModules;
import com.songoda.epicfurnaces.Locale;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.update.Module;
import com.songoda.update.Plugin;
import org.json.simple.JSONArray;
@ -22,7 +22,7 @@ public class LocaleModule implements Module {
if (file.get("type").equals("locale")) {
InputStream in = new URL((String) file.get("link")).openStream();
Locale.saveDefaultLocale(in, (String) file.get("name"));
EpicFurnaces.getInstance().getLocale().saveDefaultLocale(in, (String) file.get("name"));
}
}
} catch (IOException e) {

View File

@ -1,5 +1,4 @@
package com.songoda.epicfurnaces.utils;
package com.songoda.epicfurnaces.utils.version;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -26,7 +25,8 @@ public class NMSUtil {
public static Class<?> getNMSClass(String className) {
try {
String fullName = "net.minecraft.server." + getVersion() + className;
return Class.forName(fullName);
Class<?> clazz = Class.forName(fullName);
return clazz;
} catch (Exception e) {
e.printStackTrace();
return null;
@ -36,7 +36,8 @@ public class NMSUtil {
public static Class<?> getCraftClass(String className) {
try {
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
return Class.forName(fullName);
Class<?> clazz = Class.forName(fullName);
return clazz;
} catch (Exception e) {
e.printStackTrace();
return null;
@ -97,4 +98,3 @@ public class NMSUtil {
}
}
}

View File

@ -0,0 +1,11 @@
# EpicFurnaces furnace Recipe file
Recipes:
DIAMOND_SWORD:
result: DIAMOND
amount: 2
DIAMOND_PICKAXE:
result: DIAMOND
amount: 3
DIAMOND_AXE:
result: DIAMOND
amount: 3

View File

@ -0,0 +1,16 @@
ECO-Icon: 'This is the icon players will use to upgrade with Economy.'
XP-Icon: 'This is the icon players will use to upgrade with EXP.'
Upgrade-with-material: 'When enabled players will be able to smelt materials defined in the config to upgrade furnaces.'
Upgrade-with-eco: 'If enabled players will optionally be able to use Economy to upgrade their furnaces.'
Upgrade-with-xp: 'If enabled players will optionally be able to use XP to upgrade their furnaces.'
Turbo-level-multiplier: 'This is the amount the cost for each level, it is multiplied by the level you are currently on. So if the next level is 3 then the cost would be 100.'
On-upgrade-particles: 'If set to true particles will be generated on upgrade.'
Helpful-Tips: 'If this is enabled tips will be displayed to guide you on how to use the plugin.'
Glass-Type: 'This is the id of the glass used for the background in the guis.'
Rainbow-Glass: 'If this is enabled the glass background will be randomized colors.'
Furnace-upgrade-cost: 'This is the material that an upgrade will cost.'
Custom-recipes: 'If set to true custom recipes will be loaded from the recipe config.'
Ignore-custom-recipes-for-rewards: 'If set to true custom recipes wont count towards rewards. This is to prevent abuse.'
Reward-Icon: 'This is the icon players will use to upgrade reward.'
Performance-Icon: 'This is the icon players will use to upgrade performance.'
FuelDuration-Icon: 'This is the icon players will use to upgrade Fuel Duration.'

View File

@ -0,0 +1,55 @@
#General Messages
general.nametag.prefix = "&8[&6EpicFurnaces&8]"
general.nametag.next = "&9Next"
general.nametag.back = "&9Back"
general.nametag.nameformat = "&eLevel %level% &fFurnace"
general.hologram.outoffuel = "&cNo Fuel"
general.hologram.stats = "&a%in%&7/&c%out%";
#Interface Messages
interface.furnace.upgradewithxp = "&aUpgrade with XP"
interface.furnace.upgradewithxplore = "&7Cost: &a%cost% Levels"
interface.furnace.upgradewitheconomy = "&aUpgrade with ECO"
interface.furnace.upgradewitheconomylore = "&7Cost: &a$%cost%"
interface.furnace.currentlevel = "&6Furnace Level &7%level%"
interface.furnace.level = "&6Next Level &7%level%"
interface.furnace.performance = "&7Performance: &6%amount%"
interface.furnace.reward = "&7Reward: &6%amount%"
interface.furnace.performancetitle = "&a&lPerformance"
interface.furnace.rewardtitle = "&c&lReward"
interface.furnace.fueldurationtitle = "&7&lFuel Duration"
interface.furnace.fuelduration = "&7Fuel Duration: &6%amount%"
interface.furnace.fuelshare = "&7Fuel Share: &6%amount%&7."
interface.furnace.fuelsharetitle = "&6&lFuel Share"
interface.furnace.fuelshareinfo = "&7This furnace will power other|&7furnaces within a &6%amount%&7 block radius."
interface.furnace.overheat = "&7Overheat: &6%amount%&7."
interface.furnace.overheattitle = "&6&lOverheat"
interface.furnace.overheatinfo = "&7This furnace will melt snow |&7and ice within a &6%amount%&7 block radius."
interface.furnace.performanceinfo = "&7This furnaces performance is |&7currently boosted an extra &6%amount%%&7. | |&7Performance boosts the speed in |&7which a furnace processes |&7materials."
interface.furnace.rewardinfo = "&7This furnace currently |&7has a &6%amount%%&7 chance of |&7producing multiple resources."
interface.furnace.fueldurationinfo = "&7This furnaces fuel duration is |&7currently boosted by &6%amount%%&7. | |&7Fuel Duration boosts how long |&7fuel in the furnace lasts."
interface.furnace.smeltedx = "&7Smelted &6%amount% Materials&7."
interface.furnace.tolevel = "&6%amount% %type%s &7away from leveling up."
interface.furnace.remotefurnace = "&5&lRemote Control"
interface.furnace.remotefurnacelore = "&7Left-Click to assign a nickname.|&7Right-Click to give yourself |&7remote access.|&7Current nickname is: &6%nickname%&7."
interface.furnace.utilize = "|&7To utilize remote access|&7use the command:|&6/EF Remote %nickname%"
interface.furnace.remotelist = "&7Players with remote access:"
interface.furnace.alreadymaxed = "&7This furnace is already maxed out!"
interface.button.boostedstats = "&a&lCurrently boosted!|&7Reward multiplied by &6%amount%x&7.|&7Expires in &6%time%&7."
#Command Messages
command.give.success = "&7You have been given a &6level %level% &7Furnace."
#Event Messages
event.general.nopermission = "&cYou do not have permission to do that."
event.upgrade.cannotafford = "&cYou cannot afford this upgrade."
event.upgrade.success = "&7You successfully upgraded this furnace to &6level %level%&7!"
event.upgrade.maxed = "&7You maxed out this furnace at &6level %level%&7."
event.remote.enter = "&7Enter a unique nickname for the furnace."
event.remote.notfound = "&cRemote furnace not found."
event.remote.nicknamesuccess = "&aNickname set successfully."
event.remote.nicknameinuse = "&cThat nickname is already in use."

View File

View File

@ -0,0 +1,14 @@
name: EpicFurnaces
description: EpicFurnaces
version: maven-version-number
depend: [Arconix]
softdepend: [PlotSquared, GriefPrevention, USkyBlock, SkyBlock, WorldGuard, Factions]
main: com.songoda.epicfurnaces.EpicFurnacesPlugin
author: songoda
api-version: 1.13
commands:
EpicFurnaces:
description: I have no idea.
default: true
aliases: [ef]
usage: /<command> [reload]