file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
IMySQLStorage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/mysql/IMySQLStorage.java
package me.patothebest.gamecore.storage.mysql; import me.patothebest.gamecore.storage.Storage; import java.util.List; public interface IMySQLStorage extends Storage { List<String> getCreateTableQueries(); }
216
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SQLTask.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/mysql/SQLTask.java
package me.patothebest.gamecore.storage.mysql; import me.patothebest.gamecore.util.Callback; import me.patothebest.gamecore.util.WrappedBukkitRunnable; import java.sql.Connection; class SQLTask extends WrappedBukkitRunnable { private final MySQLConnectionHandler mySQLConnectionHandler; private final SQLCallBack<Connection> sqlCallBack; private final Callback<Throwable> errorCallback; SQLTask(MySQLConnectionHandler mySQLConnectionHandler, SQLCallBack<Connection> sqlCallBack, Callback<Throwable> errorCallback) { this.mySQLConnectionHandler = mySQLConnectionHandler; this.sqlCallBack = sqlCallBack; this.errorCallback = errorCallback; } @Override public void run() { if(mySQLConnectionHandler.isClosed()) { return; } try (Connection connection = mySQLConnectionHandler.getConnection()){ sqlCallBack.call(connection); } catch(Throwable t) { t.printStackTrace(); if(errorCallback != null) { errorCallback.call(t); } } } SQLTask executeAsync() { runTaskAsynchronously(mySQLConnectionHandler.getPlugin()); return this; } }
1,226
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PlayerQueries.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/mysql/PlayerQueries.java
package me.patothebest.gamecore.storage.mysql; class PlayerQueries { final static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `players` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `name` varchar(16) COLLATE latin1_general_ci NOT NULL,\n" + " `UUID` varchar(36) COLLATE latin1_general_ci NOT NULL,\n" + " `locale` varchar(16) COLLATE latin1_general_ci NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `name` (`name`),\n" + " UNIQUE KEY `UUID` (`UUID`),\n" + " UNIQUE KEY `id` (`id`)\n" + ")"; final static String INSERT_RECORD = "INSERT INTO players VALUES (NULL, ?, ?, ?)"; final static String SELECT_UUID = "SELECT * FROM players WHERE UUID=?"; final static String SELECT_NAME = "SELECT * FROM players WHERE name=?"; final static String SELECT_ALL = "SELECT name,UUID FROM players"; final static String UPDATE = "UPDATE players SET name=?, locale=? WHERE id=?;"; final static String UPDATE_UUID = "UPDATE players SET uuid=? WHERE id=?;"; final static String UPDATE_LOCALE = "UPDATE players SET locale=? WHERE id=?;"; }
1,209
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
KitQueries.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/mysql/KitQueries.java
package me.patothebest.gamecore.storage.mysql; import me.patothebest.gamecore.PluginConfig; public class KitQueries { private static final String TABLE_NAME = PluginConfig.SQL_PREFIX + "_kit_data"; public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `" + TABLE_NAME + "` (\n" + " `name` varchar(36) NOT NULL,\n" + " `description` text NOT NULL,\n" + " `display_item` text NOT NULL,\n" + " `items` text NOT NULL,\n" + " `armor` text NOT NULL,\n" + " `potion_effects` text NOT NULL,\n" + " `permission_group` varchar(36) NOT NULL,\n" + " `one_time_kit` tinyint(1) NOT NULL,\n" + " `price` double(11, 5) NOT NULL,\n" + " `enabled` tinyint(4) NOT NULL,\n" + " PRIMARY KEY (`name`)\n" + ") ENGINE=InnoDB DEFAULT CHARSET=latin1"; public static final String SELECT = "SELECT * FROM " + TABLE_NAME; public static final String INSERT = "INSERT INTO " + TABLE_NAME + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; public static final String UPDATE = "UPDATE " + TABLE_NAME + " SET description=?, display_item=?, " + "items=?, armor=?, potion_effects=?, permission_group=?, one_time_kit=?, price=?, enabled=? WHERE name =?;"; public static final String DELETE = "DELETE FROM " + TABLE_NAME + " WHERE name=?"; }
1,517
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ConverterCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/converter/ConverterCommand.java
package me.patothebest.gamecore.storage.converter; import com.google.inject.Inject; import me.patothebest.gamecore.commands.admin.AdminCommand; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.scheduler.PluginScheduler; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.command.ChildOf; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.modules.RegisteredCommandModule; import me.patothebest.gamecore.storage.StorageType; import me.patothebest.gamecore.storage.split.SplitType; import me.patothebest.gamecore.util.CommandUtils; import org.bukkit.command.CommandSender; import java.util.List; @ChildOf(AdminCommand.class) public class ConverterCommand implements RegisteredCommandModule { private final StorageConverter storageConverter; private final PluginScheduler pluginScheduler; @Inject private ConverterCommand(StorageConverter storageConverter, PluginScheduler pluginScheduler) { this.storageConverter = storageConverter; this.pluginScheduler = pluginScheduler; } @Command( aliases = {"convert"}, usage = "<soure(mysql|flatfile)> <destination(mysql|flatfile)> <players|kits>", min = 3, max = 3, langDescription = @LangDescription( element = "CONVERT_COMMAND", langClass = CoreLang.class ) ) public List<String> convert(CommandContext args, CommandSender sender) throws CommandException { if (args.getSuggestionContext() != null) { switch (args.getSuggestionContext().getIndex()) { case 0: case 1: CommandUtils.complete(args.getString(args.getSuggestionContext().getIndex()), new StorageType[]{StorageType.FLATFILE, StorageType.MYSQL}); break; case 2: CommandUtils.complete(args.getString(2), SplitType.values()); break; } return null; } StorageType source = Utils.getEnumValueFromString(StorageType.class, args.getString(0)); StorageType dest = Utils.getEnumValueFromString(StorageType.class, args.getString(1)); SplitType splitType = Utils.getEnumValueFromString(SplitType.class, args.getString(2)); CommandUtils.validateNotNull(source, CoreLang.STORAGE_CAN_ONLY_BE); CommandUtils.validateNotNull(dest, CoreLang.STORAGE_CAN_ONLY_BE); CommandUtils.validateNotNull(splitType, CoreLang.STORAGE_TYPE); CommandUtils.validateTrue(source != dest, CoreLang.STORAGE_CANNOT_BE_SAME); pluginScheduler.runTaskAsynchronously(() -> storageConverter.convert(splitType, source, dest)); return null; } }
2,966
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
StorageConverter.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/converter/StorageConverter.java
package me.patothebest.gamecore.storage.converter; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import me.patothebest.gamecore.kit.Kit; import me.patothebest.gamecore.modules.Module; import me.patothebest.gamecore.storage.Storage; import me.patothebest.gamecore.storage.StorageType; import me.patothebest.gamecore.storage.flatfile.IFlatFileStorage; import me.patothebest.gamecore.storage.mysql.IMySQLStorage; import me.patothebest.gamecore.storage.split.SplitType; import java.util.HashMap; import java.util.Map; import static me.patothebest.gamecore.storage.StorageType.*; public class StorageConverter implements Module { private final Provider<Injector> injector; @Inject private StorageConverter(Provider<Injector> injector) { this.injector = injector; } public void convert(SplitType splitType, StorageType sourceStorageType, StorageType destinationStorageType) { if(sourceStorageType != StorageType.FLATFILE && sourceStorageType != MYSQL) { throw new IllegalArgumentException("Storage type must be either MySQL or FlatFile!"); } if(destinationStorageType != StorageType.FLATFILE && destinationStorageType != MYSQL) { throw new IllegalArgumentException("Storage type must be either MySQL or FlatFile!"); } if(destinationStorageType == sourceStorageType) { throw new IllegalArgumentException("Source and destination storage type cannot be the same!"); } Storage sourceStorage = getStorage(sourceStorageType); Storage destinationStorage = getStorage(destinationStorageType); sourceStorage.enableStorage(); destinationStorage.enableStorage(); if(splitType == SplitType.KITS) { Map<String, Kit> kits = new HashMap<>(); sourceStorage.loadKits(kits); destinationStorage.saveKits(kits); } else { // TODO: finish this sourceStorage.loadPlayers(player -> { destinationStorage.save(player); destinationStorage.unCache(player); }); } sourceStorage.preDisableStorage(); sourceStorage.disableStorage(); destinationStorage.preDisableStorage(); destinationStorage.disableStorage(); } private Storage getStorage(StorageType storageType) { switch (storageType) { case FLATFILE: return injector.get().getInstance(IFlatFileStorage.class); case MYSQL: return injector.get().getInstance(IMySQLStorage.class); } throw new IllegalStateException("Unhandled storage type " + storageType); } }
2,738
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SplitStorage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/split/SplitStorage.java
package me.patothebest.gamecore.storage.split; import com.google.inject.Injector; import me.patothebest.gamecore.storage.flatfile.IFlatFileStorage; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.file.CoreConfig; import me.patothebest.gamecore.kit.Kit; import me.patothebest.gamecore.player.CorePlayer; import me.patothebest.gamecore.storage.Storage; import me.patothebest.gamecore.storage.StorageType; import me.patothebest.gamecore.storage.mysql.IMySQLStorage; import me.patothebest.gamecore.storage.none.NullStorage; import me.patothebest.gamecore.util.Callback; import org.bukkit.inventory.PlayerInventory; import javax.inject.Inject; import javax.inject.Provider; import java.util.HashMap; import java.util.Map; public class SplitStorage implements Storage { private final Map<SplitType, Storage> splitTypeStorageMap = new HashMap<>(); @Inject private SplitStorage(CoreConfig coreConfig, Provider<Injector> injector) { for (SplitType splitType : SplitType.values()) { StorageType storageType = Utils.getEnumValueFromString(StorageType.class, coreConfig.getString("split-storage." + splitType.name().toLowerCase())); if (storageType == null) { // unknown storage type // fallback into no storage type storageType = StorageType.NONE; } Storage storage = null; switch (storageType) { case FLATFILE: storage = injector.get().getInstance(IFlatFileStorage.class); break; case MYSQL: storage = injector.get().getInstance(IMySQLStorage.class); break; case SPLIT: throw new IllegalArgumentException("Type cannot be split"); case NONE: storage = new NullStorage(); break; } splitTypeStorageMap.put(splitType, storage); } } @Override public void loadPlayers(Callback<CorePlayer> playerCallback) { splitTypeStorageMap.get(SplitType.PLAYERS).loadPlayers(playerCallback); } @Override public void load(CorePlayer player, boolean async) { splitTypeStorageMap.get(SplitType.PLAYERS).load(player, async); } @Override public void save(CorePlayer player) { splitTypeStorageMap.get(SplitType.PLAYERS).save(player); } @Override public void unCache(CorePlayer player) { splitTypeStorageMap.get(SplitType.PLAYERS).unCache(player); } @Override public void delete(CorePlayer player) { splitTypeStorageMap.get(SplitType.PLAYERS).delete(player); } @Override public void loadKits(Map<String, Kit> kitMap) { splitTypeStorageMap.get(SplitType.KITS).loadKits(kitMap); } @Override public Kit createKit(String name, PlayerInventory playerInventory) { return splitTypeStorageMap.get(SplitType.KITS).createKit(name, playerInventory); } @Override public void saveKits(Map<String, Kit> kitMap) { splitTypeStorageMap.get(SplitType.KITS).saveKits(kitMap); } @Override public void saveKit(Kit kit) { splitTypeStorageMap.get(SplitType.KITS).saveKit(kit); } @Override public void deleteKit(Kit kit) { splitTypeStorageMap.get(SplitType.KITS).deleteKit(kit); } @Override public void enableStorage() { splitTypeStorageMap.values().forEach(Storage::enableStorage); } @Override public void disableStorage() { splitTypeStorageMap.values().forEach(Storage::disableStorage); } @Override public void postEnable() { splitTypeStorageMap.values().forEach(Storage::postEnable); } @Override public void preDisableStorage() { splitTypeStorageMap.values().forEach(Storage::preDisableStorage); } public Map<SplitType, Storage> getSplitTypeStorageMap() { return splitTypeStorageMap; } }
4,041
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
NullStorage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/none/NullStorage.java
package me.patothebest.gamecore.storage.none; import me.patothebest.gamecore.kit.Kit; import me.patothebest.gamecore.player.CorePlayer; import me.patothebest.gamecore.storage.Storage; import me.patothebest.gamecore.util.Callback; import org.bukkit.inventory.PlayerInventory; import java.util.Map; public class NullStorage implements Storage { public NullStorage() { } @Override public void loadPlayers(Callback<CorePlayer> playerCallback) { } @Override public void load(CorePlayer player, boolean async) { } @Override public void save(CorePlayer player) { } @Override public void unCache(CorePlayer player) { } @Override public void delete(CorePlayer player) { } @Override public void loadKits(Map<String, Kit> kitMap) { } @Override public void saveKits(Map<String, Kit> kitMap) { } @Override public Kit createKit(String name, PlayerInventory playerInventory) { return null; } @Override public void saveKit(Kit kit) { } @Override public void deleteKit(Kit kit) { } @Override public void enableStorage() { } @Override public void disableStorage() { } }
1,240
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
FlatFileStorage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/flatfile/FlatFileStorage.java
package me.patothebest.gamecore.storage.flatfile; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.kit.Kit; import me.patothebest.gamecore.lang.CoreLocaleManager; import me.patothebest.gamecore.logger.InjectParentLogger; import me.patothebest.gamecore.permission.PermissionGroupManager; import me.patothebest.gamecore.player.CorePlayer; import me.patothebest.gamecore.storage.StorageException; import me.patothebest.gamecore.storage.StorageManager; import me.patothebest.gamecore.util.Callback; import me.patothebest.gamecore.util.Utils; import org.bukkit.ChatColor; import org.bukkit.inventory.PlayerInventory; import javax.inject.Inject; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; public final class FlatFileStorage implements IFlatFileStorage { private final Map<String, PlayerProfileFile> playerfiles = new HashMap<>(); private final CorePlugin plugin; private final StorageManager storageManager; private final Set<FlatFileEntity> coreSQLEntities; private final File kitDirectory = new File(Utils.PLUGIN_DIR, "kits"); private final PermissionGroupManager permissionGroupManager; @InjectParentLogger(parent = StorageManager.class) private Logger logger; @Inject private FlatFileStorage(CorePlugin plugin, StorageManager storageManager, Set<FlatFileEntity> coreSQLEntities, PermissionGroupManager permissionGroupManager) { this.plugin = plugin; this.storageManager = storageManager; this.coreSQLEntities = coreSQLEntities; this.permissionGroupManager = permissionGroupManager; } @Override public void loadPlayers(Callback<CorePlayer> playerCallback) { List<CorePlayer> players = new CopyOnWriteArrayList<>(); File playerDir = new File(Utils.PLUGIN_DIR, "players/"); if(playerDir.listFiles() != null) { for(File file : playerDir.listFiles()) { //TODO: Finish } } } @Override public void load(CorePlayer player, boolean async) { if(playerfiles.containsKey(player.getName())) { return; } PlayerProfileFile file = new PlayerProfileFile(storageManager.isUseUUIDs() ? player.getUniqueId().toString() : player.getName()); player.setLocale(CoreLocaleManager.getLocale(file.getString("locale", CoreLocaleManager.DEFAULT_LOCALE.getName()))); try { for (FlatFileEntity flatFileEntity : coreSQLEntities) { flatFileEntity.loadPlayer(player, file); } } catch (StorageException e) { e.printStackTrace(); } playerfiles.put(player.getName(), file); player.setAllDataLoaded(true); } @Override public void save(CorePlayer player) { if(!playerfiles.containsKey(player.getName())) { playerfiles.put(player.getName(), new PlayerProfileFile(storageManager.isUseUUIDs() ? player.getUniqueId().toString() : player.getName())); } PlayerProfileFile file = playerfiles.get(player.getName()); file.set("locale", player.getLocale().getName()); file.set("name", player.getName()); try { for (FlatFileEntity flatFileEntity : coreSQLEntities) { flatFileEntity.savePlayer(player, file); } } catch (StorageException e) { e.printStackTrace(); } file.save(); } @Override public void unCache(CorePlayer player) { if(!playerfiles.containsKey(player.getName())) { return; } playerfiles.remove(player.getName()); player.deleteObservers(); } @Override public void delete(CorePlayer player) { PlayerProfileFile file; if(playerfiles.containsKey(player.getName())) { file = playerfiles.get(player.getName()); } else { file = new PlayerProfileFile(player.getName()); } file.delete(); unCache(player); } @Override public void loadKits(Map<String, Kit> kitMap) { if(kitDirectory.listFiles() != null) { for(File file : kitDirectory.listFiles()) { try { Kit kit = new Kit(plugin, permissionGroupManager, file.getName().replace(".yml", "")); kitMap.put(kit.getKitName(), kit); logger.info("Loaded kit " + kit.getKitName()); } catch(Throwable t) { logger.log(Level.SEVERE, ChatColor.RED + "Could not load kit " + file.getName(), t); } } } } @Override public Kit createKit(String name, PlayerInventory playerInventory) { return new Kit(plugin, permissionGroupManager, name, playerInventory.getArmorContents(), playerInventory.getContents()); } @Override public void saveKits(Map<String, Kit> kitMap) { kitMap.values().forEach(Kit::saveToFile); } @Override public void saveKit(Kit kit) { kit.saveToFile(); } @Override public void deleteKit(Kit kit) { kit.delete(); } @Override public void enableStorage() { if(!kitDirectory.exists()) { kitDirectory.mkdirs(); } } @Override public void disableStorage() { // we don't leave streams open nor connections // opened so we don't have to close anything } }
5,601
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
IFlatFileStorage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/flatfile/IFlatFileStorage.java
package me.patothebest.gamecore.storage.flatfile; import me.patothebest.gamecore.storage.Storage; public interface IFlatFileStorage extends Storage { }
155
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PlayerProfileFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/flatfile/PlayerProfileFile.java
package me.patothebest.gamecore.storage.flatfile; import me.patothebest.gamecore.file.FlatFile; import java.io.BufferedWriter; import java.io.IOException; public class PlayerProfileFile extends FlatFile { PlayerProfileFile(String playername) { super("players/" + playername); load(); } @Override public void writeFile(BufferedWriter writer) throws IOException { // Don't write anything to the file } }
451
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
FlatFileEntity.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/storage/flatfile/FlatFileEntity.java
package me.patothebest.gamecore.storage.flatfile; import me.patothebest.gamecore.storage.StorageEntity; import me.patothebest.gamecore.storage.StorageException; /** * * The interface used for all FlatFile entities * <p> * The entity ony requires a Map<String, Object> for * loading and saving the player * <p> * The player is loaded as a Map<String, Object> and * from there we just need to cast the objects or parse * the objects * <p> * To save the player, all the information is stored in * a single Map<String, Object> which is saved into * YAML format. */ public interface FlatFileEntity extends StorageEntity<PlayerProfileFile, PlayerProfileFile, StorageException> { }
691
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GUIPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/GUIPage.java
package me.patothebest.gamecore.gui.inventory; import me.patothebest.gamecore.gui.inventory.button.NullButton; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.gui.inventory.page.FailedPage; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.timings.TimingsData; import me.patothebest.gamecore.timings.TimingsManager; import me.patothebest.gamecore.util.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.util.HashMap; public abstract class GUIPage implements Listener { private final HashMap<Integer, GUIButton> buttons = new HashMap<>(); private final int size; protected final Player player; protected final Plugin plugin; private boolean overrideClose = false; private String name; private Inventory menu; protected boolean blockInventoryMovement = true; protected GUIPage(Plugin plugin, Player player, ILang locale, int size, boolean override) { this(plugin, player, locale.getMessage(player), size); this.overrideClose = override; } protected GUIPage(Plugin plugin, Player player, ILang locale, int size) { this(plugin, player, locale.getMessage(player), size); } protected GUIPage(Plugin plugin, Player player, String rawName, int size, boolean override) { this(plugin, player, rawName, size); this.overrideClose = override; } protected GUIPage(Plugin plugin, Player player, String rawName, int size) { this.player = player; Utils.invokeStaticMethod(Utils.getCBSClass("event.CraftEventFactory"), "handleInventoryCloseEvent", new Class[] {Utils.getNMSClass("EntityHuman")}, Utils.invokeMethod(player, "getHandle", new Class[] {}, null)); this.plugin = plugin; this.size = size; this.name = (rawName.length() > 32 ? rawName.substring(0, 32) : rawName); plugin.getServer().getPluginManager().registerEvents(this, plugin); this.menu = Bukkit.getServer().createInventory(null, size, name); Utils.setFieldValue(Utils.getNMSClass("EntityHuman"), "activeContainer", Utils.invokeMethod(player, "getHandle", new Class[] {}, null), Utils.getFieldValue(Utils.getNMSClass("EntityHuman"), "defaultContainer", Utils.invokeMethod(player, "getHandle", new Class[] {}, null))); this.player.openInventory(menu); } public final void build() { if(!getPlayer().isOnline()) { destroy(); return; } TimingsData timing = TimingsManager.create("Menu '" + name + "' (" + getClass().getSimpleName() + ") for " + getPlayer().getName()); try { buildPage(); getPlayer().updateInventory(); } catch (Throwable t) { t.printStackTrace(); new FailedPage(plugin, getPlayer(), CoreLang.GUI_ERROR_INIT.getMessage(player), ChatColor.RED + t.getMessage()); } timing.stop(50); } protected abstract void buildPage(); public Plugin getPlugin() { return plugin; } public Player getPlayer() { return player; } public void addPlaceholder(ItemStack itemStack) { addButton(new PlaceHolder(itemStack)); } public void addPlaceholder(ItemStack itemStack, int slot) { addButton(new PlaceHolder(itemStack), slot); } public void addButton(GUIButton button, int slot) { if(slot >= size) { return; } if(!(button instanceof NullButton)) { menu.setItem(slot, button.getItem()); } buttons.put(slot, button); } public void addButton(GUIButton button) { int slot = 0; while(!isFree(slot) && slot < size) { slot++; } if(slot > size || !isFree(slot)) { Utils.printError("Could not find empty slot", "Button= " + button.toString(), "Slot= " + slot, "Menu= " + toString()); return; } if(!(button instanceof NullButton)) { menu.setItem(slot, button.getItem()); } buttons.put(slot, button); } public void removeButton(int slot) { menu.setItem(slot, null); if (buttons.get(slot) != null) { buttons.get(slot).destroy(); } buttons.remove(slot); } private void removeAll() { for (int i = 0; i <= size - 1; i++) { removeButton(i); } buttons.clear(); } public void refresh() { removeAll(); build(); } public void setTitle(String title) { removeAll(); name = (title.length() > 32 ? title.substring(0, 32) : title); this.menu = Bukkit.getServer().createInventory(null, size, name); Utils.setFieldValue(Utils.getNMSClass("EntityHuman"), "activeContainer", Utils.invokeMethod(player, "getHandle", new Class[] {}, null), Utils.getFieldValue(Utils.getNMSClass("EntityHuman"), "defaultContainer", Utils.invokeMethod(player, "getHandle", new Class[] {}, null))); player.openInventory(menu); build(); } public boolean isFree(int slot) { return !buttons.containsKey(slot); } protected void onInventoryCloseOverride() { } @EventHandler public void onPlayerCloseInventory(InventoryCloseEvent event) { if (overrideClose) { onInventoryCloseOverride(); return; } Player player = (Player) event.getPlayer(); if (!this.player.getOpenInventory().getTitle().equalsIgnoreCase(name)) { return; } if (this.player == player) { destroy(); destroyInternal(); } } @EventHandler public void onDropItem(PlayerDropItemEvent event) { if (event.getPlayer() != this.getPlayer()) { return; } if (!this.player.getOpenInventory().getTitle().equalsIgnoreCase(name)) { return; } event.setCancelled(true); } @EventHandler public void onClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); if (this.player != player) { return; } if (!this.player.getOpenInventory().getTitle().equalsIgnoreCase(name)) { return; } event.setCancelled(blockInventoryMovement); if (!buttons.containsKey(event.getRawSlot())) { return; } event.setCancelled(true); GUIButton guiButton = buttons.get(event.getRawSlot()); TimingsData timing = TimingsManager.create(null); try { guiButton.click(event.getClick(), this); } catch(Throwable t) { t.printStackTrace(); player.sendMessage(ChatColor.RED + t.getMessage()); } if (timing.end(50)) { timing.setTiming("Menu '" + name + "' click (" + getClass().getSimpleName() + ") Button (" + (guiButton.getItem() == null ? "null item" : guiButton.getItem().toString()) + ")" + "for " + getPlayer().getName()); timing.print(); } } public void destroy() {} public void destroyInternal() { HandlerList.unregisterAll(this); this.buttons.values().forEach(GUIButton::destroy); this.buttons.clear(); } public int getSize() { return size; } @Override public String toString() { return "GUIPage{" + "buttonsSize=" + buttons.size() + ", size=" + size + ", user=" + player + ", plugin=" + plugin + ", overrideClose=" + overrideClose + ", name='" + name + '\'' + ", blockInventoryMovement=" + blockInventoryMovement + '}'; } }
8,276
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GUIUpdater.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/GUIUpdater.java
package me.patothebest.gamecore.gui.inventory; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Singleton public class GUIUpdater { private final Map<Class<? extends GUIPage>, List<GUIPage>> guis = new HashMap<>(); public void register(GUIPage guiPage) { if(!guis.containsKey(guiPage.getClass())) { guis.put(guiPage.getClass(), new ArrayList<>()); } guis.get(guiPage.getClass()).add(guiPage); } public void refresh(GUIPage guiPage) { if(!guis.containsKey(guiPage.getClass())) { throw new IllegalArgumentException("GUI " + guiPage.getClass().getCanonicalName() + " is not registered!"); } guis.get(guiPage.getClass()).forEach(GUIPage::refresh); } public void unregister(GUIPage guiPage) { if(!guis.containsKey(guiPage.getClass())) { throw new IllegalArgumentException("GUI " + guiPage.getClass().getCanonicalName() + " is not registered!"); } guis.get(guiPage.getClass()).remove(guiPage); } }
1,125
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GUIButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/GUIButton.java
package me.patothebest.gamecore.gui.inventory; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public interface GUIButton { void click(ClickType click, GUIPage page); void destroy(); ItemStack getItem(); }
257
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GUIFactory.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/GUIFactory.java
package me.patothebest.gamecore.gui.inventory; import org.bukkit.entity.Player; public interface GUIFactory<Menu extends GUIPage> { Menu create(Player player); }
170
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DescriptionEditorMainPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/descriptioneditor/DescriptionEditorMainPage.java
package me.patothebest.gamecore.gui.inventory.descriptioneditor; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.gui.anvil.AnvilSlot; import me.patothebest.gamecore.gui.inventory.button.AnvilButton; import me.patothebest.gamecore.gui.inventory.button.AnvilButtonAction; import me.patothebest.gamecore.gui.inventory.page.GUIMultiPage; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class DescriptionEditorMainPage extends GUIMultiPage { private final DescriptionEdition descriptionEdition; public DescriptionEditorMainPage(Plugin plugin, Player player, DescriptionEdition descriptionEdition) { super(plugin, player, CoreLang.GUI_DESCRIPTION_EDITOR_MAIN_TITLE.getMessage(player)); this.descriptionEdition = descriptionEdition; build(); } @Override protected void buildContent() { final int[] slot = {0}; descriptionEdition.getDescription().stream().skip(pageSize*currentPage).limit(pageSize).forEach(descriptionLine -> { addButton(new SimpleButton(new ItemStackBuilder().material(Material.WRITABLE_BOOK).name(ChatColor.translateAlternateColorCodes('&', descriptionLine))).action(() -> new DescriptionEditorLine(plugin, player, descriptionEdition, descriptionLine)), slot[0]); slot[0]++; }); addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer())).action(descriptionEdition::onBack), 47); addButton(new AnvilButton(new ItemStackBuilder().material(Material.EMERALD).name(getPlayer(), CoreLang.GUI_DESCRIPTION_EDITOR_MAIN_TITLE)).action(new AnvilButtonAction() { @Override public void onConfirm(String output) { descriptionEdition.getDescription().add(output); descriptionEdition.onUpdate(); new DescriptionEditorLine(plugin, player, descriptionEdition, output); } @Override public void onCancel() { new DescriptionEditorMainPage(plugin, player, descriptionEdition); } }).slot(AnvilSlot.INPUT_LEFT, new ItemStackBuilder().material(Material.NAME_TAG).name("lore")),51); } @Override protected int getListCount() { return descriptionEdition.getDescription().size(); } }
2,530
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DescriptionEditorLine.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/descriptioneditor/DescriptionEditorLine.java
package me.patothebest.gamecore.gui.inventory.descriptioneditor; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.gui.anvil.AnvilSlot; import me.patothebest.gamecore.gui.inventory.GUIPage; import me.patothebest.gamecore.gui.inventory.button.AnvilButton; import me.patothebest.gamecore.gui.inventory.button.AnvilButtonAction; import me.patothebest.gamecore.gui.inventory.button.BackButton; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class DescriptionEditorLine extends GUIPage { private final DescriptionEdition descriptionEdition; private final String line; public DescriptionEditorLine(Plugin plugin, Player player, DescriptionEdition descriptionEdition, String line) { super(plugin, player, CoreLang.GUI_DESCRIPTION_EDITOR_TITLE.getMessage(player), 9); this.descriptionEdition = descriptionEdition; this.line = line; build(); } @Override protected void buildPage() { addButton(new BackButton(getPlayer()).action(() -> new DescriptionEditorMainPage(plugin, player, descriptionEdition)), 0); addButton(new AnvilButton(new ItemStackBuilder().material(Material.NAME_TAG).name(getPlayer(), CoreLang.GUI_DESCRIPTION_EDITOR_RENAME)).action(new AnvilButtonAction() { @Override public void onConfirm(String output) { descriptionEdition.getDescription().remove(line); descriptionEdition.getDescription().add(output); descriptionEdition.onUpdate(); } @Override public void onCancel() { new DescriptionEditorLine(plugin, player, descriptionEdition, line); } }).slot(AnvilSlot.INPUT_LEFT, new ItemStackBuilder().material(Material.NAME_TAG).name(line)), 4); addButton(new SimpleButton(new ItemStackBuilder().material(Material.TNT).name(getPlayer(), CoreLang.GUI_DESCRIPTION_EDITOR_DELETE)).action(() -> { descriptionEdition.getDescription().remove(line); descriptionEdition.onUpdate(); new DescriptionEditorLine(plugin, player, descriptionEdition, line); }), 8); } }
2,370
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DescriptionEdition.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/descriptioneditor/DescriptionEdition.java
package me.patothebest.gamecore.gui.inventory.descriptioneditor; import me.patothebest.gamecore.gui.inventory.page.GenericGUI; import java.util.List; public interface DescriptionEdition extends GenericGUI { List<String> getDescription(); void onUpdate(); }
271
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DynamicPaginatedUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/DynamicPaginatedUI.java
package me.patothebest.gamecore.gui.inventory.page; import com.google.common.collect.Iterators; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.util.Utils; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.function.Supplier; public abstract class DynamicPaginatedUI<T> extends GUIMultiPage { private final Supplier<Collection<? extends T>> listProvider; protected DynamicPaginatedUI(Plugin plugin, Player player, String rawName, Supplier<Collection<? extends T>> listProvider) { super(plugin, player, rawName, Math.min(54, Utils.transformToInventorySize(listProvider.get().size()))); this.listProvider = listProvider; } protected DynamicPaginatedUI(Plugin plugin, Player player, ILang title, Supplier<Collection<? extends T>> listProvider) { super(plugin, player, title, Math.min(54, Utils.transformToInventorySize(listProvider.get().size()))); this.listProvider = listProvider; } protected DynamicPaginatedUI(Plugin plugin, Player player, String rawName, Supplier<Collection<? extends T>> listProvider, int size) { super(plugin, player, rawName, size); this.listProvider = listProvider; } protected DynamicPaginatedUI(Plugin plugin, Player player, ILang title, Supplier<Collection<? extends T>> listProvider, int size) { super(plugin, player, title, size); this.listProvider = listProvider; } @SuppressWarnings("unchecked") @Override protected final void buildContent() { int slot = 0; Collection<? extends T> results = listProvider.get(); final int start = pageSize * currentPage; final int end = Math.min(pageSize * (currentPage + 1), results.size()); if (results instanceof List) { List<? extends T> list = (List<? extends T>) results; for (int index = start; index < end; index++) { addButton(createButton(list.get(index)), slot++); } } else { final Iterator<? extends T> iterator = results.iterator(); for (int index = Iterators.advance(iterator, start); index < end; index++) { addButton(createButton(iterator.next()), slot++); } } } protected abstract GUIButton createButton(T item); @Override protected int getListCount() { if(listProvider.get().size() <= 45) { return -1; } return listProvider.get().size(); } }
2,669
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DualListPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/DualListPage.java
package me.patothebest.gamecore.gui.inventory.page; import com.google.common.collect.Iterators; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.StainedGlassPane; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.function.Supplier; public abstract class DualListPage<T> extends GUIMultiPage { private final Supplier<Collection<? extends T>> leftListProvider; private final Supplier<Collection<? extends T>> rightListProvider; private int size = 0; protected DualListPage(Plugin plugin, Player player, String rawName, Supplier<Collection<? extends T>> leftListProvider, Supplier<Collection<? extends T>> rightListProvider) { super(plugin, player, rawName, 54); this.leftListProvider = leftListProvider; this.rightListProvider = rightListProvider; this.pageSize = 16; } protected DualListPage(Plugin plugin, Player player, ILang title, Supplier<Collection<? extends T>> leftListProvider, Supplier<Collection<? extends T>> rightListProvider) { super(plugin, player, title, 54); this.leftListProvider = leftListProvider; this.rightListProvider = rightListProvider; this.pageSize = 16; } @SuppressWarnings("unchecked") @Override protected final void buildContent() { buildHeader(); Collection<? extends T> results = leftListProvider.get(); final int start = pageSize * currentPage; final int end = Math.min(pageSize * (currentPage + 1), results.size()); int slot = 9; if (results instanceof List) { List<? extends T> list = (List<? extends T>) results; for (int index = start; index < end; index++) { addButton(createLeftButton(list.get(index)), (index - start)/4*5 + slot); slot++; } } else { final Iterator<? extends T> iterator = results.iterator(); for (int index = Iterators.advance(iterator, start); index < end; index++) { addButton(createLeftButton(iterator.next()), (index - start)/4*5 + slot); slot++; } } Collection<? extends T> rightResults = rightListProvider.get(); final int rightEnd = Math.min(pageSize * (currentPage + 1), rightResults.size()); slot = 9; if (rightResults instanceof List) { List<? extends T> list = (List<? extends T>) rightResults; for (int index = start; index < rightEnd; index++) { addButton(createRightButton(list.get(index)), (index - start)/4*5 + slot + 5); slot++; } } else { final Iterator<? extends T> iterator = rightResults.iterator(); for (int index = Iterators.advance(iterator, start); index < rightEnd; index++) { addButton(createRightButton(iterator.next()), (index - start)/4*5 + slot + 5); slot++; } } for (int i = 13; i < 45; i+=9) { addButton(new PlaceHolder(new ItemStackBuilder(StainedGlassPane.GRAY).name("")), i); } size = Math.max(results.size(), rightResults.size()) + 20; buildFooter(); } protected abstract GUIButton createLeftButton(T item); protected abstract GUIButton createRightButton(T item); protected void buildHeader() {} protected void buildFooter() {} @Override protected int getListCount() { if (size <= 36) { return -1; } return size; } }
3,866
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
GUIMultiPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/GUIMultiPage.java
package me.patothebest.gamecore.gui.inventory.page; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public abstract class GUIMultiPage extends GUIPage { protected int currentPage; protected int pageSize = 45; protected GUIMultiPage(Plugin plugin, Player player, String rawName) { this(plugin, player, rawName, 54); } protected GUIMultiPage(Plugin plugin, Player player, String rawName, int size) { super(plugin, player, rawName, size); } protected GUIMultiPage(Plugin plugin, Player player, ILang title) { this(plugin, player, title, 54); } protected GUIMultiPage(Plugin plugin, Player player, ILang title, int size) { super(plugin, player, title, size); } public void buildPage() { ItemStack nextPage = new ItemStackBuilder().material(Material.PAPER).amount(currentPage + 2).name(CoreLang.GUI_NEXT_PAGE.replace(getPlayer(), (currentPage + 2))); ItemStack previousPage = new ItemStackBuilder().material(Material.PAPER).amount(currentPage).name(CoreLang.GUI_PREVIOUS_PAGE.replace(getPlayer(), currentPage)); ItemStack currentPageItem = new ItemStackBuilder().material(Material.PAPER).amount(currentPage + 1).name(CoreLang.GUI_YOU_ARE_ON.replace(getPlayer(), (currentPage + 1))); buildContent(); if ((currentPage + 1) * pageSize < getListCount()) { addButton(new SimpleButton(nextPage).action(() -> {currentPage++;refresh();}), 53); } if (currentPage != 0) { addButton(new SimpleButton(previousPage).action(() -> {currentPage--;refresh();}), 45); } if(getListCount() != -1) { addButton(new PlaceHolder(currentPageItem), 49); } } protected abstract void buildContent(); protected abstract int getListCount(); }
2,278
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ConfirmationPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/ConfirmationPage.java
package me.patothebest.gamecore.gui.inventory.page; import me.patothebest.gamecore.gui.inventory.GUIPage; import me.patothebest.gamecore.gui.inventory.button.ConfirmationPageButton; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public abstract class ConfirmationPage extends GUIPage { private final static ItemStack CONFIRM = new ItemStackBuilder().material(Material.EMERALD_BLOCK).name(ChatColor.GREEN + "CONFIRM"); private final static ItemStack CANCEL = new ItemStackBuilder().material(Material.REDSTONE_BLOCK).name(ChatColor.RED + "CANCEL"); private ItemStack infoTop; private ItemStack infoMiddle; public ConfirmationPage(Plugin plugin, Player player, ItemStack infoTop, ItemStack infoMiddle) { super(plugin, player, "Confirm?", 54); this.infoTop = infoTop; this.infoMiddle = infoMiddle; build(); } public void buildPage() { addButton(new PlaceHolder(infoTop), 4); addButton(new PlaceHolder(infoMiddle), 22); addButton(new ConfirmationPageButton(true, CONFIRM), 27); addButton(new ConfirmationPageButton(true, CONFIRM), 28); addButton(new ConfirmationPageButton(true, CONFIRM), 29); addButton(new ConfirmationPageButton(true, CONFIRM), 36); addButton(new ConfirmationPageButton(true, CONFIRM), 37); addButton(new ConfirmationPageButton(true, CONFIRM), 38); addButton(new ConfirmationPageButton(true, CONFIRM), 45); addButton(new ConfirmationPageButton(true, CONFIRM), 46); addButton(new ConfirmationPageButton(true, CONFIRM), 47); addButton(new ConfirmationPageButton(false, CANCEL), 33); addButton(new ConfirmationPageButton(false, CANCEL), 34); addButton(new ConfirmationPageButton(false, CANCEL), 35); addButton(new ConfirmationPageButton(false, CANCEL), 42); addButton(new ConfirmationPageButton(false, CANCEL), 43); addButton(new ConfirmationPageButton(false, CANCEL), 44); addButton(new ConfirmationPageButton(false, CANCEL), 51); addButton(new ConfirmationPageButton(false, CANCEL), 52); addButton(new ConfirmationPageButton(false, CANCEL), 53); } public void destroy() { infoMiddle = null; infoTop = null; } public abstract void onConfirm(); public abstract void onCancel(); }
2,625
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
StaticPaginatedUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/StaticPaginatedUI.java
package me.patothebest.gamecore.gui.inventory.page; import com.google.common.collect.Iterators; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.gui.inventory.GUIButton; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.function.Supplier; public abstract class StaticPaginatedUI<T> extends GUIMultiPage { private final Supplier<Collection<? extends T>> listProvider; protected StaticPaginatedUI(Plugin plugin, Player player, String rawName, Supplier<Collection<? extends T>> listProvider) { super(plugin, player, rawName, 54); this.listProvider = listProvider; } protected StaticPaginatedUI(Plugin plugin, Player player, ILang title, Supplier<Collection<? extends T>> listProvider) { super(plugin, player, title, 54); this.listProvider = listProvider; } @SuppressWarnings("unchecked") @Override protected final void buildContent() { int slot = 0; Collection<? extends T> results = listProvider.get(); final int start = pageSize * currentPage; final int end = Math.min(pageSize * (currentPage + 1), results.size()); if (results instanceof List) { List<? extends T> list = (List<? extends T>) results; for (int index = start; index < end; index++) { addButton(createButton(list.get(index)), slot++); } } else { final Iterator<? extends T> iterator = results.iterator(); for (int index = Iterators.advance(iterator, start); index < end; index++) { addButton(createButton(iterator.next()), slot++); } } buildFooter(); } protected abstract GUIButton createButton(T item); protected void buildFooter() {} @Override protected int getListCount() { return listProvider.get().size(); } }
2,002
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SuccessPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/SuccessPage.java
package me.patothebest.gamecore.gui.inventory.page; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public abstract class SuccessPage extends GUIPage { public SuccessPage(Plugin plugin, Player player) { super(plugin, player, "Success!", 54); build(); } public SuccessPage(Plugin plugin, Player player, boolean b) { super(plugin, player, "Success!", 54, true); build(); } public void buildPage() { ItemStack confirm = new ItemStackBuilder().material(Material.EMERALD_BLOCK).name(ChatColor.GREEN + "Success!"); for (int i = 0; i < 54; i++) { addButton(new PlaceHolder(confirm), i); } } }
999
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
FailedPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/page/FailedPage.java
package me.patothebest.gamecore.gui.inventory.page; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public class FailedPage extends GUIPage { private String[] reason; public FailedPage(Plugin plugin, Player player, String... reason) { super(plugin, player, "Error!", 54); this.reason = reason; build(); } public void buildPage() { ItemStack confirm = new ItemStackBuilder().material(Material.REDSTONE_BLOCK).name(ChatColor.RED + "ERROR:").lore(reason); for (int i = 0; i < 54; i++) { addButton(new PlaceHolder(confirm), i); } } public void destroy() { this.reason = null; } }
995
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ItemMainPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/itemeditor/ItemMainPage.java
package me.patothebest.gamecore.gui.inventory.itemeditor; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public class ItemMainPage extends GUIPage { private final ItemStackBuilder originalItem; private final UpdateAction updateAction; public ItemMainPage(Plugin plugin, Player player, ItemStack originalItem, UpdateAction updateAction) { super(plugin, player, CoreLang.GUI_EDIT_ITEM_TITLE.getMessage(player), 9); this.originalItem = new ItemStackBuilder(originalItem); this.updateAction = updateAction; build(); } @Override public void buildPage() { ItemStack changeDisplayItem = new ItemStackBuilder().material(Material.ITEM_FRAME).name(CoreLang.GUI_EDIT_ITEM_CHANGE_ITEM.getMessage(getPlayer())); ItemStack changeStackAmount = new ItemStackBuilder().material(Material.WHITE_WOOL).name(CoreLang.GUI_EDIT_ITEM_CHANGE_AMOUNT.getMessage(getPlayer())).amount(64); addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer()), updateAction::onBack), 0); addButton(new SimpleButton(originalItem), 3); addButton(new SimpleButton(changeDisplayItem, () -> new ItemPage(plugin, player, originalItem, updateAction)), 6); addButton(new SimpleButton(changeStackAmount, () -> new ChangeItemAmount(plugin, player, originalItem, updateAction)), 8); } }
1,704
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ItemPage.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/itemeditor/ItemPage.java
package me.patothebest.gamecore.gui.inventory.itemeditor; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.gui.anvil.AnvilSlot; import me.patothebest.gamecore.gui.inventory.button.AnvilButton; import me.patothebest.gamecore.gui.inventory.button.AnvilButtonAction; import me.patothebest.gamecore.gui.inventory.page.GUIMultiPage; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class ItemPage extends GUIMultiPage { private static final List<Material> materials = new ArrayList<>(); private final String filter; private final ItemStackBuilder itemStack; private final UpdateAction updateAction; public ItemPage(Plugin plugin, Player player, String filter, ItemStackBuilder itemStack, UpdateAction updateAction) { super(plugin, player, "Choose an item"); this.filter = filter; this.updateAction = updateAction; this.itemStack = itemStack; build(); } public ItemPage(Plugin plugin, Player player, ItemStackBuilder itemStack, UpdateAction updateAction) { super(plugin, player, "Choose an item"); this.updateAction = updateAction; this.filter = null; this.itemStack = itemStack; build(); } @Override protected void buildContent() { final int[] i = {0}; Stream<Material> stream = materials.stream(); if (filter != null) { stream = stream.filter(material -> material.name().toLowerCase().contains(filter.toLowerCase())); } stream.skip(currentPage*pageSize).limit(pageSize).forEach(material -> { addButton(new SimpleButton(new ItemStackBuilder().material(material), () -> { updateAction.onUpdate(itemStack.material(material)); new ItemMainPage(plugin, player, itemStack, updateAction); }), i[0]); i[0]++; }); addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer()), () -> new ItemMainPage(plugin, player, itemStack, updateAction)), 47); addButton(new AnvilButton(new ItemStackBuilder().material(Material.OAK_SIGN).name(getPlayer(), CoreLang.GUI_EDIT_ITEM_FILTER)).action(new AnvilButtonAction() { @Override public void onConfirm(String output) { new ItemPage(plugin, player, output, itemStack, updateAction); } @Override public void onCancel() { new ItemPage(plugin, player, itemStack, updateAction); } }).slot(AnvilSlot.INPUT_LEFT, new ItemStackBuilder().material(Material.OAK_SIGN).name("Dirt")), 51); } @Override protected int getListCount() { if (filter != null) { return (int) materials.stream().filter(material -> material.name().toLowerCase().contains(filter.toLowerCase())).count(); } return materials.size(); } static { Arrays.asList(Material.values()).forEach(material -> { if (material.isItem() && material.isSupported() && material.parseMaterial() != null) { materials.add(material); } }); } }
3,460
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
UpdateAction.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/itemeditor/UpdateAction.java
package me.patothebest.gamecore.gui.inventory.itemeditor; import me.patothebest.gamecore.gui.inventory.page.GenericGUI; import org.bukkit.inventory.ItemStack; public interface UpdateAction extends GenericGUI { void onUpdate(ItemStack itemStack); }
256
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ChangeItemAmount.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/itemeditor/ChangeItemAmount.java
package me.patothebest.gamecore.gui.inventory.itemeditor; import me.patothebest.gamecore.gui.inventory.button.SimpleButton; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.gui.inventory.GUIPage; import me.patothebest.gamecore.gui.inventory.button.IncrementingButton; import me.patothebest.gamecore.gui.inventory.button.IncrementingButtonAction; import me.patothebest.gamecore.gui.inventory.button.PlaceHolder; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class ChangeItemAmount extends GUIPage { private final ItemStackBuilder itemStack; private final UpdateAction updateAction; public ChangeItemAmount(Plugin plugin, Player player, ItemStackBuilder itemStack, UpdateAction updateAction) { super(plugin, player, CoreLang.GUI_CHANGE_AMOUNT_TITLE.getMessage(player), 9); this.itemStack = itemStack; this.updateAction = updateAction; build(); } @Override public void buildPage() { IncrementingButtonAction onUpdateItemSize = (amount) -> { if(itemStack.getAmount()+amount <= 0) { itemStack.amount(1); } else if(itemStack.getAmount()+amount > 64) { itemStack.amount(64); } else { itemStack.amount(itemStack.getAmount() + amount); } updateAction.onUpdate(itemStack); refresh(); }; addButton(new IncrementingButton(-10, onUpdateItemSize), 1); addButton(new IncrementingButton(-5, onUpdateItemSize), 2); addButton(new IncrementingButton(-1, onUpdateItemSize), 3); addButton(new IncrementingButton(1, onUpdateItemSize), 5); addButton(new IncrementingButton(5, onUpdateItemSize), 6); addButton(new IncrementingButton(10, onUpdateItemSize), 7); addButton(new SimpleButton(new ItemStackBuilder().createBackItem(getPlayer()), () -> new ItemMainPage(plugin, player, itemStack, updateAction)), 0); addButton(new PlaceHolder(itemStack), 4); addButton(new SimpleButton(new ItemStackBuilder().material(Material.TNT).name(CoreLang.GUI_CHANGE_AMOUNT_RESET.getMessage(getPlayer())), () -> { itemStack.setAmount(1); updateAction.onUpdate(itemStack); refresh(); }), 8); } }
2,420
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ClickTypeButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/ClickTypeButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class ClickTypeButton implements GUIButton { private ItemStack item; protected ClickTypeAction action; public ClickTypeButton(ItemStack item) { this.item = item; } public ClickTypeButton(ItemStack item, ClickTypeAction buttonAction) { this.item = item; this.action = buttonAction; } public ClickTypeButton action(ClickTypeAction action) { this.action = action; return this; } public ItemStack getItem() { return item; } public void click(ClickType clickType, GUIPage page) { if(action == null) { return; } action.onClick(clickType); } public void destroy() { this.action = null; this.item = null; } }
1,022
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PlaceHolder.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/PlaceHolder.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class PlaceHolder implements GUIButton { private ItemStack item; public PlaceHolder(ItemStack item) { this.item = item; } public ItemStack getItem() { return item; } public void click(ClickType clickType, GUIPage page) { } public void destroy() { this.item = null; } }
592
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilButtonAction.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/AnvilButtonAction.java
package me.patothebest.gamecore.gui.inventory.button; public interface AnvilButtonAction { void onConfirm(String output); void onCancel(); }
151
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
NullButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/NullButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class NullButton implements GUIButton { @Override public void click(ClickType clickType, GUIPage page) { } @Override public void destroy() { } @Override public ItemStack getItem() { return null; } }
505
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
IncrementingButtonAction.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/IncrementingButtonAction.java
package me.patothebest.gamecore.gui.inventory.button; public interface IncrementingButtonAction { void onClick(int amount); }
133
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ConfirmButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/ConfirmButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.GUIPage; import me.patothebest.gamecore.gui.inventory.page.ConfirmationPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class ConfirmButton extends SimpleButton { private final ItemStack item1; private final ItemStack item2; public ConfirmButton(ItemStack item, ItemStack item1, ItemStack item2) { super(item); this.item1 = item1; this.item2 = item2; } public ConfirmButton(ItemStack item, ItemStack item1, ItemStack item2, ButtonAction buttonAction) { super(item, buttonAction); this.item1 = item1; this.item2 = item2; } @Override public void click(ClickType clickType, GUIPage page) { new ConfirmationPage(page.getPlugin(), page.getPlayer(), item1, item2) { @Override public void onConfirm() { if(action == null) { return; } action.onClick(); } @Override public void onCancel() { getPlayer().closeInventory(); } }; } }
1,231
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ClickTypeAction.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/ClickTypeAction.java
package me.patothebest.gamecore.gui.inventory.button; import org.bukkit.event.inventory.ClickType; @FunctionalInterface public interface ClickTypeAction { void onClick(ClickType clickType); }
200
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ConfirmationPageButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/ConfirmationPageButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.page.ConfirmationPage; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class ConfirmationPageButton implements GUIButton { private ItemStack item; private final boolean isConfirm; public ConfirmationPageButton(boolean isConfirm, ItemStack item) { this.item = item; this.isConfirm = isConfirm; } public ItemStack getItem() { return item; } public void click(ClickType clickType, GUIPage page) { ConfirmationPage confirmationPage = (ConfirmationPage) page; if (isConfirm) { confirmationPage.onConfirm(); } else { confirmationPage.onCancel(); } } public void destroy() { this.item = null; } }
978
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BackButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/BackButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import org.bukkit.entity.Player; public class BackButton extends SimpleButton { public BackButton(Player player) { super(new ItemStackBuilder().createBackItem(player)); } public BackButton(Player player, ButtonAction buttonAction) { super(new ItemStackBuilder().createBackItem(player), buttonAction); } }
453
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
RandomGlassPaneButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/RandomGlassPaneButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.StainedGlassPane; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class RandomGlassPaneButton implements GUIButton { public RandomGlassPaneButton(final GUIPage page, int slot) { } @Override public void click(ClickType clickType, GUIPage page) { } @Override public ItemStack getItem() { return new ItemStackBuilder(StainedGlassPane.getRandom()).name(" "); } @Override public void destroy() { } }
763
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ButtonAction.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/ButtonAction.java
package me.patothebest.gamecore.gui.inventory.button; @FunctionalInterface public interface ButtonAction { void onClick(); }
132
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/AnvilButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.anvil.AnvilGUI; import me.patothebest.gamecore.gui.anvil.AnvilSlot; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.Map; public class AnvilButton implements GUIButton { private final ItemStack item; private final Map<AnvilSlot, ItemStack> items; private AnvilButtonAction action; public AnvilButton(ItemStack item) { this.item = item; this.items = new HashMap<>(); } public AnvilButton(ItemStack item, AnvilButtonAction action) { this.item = item; this.action = action; this.items = new HashMap<>(); } @Override public void click(ClickType clickType, GUIPage page) { AnvilGUI gui = new AnvilGUI(page.getPlugin(), page.getPlayer(), event -> { if(event.getSlot() == AnvilSlot.OUTPUT){ action.onConfirm(event.getName()); } else { action.onCancel(); } }); page.destroy(); page.destroyInternal(); gui.getItems().putAll(items); items.clear(); gui.open(); } public AnvilButton action(AnvilButtonAction action) { this.action = action; return this; } @Override public ItemStack getItem() { return item; } public AnvilButton slot(final AnvilSlot slot, final ItemStack item) { this.items.put(slot, item); return this; } @Override public void destroy() { } }
1,721
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SimpleButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/SimpleButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class SimpleButton implements GUIButton { private final ItemStack item; protected ButtonAction action; public SimpleButton(ItemStack item) { this.item = item; } public SimpleButton(ItemStack item, ButtonAction buttonAction) { this.item = item; this.action = buttonAction; } public SimpleButton action(ButtonAction action) { this.action = action; return this; } public ItemStack getItem() { return item; } public void click(ClickType clickType, GUIPage page) { if(action == null) { return; } action.onClick(); } public void destroy() { } @Override public String toString() { return "SimpleButton{" + "item=" + item + ", action=" + action + '}'; } }
1,118
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
IncrementingButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/IncrementingButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.itemstack.ItemStackBuilder; import me.patothebest.gamecore.itemstack.Material; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.ChatColor; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class IncrementingButton implements GUIButton { private final ItemStack item; private int amount; private IncrementingButtonAction action; public IncrementingButton(ItemStackBuilder item, int amount) { this.item = item.amount(Math.abs(amount)); } public IncrementingButton(ItemStackBuilder item, int amount, IncrementingButtonAction buttonAction) { this.item = item.amount(Math.abs(amount)); this.action = buttonAction; } public IncrementingButton(int amount, IncrementingButtonAction buttonAction) { this.item = new ItemStackBuilder().material(amount < 0 ? Material.RED_STAINED_GLASS_PANE : Material.GREEN_STAINED_GLASS_PANE).amount(Math.abs(amount)).name((amount < 0 ? ChatColor.RED : ChatColor.GREEN + "+").toString() + amount); this.amount = amount; this.action = buttonAction; } public IncrementingButton setAction(IncrementingButtonAction action) { this.action = action; return this; } public ItemStack getItem() { return item; } public void click(ClickType clickType, GUIPage page) { if(action == null) { return; } action.onClick(amount); } public void destroy() { } }
1,657
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CloseButton.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/inventory/button/CloseButton.java
package me.patothebest.gamecore.gui.inventory.button; import me.patothebest.gamecore.gui.inventory.GUIButton; import me.patothebest.gamecore.gui.inventory.GUIPage; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class CloseButton implements GUIButton { private ItemStack item; public CloseButton(ItemStack item) { this.item = item; } public ItemStack getItem() { return item; } public void click(ClickType clickType, GUIPage page) { page.getPlayer().closeInventory(); } public void destroy() { this.item = null; } }
635
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilHandler.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/anvil/AnvilHandler.java
package me.patothebest.gamecore.gui.anvil; import me.patothebest.gamecore.util.Utils; import java.lang.reflect.Constructor; class AnvilHandler { // -------------------------------------------- // // CONSTANTS // -------------------------------------------- // static final Class<?> CHAT_MESSAGE_CLASS = Utils.getNMSClass("ChatMessage"); static final Class<?> ICHAT_BASE_COMPONENT_CLASS = Utils.getNMSClass("IChatBaseComponent"); static final Class<?> ICRAFTING_CLASS = Utils.getNMSClass("ICrafting"); static final Class<?> PACKET_PLAY_OUT_OPEN_WINDOW_CLASS = Utils.getNMSClass("PacketPlayOutOpenWindow"); static final Class<?> CONTAINERS_CLASS = Utils.getNMSClassOrNull("Containers"); private static final Class<?> ANVIL_CONTAINER_CLASS = Utils.getNMSClass("ContainerAnvil"); private static final Class<?> CONTAINER_CLASS = Utils.getNMSClass("Container"); private static final Class<?> ENTITY_HUMAN_CLASS = Utils.getNMSClass("EntityHuman"); private static final Class<?> BLOCK_POSITION_CLASS = Utils.getNMSClassOrNull("BlockPosition"); private static final Class<?> ENTITY_CLASS = Utils.getNMSClass("Entity"); private static final Class<?> CONTAINER_ACCESS_CLASS = Utils.getNMSClassOrNull("ContainerAccess"); private static final Class<?> WORLD_CLASS = Utils.getNMSClassOrNull("World"); private static Object BASE_BLOCK_POSITION; static Object ANVIL_CONTAINER; static { if(!Utils.SERVER_VERSION.contains("1_7")) { try { Constructor<?> constructor = BLOCK_POSITION_CLASS.getConstructor(int.class, int.class, int.class); BASE_BLOCK_POSITION = constructor.newInstance(0, 0, 0); } catch (Exception e) { e.printStackTrace(); } } if (CONTAINERS_CLASS != null) { ANVIL_CONTAINER = Utils.getFieldValue(CONTAINERS_CLASS, "ANVIL", null); } } // -------------------------------------------- // // CLASS METHODS // -------------------------------------------- // /** * Returns a new anvil container for the entityHuman. * This is achieved by creating a new ContainerAnvil using * the players position, world, and entityhuman. Then to * make everything work, we disable the checkReachable. This * is key to making it work. * * @param entityHuman the entity human object * @param containerId the container id * @return the anvil container */ static Object getNewAnvilContainer(Object entityHuman, int containerId) { Object anvilContainer = null; try { if(BLOCK_POSITION_CLASS == null) { anvilContainer = ANVIL_CONTAINER_CLASS.getConstructors()[0].newInstance(Utils.getFieldValue(ENTITY_HUMAN_CLASS, "inventory", entityHuman), Utils.getFieldValue(ENTITY_CLASS, "world", entityHuman), 0, 0, 0, entityHuman); } else if (CONTAINERS_CLASS == null) { anvilContainer = ANVIL_CONTAINER_CLASS.getConstructors()[0].newInstance(Utils.getFieldValue(ENTITY_HUMAN_CLASS, "inventory", entityHuman), Utils.getFieldValue(ENTITY_CLASS, "world", entityHuman), BASE_BLOCK_POSITION, entityHuman); } else { Object world = Utils.invokeMethod(entityHuman, Utils.getMethodNotDeclaredValue(ENTITY_HUMAN_CLASS, "getWorld")); Object containerAccess = Utils.invokeStaticMethod(CONTAINER_ACCESS_CLASS, "at", new Class[] {WORLD_CLASS, BLOCK_POSITION_CLASS}, world, BASE_BLOCK_POSITION); anvilContainer = ANVIL_CONTAINER_CLASS.getConstructors()[1].newInstance(containerId, Utils.getFieldValue(ENTITY_HUMAN_CLASS, "inventory", entityHuman), containerAccess); Object chatMessage = AnvilHandler.CHAT_MESSAGE_CLASS.getConstructor(String.class, Object[].class).newInstance("Repair & Name", new Object[0]); Utils.invokeMethod(anvilContainer, Utils.getMethodNotDeclaredValue(CONTAINER_CLASS, "setTitle", ICHAT_BASE_COMPONENT_CLASS), chatMessage); } Utils.setFieldValue(CONTAINER_CLASS, "checkReachable", anvilContainer, false); } catch (Exception e) { e.printStackTrace(); } return anvilContainer; } }
4,264
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilGUI.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/anvil/AnvilGUI.java
package me.patothebest.gamecore.gui.anvil; import me.patothebest.gamecore.util.Utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; public class AnvilGUI implements Listener{ // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final Player player; private final HashMap<AnvilSlot, ItemStack> items; private final AnvilClickEventHandler handler; private Inventory inv; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // public AnvilGUI(final Plugin plugin, final Player player, final AnvilClickEventHandler handler) { super(); this.items = new HashMap<>(); this.player = player; this.handler = handler; // register the events since when someone clicks // the anvil, the bukkit event is triggered Bukkit.getPluginManager().registerEvents(this, plugin); } // -------------------------------------------- // // EVENTS // -------------------------------------------- // @EventHandler public void onInventoryClick(InventoryClickEvent event) { // check for the inventory if (!event.getInventory().equals(inv)) { return; } // cancel the event to prevent items from being taken event.setCancelled(true); // get the clicked item ItemStack item = event.getCurrentItem(); // get the slot the item int slot = event.getRawSlot(); String name = ""; // if the item has a custom name... if (item != null && item.hasItemMeta()) { ItemMeta meta = item.getItemMeta(); if (meta.hasDisplayName()) { // ...get it and save it name = meta.getDisplayName(); } } // create the AnvilClickEvent AnvilClickEvent clickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name, player); // call it on the handler handler.onAnvilClick(clickEvent); // if the event is set to close on click... if (clickEvent.getWillClose()) { // ...close the inventory event.getWhoClicked().closeInventory(); } } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { Inventory inv = event.getInventory(); // check for the inventory if (!inv.equals(this.inv)) { return; } // clear the inventory and destroy inv.clear(); destroy(); } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { // check for the player if (!event.getPlayer().equals(getPlayer())) { return; } // destroy destroy(); } // -------------------------------------------- // // CLASS METHODS // -------------------------------------------- // public void open() { try { open0(); } catch (Exception e) { e.printStackTrace(); } } private void open0() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException { // gets the player handle Object entityPlayer = Utils.getHandle(player); // gets the nextContainerCounter int containerId = (int) Utils.invokeMethod(entityPlayer, "nextContainerCounter", null); // create a new minecraft ContainerAnvil Object newAnvilContainer = AnvilHandler.getNewAnvilContainer(entityPlayer, containerId); // creates the bukkit container using the minecraft container // by calling the callInventoryOpenEvent method on CraftEventFactory Object container = Utils.invokeStaticMethod(Utils.getCBSClass("event.CraftEventFactory"), "callInventoryOpenEvent", new Class[] {Utils.getNMSClass("EntityPlayer"), Utils.getNMSClass("Container")}, Utils.invokeMethod(player, "getHandle", new Class[] {}, null), newAnvilContainer); if(container == null) { return; } // gets the bukkit inventory we can use and access // its methods without invoking a bunch of reflection this.inv = (Inventory) Utils.invokeMethod(Utils.invokeMethod(container, "getBukkitView", null), "getTopInventory", null); // for each item set... for (final AnvilSlot slot : this.items.keySet()) { // ...set the items in the inventory this.inv.setItem(slot.getSlot(), this.items.get(slot)); } if(Utils.SERVER_VERSION.contains("1_7")){ Utils.sendPacket(player, AnvilHandler.PACKET_PLAY_OUT_OPEN_WINDOW_CLASS.getConstructors()[1].newInstance(containerId, 8, "Repairing", 0, true)); } else if (Utils.SERVER_VERSION.contains("1_8") || Utils.SERVER_VERSION.contains("1_9") || Utils.SERVER_VERSION.contains("1_10") || Utils.SERVER_VERSION.contains("1_11") || Utils.SERVER_VERSION.contains("1_12") || Utils.SERVER_VERSION.contains("1_13")){ Object chatMessage = AnvilHandler.CHAT_MESSAGE_CLASS.getConstructor(String.class, Object[].class).newInstance("Repairing", new Object[0]); Utils.sendPacket(player, AnvilHandler.PACKET_PLAY_OUT_OPEN_WINDOW_CLASS.getConstructor(int.class, String.class, AnvilHandler.ICHAT_BASE_COMPONENT_CLASS, int.class).newInstance(containerId, "minecraft:anvil", chatMessage, 0)); } else { Object chatMessage = AnvilHandler.CHAT_MESSAGE_CLASS.getConstructor(String.class, Object[].class).newInstance("Repair & Name", new Object[0]); Utils.sendPacket(player, AnvilHandler.PACKET_PLAY_OUT_OPEN_WINDOW_CLASS.getConstructor(int.class, AnvilHandler.CONTAINERS_CLASS, AnvilHandler.ICHAT_BASE_COMPONENT_CLASS).newInstance(containerId, AnvilHandler.ANVIL_CONTAINER, chatMessage)); } // set the active container on the player to the anvil inventory Utils.setFieldValueNotDeclared(entityPlayer.getClass(), "activeContainer", entityPlayer, container); // set the windowId to the nextContainerCounter Utils.setFieldValueNotDeclared(Utils.getFieldValueNotDeclared(entityPlayer.getClass(), "activeContainer", entityPlayer).getClass(), "windowId", Utils.getFieldValueNotDeclared(entityPlayer.getClass(), "activeContainer", entityPlayer), containerId); // add the ICrafting slot listener to the container Method m = Utils.getMethodNotDeclaredValue(container.getClass(), "addSlotListener", AnvilHandler.ICRAFTING_CLASS); Utils.invokeMethod(container, m, entityPlayer); } private void destroy() { HandlerList.unregisterAll(this); } // -------------------------------------------- // // GETTERS AND SETTERS // -------------------------------------------- // private Player getPlayer() { return this.player; } public AnvilGUI setSlot(final AnvilSlot slot, final ItemStack item) { this.items.put(slot, item); return this; } public HashMap<AnvilSlot, ItemStack> getItems() { return items; } }
7,695
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilSlot.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/anvil/AnvilSlot.java
package me.patothebest.gamecore.gui.anvil; public enum AnvilSlot { INPUT_LEFT(0), INPUT_RIGHT(1), OUTPUT(2); private final int slot; AnvilSlot(int slot) { this.slot = slot; } public int getSlot() { return this.slot; } public static AnvilSlot bySlot(int slot) { for (AnvilSlot anvilSlot : values()) { if(anvilSlot.getSlot() == slot) { return anvilSlot; } } return null; } }
516
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilClickEvent.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/anvil/AnvilClickEvent.java
package me.patothebest.gamecore.gui.anvil; import org.bukkit.entity.Player; public class AnvilClickEvent { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final AnvilSlot slot; private final String name; private final String playerName; private boolean close; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // AnvilClickEvent(final AnvilSlot slot, final String name, final Player player) { super(); this.close = false; this.slot = slot; this.name = name; this.playerName = player.getName(); } // -------------------------------------------- // // GETTERS AND SETTERS // -------------------------------------------- // public String getPlayerName() { return this.playerName; } public AnvilSlot getSlot() { return this.slot; } public String getName() { return this.name; } public boolean getWillClose() { return this.close; } public void setWillClose(final boolean close) { this.close = close; } }
1,248
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
AnvilClickEventHandler.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/gui/anvil/AnvilClickEventHandler.java
package me.patothebest.gamecore.gui.anvil; public interface AnvilClickEventHandler { void onAnvilClick(AnvilClickEvent event); }
137
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandRegistrationException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandRegistrationException.java
package me.patothebest.gamecore.command; /** * A problem registering commands */ public class CommandRegistrationException extends RuntimeException { public CommandRegistrationException() { } public CommandRegistrationException(String message) { super(message); } public CommandRegistrationException(String message, Throwable cause) { super(message, cause); } public CommandRegistrationException(Throwable cause) { super(cause); } }
496
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BaseCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/BaseCommand.java
package me.patothebest.gamecore.command; import me.patothebest.gamecore.treasure.TreasureCommand; import me.patothebest.gamecore.sign.SignCommand; /** * An interface declaring the base command of the plugin * <p> * This class can be used on the {@link ChildOf} @interface * when you want a command to be a subcommand of the base command. * <p> * Some examples of {@link ChildOf} using this class are * <ul> * <li>{@link SignCommand.Parent}</li> * <li>{@link TreasureCommand.Parent}</li> * </ul> */ public interface BaseCommand { }
552
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
UnhandledCommandException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/UnhandledCommandException.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; public class UnhandledCommandException extends CommandException { }
935
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SuggestionContext.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/SuggestionContext.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import me.patothebest.gamecore.util.StringUtil; import javax.annotation.Nullable; import java.util.List; /** * Extra information about the context in which tab-completion is happening */ public class SuggestionContext { private final String context; private final String prefix; private final int index; private final @Nullable Character flag; public SuggestionContext(String context, String prefix, int index, @Nullable Character flag) { this.context = context; this.prefix = prefix; this.index = index; this.flag = flag; } /** * Return the part of the command line before the text that will be replaced by the completion. * This will be from the start of the first argument to the start of the text returned by * {@link #getPrefix()}, and may include trailing spaces. * * It is not possible for the completion to change this text. */ public String getContext() { return context; } /** * Return the part of the command line that will be replaced by the completion. * This will be the last span of non-space characters, or an empty string if the * last character is a space. * * Special characters such as quotes and backslash are treated the same as any * other non-space character. It is not possible for completion to replace * anything before this. */ public String getPrefix() { return prefix; } /** * True if completing an argument (rather than a value flag) */ public boolean isArgument() { return flag == null; } /** * True if completing the value for a flag. */ public boolean isFlag() { return flag != null; } /** * The index of the argument being completed, if {@link #isArgument()} is true, otherwise -1. * @return */ public int getIndex() { return index; } /** * The flag being completed, if {@link #isFlag()} is true, otherwise null. */ public @Nullable Character getFlag() { return flag; } /** * Is the given argument being completed? */ public boolean isArgument(int index) { return isArgument() && getIndex() == index; } /** * Is the given flag being completed? */ public boolean isFlag(char flag) { return isFlag() && getFlag() == flag; } /** * Return the sorted subset of the given choices that are valid completions, * i.e. that start with {@link #getPrefix()}. */ public List<String> complete(Iterable<String> choices) { return StringUtil.complete(getPrefix(), choices); } /** * Suggest completions based on the given choices, by throwing a {@link SuggestException}. * * Only valid choices are used, and they are sorted alphabetically. */ public void suggest(Iterable<String> choices) throws SuggestException { throw new SuggestException(complete(choices)); } /** * If the given argument is being completed, generate suggestions from the given choices, * by throwing a {@link SuggestException}. */ public void suggestArgument(int index, Iterable<String> choices) throws SuggestException { if(isArgument(index)) { suggest(choices); } } /** * If the given flag is being completed, generate suggestions from the given choices, * by throwing a {@link SuggestException}. */ public void suggestFlag(char flag, Iterable<String> choices) throws SuggestException { if(isFlag(flag)) { suggest(choices); } } @Override public String toString() { return isArgument() ? "argument " + getIndex() : "flag -" + getFlag(); } }
4,708
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
NestedCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/NestedCommand.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates a nested command. Mark methods with this annotation to tell * {@link CommandsManager} that a method is merely a shell for child * commands. Note that the body of a method marked with this annotation * will never called. Additionally, not all fields of {@link Command} apply * when it is used in conjunction with this annotation, although both * are still required. */ @Retention(RetentionPolicy.RUNTIME) public @interface NestedCommand { /** * A list of classes with the child commands. * * @return a list of classes */ Class<?>[] value() default {}; /** * If set to true it will execute the body of the tagged method. * * @return true to execute the body of the annotated method */ boolean executeBody() default false; /** * If set to true it will execute the body of the tagged method * when there is no nested command to be executed * * @return true to execute the body of the annotated method */ boolean defaultToBody() default false; }
2,008
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandAlias.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandAlias.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Any command with this annotation will run the raw command as shown in the * thing, as long as it is registered in the current {@link CommandsManager}. * Mostly to move commands around without breaking things. */ @Retention(RetentionPolicy.RUNTIME) public @interface CommandAlias { /** * Get the raw {@link CommandsManager}-formatted command arg array to run * * @return the command */ String[] value(); }
1,396
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Console.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/Console.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This annotation indicates that a command can be used from the console. */ @Retention(RetentionPolicy.RUNTIME) public @interface Console { }
1,100
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
WrappedCommandsManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/WrappedCommandsManager.java
package me.patothebest.gamecore.command; import me.patothebest.gamecore.lang.interfaces.ILang; public class WrappedCommandsManager extends CommandsManager<WrappedCommandSender> { @Override public boolean hasPermission(WrappedCommandSender player, String perm) { return player.hasPermission(perm); } @Override public String getLocalizedMessage(WrappedCommandSender player, ILang message) { return null; } }
449
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandContext.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandContext.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; public class CommandContext { // Raw command line words, including the command itself // Split on literal ' ', so any element can be blank except the first one protected final String[] originalArgs; // Name of the command, i.e. the first element of originalArgs protected final String command; // Final arguments, after all parsing and escaping // Does not include the command name, flags, or flag values // Last element can be blank if completing protected final List<String> parsedArgs = new ArrayList<>(); // Starting index in originalArgs of each respective element of parsedArgs protected final List<Integer> originalArgIndices = new ArrayList<>(); // Boolean flags present protected final Set<Character> booleanFlags = new HashSet<>(); // Value flags present, and their values // One flag may have a blank value if its being completed protected final Map<Character, String> valueFlags = new HashMap<>(); protected final @Nullable SuggestionContext suggestionContext; protected final CommandLocals locals; // the original command being executed with the level this subcommand is on private final String[] wholeArgs; private final int level; public CommandContext(String[] args, Set<Character> valueFlags, boolean completing, String[] wholeArgs, int level) throws CommandException { this(args, valueFlags, completing, null, wholeArgs, level); } /** * Parse the given array of arguments. * * <p>Empty arguments are removed from the list of arguments.</p> * * @param args an array with arguments * @param valueFlagNames a set containing all value flags (pass null to disable value flag parsing) * @param completing true if completing a partial command, false if executing the command * @param locals the locals, null to create empty one * @param wholeArgs the whole executed command * @param level the level this command being executed is on * @throws CommandException thrown on a parsing error */ public CommandContext(String[] args, @Nullable Set<Character> valueFlagNames, boolean completing, @Nullable CommandLocals locals, String[] wholeArgs, int level) throws CommandException { this.wholeArgs = wholeArgs; this.level = level; if (valueFlagNames == null) { valueFlagNames = Collections.emptySet(); } this.originalArgs = args; this.command = args[0]; this.locals = locals != null ? locals : new CommandLocals(); if(args.length < 2) completing = false; boolean acceptingFlags = true; Character valueFlag = null; Character completingFlag = null; int completingIndex = -1; for(int argIndex = 1; argIndex < args.length; ++argIndex) { String arg = args[argIndex]; final int startIndex = argIndex; if(arg.isEmpty()) { // If arg is empty, and it's not the last arg being completed, skip it if(!completing || argIndex != args.length - 1) continue; } else { final char c = arg.charAt(0); if(c == '\\' || c == '"') { // Start of quoted argument, consume unparsed args until // closing quote, and append them to the parsed arg. boolean first = true; for(;argIndex < args.length; ++argIndex) { final String part; if(first) { // Remove leading quote from first part first = false; part = args[argIndex].substring(1); } else { // Insert space before non-first parts arg += ' '; part = args[argIndex]; } if(!part.isEmpty() && part.charAt(part.length() - 1) == c) { // If part ends in a quote, append it without the quote, and terminate arg += part.substring(0, part.length() - 1); break; } else { // Otherwise, just append the part arg += part; } } } else if(valueFlag == null) { // If not expecting a flag value, parse flags if("--".equals(arg)) { // Flag terminator '--', don't try to parse flags after this acceptingFlags = false; arg = null; } else if(acceptingFlags && arg.matches("^-[a-zA-Z?]+$")) { // Flag set, parse any number of boolean flags, and up to one value flag for(int iFlag = 1; iFlag < arg.length(); iFlag++) { final char flagName = arg.charAt(iFlag); if(valueFlagNames.contains(flagName)) { if(valueFlags.containsKey(flagName)) { throw new CommandException("Value flag '" + flagName + "' already given"); } if(valueFlag == null) { valueFlag = flagName; } else { throw new CommandException("No value specified for the '-" + flagName + "' flag."); } } else { booleanFlags.add(flagName); } } arg = null; } } } if(arg != null) { if(valueFlag == null) { // Append the parsed argument and its source index if(completing) { completingIndex = parsedArgs.size(); completingFlag = null; } parsedArgs.add(arg); originalArgIndices.add(startIndex); } else { // Assign the parsed arg to the preceding value flag if(completing) { completingIndex = -1; completingFlag = valueFlag; } valueFlags.put(valueFlag, arg); valueFlag = null; } } } if(valueFlag != null) { // Last arg cannot be a value flag throw new CommandException("No value specified for the '-" + valueFlag + "' flag."); } if(completing) { StringBuilder context = new StringBuilder(); for(int i = 1; i < args.length - 1; i++) { context.append(args[i]).append(' '); } suggestionContext = new SuggestionContext(context.toString(), args[args.length - 1], completingIndex, completingFlag); } else { suggestionContext = null; } } /** * Return the context for which command completion is being requested, * or null if the command is not being completed. */ public @Nullable SuggestionContext getSuggestionContext() { return suggestionContext; } /** * Is the command being executed, rather than completed? */ public boolean isExecuting() { return getSuggestionContext() == null; } /** * Is the command being completed, rather than executed? */ public boolean isSuggesting() { return getSuggestionContext() != null; } /** * Is the given argument being completed? */ public boolean isSuggestingArgument(int index) { return isSuggesting() && getSuggestionContext().isArgument(index); } /** * Is the given flag being completed? */ public boolean isSuggestingFlag(char flag) { return isSuggesting() && getSuggestionContext().isFlag(flag); } /** * If the given argument is being completed, generate suggestions based on the given choices. */ public void suggestArgument(int index, Iterable<String> choices) throws SuggestException { if(isSuggesting() && getSuggestionContext().isArgument()) { getSuggestionContext().suggestArgument(index, choices); } } /** * If the given flag is being completed, generate suggestions based on the given choices. */ public void suggestFlag(char flag, Iterable<String> choices) throws SuggestException { if(isSuggesting()) { getSuggestionContext().suggestFlag(flag, choices); } } /** * If the command is being completed from anywhere at or after the given argument index, * generate suggestions for the entire command from that index, based on the given choices. */ public void suggestJoinedArguments(int start, Iterable<String> choices) throws SuggestException { final SuggestionContext ctx = getSuggestionContext(); if(ctx != null && ctx.isArgument()) { if(start == ctx.getIndex()) { ctx.suggestArgument(start, choices); } else if(start < ctx.getIndex()) { final String prefix = String.join(" ", parsedArgs.subList(start, ctx.getIndex())).toLowerCase() + " "; final List<String> filtered = new ArrayList<>(); for(String choice : choices) { if(choice.toLowerCase().startsWith(prefix)) { filtered.add(choice.substring(prefix.length())); } } ctx.suggestArgument(ctx.getIndex(), filtered); } } } public String getCommand() { return command; } public String[] getOriginalArgs() { return originalArgs; } public String[] getArgs() { String[] newArgs = new String[originalArgs.length-1]; System.arraycopy(originalArgs, 1, newArgs, 0, originalArgs.length - 1); return newArgs; } public boolean matches(String command) { return this.command.equalsIgnoreCase(command); } public String getString(int index) { return parsedArgs.get(index); } /** * Return the argument at the given index as a String, if it is present. */ public Optional<String> tryString(int index) { return index < parsedArgs.size() ? Optional.of(parsedArgs.get(index)) : Optional.empty(); } public String getString(int index, String def) { return index < parsedArgs.size() ? parsedArgs.get(index) : def; } /** * Return the argument at the given index as a String. * @throws CommandException if the argument is missing */ public String string(int index) throws CommandException { if(index >= parsedArgs.size()) { throw new CommandUsageException("Missing argument"); } return getString(index); } /** * Return the argument at the given index as a String, or generate suggestions * if that argument is being completed. * * @throws CommandException if the argument is missing * @throws SuggestException if the argument is being completed */ public String string(int index, Iterable<String> choices) throws CommandException, SuggestException { suggestArgument(index, choices); return string(index); } public Optional<String> tryString(int index, Iterable<String> choices) throws SuggestException { suggestArgument(index, choices); return tryString(index); } public String getJoinedStrings(int initialIndex) { initialIndex = originalArgIndices.get(initialIndex); StringBuilder buffer = new StringBuilder(originalArgs[initialIndex]); for (int i = initialIndex + 1; i < originalArgs.length; ++i) { buffer.append(" ").append(originalArgs[i]); } return buffer.toString(); } public String getJoinedStrings(int initialIndex, String def) { return initialIndex < originalArgIndices.size() ? getJoinedStrings(initialIndex) : def; } /** * Return the rest of the command line, starting at the given argument index. * * Any flags that appear after the given index are included in the result. * * @throws CommandException if the argument is missing */ public String joinedStrings(int initialIndex) throws CommandException { if(initialIndex >= originalArgIndices.size()) { throw new CommandUsageException("Missing argument"); } return getJoinedStrings(initialIndex); } public String joinedStrings(int initialIndex, Iterable<String> choices) throws CommandException, SuggestException { suggestJoinedArguments(initialIndex, choices); return joinedStrings(initialIndex); } public Optional<String> tryJoinedStrings(int initialIndex) { return initialIndex < originalArgIndices.size() ? Optional.of(getJoinedStrings(initialIndex)) : Optional.empty(); } public Optional<String> tryJoinedStrings(int initialIndex, Iterable<String> choices) throws SuggestException { suggestJoinedArguments(initialIndex, choices); return tryJoinedStrings(initialIndex); } public String getRemainingString(int start) { return getString(start, parsedArgs.size() - 1); } /** * Return the given argument and all arguments after it, joined with spaces. * * Flags are never included in the result, even if they appear between between * the arguments that are included. * * @throws CommandException if the argument is missing */ public String remainingString(int start) throws CommandException { return string(start, parsedArgs.size() - 1); } public String remainingString(int start, Iterable<String> choices) throws CommandException, SuggestException { suggestJoinedArguments(start, choices); return remainingString(start); } public Optional<String> tryRemainingString(int start) { return tryString(start, parsedArgs.size() - 1); } public Optional<String> tryRemainingString(int start, Iterable<String> choices) throws SuggestException { suggestJoinedArguments(start, choices); return tryRemainingString(start); } public String getString(int start, int end) { StringBuilder buffer = new StringBuilder(parsedArgs.get(start)); for (int i = start + 1; i < end + 1; ++i) { buffer.append(" ").append(parsedArgs.get(i)); } return buffer.toString(); } public String string(int start, int end) throws CommandException { if(start >= parsedArgs.size() || end >= parsedArgs.size()) { throw new CommandUsageException("Missing argument"); } return getString(start, end); } public Optional<String> tryString(int start, int end) { return start < parsedArgs.size() && end < parsedArgs.size() ? Optional.of(getString(start, end)) : Optional.empty(); } public int getInteger(int index) throws CommandNumberFormatException { final String text = parsedArgs.get(index); try { return Integer.parseInt(text); } catch(NumberFormatException e) { throw new CommandNumberFormatException(text); } } public boolean isInBounds(int index) { return index < parsedArgs.size(); } public boolean isInteger(int index) { final String text = parsedArgs.get(index); try { Integer.parseInt(text); return true; } catch(NumberFormatException e) { return false; } } public int getInteger(int index, int def) throws CommandNumberFormatException { return index < parsedArgs.size() ? getInteger(index) : def; } public double getDouble(int index) throws CommandNumberFormatException { final String text = parsedArgs.get(index); try { return Double.parseDouble(text); } catch(NumberFormatException e) { throw new CommandNumberFormatException(text); } } public double getDouble(int index, double def) throws CommandNumberFormatException { return index < parsedArgs.size() ? getDouble(index) : def; } public String[] getSlice(int index) { String[] slice = new String[originalArgs.length - index]; System.arraycopy(originalArgs, index, slice, 0, originalArgs.length - index); return slice; } public String[] getPaddedSlice(int index, int padding) { String[] slice = new String[originalArgs.length - index + padding]; System.arraycopy(originalArgs, index, slice, padding, originalArgs.length - index); return slice; } public String[] getParsedSlice(int index) { String[] slice = new String[parsedArgs.size() - index]; System.arraycopy(parsedArgs.toArray(new String[parsedArgs.size()]), index, slice, 0, parsedArgs.size() - index); return slice; } public String[] getParsedPaddedSlice(int index, int padding) { String[] slice = new String[parsedArgs.size() - index + padding]; System.arraycopy(parsedArgs.toArray(new String[parsedArgs.size()]), index, slice, padding, parsedArgs.size() - index); return slice; } public boolean hasFlag(char ch) { return booleanFlags.contains(ch) || valueFlags.containsKey(ch); } public Set<Character> getFlags() { return booleanFlags; } public Map<Character, String> getValueFlags() { return valueFlags; } public @Nullable String getFlag(char ch) { return valueFlags.get(ch); } public String getFlag(char ch, String def) { final String value = valueFlags.get(ch); if (value == null) { return def; } return value; } public @Nullable String flagOrNull(char ch, Iterable<String> choices) throws SuggestException { suggestFlag(ch, choices); return getFlag(ch); } public Optional<String> tryFlag(char ch) { return Optional.ofNullable(getFlag(ch)); } public Optional<String> tryFlag(char ch, Iterable<String> choices) throws SuggestException { suggestFlag(ch, choices); return tryFlag(ch); } public int getFlagInteger(char ch) throws CommandNumberFormatException { final String text = valueFlags.get(ch); try { return Integer.parseInt(text); } catch(NumberFormatException e) { throw new CommandNumberFormatException(text); } } public int getFlagInteger(char ch, int def) throws CommandNumberFormatException { return !valueFlags.containsKey(ch) ? def : getFlagInteger(ch); } public double getFlagDouble(char ch) throws CommandNumberFormatException { final String text = valueFlags.get(ch); try { return Double.parseDouble(text); } catch(NumberFormatException e) { throw new CommandNumberFormatException(text); } } public double getFlagDouble(char ch, double def) throws CommandNumberFormatException { return !valueFlags.containsKey(ch) ? def : getFlagDouble(ch); } public int argsLength() { return parsedArgs.size(); } public CommandLocals getLocals() { return locals; } public String[] getWholeArgs() { return wholeArgs; } public int getLevel() { return level; } @Override public String toString() { return "CommandContext{" + "originalArgs=" + Arrays.toString(originalArgs) + ", command='" + command + '\'' + ", parsedArgs=" + parsedArgs + ", originalArgIndices=" + originalArgIndices + ", booleanFlags=" + booleanFlags + ", valueFlags=" + valueFlags + ", suggestionContext=" + suggestionContext + ", locals=" + locals + '}'; } }
21,783
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Command.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/Command.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This annotation indicates a command. Methods should be marked with this * annotation to tell {@link CommandsManager} that the method is a command. * Note that the method name can actually be anything. */ @Retention(RetentionPolicy.RUNTIME) public @interface Command { /** * A list of aliases for the command. The first alias is the most * important -- it is the main name of the command. (The method name * is never used for anything). * * @return Aliases for a command */ String[] aliases(); /** * Usage instruction. Example text for usage could be * {@code [-h harps] [name] [message]}. * * @return Usage instructions for a command */ String usage() default ""; /** * @return A short description for the command. * @deprecated Use {@link Command#langDescription()} */ @Deprecated String desc() default ""; /** * @return the description we can translate */ LangDescription langDescription(); /** * The minimum number of arguments. This should be 0 or above. * * @return the minimum number of arguments */ int min() default 0; /** * The maximum number of arguments. Use -1 for an unlimited number * of arguments. * * @return the maximum number of arguments */ int max() default -1; /** * Flags allow special processing for flags such as -h in the command, * allowing users to easily turn on a flag. This is a string with * each character being a flag. Use A-Z and a-z as possible flags. * Appending a flag with a : makes the flag character before a value flag, * meaning that if it is given it must have a value * * @return Flags matching a-zA-Z */ String flags() default ""; /** * @return A long description for the command. */ String help() default ""; /** * Get whether any flag can be used. * * @return true if so */ boolean anyFlags() default false; }
2,999
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SuggestException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/SuggestException.java
package me.patothebest.gamecore.command; import com.google.common.collect.ImmutableList; import java.util.List; /** * Throw this exception out of a command method to suggest completions for the command. * * This is only allowed when {@link CommandContext#isSuggesting()} is true. If it isn't, * then the exception is handled like any other uncaught exception. */ public class SuggestException extends Exception { private final ImmutableList<String> suggestions; public SuggestException(Iterable<String> suggestions) { this.suggestions = ImmutableList.copyOf(suggestions); } public List<String> suggestions() { return suggestions; } }
681
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Injector.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/Injector.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import javax.annotation.Nullable; import javax.inject.Provider; import java.lang.reflect.InvocationTargetException; /** * Constructs new instances. */ public interface Injector { /** * Return a {@link Provider} for the given command class. The framework will * call this at registration time, and use the provider to get a {@link T} * instance every time a command is executed. * * If null is returned, then {@link #getInstance(Class)} will be called at * registration time to get the instance, and it will be reused forever. */ default @Nullable <T> Provider<? extends T> getProviderOrNull(Class<T> cls) { return null; } /** * Constructs a new instance of the given class. * * @param cls class * @return object * @throws IllegalAccessException thrown on injection fault * @throws InstantiationException thrown on injection fault * @throws InvocationTargetException thrown on injection fault */ Object getInstance(Class<?> cls) throws InvocationTargetException, IllegalAccessException, InstantiationException; }
1,992
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
MissingNestedCommandException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/MissingNestedCommandException.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; public class MissingNestedCommandException extends CommandUsageException { public MissingNestedCommandException(String message, String usage) { super(message, usage); } }
1,055
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandOverride.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandOverride.java
package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Defines a command as one that'll override any axisting command * with the aliases */ @Retention(RetentionPolicy.RUNTIME) public @interface CommandOverride { }
295
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Logging.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/Logging.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //$Id$ package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates how the affected blocks should be hinted at in the log. */ @Retention(RetentionPolicy.RUNTIME) public @interface Logging { enum LogMode { /** * Player position */ POSITION, /** * Region selection */ REGION, /** * Player orientation and region selection */ ORIENTATION_REGION, /** * Either the player position or pos1, depending on the placeAtPos1 flag */ PLACEMENT, /** * Log all information available */ ALL } /** * Log mode. * * @return either POSITION, REGION, ORIENTATION_REGION, PLACEMENT or ALL */ LogMode value(); }
1,714
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ChatColor.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/ChatColor.java
package me.patothebest.gamecore.command; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; /** * All supported color values for chat * * Class provided as part of the Bukkit project with slight modifications to * reduce dependencies. * */ public enum ChatColor { /** * Represents black */ BLACK('0', 0x00), /** * Represents dark blue */ DARK_BLUE('1', 0x1), /** * Represents dark green */ DARK_GREEN('2', 0x2), /** * Represents dark blue (aqua) */ DARK_AQUA('3', 0x3), /** * Represents dark red */ DARK_RED('4', 0x4), /** * Represents dark purple */ DARK_PURPLE('5', 0x5), /** * Represents gold */ GOLD('6', 0x6), /** * Represents gray */ GRAY('7', 0x7), /** * Represents dark gray */ DARK_GRAY('8', 0x8), /** * Represents blue */ BLUE('9', 0x9), /** * Represents green */ GREEN('a', 0xA), /** * Represents aqua */ AQUA('b', 0xB), /** * Represents red */ RED('c', 0xC), /** * Represents light purple */ LIGHT_PURPLE('d', 0xD), /** * Represents yellow */ YELLOW('e', 0xE), /** * Represents white */ WHITE('f', 0xF), /** * Represents magical characters that change around randomly */ MAGIC('k', 0x10, true), /** * Makes the text bold. */ BOLD('l', 0x11, true), /** * Makes a line appear through the text. */ STRIKETHROUGH('m', 0x12, true), /** * Makes the text appear underlined. */ UNDERLINE('n', 0x13, true), /** * Makes the text italic. */ ITALIC('o', 0x14, true), /** * Resets all previous chat colors or formats. */ RESET('r', 0x15); /** * The special character which prefixes all chat colour codes. Use this if you need to dynamically * convert colour codes from your custom format. */ public static final char COLOR_CHAR = '\u00A7'; private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + COLOR_CHAR + "[0-9A-FK-OR]"); private final int intCode; private final char code; private final boolean isFormat; private final String toString; private final static Map<String, ChatColor> BY_NAME = new HashMap<>(); private final static Map<Integer, ChatColor> BY_ID = new HashMap<>(); private final static Map<Character, ChatColor> BY_CHAR = new HashMap<>(); ChatColor(char code, int intCode) { this(code, intCode, false); } ChatColor(char code, int intCode, boolean isFormat) { this.code = code; this.intCode = intCode; this.isFormat = isFormat; this.toString = new String(new char[] {COLOR_CHAR, code}); } /** * Gets the char value associated with this color * * @return A char value of this color code */ public char getChar() { return this.code; } @Override public String toString() { return this.toString; } /** * Checks if this code is a format code as opposed to a color code. */ public boolean isFormat() { return this.isFormat; } /** * Checks if this code is a color code as opposed to a format code. */ public boolean isColor() { return !this.isFormat && this != RESET; } /** * Gets the color represented by the specified color code * * @param code Code to check * @return Associative with the given code, or null if it doesn't exist */ public static ChatColor getByChar(char code) { return BY_CHAR.get(code); } /** * Gets the color represented by the name * * @param name Name of the color * @return Associative with the given name, or null if it doesn't exist */ public static ChatColor getByName(String name) { return BY_NAME.get(name); } /** * Gets the color represented by the specified color code * * @param code Code to check * @return Associative with the given code, or null if it doesn't exist */ public static ChatColor getByChar(String code) { if (code == null) throw new NullPointerException("Code cannot be null"); if (code.isEmpty()) throw new IllegalArgumentException("Code must have at least one char"); return BY_CHAR.get(code.charAt(0)); } /** * Strips the given message of all color codes * * @param input String to strip of color * @return A copy of the input string, without any coloring */ public static String stripColor(final String input) { if (input == null) { return null; } return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); } /** * Translates a string using an alternate color code character into a string that uses the internal * ChatColor.COLOR_CODE color code character. The alternate color code character will only be replaced * if it is immediately followed by 0-9, A-F, a-f, K-O, k-o, R or r. * * @param altColorChar The alternate color code character to replace. Ex: & * @param textToTranslate Text containing the alternate color code character. * @return Text containing the ChatColor.COLOR_CODE color code character. */ public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { char[] b = textToTranslate.toCharArray(); for (int i = 0; i < b.length - 1; i++) { if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i+1]) > -1) { b[i] = ChatColor.COLOR_CHAR; b[i+1] = Character.toLowerCase(b[i+1]); } } return new String(b); } /** * Gets the ChatColors used at the end of the given input string. * * @param input Input string to retrieve the colors from. * @return Any remaining ChatColors to pass onto the next line. */ public static String getLastColors(String input) { String result = ""; int length = input.length(); // Search backwards from the end as it is faster for (int index = length - 1; index > -1; index--) { char section = input.charAt(index); if (section == COLOR_CHAR && index < length - 1) { char c = input.charAt(index + 1); ChatColor color = getByChar(c); if (color != null) { result = color.toString() + result; // Once we find a color or reset we can stop searching if (color.isColor() || color.equals(RESET)) { break; } } } } return result; } static { for (ChatColor color : values()) { BY_ID.put(color.intCode, color); BY_CHAR.put(color.code, color); BY_NAME.put(color.name(), color); } } }
7,141
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandsManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandsManager.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.StringUtil; import javax.annotation.Nullable; import javax.inject.Provider; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; /** * Manager for handling commands. This allows you to easily process commands, * including nested commands, by correctly annotating methods of a class. * * <p>To use this, it is merely a matter of registering classes containing * the commands (as methods with the proper annotations) with the * manager. When you want to process a command, use one of the * {@code execute} methods. If something is wrong, such as incorrect * usage, insufficient permissions, or a missing command altogether, an * exception will be raised for upstream handling.</p> * * <p>Methods of a class to be registered can be static, but if an injector * is registered with the class, the instances of the command classes * will be created automatically and methods will be called non-statically.</p> * * <p>To mark a method as a command, use {@link Command}. For nested commands, * see {@link NestedCommand}. To handle permissions, use * {@link CommandPermissions}.</p> * * <p>This uses Java reflection extensively, but to reduce the overhead of * reflection, command lookups are completely cached on registration. This * allows for fast command handling. Method invocation still has to be done * with reflection, but this is quite fast in that of itself.</p> * * @param <T> command sender class */ @SuppressWarnings("ProtectedField") public abstract class CommandsManager<T> { protected static final Logger logger = Logger.getLogger(CommandsManager.class.getCanonicalName()); /** * Mapping of commands (including aliases) with a description. Root * commands are stored under a key of null, whereas child commands are * cached under their respective {@link Method}. The child map has * the key of the command name (one for each alias) with the * method. */ protected final Map<Method, Map<String, Method>> commands = new HashMap<>(); /** * Used to store the providers associated with a method. */ protected final Map<Class, Object> instances = new HashMap<>(); protected final Map<Method, Provider> providers = new HashMap<>(); /** * Mapping of commands (not including aliases) with a description. This * is only for top level commands. */ protected final Map<String, String> descs = new HashMap<>(); /** * Stores the injector used to getInstance. */ protected Injector injector; /** * Mapping of commands (not including aliases) with a description. This * is only for top level commands. */ protected final Map<String, String> helpMessages = new HashMap<>(); /** * Mapping of commands (not including aliases) with a description. This * is only for top level commands. Different from helpMessages. The format * is Key: <command> <usage> Value: <description> */ protected final Map<String, String> simpleHelp = new HashMap<>(); /** * Mapping of subcommands with a description. */ protected final Map<String, Map<String, Command>> subcommandsHelp = new HashMap<>(); /** * Mapping of subcommands with a description. */ protected final Map<String, CommandPermissions> commandPermissions = new HashMap<>(); /** * A list of classes containing the {@link ChildOf} annotation. * These classes must be processed later when all the commands have * been already registered. */ protected final List<Class<?>> childOfClasses = new CopyOnWriteArrayList<>(); /** * Register an class that contains commands (denoted by {@link Command}. * If no dependency injector is specified, then the methods of the * class will be registered to be called statically. Otherwise, new * instances will be created of the command classes and methods will * not be called statically. * * @param cls the class to register */ public void register(Class<?> cls) { registerMethods(cls, null); } /** * Register an class that contains commands (denoted by {@link Command}. * If no dependency injector is specified, then the methods of the * class will be registered to be called statically. Otherwise, new * instances will be created of the command classes and methods will * not be called statically. A List of {@link Command} annotations from * registered commands is returned. * * @param cls the class to register * @return A List of {@link Command} annotations from registered commands, * for use in eg. a dynamic command registration system. */ public List<Command> registerAndReturn(Class<?> cls) { return registerMethods(cls, null); } /** * Register the methods of a class. This will automatically construct * instances as necessary. * * @param cls the class to register * @param parent the parent method * @return Commands Registered */ public List<Command> registerMethods(Class<?> cls, Method parent) { return registerMethods(cls, parent, null); } public <C> List<Command> registerMethods(Class<C> cls, @Nullable Method parent, @Nullable Provider<? extends C> provider) { try { return registerMethods0(cls, parent, provider, false); } catch (Exception e) { throw new CommandRegistrationException("Failed to register commands in class " + cls.getName(), e); } } /** * Register the methods of a class. * * @param cls the class to register * @param parent the parent method * @param provider provides instances of the command method, or null to use the {@link Injector} * @return a list of commands */ private <C> List<Command> registerMethods0(Class<C> cls, Method parent, @Nullable Provider<? extends C> provider, boolean processParents) throws IllegalAccessException, InstantiationException, InvocationTargetException { Map<String, Method> map; List<Command> registered = new ArrayList<>(); if(cls.isAnnotationPresent(ChildOf.class) && parent == null) { if(!processParents) { childOfClasses.add(cls); return registered; } ChildOf parentCmd = cls.getAnnotation(ChildOf.class); for (Map<String, Method> stringMethodMap : commands.values()) { for (Method method : stringMethodMap.values()) { if(method == null) { continue; } if(method.getDeclaringClass() == parentCmd.value() || parentCmd.value().isAssignableFrom(method.getDeclaringClass())) { parent = method; } } } if(parent == null) { return registered; } childOfClasses.remove(cls); } // Make a new hash map to cache the commands for this class // as looking up methods via reflection is fairly slow if (commands.containsKey(parent)) { map = commands.get(parent); } else { map = new HashMap<>(); commands.put(parent, map); } for (Method method : cls.getMethods()) { if (!method.isAnnotationPresent(Command.class)) { continue; } if (!(Void.TYPE.equals(method.getReturnType()) || List.class.isAssignableFrom(method.getReturnType()))) { throw new CommandRegistrationException("Command method " + method.getDeclaringClass().getName() + "#" + method.getName() + " must return either void or List<String>"); } boolean isStatic = Modifier.isStatic(method.getModifiers()); Command cmd = method.getAnnotation(Command.class); boolean registeredCommand = false; // Cache the aliases too for (String alias : cmd.aliases()) { if (map.containsKey(alias)) { if (method.isAnnotationPresent(CommandOverride.class)) { map.remove(alias); } else { continue; } } map.put(alias, method); registeredCommand = true; } if (!registeredCommand) { continue; } // We want to be able invoke with an instance if (!isStatic) { if (provider == null && injector != null) { // If we weren't given a Provider, try to get one from the Injector provider = injector.getProviderOrNull(cls); if (provider == null) { // If we can't get a provider, check if we have already instantiated the class C instance = (C) instances.get(cls); if (instance == null) { // If we haven't, do that now and save it instance = (C) injector.getInstance(cls); instances.put(cls, instance); } // Generate a provider that just returns the saved instance final C finalInstance = instance; provider = () -> finalInstance; } } if (provider != null) { providers.put(method, provider); } else { String text = "Failed to get an instance/provider of " + cls.getName() + " for command method " + method.getDeclaringClass().getName() + "#" + method.getName(); if (injector == null) { text += " (no Injector is available to create it)"; } else { text += " (the Injector returned null when asked for one)"; } throw new CommandRegistrationException(text); } } final String commandName = cmd.aliases()[0]; final String desc = cmd.desc(); if (map.get(commandName).equals(method)) { final String usage = cmd.usage(); if (usage.isEmpty()) { descs.put(commandName, desc); } else { descs.put(commandName, usage + " - " + desc); } String help = cmd.help(); if (help.isEmpty()) { help = desc; } String parentCommandName = null; // Build a list of commands and their usage details if (parent == null) { // Simple help message simpleHelp.put(commandName + " " + usage, help); final CharSequence arguments = getArguments(cmd); for (String alias : cmd.aliases()) { final String helpMessage = "/" + alias + " " + arguments + "\n\n" + help; final String key = alias.replaceAll("/", ""); String previous = helpMessages.put(key, helpMessage); if (previous != null && !previous.replaceAll("^/[^ ]+ ", "").equals(helpMessage.replaceAll("^/[^ ]+ ", ""))) { helpMessages.put(key, previous + "\n\n" + helpMessage); } } } else { Command parentCommand = parent.getAnnotation(Command.class); parentCommandName = parentCommand.aliases()[0]; } Map<String, Command> helpMap; if (subcommandsHelp.containsKey(parentCommandName)) { helpMap = subcommandsHelp.get(parentCommandName); } else { helpMap = new HashMap<>(); subcommandsHelp.put(parentCommandName, helpMap); } if (!method.isAnnotationPresent(HiddenCommand.class)) { helpMap.put(commandName + " " + usage, cmd); } // Put the command permissions in the map if(method.isAnnotationPresent(CommandPermissions.class)) { commandPermissions.put(commandName, method.getAnnotation(CommandPermissions.class)); } } // Add the command to the registered command list for return registered.add(cmd); // Look for nested commands -- if there are any, those have // to be cached too so that they can be quickly looked // up when processing commands if (method.isAnnotationPresent(NestedCommand.class)) { NestedCommand nestedCmd = method.getAnnotation(NestedCommand.class); for (Class<?> nestedCls : nestedCmd.value()) { registerMethods(nestedCls, method); } } } if (cls.getSuperclass() != null) { registerMethods0(cls.getSuperclass(), parent, provider, false); } return registered; } public void processChildCommands() throws IllegalAccessException, InvocationTargetException, InstantiationException { boolean register = true; while (!childOfClasses.isEmpty() && register) { register = false; for (Class<?> childClass : childOfClasses) { if (!registerMethods0(childClass, null, null, true).isEmpty()) { register = true; } } } if(childOfClasses.isEmpty()) { System.out.println("All child command classes have been processed!"); return; } Utils.printError("Some child classes have not been registered!", childOfClasses); } /** * Checks to see whether there is a command named such at the root level. * This will check aliases as well. * * @param command the command * @return true if the command exists */ public boolean hasCommand(String command) { return commands.get(null).containsKey(command.toLowerCase()); } /** * Get a list of command descriptions. This is only for root commands. * * @return a map of commands */ public Map<String, String> getCommands() { return descs; } /** * Get the mapping of methods under a parent command. * * @return the mapping */ public Map<Method, Map<String, Method>> getMethods() { return commands; } /** * Get a map from command name to help message. This is only for root commands. * * @return a map of help messages for each command */ public Map<String, String> getHelpMessages() { return helpMessages; } /** * Get a map from command name to help message. This is only for root commands. * The format is Key: <command> <usage> Value: <description> * * @return a map of help messages for each command */ public Map<String, String> getSimpleHelp() { return simpleHelp; } /** * Gets the map of all the registered commands that are annotated * with the @CommandPermissions annotation * * @return a map of the command permissions */ public Map<String, CommandPermissions> getCommandPermissions() { return commandPermissions; } /** * Get a map with all the command subcommands and description * * @return a map of each subcommand with description */ public Map<String, Map<String, Command>> getSubcommandsHelp() { return subcommandsHelp; } /** * Get the usage string for a command. * * @param args the arguments * @param level the depth of the command * @param cmd the command annotation * @return the usage string */ protected String getUsage(String[] args, int level, Command cmd) { final StringBuilder command = new StringBuilder(); command.append('/'); for (int i = 0; i <= level; ++i) { command.append(args[i]); command.append(' '); } command.append(getArguments(cmd)); final String help = cmd.help(); if (!help.isEmpty()) { command.append("\n\n"); command.append(help); } return command.toString(); } protected CharSequence getArguments(Command cmd) { final String flags = cmd.flags(); final StringBuilder command2 = new StringBuilder(); if (!flags.isEmpty()) { String flagString = flags.replaceAll(".:", ""); if (!flagString.isEmpty()) { command2.append("[-"); for (int i = 0; i < flagString.length(); ++i) { command2.append(flagString.charAt(i)); } command2.append("] "); } } command2.append(cmd.usage()); return command2; } /** * Get the usage string for a nested command. * * @param args the arguments * @param level the depth of the command * @param method the parent method * @param player the player * @return the usage string * @throws CommandException on some error */ protected String getNestedUsage(String[] args, int level, Method method, T player) throws CommandException { StringBuilder command = new StringBuilder(); command.append("/"); for (int i = 0; i <= level; ++i) { command.append(args[i]).append(" "); } Map<String, Method> map = commands.get(method); boolean found = false; command.append("<"); Set<String> allowedCommands = new HashSet<>(); for (Map.Entry<String, Method> entry : map.entrySet()) { Method childMethod = entry.getValue(); found = true; if (hasPermission(childMethod, player)) { Command childCmd = childMethod.getAnnotation(Command.class); allowedCommands.add(childCmd.aliases()[0]); } } if (!allowedCommands.isEmpty()) { command.append(StringUtil.joinString(allowedCommands, "|", 0)); } else { if (!found) { command.append("?"); } else { //command.append("action"); throw new CommandPermissionsException(); } } command.append(">"); return command.toString(); } private static boolean supportsCompletion(Method method) { return List.class.isAssignableFrom(method.getReturnType()) || Stream.of(method.getExceptionTypes()) .anyMatch(SuggestException.class::isAssignableFrom); } /** * Attempt to execute a command. This version takes a separate command * name (for the root command) and then a list of following arguments. * * @param cmd command to run * @param args arguments * @param player command source * @param methodArgs method arguments * @throws CommandException thrown when the command throws an error */ public void execute(String cmd, String[] args, T player, Object... methodArgs) throws CommandException { executeMethod(false, cmd, args, player, methodArgs); } /** * Attempt to complete a command. * * If null is returned, the server's default completion should be used. * Any non-null return should be used as the completion results, even if empty. */ public @Nullable List<String> complete(String cmd, String[] args, T player, Object... methodArgs) throws CommandException { return executeMethod(true, cmd, args, player, methodArgs); } private List<String> executeMethod(boolean completing, String cmd, String[] args, T player, Object... methodArgs) throws CommandException { String[] newArgs = new String[args.length + 1]; System.arraycopy(args, 0, newArgs, 1, args.length); newArgs[0] = cmd; Object[] newMethodArgs = new Object[methodArgs.length + 1]; System.arraycopy(methodArgs, 0, newMethodArgs, 1, methodArgs.length); return executeMethod(null, completing, newArgs, player, newMethodArgs, 0); } /** * Attempt to execute a command. * * @param parent the parent method * @param completing true if completing the command, false if executing * @param args an array of arguments * @param player the player * @param methodArgs the array of method arguments * @param level the depth of the command * * @return A list of completions, or null to use the server's default completion (player names). * Returning an empty list will prevent any completion from happening. * * @throws CommandException thrown on a command error */ private List<String> executeMethod(Method parent, boolean completing, String[] args, T player, Object[] methodArgs, int level) throws CommandException { final String cmdName = args[level]; final String cmdNameLower = cmdName.toLowerCase(); final int argsCount = args.length - 1 - level; final Map<String, Method> map = commands.get(parent); boolean defaultToParent = false; if(completing && argsCount == 0) { // Completing with no args means the command itself is being completed. // Gather all matching commands, that the player has permission to run, // and return them as completion options. If a full command is being // completed, it will be returned alone, which will just advance the cursor. final List<String> children = new ArrayList<>(); final Set<Method> methods = new HashSet<>(); for(Map.Entry<String, Method> entry : map.entrySet()) { final String child = entry.getKey(); // don't tab complete hidden commands if (entry.getValue().getAnnotation(HiddenCommand.class) != null) { continue; } // don't tab complete aliases if (methods.contains(entry.getValue())) { continue; } if(child.toLowerCase().startsWith(cmdNameLower) && hasPermission(entry.getValue(), player)) { children.add(child); methods.add(entry.getValue()); } } return children; } Method method = map.get(cmdNameLower); if (method == null) { if (parent == null) { // Root throw new UnhandledCommandException(); } else { final NestedCommand nestedParentAnnot = parent.getAnnotation(NestedCommand.class); if(nestedParentAnnot == null || !nestedParentAnnot.defaultToBody()) { throw new MissingNestedCommandException("Unknown command: " + cmdName, getNestedUsage(args, level - 1, parent, player)); } method = parent; defaultToParent = true; } } if(!hasPermission(method, player)) { throw new CommandPermissionsException(); } // checks if we need to execute the body of the nested command method (false) // or display the help what commands are available (true) // this is all for an args count of 0 if it is > 0 and a NestedCommand Annotation is present // it will always handle the methods that NestedCommand points to // e.g.: // - /cmd - @NestedCommand(executeBody = true) will go into the else loop and execute code in that method // - /cmd <arg1> <arg2> - @NestedCommand(executeBody = true) will always go to the nested command class // - /cmd <arg1> - @NestedCommand(executeBody = false) will always go to the nested command class not matter the args final NestedCommand nestedAnnot = method.getAnnotation(NestedCommand.class); if (nestedAnnot != null && (argsCount > 0 || nestedAnnot.executeBody()) && !defaultToParent) { if (argsCount == 0) { throw new MissingNestedCommandException("Sub-command required.", getNestedUsage(args, level, method, player)); } else { return executeMethod(method, completing, args, player, methodArgs, level + 1); } } else if (method.isAnnotationPresent(CommandAlias.class) && !defaultToParent) { CommandAlias aCmd = method.getAnnotation(CommandAlias.class); return executeMethod(parent, completing, aCmd.value(), player, methodArgs, level); } else { Command cmd = method.getAnnotation(Command.class); // If the command method doesn't do completions, return null to indicate that // the default completion (player name) should be used. if(completing && !supportsCompletion(method)) return null; if(defaultToParent) { // We go down a level because the command was not found, and it defaulted to the body // Let's say we executed '/cmd subcommand unknowncommand test' and the subcommand has // the property to execute parent, it'll call the subcommand method with the parameters // args["unknowncommand", "test"] level--; } String[] newArgs = new String[args.length - level]; System.arraycopy(args, level, newArgs, 0, args.length - level); final Set<Character> valueFlags = new HashSet<>(); char[] flags = cmd.flags().toCharArray(); Set<Character> newFlags = new HashSet<>(); for (int i = 0; i < flags.length; ++i) { if (flags.length > i + 1 && flags[i + 1] == ':') { valueFlags.add(flags[i]); ++i; } newFlags.add(flags[i]); } CommandContext context = new CommandContext(newArgs, valueFlags, completing, args, level); if(!completing) { if (context.argsLength() < cmd.min()) { throw new CommandUsageException(getLocalizedMessage(player, CoreLang.TOO_FEW_ARGUMENTS), nestedAnnot != null ? getNestedUsage(args, level, method, player) : getUsage(args, level, cmd)); } if (cmd.max() != -1 && context.argsLength() > cmd.max()) { throw new CommandUsageException(getLocalizedMessage(player, CoreLang.TOO_MANY_ARGUMENTS), getUsage(args, level, cmd)); } if (!cmd.anyFlags()) { for (char flag : context.getFlags()) { if (!newFlags.contains(flag)) { String flagString = flag + ""; throw new CommandUsageException(getLocalizedMessage(player, CoreLang.UNKNOWN_FLAG).replace("%flag%", flagString), getUsage(args, level, cmd)); } } } } methodArgs[0] = context; Provider provider = providers.get(method); Object instance = provider == null ? null : provider.get(); try { // If we get here while completing, it means the method's return type is a List<String>, // and we never want to use the default completion. So if it returns null, convert it to // an empty list. List<String> completions = (List<String>) method.invoke(instance, methodArgs); return completions != null ? completions : Collections.emptyList(); } catch (InvocationTargetException e) { if (e.getCause() instanceof SuggestException && context.isSuggesting()) { return ((SuggestException) e.getCause()).suggestions(); } else if (e.getCause() instanceof CommandException) { if(e.getCause() instanceof CommandUsageException) { ((CommandUsageException) e.getCause()).offerUsage(getUsage(args, argsCount, method.getAnnotation(Command.class))); } throw (CommandException) e.getCause(); } else if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new WrappedCommandException(e.getCause()); } } catch (Exception e) { logger.log(Level.SEVERE, "Error al ejecutar el comando", e); return Collections.emptyList(); } } } /** * Returns whether a player has access to a command. * * @param method the method * @param player the player * @return true if permission is granted */ protected boolean hasPermission(Method method, T player) { CommandPermissions perms = method.getAnnotation(CommandPermissions.class); if (perms == null) { return true; } for (String perm : perms.value()) { if (hasPermission(player, perm)) { return true; } } if(perms.permission() != Permission.USER) { return hasPermission(player, perms.permission().getPermissionRaw()); } return false; } /** * Returns whether a player has permission.. * * @param player the player * @param permission the permission * @return true if permission is granted */ public abstract boolean hasPermission(T player, String permission); /** * Returns the localized message for the player * * @param player the player * @param message the message * @return the message */ public abstract String getLocalizedMessage(T player, ILang message); /** * Get the injector used to create new instances. This can be * null, in which case only classes will be registered statically. * * @return an injector instance */ public Injector getInjector() { return injector; } /** * Set the injector for creating new instances. * * @param injector injector or null */ public void setInjector(Injector injector) { this.injector = injector; } }
32,455
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandPermissions.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandPermissions.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import me.patothebest.gamecore.permission.Permission; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates a list of permissions that should be checked. */ @Retention(RetentionPolicy.RUNTIME) public @interface CommandPermissions { /** * A list of permissions. Only one permission has to be met * for the command to be permitted. * * @return a list of permissions strings */ String[] value() default {}; /** * @return the permission required to execute the command */ Permission permission() default Permission.USER; }
1,489
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ChildOf.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/ChildOf.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import me.patothebest.gamecore.injector.AbstractBukkitModule; import me.patothebest.gamecore.modules.RegisteredCommandModule; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates a child command. Mark classes with this annotation to tell * {@link CommandsManager} that a class is a child for the parent * command. Not all fields of {@link Command} apply when it is used in * conjunction with this annotation, although both are still required. * <p> * The annotated class must implement the interface * {@link RegisteredCommandModule} and must be registered on the module * with {@link AbstractBukkitModule#registerModule(Class)} */ @Retention(RetentionPolicy.RUNTIME) public @interface ChildOf { /** * The parent command class * * @return the parent command class */ Class<?> value(); }
1,741
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandNumberFormatException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandNumberFormatException.java
package me.patothebest.gamecore.command; public class CommandNumberFormatException extends CommandException { private final String actualText; public CommandNumberFormatException(String actualText) { super("Number expected in place of '" + actualText + "'"); this.actualText = actualText; } public String getActualText() { return actualText; } }
394
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandPermissionsException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandPermissionsException.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; /** * Thrown when not enough permissions are satisfied. */ public class CommandPermissionsException extends CommandException { }
998
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
WrappedCommandException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/WrappedCommandException.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; public class WrappedCommandException extends CommandException { public WrappedCommandException(Throwable t) { super(t); } }
1,008
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
WrappedCommandSender.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/WrappedCommandSender.java
package me.patothebest.gamecore.command; public interface WrappedCommandSender { String getName(); void sendMessage(String message); void sendMessage(String[] messages); boolean hasPermission(String permission); Type getType(); Object getCommandSender(); enum Type { CONSOLE, PLAYER, BLOCK, UNKNOWN } }
374
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
HiddenCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/HiddenCommand.java
package me.patothebest.gamecore.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Defines a command that will be hidden from the help menu */ @Retention(RetentionPolicy.RUNTIME) public @interface HiddenCommand { }
267
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
SimpleInjector.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/SimpleInjector.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import java.lang.reflect.Constructor; import java.util.logging.Level; import java.util.logging.Logger; public class SimpleInjector implements Injector { private static final Logger log = Logger.getLogger(SimpleInjector.class.getCanonicalName()); private final Object[] args; private final Class<?>[] argClasses; public SimpleInjector(Object... args) { this.args = args; argClasses = new Class[args.length]; for (int i = 0; i < args.length; ++i) { argClasses[i] = args[i].getClass(); } } @Override public Object getInstance(Class<?> clazz) { try { Constructor<?> ctr = clazz.getConstructor(argClasses); ctr.setAccessible(true); return ctr.newInstance(args); } catch (Exception e) { log.log(Level.SEVERE, "Error initializing commands class " + clazz, e); return null; } } }
1,802
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandException.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import me.patothebest.gamecore.lang.interfaces.ILang; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import static com.google.common.base.Preconditions.*; public class CommandException extends Exception { private final List<String> commandStack = new ArrayList<>(); private ILang lang; public CommandException() { super(); } public CommandException(ILang lang) { super(); this.lang = lang; } public CommandException(String message) { super(message); } public CommandException(String message, Throwable t) { super(message, t); } public CommandException(Throwable t) { super(t); } public void prependStack(String name) { commandStack.add(name); } /** * Gets the command that was called, which will include the sub-command * (i.e. "/br sphere"). * * @param prefix the command shebang character (such as "/") -- may be empty * @param spacedSuffix a suffix to put at the end (optional) -- may be null * @return the command that was used */ public String getCommandUsed(String prefix, @Nullable String spacedSuffix) { checkNotNull(prefix); StringBuilder builder = new StringBuilder(); builder.append(prefix); ListIterator<String> li = commandStack.listIterator(commandStack.size()); while (li.hasPrevious()) { if (li.previousIndex() != commandStack.size() - 1) { builder.append(" "); } builder.append(li.previous()); } if (spacedSuffix != null) { if (builder.length() > 0) { builder.append(" "); } builder.append(spacedSuffix); } return builder.toString().trim(); } public ILang getLang() { return lang; } }
2,800
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandLocals.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandLocals.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import java.util.HashMap; import java.util.Map; public class CommandLocals { private final Map<Object, Object> locals = new HashMap<>(); public boolean containsKey(Object key) { return locals.containsKey(key); } public boolean containsValue(Object value) { return locals.containsValue(value); } public Object get(Object key) { return locals.get(key); } @SuppressWarnings("unchecked") public <T> T get(Class<T> key) { return (T) locals.get(key); } public Object put(Object key, Object value) { return locals.put(key, value); } }
1,494
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandUsageException.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/CommandUsageException.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command; import javax.annotation.Nullable; public class CommandUsageException extends CommandException { protected @Nullable String usage; public CommandUsageException(String message) { this(message, null); } public CommandUsageException(String message, @Nullable String usage) { super(message); this.usage = usage; } public String getUsage() { return usage != null ? usage : ""; } public void offerUsage(String usage) { if(this.usage == null) { this.usage = usage; } } }
1,435
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
LangDescription.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/LangDescription.java
package me.patothebest.gamecore.command; import me.patothebest.gamecore.lang.interfaces.ILang; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This annotation indicates that a command has a description * that can be translatable per player, meaning that the description * is an enum element which implements {@link ILang}. */ @Retention(value = RetentionPolicy.RUNTIME) public @interface LangDescription { /** * The enum class that extends ILang * * @return the class which we will use to get the enum element */ Class<? extends Enum<? extends ILang>> langClass(); /** * The element name inside the enum * * @return the name of the element we will be using */ String element(); }
788
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandAlias.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/CommandAlias.java
package me.patothebest.gamecore.command.impl; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.Arrays; /** * Hacky class to have command aliases for commands such * as /night to be redirected to /time night and so on * * @author PatoTheBest */ public class CommandAlias extends Command { private final String destCommand; public CommandAlias(String[] commandAliases, String destCommand) { super(commandAliases[0], "Alias para " + destCommand, "/" + commandAliases[0], Arrays.asList(commandAliases)); this.destCommand = destCommand; } @Override public boolean execute(CommandSender sender, String commandLabel, String[] args) { Bukkit.dispatchCommand(sender, destCommand + " " + StringUtils.join(args, " ")); return true; } }
907
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandInfo.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/CommandInfo.java
/* * WorldEdit * Copyright (C) 2012 sk89q <http://www.sk89q.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command.impl; /** * @author zml2008 */ public class CommandInfo { private final String[] aliases; private final Object registeredWith; private final String usage, desc; private final String[] permissions; public CommandInfo(String usage, String desc, String[] aliases, Object registeredWith, String[] permissions) { this.usage = usage; this.desc = desc; this.aliases = aliases; this.permissions = permissions; this.registeredWith = registeredWith; } public String[] getAliases() { return aliases; } public String getName() { return aliases[0]; } public String getUsage() { return usage; } public String getDesc() { return desc; } public String[] getPermissions() { return permissions; } public Object getRegisteredWith() { return registeredWith; } }
1,671
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/CommandManager.java
package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.command.CommandsManager; import org.bukkit.command.CommandSender; public class CommandManager extends CommandsManagerRegistration<CommandSender> { public CommandManager(CorePlugin abstractJavaPlugin) { super(abstractJavaPlugin, new BukkitCommandsManager()); } public CommandsManager<CommandSender> getCommandManager() { return commands; } }
497
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandsManagerRegistration.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/CommandsManagerRegistration.java
// $Id$ /* * WorldEdit * Copyright (C) 2011 sk89q <http://www.sk89q.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.plugin.Plugin; import javax.annotation.Nullable; import javax.inject.Provider; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * @author zml2008 */ public class CommandsManagerRegistration<Sender extends CommandSender> extends CommandRegistration { protected final CommandsManager<Sender> commands; public CommandsManagerRegistration(Plugin plugin, CommandsManager<Sender> commands) { super(plugin); this.commands = commands; } public CommandsManagerRegistration(Plugin plugin, CommandExecutor executor, CommandsManager<Sender> commands) { super(plugin, executor); this.commands = commands; } public CommandsManagerRegistration(Plugin plugin, CommandExecutor executor, @Nullable TabCompleter completer, CommandsManager<Sender> commands) { super(plugin, executor, completer); this.commands = commands; } public boolean register(Class<?> clazz) { return register(clazz, null); } public <T> boolean register(Class<T> clazz, @Nullable Provider<? extends T> provider) { return registerAll(commands.registerMethods(clazz, null, provider)); } public boolean registerAll(List<Command> registered) { List<CommandInfo> toRegister = new ArrayList<>(); for (Command command : registered) { String[] permissions = null; Method cmdMethod = commands.getMethods().get(null).get(command.aliases()[0]); if(cmdMethod != null) { if(cmdMethod.isAnnotationPresent(CommandPermissions.class)) { permissions = cmdMethod.getAnnotation(CommandPermissions.class).value(); } } toRegister.add(new CommandInfo(command.usage(), command.desc(), command.aliases(), commands, permissions)); } return register(toRegister); } }
2,999
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DynamicPluginCommand.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/DynamicPluginCommand.java
// $Id$ /* * WorldEdit * Copyright (C) 2011 sk89q <http://www.sk89q.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.util.StringUtil; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginIdentifiableCommand; import org.bukkit.command.TabCompleter; import org.bukkit.plugin.Plugin; import javax.annotation.Nullable; import java.util.Arrays; import java.util.List; /** * @author zml2008 */ public class DynamicPluginCommand extends org.bukkit.command.Command implements PluginIdentifiableCommand { protected final CommandExecutor executor; protected final @Nullable TabCompleter completer; protected final Object registeredWith; protected final Plugin owningPlugin; protected String[] permissions = new String[0]; public DynamicPluginCommand(String[] aliases, String desc, String usage, CommandExecutor executor, @Nullable TabCompleter completer, Object registeredWith, Plugin plugin) { super(aliases[0], desc, usage, Arrays.asList(aliases)); this.executor = executor; this.completer = completer; this.owningPlugin = plugin; this.registeredWith = registeredWith; } @Override public boolean execute(CommandSender sender, String label, String[] args) { return executor.onCommand(sender, this, label, args); } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { if(completer != null) { final List<String> completions = completer.onTabComplete(sender, this, alias, args); if(completions != null) { return completions; } } return super.tabComplete(sender, alias, args); } public CommandExecutor getExecutor() { return executor; } public TabCompleter getCompleter() { return completer; } public Object getRegisteredWith() { return registeredWith; } public void setPermissions(String[] permissions) { this.permissions = permissions; if (permissions != null) { super.setPermission(StringUtil.joinString(permissions, ";")); } } public String[] getPermissions() { return permissions; } @Override public Plugin getPlugin() { return owningPlugin; } @SuppressWarnings("unchecked") @Override public boolean testPermissionSilent(CommandSender sender) { if (permissions == null || permissions.length == 0) { return true; } if (registeredWith instanceof CommandsManager<?>) { try { for (String permission : permissions) { if (((CommandsManager<CommandSender>) registeredWith).hasPermission(sender, permission)) { return true; } } return false; } catch (Throwable ignore) { } } return super.testPermissionSilent(sender); } }
3,843
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
FallbackRegistrationListener.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/FallbackRegistrationListener.java
// $Id$ /* * WorldEdit * Copyright (C) 2011 sk89q <http://www.sk89q.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command.impl; import org.bukkit.command.CommandMap; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; /** * @author zml2008 */ public class FallbackRegistrationListener implements Listener { private final CommandMap commandRegistration; public FallbackRegistrationListener(CommandMap commandRegistration) { this.commandRegistration = commandRegistration; } @EventHandler(ignoreCancelled = true) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { if (commandRegistration.dispatch(event.getPlayer(), event.getMessage())) { event.setCancelled(true); } } }
1,502
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DynamicPluginCommandHelpTopic.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/DynamicPluginCommandHelpTopic.java
/* * WorldEdit * Copyright (C) 2012 sk89q <http://www.sk89q.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.command.CommandsManager; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.help.HelpTopic; import org.bukkit.help.HelpTopicFactory; import java.util.Map; /** * @author zml2008 */ public class DynamicPluginCommandHelpTopic extends HelpTopic { private final DynamicPluginCommand cmd; public DynamicPluginCommandHelpTopic(DynamicPluginCommand cmd) { this.cmd = cmd; this.name = "/" + cmd.getName(); String fullTextTemp = null; StringBuilder fullText = new StringBuilder(); if (cmd.getRegisteredWith() instanceof CommandsManager) { Map<String, String> helpText = ((CommandsManager<?>) cmd.getRegisteredWith()).getHelpMessages(); final String lookupName = cmd.getName().replaceAll("/", ""); if (helpText.containsKey(lookupName)) { // We have full help text for this command fullTextTemp = helpText.get(lookupName); } // No full help text, assemble help text from info helpText = ((CommandsManager<?>) cmd.getRegisteredWith()).getCommands(); if (helpText.containsKey(cmd.getName())) { final String shortText = helpText.get(cmd.getName()); if (fullTextTemp == null) { fullTextTemp = this.name + " " + shortText; } this.shortText = shortText; } } else { this.shortText = cmd.getDescription(); } // Put the usage in the format: Usage string (newline) Aliases (newline) Help text String[] split = fullTextTemp == null ? new String[2] : fullTextTemp.split("\n", 2); fullText.append(ChatColor.BOLD).append(ChatColor.GOLD).append("Usage: ").append(ChatColor.WHITE); fullText.append(split[0]).append("\n"); if (cmd.getAliases().size() > 0) { fullText.append(ChatColor.BOLD).append(ChatColor.GOLD).append("Aliases: ").append(ChatColor.WHITE); boolean first = true; for (String alias : cmd.getAliases()) { if (!first) { fullText.append(", "); } fullText.append(alias); first = false; } fullText.append("\n"); } if (split.length > 1) { fullText.append(split[1]); } this.fullText = fullText.toString(); } @Override @SuppressWarnings("unchecked") public boolean canSee(CommandSender player) { if (cmd.getPermissions() != null && cmd.getPermissions().length > 0) { if (cmd.getRegisteredWith() instanceof CommandsManager) { try { for (String perm : cmd.getPermissions()) { if (((CommandsManager<Object>) cmd.getRegisteredWith()).hasPermission(player, perm)) { return true; } } } catch (Throwable t) { // Doesn't take the CommandSender (Hooray for compile-time generics!), we have other methods at our disposal } } for (String perm : cmd.getPermissions()) { if (player.hasPermission(perm)) { return true; } } return false; } return true; } @Override public String getFullText(CommandSender forWho) { if (this.fullText == null || this.fullText.length() == 0) { return getShortText(); } else { return this.fullText; } } public static class Factory implements HelpTopicFactory<DynamicPluginCommand> { @Override public HelpTopic createTopic(DynamicPluginCommand command) { return new DynamicPluginCommandHelpTopic(command); } } }
4,696
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BukkitCommandsManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/BukkitCommandsManager.java
package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.command.CommandsManager; import org.bukkit.command.CommandSender; public class BukkitCommandsManager extends CommandsManager<CommandSender> { @Override public boolean hasPermission(CommandSender player, String perm) { return player.hasPermission(perm); } @Override public String getLocalizedMessage(CommandSender player, ILang message) { return message.getMessage(player); } }
552
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandRegistration.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/CommandRegistration.java
// $Id$ /* * WorldEdit * Copyright (C) 2011 sk89q <http://www.sk89q.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.util.ReflectionUtil; import org.bukkit.Bukkit; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandMap; import org.bukkit.command.SimpleCommandMap; import org.bukkit.command.TabCompleter; import org.bukkit.plugin.Plugin; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * @author zml2008 */ public class CommandRegistration { static { Bukkit.getServer().getHelpMap().registerHelpTopicFactory(DynamicPluginCommand.class, new DynamicPluginCommandHelpTopic.Factory()); } protected final Plugin plugin; protected final CommandExecutor executor; protected final TabCompleter completer; private CommandMap fallbackCommands; public CommandRegistration(Plugin plugin) { this(plugin, plugin, plugin); } public CommandRegistration(Plugin plugin, CommandExecutor executor) { this(plugin, executor, null); } public CommandRegistration(Plugin plugin, CommandExecutor executor, @Nullable TabCompleter completer) { this.plugin = plugin; this.executor = executor; this.completer = completer; } public boolean register(List<CommandInfo> registered) { CommandMap commandMap = getCommandMap(); if (registered == null || commandMap == null) { return false; } for (CommandInfo command : registered) { DynamicPluginCommand cmd = new DynamicPluginCommand(command.getAliases(), command.getDesc(), "/" + command.getAliases()[0] + " " + command.getUsage(), executor, completer, command.getRegisteredWith(), plugin); cmd.setPermissions(command.getPermissions()); commandMap.register(plugin.getDescription().getName(), cmd); } return true; } public boolean registerAlias(String[] commandAlias, String destinationCommand) { return register(new CommandAlias(commandAlias, destinationCommand)); } public boolean register(CommandAlias commandAlias) { CommandMap commandMap = getCommandMap(); if (commandAlias == null || commandMap == null) { return false; } commandMap.register(plugin.getDescription().getName(), commandAlias); return true; } public CommandMap getCommandMap() { CommandMap commandMap = ReflectionUtil.getField(plugin.getServer().getPluginManager(), "commandMap"); if (commandMap == null) { if (fallbackCommands != null) { commandMap = fallbackCommands; } else { Bukkit.getServer().getLogger().severe(plugin.getDescription().getName() + ": Could not retrieve server CommandMap, using fallback instead! Please report to Pato"); fallbackCommands = commandMap = new SimpleCommandMap(Bukkit.getServer()); Bukkit.getServer().getPluginManager().registerEvents(new FallbackRegistrationListener(fallbackCommands), plugin); } } return commandMap; } public boolean unregisterCommands() { CommandMap commandMap = getCommandMap(); List<String> toRemove = new ArrayList<>(); Map<String, org.bukkit.command.Command> knownCommands = ReflectionUtil.getField(commandMap, "knownCommands"); Set<String> aliases = ReflectionUtil.getField(commandMap, "aliases"); if (knownCommands == null || aliases == null) { return false; } for (Iterator<org.bukkit.command.Command> i = knownCommands.values().iterator(); i.hasNext();) { org.bukkit.command.Command cmd = i.next(); if ((cmd instanceof DynamicPluginCommand && ((DynamicPluginCommand) cmd).getExecutor().equals(executor)) || (cmd instanceof CommandAlias)) { i.remove(); for (String alias : cmd.getAliases()) { org.bukkit.command.Command aliasCmd = knownCommands.get(alias); if (cmd.equals(aliasCmd)) { aliases.remove(alias); toRemove.add(alias); } } } } for (String string : toRemove) { knownCommands.remove(string); } return true; } }
5,551
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
BukkitWrappedCommandSender.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/command/impl/BukkitWrappedCommandSender.java
package me.patothebest.gamecore.command.impl; import me.patothebest.gamecore.command.WrappedCommandSender; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; public class BukkitWrappedCommandSender implements WrappedCommandSender { public BukkitWrappedCommandSender(CommandSender wrapped) { this.wrapped = wrapped; } @Override public String getName() { return this.wrapped.getName(); } @Override public void sendMessage(String message) { this.wrapped.sendMessage(message); } @Override public void sendMessage(String[] messages) { this.wrapped.sendMessage(messages); } @Override public boolean hasPermission(String permission) { return this.wrapped.hasPermission(permission); } @Override public Type getType() { if (this.wrapped instanceof ConsoleCommandSender) { return Type.CONSOLE; } else if (this.wrapped instanceof Player) { return Type.PLAYER; } else if (this.wrapped instanceof BlockCommandSender) { return Type.BLOCK; } else { return Type.UNKNOWN; } } @Override public Object getCommandSender() { return this.wrapped; } private final CommandSender wrapped; }
1,413
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ScoreboardManager.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/ScoreboardManager.java
package me.patothebest.gamecore.scoreboard; import com.google.inject.Inject; import com.google.inject.Singleton; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.event.player.ArenaLeaveEvent; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.pluginhooks.PluginHookManager; import me.patothebest.gamecore.pluginhooks.hooks.FeatherBoardHook; import me.patothebest.gamecore.event.EventRegistry; import me.patothebest.gamecore.event.player.GameJoinEvent; import me.patothebest.gamecore.event.player.LobbyJoinEvent; import me.patothebest.gamecore.event.player.PlayerJoinPrepareEvent; import me.patothebest.gamecore.modules.ActivableModule; import me.patothebest.gamecore.modules.ReloadPriority; import me.patothebest.gamecore.modules.ReloadableModule; import me.patothebest.gamecore.player.PlayerManager; import me.patothebest.gamecore.util.Priority; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @Singleton @ReloadPriority(priority = Priority.LOW) @ModuleName("Scoreboard Manager") public class ScoreboardManager implements Listener, ActivableModule, ReloadableModule { private final CorePlugin plugin; private final PluginHookManager pluginHookManager; private final PlayerManager playerManager; private final ScoreboardFile scoreboardFile; private final EventRegistry eventRegistry; @Inject private ScoreboardManager(CorePlugin plugin, PluginHookManager pluginHookManager, PlayerManager playerManager, ScoreboardFile scoreboardFile, EventRegistry eventRegistry) { this.plugin = plugin; this.pluginHookManager = pluginHookManager; this.playerManager = playerManager; this.scoreboardFile = scoreboardFile; this.eventRegistry = eventRegistry; } @Override public void onPostEnable() { if(pluginHookManager.isHookLoaded(FeatherBoardHook.class)) { return; } eventRegistry.registerListener(this); } @Override public void onReload() { scoreboardFile.load(); } @Override public String getReloadName() { return "scoreboards"; } @EventHandler(priority = EventPriority.LOWEST) public void onPrepare(PlayerJoinPrepareEvent event) { event.getPlayer().getScoreboards().put(CoreScoreboardType.LOBBY, new CustomScoreboard(plugin, event.getPlayer().getPlayer(), "lobby", scoreboardFile.getConfigurationSection("lobby-scoreboard"))); event.getPlayer().getScoreboards().put(CoreScoreboardType.WAITING, new CustomScoreboard(plugin, event.getPlayer().getPlayer(), "waiting", scoreboardFile.getConfigurationSection("waiting-scoreboard"))); event.getPlayer().show(event.getPlayer().getScoreboardToShow()); } @EventHandler public void onLeaveArena(ArenaLeaveEvent event) { playerManager.getPlayer(event.getPlayer()).show(CoreScoreboardType.LOBBY); if(playerManager.getPlayer(event.getPlayer()).getScoreboards().containsKey(CoreScoreboardType.GAME)) { playerManager.getPlayer(event.getPlayer()).destroy(CoreScoreboardType.GAME); } } @EventHandler public void onJoinLobby(LobbyJoinEvent event) { playerManager.getPlayer(event.getPlayer()).show(CoreScoreboardType.WAITING); } @EventHandler public void onJoinGame(GameJoinEvent event) { playerManager.getPlayer(event.getPlayer()).getScoreboards().put(CoreScoreboardType.GAME, new CustomScoreboard(plugin, event.getPlayer().getPlayer(), "game", scoreboardFile.getConfigurationSection("game-scoreboard"))); playerManager.getPlayer(event.getPlayer()).show(CoreScoreboardType.GAME); } }
3,724
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CoreScoreboardType.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/CoreScoreboardType.java
package me.patothebest.gamecore.scoreboard; public enum CoreScoreboardType implements ScoreboardType { LOBBY("lobby-scoreboard"), WAITING("waiting-scoreboard"), GAME("game-scoreboard"), NONE("none") ; private boolean enabled; private final String configName; CoreScoreboardType(String configName) { this.configName = configName; } @Override public boolean isEnabled() { return enabled; } @Override public String getConfigName() { return configName; } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; } }
643
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
PlayerScoreboard.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/PlayerScoreboard.java
package me.patothebest.gamecore.scoreboard; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; import java.util.HashMap; import java.util.Map; public class PlayerScoreboard { private final static String[] scoreTeams = new String[16]; private static int SCOREBOARD_INDEX; private final Player player; private final Scoreboard scoreboard; private boolean update; private final Objective obj; private final Map<Integer, ScoreboardTeam> teams; public PlayerScoreboard(Player player) { this.player = player; this.teams = new HashMap<>(); this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); this.obj = scoreboard.registerNewObjective("TT-" + SCOREBOARD_INDEX++, "dummy"); this.obj.setDisplaySlot(DisplaySlot.SIDEBAR); } public void tryChange(String text, int score) { Validate.notNull(text, "Scoreboard text cannot be null"); getOrCreateTeam(score).setText(text); } public void remove(int score) { ScoreboardTeam team = getTeam(score); if(team == null) { throw new IllegalArgumentException("Team cannot be found"); } team.getTeam().unregister(); scoreboard.resetScores(team.getScore().getEntry()); teams.remove(score); } public void update() { if(update) { forceUpdate(); update = false; } } public ScoreboardTeam getOrCrateTeam() { for(int i = 0; i < 15; i++) { if(teams.keySet().contains(i)) { continue; } return getOrCreateTeam(i); } return null; } public void destroy() { scoreboard.getTeams().forEach(Team::unregister); teams.clear(); } public void remove(ScoreboardTeam scoreboardTeam) { remove(scoreboardTeam.getOriginalScore()); } public void forceUpdate() { teams.values().forEach(ScoreboardTeam::updateTeam); } public void queueUpdate() { update = true; } public void setTitle(String title) { obj.setDisplayName(title); } public void show() { player.setScoreboard(scoreboard); } public void show(Player player) { player.setScoreboard(scoreboard); } public Scoreboard getScoreboard() { return scoreboard; } /* PRIVATE METHODS */ private ScoreboardTeam getTeam(int score) { return teams.get(score); } ScoreboardTeam getOrCreateTeam(int score) { if(getTeam(score) != null) { return getTeam(score); } Score score1 = obj.getScore(scoreTeams[score]); score1.setScore(score); ScoreboardTeam scoreboardTeam = new ScoreboardTeam(this, scoreboard.registerNewTeam(scoreTeams[score]), scoreTeams[score], score, score1); scoreboardTeam.getTeam().addEntry(scoreTeams[score]); teams.put(score, scoreboardTeam); return scoreboardTeam; } static { for(int i = 0; i < 15; i++) { scoreTeams[i] = ChatColor.values()[i].toString() + ChatColor.RESET; } } }
3,429
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ScoreboardFile.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/ScoreboardFile.java
package me.patothebest.gamecore.scoreboard; import com.google.inject.Inject; import com.google.inject.Singleton; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.modules.ModuleName; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.file.VersionFile; import me.patothebest.gamecore.modules.ActivableModule; import java.io.BufferedWriter; import java.io.IOException; @Singleton @ModuleName("Scoreboard File") public class ScoreboardFile extends VersionFile implements ActivableModule { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final CorePlugin plugin; // -------------------------------------------- // // CONSTRUCTOR // -------------------------------------------- // @Inject private ScoreboardFile(CorePlugin plugin) { super(plugin, "scoreboards"); this.header = "Scoreboards"; this.plugin = plugin; load(); } // -------------------------------------------- // // CACHE // -------------------------------------------- // @Override public void onPreEnable() { for (ScoreboardType scoreboardType : CoreScoreboardType.values()) { if(scoreboardType == CoreScoreboardType.NONE) { continue; } scoreboardType.setEnabled(getBoolean(scoreboardType.getConfigName() + ".enabled")); } } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override protected void writeFile(BufferedWriter writer) throws IOException { super.writeFile(writer); Utils.writeFileToWriter(writer, plugin.getResource("scoreboards.yml")); } }
1,809
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ScoreboardType.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/ScoreboardType.java
package me.patothebest.gamecore.scoreboard; public interface ScoreboardType { boolean isEnabled(); String getConfigName(); void setEnabled(boolean enabled); }
174
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CustomScoreboard.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/CustomScoreboard.java
package me.patothebest.gamecore.scoreboard; import me.patothebest.gamecore.CorePlugin; import me.patothebest.gamecore.util.WrappedBukkitRunnable; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class CustomScoreboard extends WrappedBukkitRunnable { private final CorePlugin plugin; private final Player player; private final String name; private final ScoreboardEntry title; private final PlayerScoreboard playerScoreboard; private final Map<String, ScoreboardEntry> scoreboardEntryMap; private final WrappedBukkitRunnable tickRunnable; public CustomScoreboard(CorePlugin plugin, Player player, String name, ConfigurationSection data) { this.plugin = plugin; this.player = player; this.name = name; this.playerScoreboard = new PlayerScoreboard(player); this.scoreboardEntryMap = new ConcurrentHashMap<>(); final int[] size = {data.getConfigurationSection("content").getKeys(false).size()}; data.getConfigurationSection("content").getKeys(false).forEach(s -> scoreboardEntryMap.put(s, new ScoreboardEntry(this, player, playerScoreboard.getOrCreateTeam(size[0]--), data.getConfigurationSection("content." + s).getValues(true)))); title = new ScoreboardEntry(this, player, playerScoreboard, data.getConfigurationSection("title").getValues(true)); playerScoreboard.update(); this.tickRunnable = new WrappedBukkitRunnable() { @Override public void run() { title.tick(); scoreboardEntryMap.values().forEach(ScoreboardEntry::tick); } }; } public void show() { title.prepare(); scoreboardEntryMap.values().forEach(ScoreboardEntry::prepare); tickRunnable.runTaskTimerAsynchronously(plugin, 1L, 1L); runTaskTimer(plugin, 1L, 1L); playerScoreboard.show(); } @Override public void run() { playerScoreboard.update(); } public void destroy() { if(hasBeenScheduled()) { cancel(); tickRunnable.cancel(); } playerScoreboard.destroy(); scoreboardEntryMap.clear(); } @Override public synchronized void cancel() throws IllegalStateException { super.cancel(); tickRunnable.cancel(); if(player.getScoreboard() == playerScoreboard.getScoreboard()) { player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); } } public Map<String, ScoreboardEntry> getScoreboardEntryMap() { return scoreboardEntryMap; } }
2,745
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ScoreboardEntry.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/ScoreboardEntry.java
package me.patothebest.gamecore.scoreboard; import me.patothebest.gamecore.placeholder.PlaceHolderManager; import me.patothebest.gamecore.util.Tickable; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.animation.AnimationManager; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; public class ScoreboardEntry implements Tickable { private final CustomScoreboard masterBoard; private final Player player; private final int interval; private final List<String> text; private final List<String> parsed; private ScoreboardTeam scoreboardTeam; private final PlayerScoreboard playerScoreboard; private boolean condition; private int tick = 0; private int index = 1; public ScoreboardEntry(CustomScoreboard masterBoard, Player player, ScoreboardTeam scoreboardTeam, Map<String, Object> map) { this(masterBoard, player, (PlayerScoreboard) null, map); this.scoreboardTeam = scoreboardTeam; } @SuppressWarnings("unchecked") public ScoreboardEntry(CustomScoreboard masterBoard, Player player, PlayerScoreboard playerScoreboard, Map<String, Object> map) { this.masterBoard = masterBoard; this.playerScoreboard = playerScoreboard; this.player = player; text = new ArrayList<>(); parsed = new ArrayList<>(); interval = (int) map.get("interval"); text.addAll((Collection<? extends String>) map.get("text")); } public void prepare() { parsed.clear(); text.forEach(s -> parsed.addAll(AnimationManager.parseAnimation(this, PlaceHolderManager.replace(player, s)))); if(parsed.isEmpty()) { return; } if (!condition) { parsed.clear(); text.forEach(s -> parsed.addAll(AnimationManager.parseAnimation(this, s))); } setText(parsed.get(0), !condition); } private void parseText() { parsed.clear(); text.forEach(s -> parsed.addAll(AnimationManager.parseAnimation(this, PlaceHolderManager.replace(player, s)))); } @Override public void tick() { if(parsed.isEmpty()) { return; } tick++; if(tick >= interval) { tick = 0; if(condition) { parseText(); } setText(parsed.get(index++ % parsed.size()), !condition); } } private void setText(String text, boolean replacePlaceholders) { if(playerScoreboard == null) { if(text.contains("|")) { String[] split = text.split("\\|"); if(Utils.isNumber(split[0])) { scoreboardTeam.setScore(Integer.parseInt(split[0])); } text = split[1]; } scoreboardTeam.setText((replacePlaceholders ? PlaceHolderManager.replace(player, text) : text)); scoreboardTeam.getPlayerScoreboard().queueUpdate(); } else { playerScoreboard.setTitle((replacePlaceholders ? PlaceHolderManager.replace(player, text) : text)); } } public ScoreboardTeam getScoreboardTeam() { return scoreboardTeam; } public PlayerScoreboard getPlayerScoreboard() { if(playerScoreboard != null) { return playerScoreboard; } return scoreboardTeam.getPlayerScoreboard(); } public CustomScoreboard getMasterBoard() { return masterBoard; } public Player getPlayer() { return player; } public void setCondition(boolean condition) { this.condition = condition; } }
3,725
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
ScoreboardTeam.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/scoreboard/ScoreboardTeam.java
package me.patothebest.gamecore.scoreboard; import com.google.common.base.Splitter; import org.bukkit.ChatColor; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Team; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ScoreboardTeam { private final PlayerScoreboard playerScoreboard; private final Team team; private final String originalText; private final int originalScore; private final Score score; private String text; private String lastText = null; public ScoreboardTeam(PlayerScoreboard playerScoreboard, Team team, String originalText, int originalScore, Score score) { this.playerScoreboard = playerScoreboard; this.team = team; this.originalText = originalText; this.originalScore = originalScore; this.score = score; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Team getTeam() { return team; } public String getOriginalText() { return originalText; } public int getOriginalScore() { return originalScore; } public PlayerScoreboard getPlayerScoreboard() { return playerScoreboard; } public Score getScore() { return score; } public void setScore(int score) { this.score.setScore(score); } void updateTeam() { if(text == null) { team.setPrefix("ERROR"); return; } if (text.equalsIgnoreCase(lastText)) { return; } lastText = text; if (text.contains("#N/A")) { team.setPrefix(""); team.setSuffix(""); return; } List<String> strings = split(text); team.setPrefix(strings.get(0)); if(strings.size() > 1) { team.setSuffix(strings.get(1)); } else { team.setSuffix(""); } } @Override public String toString() { return "ScoreboardTeam{" + "team=" + team + ", text='" + text + '\'' + '}'; } private List<String> split(final String text) { List<String> list = new ArrayList<>(); if (text.length() <= 16) { list.add(text); return list; } Iterator<String> iterator = Splitter.fixedLength(16).split(text).iterator(); list.add(iterator.next()); if (text.length() > 16) { String line = iterator.next(); char lastChar = list.get(0).charAt(15); char firstChar = line.charAt(0); if ((lastChar == '&' || lastChar == ChatColor.COLOR_CHAR) && ChatColor.getByChar(firstChar) != null) { list.set(0, list.get(0).substring(0, 15)); line = lastChar + line; } line = ChatColor.getLastColors(list.get(0)) + line; if (line.length() > 16) { line = line.substring(0, 15); } list.add(line); } return list; } }
3,106
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
DefaultFontInfo.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/chat/DefaultFontInfo.java
package me.patothebest.gamecore.chat; public enum DefaultFontInfo { A('A', 5), a('a', 5), B('B', 5), b('b', 5), C('C', 5), c('c', 5), D('D', 5), d('d', 5), E('E', 5), e('e', 5), F('F', 5), f('f', 4), G('G', 5), g('g', 5), H('H', 5), h('h', 5), I('I', 3), i('i', 1), J('J', 5), j('j', 5), K('K', 5), k('k', 4), L('L', 5), l('l', 1), M('M', 5), m('m', 5), N('N', 5), n('n', 5), O('O', 5), o('o', 5), P('P', 5), p('p', 5), Q('Q', 5), q('q', 5), R('R', 5), r('r', 5), S('S', 5), s('s', 5), T('T', 5), t('t', 4), U('U', 5), u('u', 5), V('V', 5), v('v', 5), W('W', 5), w('w', 5), X('X', 5), x('x', 5), Y('Y', 5), y('y', 5), Z('Z', 5), z('z', 5), NUM_1('1', 5), NUM_2('2', 5), NUM_3('3', 5), NUM_4('4', 5), NUM_5('5', 5), NUM_6('6', 5), NUM_7('7', 5), NUM_8('8', 5), NUM_9('9', 5), NUM_0('0', 5), EXCLAMATION_POINT('!', 1), AT_SYMBOL('@', 6), NUM_SIGN('#', 5), DOLLAR_SIGN('$', 5), PERCENT('%', 5), UP_ARROW('^', 5), AMPERSAND('&', 5), ASTERISK('*', 5), LEFT_PARENTHESIS('(', 4), RIGHT_PARENTHESIS(')', 4), MINUS('-', 5), UNDERSCORE('_', 5), PLUS_SIGN('+', 5), EQUALS_SIGN('=', 5), LEFT_CURL_BRACE('{', 4), RIGHT_CURL_BRACE('}', 4), LEFT_BRACKET('[', 3), RIGHT_BRACKET(']', 3), COLON(':', 1), SEMI_COLON(';', 1), DOUBLE_QUOTE('"', 3), SINGLE_QUOTE('\'', 1), LEFT_ARROW('<', 4), RIGHT_ARROW('>', 4), QUESTION_MARK('?', 5), SLASH('/', 5), BACK_SLASH('\\', 5), LINE('|', 1), TILDE('~', 5), TICK('`', 2), PERIOD('.', 1), COMMA(',', 1), SPACE(' ', 3), DEFAULT('a', 4); private final char character; private final int length; DefaultFontInfo(char character, int length) { this.character = character; this.length = length; } public char getCharacter(){ return this.character; } public int getLength(){ return this.length; } public int getBoldLength(){ if(this == DefaultFontInfo.SPACE) return this.getLength(); return this.length + 1; } public static DefaultFontInfo getDefaultFontInfo(char c){ for(DefaultFontInfo dFI : DefaultFontInfo.values()){ if(dFI.getCharacter() == c) return dFI; } return DefaultFontInfo.DEFAULT; } }
2,597
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
Pagination.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/chat/Pagination.java
package me.patothebest.gamecore.chat; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import me.patothebest.gamecore.command.ChatColor; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.util.Utils; import me.patothebest.gamecore.util.IndexedFunction; import org.bukkit.command.CommandSender; import javax.annotation.Nullable; import java.util.Collection; import java.util.Iterator; import java.util.List; import static com.google.common.base.Preconditions.*; public class Pagination<T> { public static final int DEFAULT_PER_PAGE = 14; private int perPage = DEFAULT_PER_PAGE; private @Nullable String title; private IndexedFunction<? super T, String> formatter = (t, i) -> String.valueOf(t); public Pagination() { this(DEFAULT_PER_PAGE); } public Pagination(int perPage) { checkArgument(perPage > 0); this.perPage = perPage; } public Pagination<T> perPage(int perPage) { this.perPage = perPage; return this; } public Pagination<T> title(@Nullable String title) { this.title = title; return this; } public Pagination<T> entries(IndexedFunction<? super T, String> formatter) { this.formatter = checkNotNull(formatter); return this; } @SuppressWarnings("unchecked") public void display(CommandSender sender, Collection<? extends T> results, int page) { if (results.isEmpty()) { sender.sendMessage(CoreLang.NO_RESULTS.getMessage(sender)); return; } final int pages = Utils.divideRoundingUp(results.size(), perPage); if (page < 1 || page > pages) { sender.sendMessage(CoreLang.INVALID_PAGRE.replace(sender, page, pages)); return; } final int start = perPage * (page - 1); final int end = Math.min(perPage * page, results.size()); sender.sendMessage(header(page, pages, sender)); String subHeader = subHeader(page, pages); if (subHeader != null && !subHeader.isEmpty()) { sender.sendMessage(subHeader); } if (results instanceof List) { List<? extends T> list = (List<? extends T>) results; for (int index = start; index < end; index++) { multiEntry(list.get(index), index, sender).forEach(o -> { if (o != null) { sendMessage(sender, o); } }); } } else { final Iterator<? extends T> iterator = results.iterator(); for (int index = Iterators.advance(iterator, start); index < end; index++) { multiEntry(iterator.next(), index, sender).forEach(o -> { if (o != null) { sendMessage(sender, o); } }); } } footer(page, pages, sender); } private void sendMessage(CommandSender sender, String message) { if (message == null) { return; } sender.sendMessage(message); } public String header(int page, int pages, CommandSender sender) { String string = org.bukkit.ChatColor.GRAY.toString(); String title = title(); if (title != null) { string += title + ChatColor.BLUE; } string += CoreLang.PAGE.replace(sender, page, pages); return string; } public String subHeader(int page, int pages) { return ""; } public void footer(int page, int pages, CommandSender sender) { } protected @Nullable String title() { return title; } protected String entry(T entry, int index, CommandSender commandSender) { return formatter.apply(entry, index); } protected List<? extends String> multiEntry(T entry, int index, CommandSender commandSender) { String entry1 = entry(entry, index, commandSender); return entry1 != null ? ImmutableList.of(entry1) : ImmutableList.of(); } }
4,123
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z
CommandPagination.java
/FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/chat/CommandPagination.java
package me.patothebest.gamecore.chat; import me.patothebest.gamecore.PluginConfig; import me.patothebest.gamecore.command.ChatColor; import me.patothebest.gamecore.lang.CoreLang; import me.patothebest.gamecore.lang.interfaces.ILang; import me.patothebest.gamecore.permission.Permission; import me.patothebest.gamecore.command.Command; import me.patothebest.gamecore.command.CommandContext; import me.patothebest.gamecore.command.CommandException; import me.patothebest.gamecore.command.CommandPermissions; import me.patothebest.gamecore.command.CommandsManager; import me.patothebest.gamecore.command.LangDescription; import me.patothebest.gamecore.util.Levenshtein; import org.bukkit.command.CommandSender; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class CommandPagination extends Pagination<Map.Entry<String, Command>> { private final CommandsManager<CommandSender> commandsManager; private final CommandContext args; private final String wholeCommand; private final int page; private final Map<String, Command> helpMap; private boolean showAdminInFooter = false; public CommandPagination(CommandsManager<CommandSender> commandManager, CommandContext args) throws CommandException { this.commandsManager = commandManager; StringBuilder cmd = new StringBuilder(); for (int i = 0; i <= args.getLevel(); i++) { cmd.append(args.getWholeArgs()[i]).append(" "); } this.wholeCommand = cmd.toString(); this.args = args; this.perPage(10); if(args.isInBounds(0)) { if(args.isInteger(0)) { page = args.getInteger(0); } else if(args.isInBounds(1) && args.isInteger(1)) { page = args.getInteger(1); } else { page = 1; } } else { page = 1; } helpMap = commandManager.getSubcommandsHelp().get(args.getWholeArgs()[args.getLevel()]); } @Override public String header(int page, int pages, CommandSender sender) { return "§6§l" + PluginConfig.PLUGIN_TITLE + "§f | §7/" + wholeCommand + "help " + CoreLang.PAGE.replace(sender, page, pages); } @Override public String subHeader(int page, int pages) { return ChatColor.GOLD + "Oo-----------------------oOo-----------------------oO"; } @Override protected String entry(Map.Entry<String, Command> entry, int index, CommandSender commandSender) { Command command = entry.getValue(); String description = getDescriptionFromCommand(command, commandSender); CommandPermissions commandPermissions = commandsManager.getCommandPermissions().get(command.aliases()[0]); if(commandPermissions != null) { if(showAdminInFooter) { return null; } else { if(!commandSender.hasPermission(commandPermissions.permission().getBukkitPermission())) { return null; } } } return "§2/" + wholeCommand + command.aliases()[0] + " " + (!command.usage().isEmpty() ? command.usage() + " " : "") + "§a - " + description; } public CommandPagination showAdminInFooter(boolean showAdminCommands) { this.showAdminInFooter = showAdminCommands; this.perPage(DEFAULT_PER_PAGE); return this; } @Override public void footer(int page, int pages, CommandSender sender) { if (showAdminInFooter) { for (Command command : helpMap.values()) { CommandPermissions commandPermissions = commandsManager.getCommandPermissions().get(command.aliases()[0]); if (commandPermissions == null) { continue; } Permission permission = commandPermissions.permission(); if(permission.getDisplayName() != null) { if(sender.hasPermission(permission.getBukkitPermission())) { String description = getDescriptionFromCommand(command, sender); sender.sendMessage("§4" + permission.getDisplayName() + ": §2/" + wholeCommand + command.aliases()[0] + " " + (!command.usage().isEmpty() ? command.usage() + " " : "") + "§a - " + description); } } } } sender.sendMessage(ChatColor.GOLD + "Oo-----------------------oOo-----------------------oO"); } public void display(CommandSender sender) { super.display(sender, helpMap.entrySet(), page); if(args.isInBounds(0) && !args.getString(0).equalsIgnoreCase("help") && !args.isInteger(0)) { sendCorrection(sender, args.getString(0), new ArrayList<>(helpMap.keySet()).stream().map(s -> { if(s.contains(" ")) { return s.split(" ")[0]; } return s; }).collect(Collectors.toList())); } } private void sendCorrection(CommandSender sender, String input, List<String> options) { // get the closest command with the invalid command // using the Levenshtein distance algorithm String closest = Levenshtein.getClosestString(input, options.toArray(new String[0])); if(closest.equals("")) return; // send the correction to the player sender.sendMessage(CoreLang.COMMAND_CORRECTION.replace(sender, "/" + wholeCommand + closest)); } private String getDescriptionFromCommand(Command command, CommandSender commandSender) { LangDescription langDescription = command.langDescription(); if(!langDescription.element().isEmpty()) { Class<? extends Enum<? extends ILang>> aClass = langDescription.langClass(); Enum[] enumValArr = aClass.getEnumConstants(); for (Enum anEnum : enumValArr) { if(anEnum.name().equals(langDescription.element())) { ILang iLang = (ILang) anEnum; return iLang.getMessage(commandSender); } } } else { return command.desc(); } return null; } }
6,303
Java
.java
PatoTheBest/MiniGames
13
2
1
2020-08-07T03:43:56Z
2022-01-23T23:52:46Z