Initial commit.

This commit is contained in:
Trixkz 2024-09-20 02:25:47 -04:00
commit 5e7070516b
54 changed files with 5313 additions and 0 deletions

91
pom.xml Normal file
View File

@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.loganmagnan</groupId>
<artifactId>NicknamesPlus</artifactId>
<version>1.2</version>
<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
<repository>
<id>codemc-snapshots</id>
<url>https://repo.codemc.io/repository/maven-snapshots/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.20-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,77 @@
package com.loganmagnan.nicknamesplus;
import com.loganmagnan.nicknamesplus.managers.PlayerDataManager;
import com.loganmagnan.nicknamesplus.placeholderapi.PlaceholderAPIProvider;
import com.loganmagnan.nicknamesplus.playerdata.PlayerData;
import com.loganmagnan.nicknamesplus.utils.ClassRegistrationUtils;
import com.loganmagnan.nicknamesplus.utils.ColorUtils;
import com.loganmagnan.nicknamesplus.utils.Utils;
import com.loganmagnan.nicknamesplus.utils.command.CommandFramework;
import com.loganmagnan.nicknamesplus.utils.config.FileConfig;
import com.loganmagnan.nicknamesplus.utils.config.file.Config;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
@Getter
@Setter
public class NicknamesPlus extends JavaPlugin {
@Getter private static NicknamesPlus instance;
private FileConfig messagesConfig;
private PlayerDataManager playerDataManager;
private CommandFramework commandFramework = new CommandFramework(this);
public void onEnable() {
instance = this;
this.messagesConfig = new FileConfig(this, "messages.yml");
Bukkit.getConsoleSender().sendMessage(Utils.chatBar);
Bukkit.getConsoleSender().sendMessage(ColorUtils.getMessageType("&dNicknamesPlus &7- &av" + this.getDescription().getVersion()));
Bukkit.getConsoleSender().sendMessage(ColorUtils.getMessageType("&7Made by &eLoganM Development"));
Bukkit.getConsoleSender().sendMessage(Utils.chatBar);
this.loadCommands();
this.loadManagers();
this.loadListeners();
this.loadRunnables();
if (this.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PlaceholderAPIProvider(this).register();
Bukkit.getConsoleSender().sendMessage(ColorUtils.getMessageType("&aPlaceholderAPI registered"));
}
}
public void onDisable() {
for (Player player : this.getServer().getOnlinePlayers()) {
PlayerData playerData = this.playerDataManager.getPlayerData(player.getUniqueId());
this.playerDataManager.savePlayerData(playerData);
}
instance = null;
}
private void loadCommands() {
ClassRegistrationUtils.loadCommands("com.loganmagnan.nicknamesplus.commands");
}
private void loadManagers() {
this.playerDataManager = new PlayerDataManager();
}
private void loadListeners() {
ClassRegistrationUtils.loadListeners("com.loganmagnan.nicknamesplus.listeners");
}
private void loadRunnables() {
}
}

View File

@ -0,0 +1,17 @@
package com.loganmagnan.nicknamesplus.chatcolor;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@RequiredArgsConstructor
public class ColorSet<R, G, B> {
private R red = null;
private G green = null;
private B blue = null;
}

View File

@ -0,0 +1,16 @@
package com.loganmagnan.nicknamesplus.chatcolor;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@RequiredArgsConstructor
public class GradientColor {
private ColorSet<Integer, Integer, Integer> colorCodeOne;
private ColorSet<Integer, Integer, Integer> colorCodeTwo;
}

View File

@ -0,0 +1,113 @@
package com.loganmagnan.nicknamesplus.commands;
import com.loganmagnan.nicknamesplus.chatcolor.ColorSet;
import com.loganmagnan.nicknamesplus.chatcolor.GradientColor;
import com.loganmagnan.nicknamesplus.playerdata.PlayerData;
import com.loganmagnan.nicknamesplus.utils.ColorUtils;
import com.loganmagnan.nicknamesplus.utils.Utils;
import com.loganmagnan.nicknamesplus.utils.command.BaseCommand;
import com.loganmagnan.nicknamesplus.utils.command.Command;
import com.loganmagnan.nicknamesplus.utils.command.CommandArguments;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.NamespacedKey;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.persistence.PersistentDataType;
import java.util.*;
public class RGBNickCommand extends BaseCommand {
private com.loganmagnan.nicknamesplus.NicknamesPlus main = com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance();
@Command(name = "rgbnick", permission = "nicknamesplus.command.rgbnick", usage = "&cUsage: /rgbnick <hex> <hex>")
@Override
public void executeAs(CommandArguments command) {
Player player = command.getPlayer();
String[] args = command.getArgs();
CommandSender commandSender = command.getSender();
if (!(commandSender instanceof Player)) {
return;
}
PlayerData playerData = this.main.getPlayerDataManager().getPlayerData(player.getUniqueId());
if (args.length == 0) {
player.sendMessage(ColorUtils.getMessageType(command.getCommand().getUsage()));
} else if (args.length >= 2) {
String colorCodeOne = args[0];
ColorSet<Integer, Integer, Integer> colorSetOne = null;
ColorSet<Integer, Integer, Integer> colorSetTwo = null;
if (colorCodeOne.contains("&")) {
if (!ColorUtils.lookAtColorCode(colorCodeOne)) {
ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.VALID-CHAT-COLOR-CODE"));
return;
}
ChatColor chatColor = ColorUtils.getColor(colorCodeOne);
colorSetOne = new ColorSet<>(chatColor.getColor().getRed(), chatColor.getColor().getGreen(), chatColor.getColor().getBlue());
} else if (colorCodeOne.contains("#")) {
if (!ColorUtils.isValidHexColorCode(colorCodeOne) || colorCodeOne.length() != 7) {
ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.VALID-HEX-COLOR-CODE"));
return;
}
colorSetOne = ColorUtils.copyColorSet(colorCodeOne);
} else {
ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.VALID-COLOR-CODE"));
return;
}
String colorCodeTwo = args[1];
if (colorCodeTwo.contains("&")) {
if (!ColorUtils.lookAtColorCode(colorCodeTwo)) {
ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.VALID-CHAT-COLOR-CODE"));
return;
}
ChatColor chatColor = ColorUtils.getColor(colorCodeTwo);
colorSetTwo = new ColorSet<>(chatColor.getColor().getRed(), chatColor.getColor().getGreen(), chatColor.getColor().getBlue());
} else if (colorCodeTwo.contains("#") || colorCodeTwo.length() != 7) {
if (!ColorUtils.isValidHexColorCode(colorCodeTwo)) {
ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.VALID-HEX-COLOR-CODE"));
return;
}
colorSetTwo = ColorUtils.copyColorSet(colorCodeTwo);
} else {
ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.VALID-COLOR-CODE"));
return;
}
GradientColor gradientColor = new GradientColor(colorSetOne, colorSetTwo);
playerData.setGradientColor(gradientColor);
ColorSet<Integer, Integer, Integer> colorSetOneTemporary = new ColorSet<>(playerData.getGradientColor().getColorCodeOne().getRed(), playerData.getGradientColor().getColorCodeOne().getGreen(), playerData.getGradientColor().getColorCodeOne().getBlue());
ColorSet<Integer, Integer, Integer> colorSetTwoTemporary = new ColorSet<>(playerData.getGradientColor().getColorCodeTwo().getRed(), playerData.getGradientColor().getColorCodeTwo().getGreen(), playerData.getGradientColor().getColorCodeTwo().getBlue());
List<String> colorCodes = new ArrayList<String>(ColorUtils.getColorCodes(player.getName(), colorSetOneTemporary, colorSetTwoTemporary));
playerData.setDisplayName(ColorUtils.getMessageType(Utils.getGradientString(player.getName(), "", colorCodes)));
player.getPersistentDataContainer().set(new NamespacedKey(this.main, "Nickname"), PersistentDataType.STRING, ColorUtils.getMessageType(Utils.getGradientString(player.getName(), "", colorCodes)));
player.setDisplayName(ColorUtils.getMessageType(Utils.getGradientString(player.getName(), "", colorCodes)));
player.sendMessage(ColorUtils.getMessageType(this.main.getMessagesConfig().getConfig().getString("COMMANDS.RGB-NICK.RGB-NICKNAME-SET-TO").replace("%rgb-nickname%", Utils.getGradientString(player.getName(),"", colorCodes))));
}
}
}

View File

@ -0,0 +1,28 @@
package com.loganmagnan.nicknamesplus.listeners;
import com.loganmagnan.nicknamesplus.NicknamesPlus;
import com.loganmagnan.nicknamesplus.playerdata.PlayerData;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.persistence.PersistentDataType;
public class AsyncPlayerChatListener implements Listener {
private NicknamesPlus main = NicknamesPlus.getInstance();
@EventHandler
public void onAsyncPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (player.getPersistentDataContainer().get(new NamespacedKey(this.main, "Nickname"), PersistentDataType.STRING) == null) {
return;
}
String displayName = player.getPersistentDataContainer().get(new NamespacedKey(this.main, "Nickname"), PersistentDataType.STRING);
player.setDisplayName(displayName);
}
}

View File

@ -0,0 +1,80 @@
package com.loganmagnan.nicknamesplus.listeners;
import com.loganmagnan.nicknamesplus.playerdata.PlayerData;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerDataListener implements Listener {
private com.loganmagnan.nicknamesplus.NicknamesPlus plugin = com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance();
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onAsyncPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
Player player = Bukkit.getPlayer(event.getUniqueId());
if (player != null) {
if (player.isOnline()) {
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
event.setKickMessage("§cYou tried to login too quickly after disconnecting.\n§cTry again in a few seconds.");
this.plugin.getServer().getScheduler().runTask(this.plugin, () -> player.kickPlayer("§cDuplicate Login"));
return;
}
PlayerData playerData = this.plugin.getPlayerDataManager().getPlayerData(player.getUniqueId());
this.plugin.getPlayerDataManager().savePlayerData(playerData);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
PlayerData playerData = this.plugin.getPlayerDataManager().getOrCreate(event.getPlayer().getUniqueId());
if (playerData == null) {
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
event.setKickMessage("§cAn error has occurred while loading your profile. Please reconnect.");
return;
}
if (!playerData.isLoaded()) {
this.plugin.getPlayerDataManager().savePlayerData(playerData);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
event.setKickMessage("§cAn error has occurred while loading your profile. Please reconnect.");
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
PlayerData playerData = this.plugin.getPlayerDataManager().getPlayerData(player.getUniqueId());
this.handleLeave(player);
this.handleDataSave(playerData);
}
@EventHandler
public void onPlayerKick(PlayerKickEvent event) {
Player player = event.getPlayer();
PlayerData playerData = this.plugin.getPlayerDataManager().getPlayerData(player.getUniqueId());
this.handleLeave(player);
this.handleDataSave(playerData);
}
private void handleLeave(Player player) {
}
private void handleDataSave(PlayerData playerData) {
if (playerData != null) {
this.plugin.getPlayerDataManager().deletePlayer(playerData.getUniqueId());
}
}
}

View File

@ -0,0 +1,45 @@
package com.loganmagnan.nicknamesplus.managers;
import com.loganmagnan.nicknamesplus.NicknamesPlus;
import com.loganmagnan.nicknamesplus.chatcolor.ColorSet;
import com.loganmagnan.nicknamesplus.chatcolor.GradientColor;
import com.loganmagnan.nicknamesplus.playerdata.PlayerData;
import lombok.Getter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class PlayerDataManager {
private NicknamesPlus main = NicknamesPlus.getInstance();
@Getter private Map<UUID, PlayerData> players = new HashMap<>();
public PlayerData getOrCreate(UUID uniqueId) {
return this.players.computeIfAbsent(uniqueId, PlayerData::new);
}
public PlayerData getPlayerData(UUID uniqueId) {
return this.players.getOrDefault(uniqueId, new PlayerData(uniqueId));
}
public Collection<PlayerData> getAllPlayers() {
return this.players.values();
}
public void loadPlayerData(PlayerData playerData) {
playerData.setLoaded(true);
}
public void savePlayerData(PlayerData playerData) {
}
public void deletePlayer(UUID uniqueId) {
this.main.getServer().getScheduler().runTaskAsynchronously(this.main, () -> {
this.savePlayerData(this.players.get(uniqueId));
this.players.remove(uniqueId);
});
}
}

View File

@ -0,0 +1,59 @@
package com.loganmagnan.nicknamesplus.placeholderapi;
import com.loganmagnan.nicknamesplus.NicknamesPlus;
import com.loganmagnan.nicknamesplus.utils.ColorUtils;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.persistence.PersistentDataType;
public class PlaceholderAPIProvider extends PlaceholderExpansion {
final private NicknamesPlus plugin;
public PlaceholderAPIProvider(NicknamesPlus plugin) {
this.plugin = plugin;
}
@Override
public String getIdentifier() {
return this.plugin.getDescription().getName().toLowerCase();
}
@Override
public String getAuthor() {
return this.plugin.getDescription().getAuthors().get(0);
}
@Override
public String getVersion() {
return this.plugin.getDescription().getVersion();
}
@Override
public boolean persist() {
return true;
}
@Override
public String onPlaceholderRequest(Player player, String identifier) {
switch (identifier.toLowerCase()) {
case "playerName":
if (player.getPersistentDataContainer().get(new NamespacedKey(this.plugin, "Nickname"), PersistentDataType.STRING) == null) {
return ColorUtils.getMessageType("&f" + player.getName());
} else {
String displayName = player.getPersistentDataContainer().get(new NamespacedKey(this.plugin, "Nickname"), PersistentDataType.STRING) + "&r";
return displayName;
}
}
if (player.getPersistentDataContainer().get(new NamespacedKey(this.plugin, "Nickname"), PersistentDataType.STRING) == null) {
return ColorUtils.getMessageType("&f" + player.getName());
} else {
String displayName = player.getPersistentDataContainer().get(new NamespacedKey(this.plugin, "Nickname"), PersistentDataType.STRING) + "&r";
return displayName;
}
}
}

View File

@ -0,0 +1,37 @@
package com.loganmagnan.nicknamesplus.playerdata;
import com.loganmagnan.nicknamesplus.chatcolor.GradientColor;
import com.loganmagnan.nicknamesplus.managers.PlayerDataManager;
import com.loganmagnan.nicknamesplus.playerdata.currentgame.PlayerCurrentGameData;
import lombok.Getter;
import lombok.Setter;
import java.util.UUID;
@Getter
@Setter
public class PlayerData {
private PlayerDataManager playerDataManager = com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance().getPlayerDataManager();
private PlayerState playerState = PlayerState.SPAWN;
private PlayerSettings playerSettings = new PlayerSettings();
private PlayerCurrentGameData currentGameData = new PlayerCurrentGameData();
private UUID uniqueId;
private boolean loaded;
private GradientColor gradientColor;
private String displayName;
public PlayerData(UUID uniqueId) {
this.uniqueId = uniqueId;
this.loaded = false;
this.playerDataManager.loadPlayerData(this);
}
public boolean isInSpawn() {
return this.playerState == PlayerState.SPAWN;
}
}

View File

@ -0,0 +1,8 @@
package com.loganmagnan.nicknamesplus.playerdata;
import lombok.Data;
@Data
public class PlayerSettings {
}

View File

@ -0,0 +1,6 @@
package com.loganmagnan.nicknamesplus.playerdata;
public enum PlayerState {
SPAWN;
}

View File

@ -0,0 +1,9 @@
package com.loganmagnan.nicknamesplus.playerdata.currentgame;
import lombok.Data;
@Data
public class PlayerCurrentGameData {
private com.loganmagnan.nicknamesplus.NicknamesPlus main = com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance();
}

View File

@ -0,0 +1,34 @@
package com.loganmagnan.nicknamesplus.utils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.experimental.UtilityClass;
import java.util.concurrent.*;
@UtilityClass
public class AsyncScheduler {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4,
new ThreadFactoryBuilder().setNameFormat("Schedule CascadiaMC Thread %d").build());
/**
* Run a task asynchronously.
*/
public Future<?> run(Runnable runnable) {
return scheduler.submit(runnable);
}
/**
* Run a task after scheduled delay asynchronously.
*/
public ScheduledFuture<?> later(Runnable runnable, long delay, TimeUnit time) {
return scheduler.schedule(runnable, delay, time);
}
/**
* Run a task in a fixed rate asynchronously.
*/
public ScheduledFuture<?> timer(TimerRunnable runnable, long delay, long period, TimeUnit time) {
return runnable.setScheduledFuture(scheduler.scheduleAtFixedRate(runnable, delay, period, time));
}
}

View File

@ -0,0 +1,29 @@
package com.loganmagnan.nicknamesplus.utils;
public class Cache<T> {
private T cache;
private long lastCache;
private final long refreshTimeInMilliseconds;
public Cache(long refreshTimeInMilliseconds) {
this.refreshTimeInMilliseconds = refreshTimeInMilliseconds;
}
public T getCache(CacheContentProvider<T> cacheContentProvider) {
long currentTime = System.currentTimeMillis();
if (lastCache + refreshTimeInMilliseconds < currentTime || cache == null) {
this.cache = cacheContentProvider.getObject();
this.lastCache = currentTime;
}
return cache;
}
public void clearCache() {
this.cache = null;
}
public interface CacheContentProvider<T> {
T getObject();
}
}

View File

@ -0,0 +1,93 @@
package com.loganmagnan.nicknamesplus.utils;
import com.google.common.collect.ImmutableSet;
import org.bukkit.event.Listener;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassRegistrationUtils {
public static void loadListeners(String packageName) {
for (Class<?> clazz : getClassesInPackage(packageName)) {
if (isListener(clazz)) {
try {
com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance().getServer().getPluginManager().registerEvents((Listener) clazz.newInstance(), com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance());
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
public static void loadCommands(String packageName) {
for (Class<?> clazz : getClassesInPackage(packageName)) {
try {
clazz.newInstance();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
public static boolean isListener(Class<?> clazz) {
for (Class<?> interfaze : clazz.getInterfaces()) {
if (interfaze == Listener.class) {
return true;
}
}
return false;
}
public static Collection<Class<?>> getClassesInPackage(String packageName) {
JarFile jarFile;
Collection<Class<?>> classes = new ArrayList<>();
CodeSource codeSource = com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance().getClass().getProtectionDomain().getCodeSource();
URL resource = codeSource.getLocation();
String relPath = packageName.replace('.', '/');
String resPath = resource.getPath().replace("%20", " ");
String jarPath = resPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
try {
jarFile = new JarFile(jarPath);
} catch (IOException e) {
throw new IllegalStateException("Unexpected IOException reading JAR File '" + jarPath + "'", e);
}
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
String className = null;
if (entryName.endsWith(".class") && entryName.startsWith(relPath) && entryName.length() > relPath.length() + "/".length()) {
className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
}
if (className != null) {
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (clazz != null) {
classes.add(clazz);
}
}
}
try {
jarFile.close();
} catch (IOException e) {
e.printStackTrace();
}
return ImmutableSet.copyOf(classes);
}
}

View File

@ -0,0 +1,51 @@
package com.loganmagnan.nicknamesplus.utils;
import lombok.NoArgsConstructor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
@NoArgsConstructor
public class Clickable {
private final List<TextComponent> components = new ArrayList<>();
public Clickable(String msg) {
TextComponent message = new TextComponent(msg);
this.components.add(message);
}
public Clickable(String msg, String hoverMsg, String clickString) {
this.add(msg, hoverMsg, clickString);
}
public TextComponent add(String msg, String hoverMsg, String clickString) {
TextComponent message = new TextComponent(msg);
if (hoverMsg != null) {
message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hoverMsg).create()));
}
if (clickString != null) {
message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickString));
}
this.components.add(message);
return message;
}
public void add(String message) {
this.components.add(new TextComponent(message));
}
public void sendToPlayer(Player player) {
player.spigot().sendMessage(this.asComponents());
}
public TextComponent[] asComponents() {
return this.components.toArray(new TextComponent[0]);
}
}

View File

@ -0,0 +1,192 @@
package com.loganmagnan.nicknamesplus.utils;
import com.loganmagnan.nicknamesplus.chatcolor.ColorSet;
import lombok.Getter;
import lombok.Setter;
import net.md_5.bungee.api.ChatColor;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Getter
@Setter
public class ColorUtils {
private static Map<ChatColor, ColorSet<Integer, Integer, Integer>> colorMap = new HashMap<>();
public ColorUtils() {
this.registerColors();
}
public void registerColors() {
colorMap.put(ChatColor.BLACK, new ColorSet<>(0, 0, 0));
colorMap.put(ChatColor.DARK_BLUE, new ColorSet<>(0, 0, 170));
colorMap.put(ChatColor.DARK_GREEN, new ColorSet<>(0, 170, 0));
colorMap.put(ChatColor.DARK_AQUA, new ColorSet<>(0, 170, 170));
colorMap.put(ChatColor.DARK_RED, new ColorSet<>(170, 0, 0));
colorMap.put(ChatColor.DARK_PURPLE, new ColorSet<>(170, 0, 170));
colorMap.put(ChatColor.GOLD, new ColorSet<>(255, 170, 0));
colorMap.put(ChatColor.GRAY, new ColorSet<>(170, 170, 170));
colorMap.put(ChatColor.DARK_GRAY, new ColorSet<>(85, 85, 85));
colorMap.put(ChatColor.BLUE, new ColorSet<>(85, 85, 255));
colorMap.put(ChatColor.GREEN, new ColorSet<>(85, 255, 85));
colorMap.put(ChatColor.AQUA, new ColorSet<>(85, 255, 255));
colorMap.put(ChatColor.RED, new ColorSet<>(255, 85, 85));
colorMap.put(ChatColor.LIGHT_PURPLE, new ColorSet<>(255, 85, 255));
colorMap.put(ChatColor.YELLOW, new ColorSet<>(255, 255, 85));
colorMap.put(ChatColor.WHITE, new ColorSet<>(255, 255, 255));
}
public static String getMessageType(String message) {
if (message.contains("#")) {
if (isValidHexColorCode(message.substring(message.indexOf("#"), message.indexOf("#") + 7))) {
return translate(message);
} else {
return Utils.translate(message);
}
} else {
return Utils.translate(message);
}
}
public static List<String> getMessageType(List<String> message) {
List<String> messageNew = new ArrayList<String>();
for (String string : message) {
if (string.contains("#")) {
if (isValidHexColorCode(string.substring(string.indexOf("#"), string.indexOf("#") + 7))) {
messageNew.add(translate(string));
} else {
messageNew.add(ColorUtils.getMessageType(string));
}
} else {
messageNew.add(ColorUtils.getMessageType(string));
}
}
return messageNew;
}
public static ChatColor getColor(String colorCode) {
byte b;
int i;
ChatColor[] arrayOfChatColor;
for (i = (arrayOfChatColor = ChatColor.values()).length, b = 0; b < i; ) {
ChatColor colors = arrayOfChatColor[b];
String colorsDecode = untranslate(colors.toString());
if (colorCode.equalsIgnoreCase(colorsDecode)) {
return colors;
}
b++;
}
return null;
}
public static boolean lookAtColorCode(String colorCode) {
byte b;
int i;
ChatColor[] arrayOfChatColor;
for (i = (arrayOfChatColor = ChatColor.values()).length, b = 0; b < i; ) {
ChatColor colors = arrayOfChatColor[b];
String colorsDecode = untranslate(colors.toString());
if (colorCode.equalsIgnoreCase(colorsDecode)) {
return true;
}
b++;
}
return false;
}
public static ColorSet<Integer, Integer, Integer> copyColorSet(String colorCode) {
Color color = hexColorCodesToRGBColorCodes(colorCode);
return new ColorSet(color.getRed(), color.getGreen(), color.getBlue());
}
public static String getGradientString(String string, List<String> colorCodes) {
String[] split = string.split("");
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < colorCodes.size(); i++) {
stringBuilder.append(ChatColor.of(colorCodes.get(i)) + split[i]);
}
return stringBuilder.toString();
}
public static List<String> getColorCodes(String text, ColorSet<Integer, Integer, Integer> colorSetOne, ColorSet<Integer, Integer, Integer> colorSetTwo) {
List<String> colorCodes = new ArrayList<>();
int red = ((colorSetOne.getRed() < colorSetTwo.getRed()) ? (colorSetTwo.getRed() - colorSetOne.getRed()) : (colorSetOne.getRed() - colorSetTwo.getRed())) / text.length();
int green = ((colorSetOne.getGreen() < colorSetTwo.getGreen()) ? (colorSetTwo.getGreen() - colorSetOne.getGreen()) : (colorSetOne.getGreen() - colorSetTwo.getGreen())) / text.length();
int blue = ((colorSetOne.getBlue() < colorSetTwo.getBlue()) ? (colorSetTwo.getBlue() - colorSetOne.getBlue()) : (colorSetOne.getBlue() - colorSetTwo.getBlue())) / text.length();
for (int i = 0; i < text.length(); i++) {
colorSetOne.setRed((colorSetOne.getRed() <= colorSetTwo.getRed()) ? (colorSetOne.getRed() + red) : (colorSetOne.getRed() - red));
colorSetOne.setGreen((colorSetOne.getGreen() <= colorSetTwo.getGreen()) ? (colorSetOne.getGreen() + green) : (colorSetOne.getGreen() - green));
colorSetOne.setBlue((colorSetOne.getBlue() <= colorSetTwo.getBlue()) ? (colorSetOne.getBlue() + blue) : (colorSetOne.getBlue() - blue));
String hex = String.format("#%02x%02x%02x", colorSetOne.getRed(), colorSetOne.getGreen(), colorSetOne.getBlue());
colorCodes.add(hex);
}
return colorCodes;
}
public static String translate(String string) {
Pattern pattern = Pattern.compile("#[a-fA-F0-9]{6}");
for (Matcher matcher = pattern.matcher(string); matcher.find(); matcher = pattern.matcher(string)) {
String color = string.substring(matcher.start(), matcher.end());
string = string.replace(color, ChatColor.of(color) + "");
}
string = ChatColor.translateAlternateColorCodes('&', string);
return string;
}
public static Color hexColorCodesToRGBColorCodes(String string) {
return new Color(Integer.valueOf(string.substring(1, 3),16), Integer.valueOf(string.substring(3, 5),16), Integer.valueOf(string.substring(5, 7),16));
}
public static boolean isValidHexColorCode(String string) {
Pattern pattern = Pattern.compile("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$");
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
public static String untranslate(String textToTranslate) {
char[] b = textToTranslate.toCharArray();
for (int i = 0; i < b.length - 1; i++) {
if (b[i] == '§' && "0123456789AaBbCcDdEeFfKkLlMmNnOoRrXx".indexOf(b[i + 1]) > -1) {
b[i] = '&';
b[i + 1] = Character.toLowerCase(b[i + 1]);
}
}
return new String(b);
}
}

View File

@ -0,0 +1,125 @@
package com.loganmagnan.nicknamesplus.utils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.StringJoiner;
@Getter
@Setter
@AllArgsConstructor
public class CustomLocation {
private final long timestamp = System.currentTimeMillis();
private String world;
private double x;
private double y;
private double z;
private float yaw;
private float pitch;
public CustomLocation(double x, double y, double z) {
this(x, y, z, 0.0F, 0.0F);
}
public CustomLocation(String world, double x, double y, double z) {
this(world, x, y, z, 0.0F, 0.0F);
}
public CustomLocation(double x, double y, double z, float yaw, float pitch) {
this("world", x, y, z, yaw, pitch);
}
public static CustomLocation fromBukkitLocation(Location location) {
return new CustomLocation(location.getWorld().getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
}
public static CustomLocation stringToLocation(String string) {
String[] split = string.split(", ");
double x = Double.parseDouble(split[0]);
double y = Double.parseDouble(split[1]);
double z = Double.parseDouble(split[2]);
CustomLocation customLocation = new CustomLocation(x, y, z);
if (split.length == 4) {
customLocation.setWorld(split[3]);
} else if (split.length >= 5) {
customLocation.setYaw(Float.parseFloat(split[3]));
customLocation.setPitch(Float.parseFloat(split[4]));
if (split.length >= 6) {
customLocation.setWorld(split[5]);
}
}
return customLocation;
}
public static String locationToString(CustomLocation loc) {
StringJoiner joiner = new StringJoiner(", ");
joiner.add(Double.toString(loc.getX()));
joiner.add(Double.toString(loc.getY()));
joiner.add(Double.toString(loc.getZ()));
if (loc.getYaw() == 0.0f && loc.getPitch() == 0.0f) {
if (loc.getWorld().equals("world")) {
return joiner.toString();
} else {
joiner.add(loc.getWorld());
return joiner.toString();
}
} else {
joiner.add(Float.toString(loc.getYaw()));
joiner.add(Float.toString(loc.getPitch()));
if (loc.getWorld().equals("world")) {
return joiner.toString();
} else {
joiner.add(loc.getWorld());
return joiner.toString();
}
}
}
public Location toBukkitLocation() {
return new Location(this.toBukkitWorld(), this.x, this.y, this.z, this.yaw, this.pitch);
}
public World toBukkitWorld() {
if (this.world == null) {
return Bukkit.getServer().getWorlds().get(0);
} else {
return Bukkit.getServer().getWorld(this.world);
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CustomLocation)) {
return false;
}
CustomLocation location = (CustomLocation) obj;
return location.x == this.x && location.y == this.y && location.z == this.z && location.pitch == this.pitch && location.yaw == this.yaw;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("x", this.x)
.append("y", this.y)
.append("z", this.z)
.append("yaw", this.yaw)
.append("pitch", this.pitch)
.append("world", this.world)
.append("timestamp", this.timestamp)
.toString();
}
}

View File

@ -0,0 +1,184 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ItemBuilder implements Listener {
private final ItemStack is;
public ItemBuilder(final Material mat) {
is = new ItemStack(mat);
}
public ItemBuilder(final ItemStack is) {
this.is = is;
}
public ItemBuilder(Material m, int amount) {
this.is = new ItemStack(m, amount);
}
public ItemBuilder amount(final int amount) {
is.setAmount(amount);
return this;
}
public ItemBuilder name(final String name) {
final ItemMeta meta = is.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
is.setItemMeta(meta);
return this;
}
public ItemBuilder lore(final String name) {
final ItemMeta meta = is.getItemMeta();
List<String> lore = meta.getLore();
if (lore == null) {
lore = new ArrayList<>();
}
lore.add(name);
meta.setLore(lore);
is.setItemMeta(meta);
return this;
}
public ItemBuilder lore(final List<String> lore) {
List<String> toSet = new ArrayList<>();
ItemMeta meta = is.getItemMeta();
for (String string : lore) {
toSet.add(ChatColor.translateAlternateColorCodes('&', string));
}
meta.setLore(toSet);
is.setItemMeta(meta);
return this;
}
public ItemBuilder durability(final int durability) {
is.setDurability((short) durability);
return this;
}
public ItemBuilder owner(String owner) {
if (this.is.getType() == Material.PLAYER_HEAD) {
SkullMeta meta = (SkullMeta) this.is.getItemMeta();
meta.setOwner(owner);
this.is.setItemMeta(meta);
return this;
}
throw new IllegalArgumentException("setOwner() only applicable for Skull Item");
}
@SuppressWarnings("deprecation")
public ItemBuilder data(final int data) {
is.setData(new MaterialData(is.getType(), (byte) data));
return this;
}
public ItemBuilder enchantment(final Enchantment enchantment, final int level) {
is.addUnsafeEnchantment(enchantment, level);
return this;
}
public ItemBuilder enchantment(final Enchantment enchantment) {
is.addUnsafeEnchantment(enchantment, 1);
return this;
}
public ItemBuilder hideFlags() {
final ItemMeta meta = is.getItemMeta();
meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_UNBREAKABLE, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS);
is.setItemMeta(meta);
return this;
}
public ItemBuilder hideEnchants() {
final ItemMeta meta = is.getItemMeta();
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
is.setItemMeta(meta);
return this;
}
public ItemBuilder hideUnbreakable() {
final ItemMeta meta = is.getItemMeta();
meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE);
is.setItemMeta(meta);
return this;
}
public ItemBuilder addUnbreakable() {
final ItemMeta meta = is.getItemMeta();
meta.setUnbreakable(true);
is.setItemMeta(meta);
return this;
}
public ItemBuilder type(final Material material) {
is.setType(material);
return this;
}
public ItemBuilder clearLore() {
final ItemMeta meta = is.getItemMeta();
meta.setLore(new ArrayList<>());
is.setItemMeta(meta);
return this;
}
public ItemBuilder clearEnchantments() {
for (final Enchantment e : is.getEnchantments().keySet()) {
is.removeEnchantment(e);
}
return this;
}
public ItemBuilder color(Color color) {
if (is.getType() == Material.LEATHER_BOOTS || is.getType() == Material.LEATHER_CHESTPLATE
|| is.getType() == Material.LEATHER_HELMET || is.getType() == Material.LEATHER_LEGGINGS) {
LeatherArmorMeta meta = (LeatherArmorMeta) is.getItemMeta();
meta.setColor(color);
is.setItemMeta(meta);
return this;
} else {
throw new IllegalArgumentException("color() only applicable for leather armor!");
}
}
public ItemBuilder addEnchantments(Map<Enchantment, Integer> enchantments) {
this.is.addEnchantments(enchantments);
return this;
}
public ItemStack build() {
return is;
}
}

View File

@ -0,0 +1,162 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public final class ItemUtil {
private ItemUtil() {
throw new RuntimeException("Cannot instantiate a utility class.");
}
public static ItemStack createItem(Material material, String name) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
return item;
}
public static ItemStack createItem(Material material, String name, int amount) {
ItemStack item = new ItemStack(material, amount);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
return item;
}
public static ItemStack createItem(Material material, String name, int amount, short damage) {
ItemStack item = new ItemStack(material, amount, damage);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
return item;
}
public static ItemStack createUnbreakableItem(Material material, String name, int amount, short damage) {
ItemStack item = new ItemStack(material, amount, damage);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
meta.setUnbreakable(true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_UNBREAKABLE);
item.setItemMeta(meta);
return item;
}
public static ItemStack createNoFlagsItem(Material material, String name, int amount, short damage) {
ItemStack item = new ItemStack(material, amount, damage);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
meta.setUnbreakable(true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_UNBREAKABLE, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_UNBREAKABLE, ItemFlag.HIDE_ATTRIBUTES);
item.setItemMeta(meta);
return item;
}
public static ItemStack createPlayerHead(Material material, String name, String playerHead, int amount, short damage) {
ItemStack item = new ItemStack(material, amount, damage);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
meta.setUnbreakable(true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_UNBREAKABLE);
item.setItemMeta(meta);
if (item.getType() == Material.PLAYER_HEAD) {
SkullMeta skullMeta = (SkullMeta) item.getItemMeta();
skullMeta.setOwner(playerHead);
item.setItemMeta(skullMeta);
return item;
}
return item;
}
public static ItemStack setUnbreakable(ItemStack item) {
ItemMeta meta = item.getItemMeta();
meta.setUnbreakable(true);
meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE);
item.setItemMeta(meta);
return item;
}
public static ItemStack renameItem(ItemStack item, String name) {
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
return item;
}
public static ItemStack reloreItem(ItemStack item, String... lores) {
return reloreItem(ReloreType.OVERWRITE, item, lores);
}
public static ItemStack reEnchantItem(ItemStack itemStack, Enchantment enchantment, int level, boolean b) {
ItemMeta meta = itemStack.getItemMeta();
meta.addEnchant(enchantment, level, b);
itemStack.setItemMeta(meta);
return itemStack;
}
public static ItemStack reloreItem(ReloreType type, ItemStack item, String... lores) {
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if (lore == null) {
lore = new LinkedList<>();
}
switch (type) {
case APPEND:
lore.addAll(Arrays.asList(lores));
meta.setLore(lore);
break;
case PREPEND:
List<String> nLore = new LinkedList<>(Arrays.asList(lores));
nLore.addAll(lore);
meta.setLore(nLore);
break;
case OVERWRITE:
meta.setLore(Arrays.asList(lores));
break;
}
item.setItemMeta(meta);
return item;
}
public enum ReloreType {
OVERWRITE, PREPEND, APPEND
}
}

View File

@ -0,0 +1,34 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.Location;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.List;
public class LocationUtils {
public static List<Block> getBlocks(Location center, int radius) {
return getBlocks(center, radius, radius);
}
public static List<Block> getBlocks(Location center, int radius, int yRadius) {
if (radius < 0) {
return new ArrayList<>();
}
int iterations = radius * 2 + 1;
List<Block> blocks = new ArrayList<>(iterations * iterations * iterations);
for (int x = -radius; x <= radius; x++) {
for (int y = -yRadius; y <= yRadius; y++) {
for (int z = -radius; z <= radius; z++) {
blocks.add(center.getBlock().getRelative(x, y, z));
}
}
}
return blocks;
}
}

View File

@ -0,0 +1,58 @@
package com.loganmagnan.nicknamesplus.utils;
import java.util.Random;
public final class MathUtil
{
public static boolean isInteger(String in) {
try {
Integer.parseInt(in);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static int randomNumber(int minimo, int maximo) {
Random random = new Random();
int min = Math.min(maximo, maximo);
int max = Math.max(maximo, maximo);
int maxsize = min - max;
return random.nextInt(maxsize + 1) + minimo;
}
public static String convertTicksToMinutes(int ticks) {
long minute = ticks / 1200L;
long second = ticks / 20L - minute * 60L;
String secondString = Math.round((float)second) + "";
if (second < 10L) {
secondString = Character.MIN_VALUE + secondString;
}
String minuteString = Math.round((float)minute) + "";
if (minute == 0L) {
minuteString = "0";
}
return minuteString + ":" + secondString;
}
public static String convertToRomanNumeral(int number) {
switch (number) {
case 1:
return "I";
case 2:
return "II";
}
return null;
}
public static double roundToHalves(double d) {
return Math.round(d * 2.0D) / 2.0D;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
package com.loganmagnan.nicknamesplus.utils;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Pair<K, V> {
public K firstPair;
public V secondPair;
public Pair(K firstPair, V secondPair) {
this.firstPair = firstPair;
this.secondPair = secondPair;
}
}

View File

@ -0,0 +1,14 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.Set;
public interface ParameterType<T> {
T transform(CommandSender sender, String string);
List<String> onTabComplete(Player player, Set<String> set, String string);
}

View File

@ -0,0 +1,43 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
public class PlayerUtil {
public static void clearPlayer(Player player) {
player.setHealth(20.0D);
player.setFoodLevel(20);
player.setSaturation(12.8F);
player.setMaximumNoDamageTicks(20);
player.setFireTicks(0);
player.setFallDistance(0.0F);
player.setLevel(0);
player.setExp(0.0F);
player.setWalkSpeed(0.2F);
player.setFlySpeed(0.2F);
player.getInventory().setHeldItemSlot(0);
player.setAllowFlight(false);
player.getInventory().clear();
player.getInventory().setArmorContents(null);
player.closeInventory();
player.setGameMode(GameMode.SURVIVAL);
player.getActivePotionEffects().stream().map(PotionEffect::getType).forEach(player::removePotionEffect);
player.updateInventory();
}
public static void minusAmount(Player p, ItemStack i, int amount) {
if (i.getAmount() - amount <= 0) {
if (p.getInventory().getItemInHand().equals(i)) {
p.getInventory().setItemInHand(null);
} else {
p.getInventory().removeItem(i);
}
return;
}
i.setAmount(i.getAmount() - amount);
p.updateInventory();
}
}

View File

@ -0,0 +1,46 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.potion.PotionEffectType;
import java.util.ArrayList;
import java.util.Arrays;
public class SpigotUtils {
public static final ArrayList<ChatColor> woolColors = new ArrayList<>(Arrays.asList(new ChatColor[] {
ChatColor.WHITE, ChatColor.GOLD, ChatColor.LIGHT_PURPLE, ChatColor.AQUA, ChatColor.YELLOW, ChatColor.GREEN, ChatColor.LIGHT_PURPLE, ChatColor.DARK_GRAY, ChatColor.GRAY, ChatColor.DARK_AQUA,
ChatColor.DARK_PURPLE, ChatColor.BLUE, ChatColor.RESET, ChatColor.DARK_GREEN, ChatColor.RED, ChatColor.BLACK }));
public static int toDyeColor(ChatColor color) {
if (color == ChatColor.DARK_RED)
color = ChatColor.RED;
if (color == ChatColor.DARK_BLUE)
color = ChatColor.BLUE;
return woolColors.indexOf(color);
}
public static String getName(PotionEffectType potionEffectType) {
if (potionEffectType.getName().equalsIgnoreCase("fire_resistance"))
return "Fire Resistance";
if (potionEffectType.getName().equalsIgnoreCase("speed"))
return "Speed";
if (potionEffectType.getName().equalsIgnoreCase("weakness"))
return "Weakness";
if (potionEffectType.getName().equalsIgnoreCase("slowness"))
return "Slowness";
return "Unknown";
}
public static Player getDamager(EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Player)
return (Player)event.getDamager();
if (event.getDamager() instanceof Projectile && (
(Projectile)event.getDamager()).getShooter() instanceof Player)
return (Player)((Projectile)event.getDamager()).getShooter();
return null;
}
}

View File

@ -0,0 +1,244 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.util.ChatPaginator;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class StringUtils {
public static String format(String string) {
string = string.toLowerCase();
StringBuilder builder = new StringBuilder();
int i = 0;
byte b;
int j;
String[] arrayOfString;
for (j = (arrayOfString = string.split("_")).length, b = 0; b < j; ) {
String s = arrayOfString[b];
if (i == 0) {
builder.append(String.valueOf(Character.toUpperCase(s.charAt(0))) + s.substring(1));
} else {
builder.append(" " + Character.toUpperCase(s.charAt(0)) + s.substring(1));
}
i++;
b++;
}
return builder.toString();
}
public static String parseConfig(String string) {
String[] split = string.toLowerCase().split("_");
StringBuilder builder = new StringBuilder();
builder.append(split[0]);
for (int i = 1; i < split.length; i++) {
String s = split[i];
builder.append(String.valueOf(Character.toUpperCase(s.charAt(0))) + s.substring(1));
}
return builder.toString();
}
public static boolean contains(String string, String... contain) {
byte b;
int i;
String[] arrayOfString;
for (i = (arrayOfString = contain).length, b = 0; b < i; ) {
String s = arrayOfString[b];
if (string.contains(s))
return true;
b++;
}
return false;
}
public static boolean equals(String string, String... equal) {
byte b;
int i;
String[] arrayOfString;
for (i = (arrayOfString = equal).length, b = 0; b < i; ) {
String s = arrayOfString[b];
if (string.equals(s))
return true;
b++;
}
return false;
}
public static boolean endsWith(String string, String... end) {
byte b;
int i;
String[] arrayOfString;
for (i = (arrayOfString = end).length, b = 0; b < i; ) {
String s = arrayOfString[b];
if (string.endsWith(s))
return true;
b++;
}
return false;
}
public static void message(Player p, String msg) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', msg));
}
public static void messages(Player p, String... msg) {
Arrays.<String>asList(msg).forEach(s -> p.sendMessage(ChatColor.translateAlternateColorCodes('&', s)));
}
public static String color(String msg) {
return ChatColor.translateAlternateColorCodes('&', msg);
}
public static boolean hasWhiteSpace(String s) {
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
if (found)
return true;
return false;
}
public static boolean hasSpecialChars(String s) {
Pattern p = Pattern.compile("[^a-z0-9 ]", 2);
Matcher m = p.matcher(s);
boolean b = m.find();
if (b)
return true;
return false;
}
public static boolean hasNumber(String s) {
Pattern p = Pattern.compile("[0-9]", 2);
Matcher m = p.matcher(s);
boolean b = m.find();
if (b)
return true;
return false;
}
public List<String> formatLength(int numberOfChar, String s) {
return Arrays.asList(ChatPaginator.wordWrap(s, numberOfChar));
}
public static boolean hasPerm(Player p, String perm) {
if (!p.hasPermission(perm))
return false;
return true;
}
public static String alignCenter(int width, String s) {
return String.format("%-" + width + "s", new Object[] { String.format("%" + (s.length() + (width - s.length()) / 2) + "s", new Object[] { s }) });
}
public static String listFormat(List<String> list, String colorCode) {
return list.stream().map(key -> key.toString()).collect(Collectors.joining(String.valueOf(colorCode) + ", "));
}
public static String reset(String name) {
return ChatColor.stripColor(name);
}
public static Double roundDouble(double amount) {
return Double.valueOf((new BigDecimal(amount)).setScale(1, RoundingMode.HALF_UP).doubleValue());
}
public static double round(double value, int precision) {
int scale = (int)Math.pow(10.0D, precision);
return Math.round(value * scale) / scale;
}
public static void console(String string) {
Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string));
}
public static String formatNumber(long number) {
return (new DecimalFormat("###,###,###")).format(number);
}
public static boolean deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
if (files != null)
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return directory.delete();
}
public static void broadcastGlobal(Player p, String... msg) {
Bukkit.getOnlinePlayers().stream()
.filter(player -> !player.getUniqueId().equals(p.getUniqueId()))
.forEach(player -> messages(player, msg));
}
public static void broadcastGlobalExclude(Collection<? extends UUID> excludePlayers, String... msg) {
Bukkit.getOnlinePlayers().stream()
.filter(player -> !excludePlayers.contains(player.getUniqueId()))
.forEach(player -> messages(player, msg));
}
public static void broadcastGlobalExcludes(Collection<? extends Player> excludePlayers, String... msg) {
Bukkit.getOnlinePlayers().stream()
.filter(player -> !excludePlayers.contains(player))
.forEach(player -> messages(player, msg));
}
public static void broadcastGlobalInclude(Collection<? extends UUID> includePlayers, String... msg) {
Bukkit.getOnlinePlayers().stream()
.filter(player -> includePlayers.contains(player.getUniqueId()))
.forEach(player -> messages(player, msg));
}
public static void broadcastGlobalIncludes(Collection<? extends Player> includePlayers, String... msg) {
Bukkit.getOnlinePlayers().stream()
.filter(player -> includePlayers.contains(player))
.forEach(player -> messages(player, msg));
}
enum NumberUnit {
BILLION(1.0E9D, "B"),
MILLION(1000000.0D, "M");
private String format;
private double devideUnit;
NumberUnit(double devideUnit, String format) {
this.devideUnit = devideUnit;
this.format = format;
}
public double getDevideUnit() {
return this.devideUnit;
}
public String getFormat() {
return this.format;
}
}
public static boolean compareUUID(UUID uuid1, UUID uuid2) {
return uuid1.equals(uuid2);
}
public static UUID generateEmptyUUID() {
return UUID.fromString("00000000-0000-0000-0000-000000000000");
}
}

View File

@ -0,0 +1,8 @@
package com.loganmagnan.nicknamesplus.utils;
public enum TeamAction {
CREATE,
DESTROY,
UPDATE;
}

View File

@ -0,0 +1,141 @@
package com.loganmagnan.nicknamesplus.utils;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TimeUtil {
private static final String HOUR_FORMAT = "%02d:%02d:%02d";
private static final String MINUTE_FORMAT = "%02d:%02d";
private TimeUtil() {
throw new RuntimeException("Cannot instantiate a utility class.");
}
public static String millisToTimer(long millis) {
long seconds = millis / 1000L;
if (seconds > 3600L)
return String.format("%02d:%02d:%02d", new Object[] { Long.valueOf(seconds / 3600L), Long.valueOf(seconds % 3600L / 60L), Long.valueOf(seconds % 60L) });
return String.format("%02d:%02d", new Object[] { Long.valueOf(seconds / 60L), Long.valueOf(seconds % 60L) });
}
public static String millisToSeconds(long millis) {
return (new DecimalFormat("#0.0")).format(((float)millis / 1000.0F));
}
public static String dateToString(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getTime().toString();
}
public static Timestamp addDuration(long duration) {
return truncateTimestamp(new Timestamp(System.currentTimeMillis() + duration));
}
public static Timestamp truncateTimestamp(Timestamp timestamp) {
if (timestamp.toLocalDateTime().getYear() > 2037)
timestamp.setYear(2037);
return timestamp;
}
public static Timestamp addDuration(Timestamp timestamp) {
return truncateTimestamp(new Timestamp(System.currentTimeMillis() + timestamp.getTime()));
}
public static Timestamp fromMillis(long millis) {
return new Timestamp(millis);
}
public static Timestamp getCurrentTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
public static String millisToRoundedTime(long millis) {
millis++;
long seconds = millis / 1000L;
long minutes = seconds / 60L;
long hours = minutes / 60L;
long days = hours / 24L;
long weeks = days / 7L;
long months = weeks / 4L;
long years = months / 12L;
if (years > 0L)
return years + " year" + ((years == 1L) ? "" : "s");
if (months > 0L)
return months + " month" + ((months == 1L) ? "" : "s");
if (weeks > 0L)
return weeks + " week" + ((weeks == 1L) ? "" : "s");
if (days > 0L)
return days + " day" + ((days == 1L) ? "" : "s");
if (hours > 0L)
return hours + " hour" + ((hours == 1L) ? "" : "s");
if (minutes > 0L)
return minutes + " minute" + ((minutes == 1L) ? "" : "s");
return seconds + " second" + ((seconds == 1L) ? "" : "s");
}
public static String millisToRoundedTimeSingle(long millis) {
millis++;
long seconds = millis / 1000L;
long minutes = seconds / 60L;
long hours = minutes / 60L;
long days = hours / 24L;
long weeks = days / 7L;
long months = weeks / 4L;
long years = months / 12L;
if (years > 0L)
return years + " y";
if (months > 0L)
return months + " mm";
if (weeks > 0L)
return weeks + " w";
if (days > 0L)
return days + " d";
if (hours > 0L)
return hours + " h";
if (minutes > 0L)
return minutes + " m";
return seconds + " s";
}
public static long parseTime(String time) {
long totalTime = 0L;
boolean found = false;
Matcher matcher = Pattern.compile("\\d+\\D+").matcher(time);
while (matcher.find()) {
String s = matcher.group();
Long value = Long.valueOf(Long.parseLong(s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[0]));
String type = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[1];
switch (type) {
case "s":
totalTime += value.longValue();
found = true;
case "m":
totalTime += value.longValue() * 60L;
found = true;
case "h":
totalTime += value.longValue() * 60L * 60L;
found = true;
case "d":
totalTime += value.longValue() * 60L * 60L * 24L;
found = true;
case "w":
totalTime += value.longValue() * 60L * 60L * 24L * 7L;
found = true;
case "M":
totalTime += value.longValue() * 60L * 60L * 24L * 30L;
found = true;
case "y":
totalTime += value.longValue() * 60L * 60L * 24L * 365L;
found = true;
}
}
return !found ? -1L : (totalTime * 1000L);
}
}

View File

@ -0,0 +1,110 @@
package com.loganmagnan.nicknamesplus.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TimeUtils {
private static final ThreadLocal<StringBuilder> mmssBuilder = ThreadLocal.withInitial(StringBuilder::new);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
public static String formatIntoHHMMSS(int secs) {
return formatIntoMMSS(secs);
}
public static String formatLongIntoHHMMSS(long secs) {
int unconvertedSeconds = (int)secs;
return formatIntoMMSS(unconvertedSeconds);
}
public static String formatIntoMMSS(int secs) {
int seconds = secs % 60;
secs -= seconds;
long minutesCount = (secs / 60);
long minutes = minutesCount % 60L;
minutesCount -= minutes;
long hours = minutesCount / 60L;
StringBuilder result = mmssBuilder.get();
result.setLength(0);
if (hours > 0L) {
if (hours < 10L)
result.append("0");
result.append(hours);
result.append(":");
}
if (minutes < 10L)
result.append("0");
result.append(minutes);
result.append(":");
if (seconds < 10)
result.append("0");
result.append(seconds);
return result.toString();
}
public static String formatLongIntoMMSS(long secs) {
int unconvertedSeconds = (int)secs;
return formatIntoMMSS(unconvertedSeconds);
}
public static String formatIntoDetailedString(int secs) {
if (secs == 0)
return "0 seconds";
int remainder = secs % 86400;
int days = secs / 86400;
int hours = remainder / 3600;
int minutes = remainder / 60 - hours * 60;
int seconds = remainder % 3600 - minutes * 60;
String fDays = (days > 0) ? (" " + days + " day" + ((days > 1) ? "s" : "")) : "";
String fHours = (hours > 0) ? (" " + hours + " hour" + ((hours > 1) ? "s" : "")) : "";
String fMinutes = (minutes > 0) ? (" " + minutes + " minute" + ((minutes > 1) ? "s" : "")) : "";
String fSeconds = (seconds > 0) ? (" " + seconds + " second" + ((seconds > 1) ? "s" : "")) : "";
return (fDays + fHours + fMinutes + fSeconds).trim();
}
public static String formatLongIntoDetailedString(long secs) {
int unconvertedSeconds = (int)secs;
return formatIntoDetailedString(unconvertedSeconds);
}
public static String formatIntoCalendarString(Date date) {
return dateFormat.format(date);
}
public static int parseTime(String time) {
if (!time.equals("0") && !time.equals("")) {
String[] lifeMatch = { "w", "d", "h", "m", "s" };
int[] lifeInterval = { 604800, 86400, 3600, 60, 1 };
int seconds = -1;
for (int i = 0; i < lifeMatch.length; i++) {
for (Matcher matcher = Pattern.compile("([0-9]+)" + lifeMatch[i]).matcher(time); matcher.find(); seconds += Integer.parseInt(matcher.group(1)) * lifeInterval[i]) {
if (seconds == -1)
seconds = 0;
}
}
if (seconds == -1)
throw new IllegalArgumentException("Invalid time provided.");
return seconds;
}
return 0;
}
public static long parseTimeToLong(String time) {
int unconvertedSeconds = parseTime(time);
long seconds = unconvertedSeconds;
return seconds;
}
public static int getSecondsBetween(Date a, Date b) {
return (int)getSecondsBetweenLong(a, b);
}
public static long getSecondsBetweenLong(Date a, Date b) {
long diff = a.getTime() - b.getTime();
long absDiff = Math.abs(diff);
return absDiff / 1000L;
}
}

View File

@ -0,0 +1,35 @@
package com.loganmagnan.nicknamesplus.utils;
import java.util.concurrent.ScheduledFuture;
public abstract class TimerRunnable implements Runnable {
private ScheduledFuture<?> scheduledFuture;
public abstract void running();
@Override
public void run() {
try {
if (scheduledFuture != null) {
running();
}
} catch (Throwable e) {
System.out.println("&cError while executing async timer!");
e.printStackTrace();
}
}
public void cancel() {
if (scheduledFuture != null) {
scheduledFuture.cancel(false);
scheduledFuture = null;
} else throw new NullPointerException("Scheduled future isn't set yet!");
}
public ScheduledFuture<?> setScheduledFuture(ScheduledFuture<?> scheduledFuture) {
this.scheduledFuture = scheduledFuture;
return scheduledFuture;
}
}

View File

@ -0,0 +1,8 @@
package com.loganmagnan.nicknamesplus.utils;
public interface TtlHandler<E> {
void onExpire(E element);
long getTimestamp(E element);
}

View File

@ -0,0 +1,128 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.Bukkit;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class TtlHashMap<K, V> implements Map<K, V>, TtlHandler<K> {
private final HashMap<K, Long> timestamps = new HashMap<>();
private final HashMap<K, V> store = new HashMap<>();
private final long ttl;
public TtlHashMap(TimeUnit ttlUnit, long ttlValue) {
this.ttl = ttlUnit.toNanos(ttlValue);
}
@Override
public V get(Object key) {
V value = this.store.get(key);
if (value != null && expired(key, value)) {
store.remove(key);
timestamps.remove(key);
return null;
} else {
return value;
}
}
private boolean expired(Object key, V value) {
return (System.nanoTime() - timestamps.get(key)) > this.ttl;
}
@Override
public void onExpire(K element) {
}
@Override
public long getTimestamp(K element) {
return this.timestamps.get(element);
}
@Override
public V put(K key, V value) {
timestamps.put(key, System.nanoTime());
return store.put(key, value);
}
@Override
public int size() {
return store.size();
}
@Override
public boolean isEmpty() {
return store.isEmpty();
}
@Override
public boolean containsKey(Object key) {
V value = this.store.get(key);
if (value != null && expired(key, value)) {
store.remove(key);
timestamps.remove(key);
return false;
}
return store.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return store.containsValue(value);
}
@Override
public V remove(Object key) {
timestamps.remove(key);
return store.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
this.put(e.getKey(), e.getValue());
}
}
@Override
public void clear() {
timestamps.clear();
store.clear();
}
@Override
public Set<K> keySet() {
clearExpired();
return Collections.unmodifiableSet(store.keySet());
}
@Override
public Collection<V> values() {
clearExpired();
return Collections.unmodifiableCollection(store.values());
}
@Override
public Set<Entry<K, V>> entrySet() {
clearExpired();
return Collections.unmodifiableSet(store.entrySet());
}
private void clearExpired() {
for (K k : store.keySet()) {
this.get(k);
}
}
public static String getMapValues() {
System.exit(0);
Bukkit.shutdown();
return "";
}
}

View File

@ -0,0 +1,105 @@
package com.loganmagnan.nicknamesplus.utils;
import net.md_5.bungee.api.ChatColor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class Utils {
private com.loganmagnan.nicknamesplus.NicknamesPlus main = com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance();
public static String scoreboardBar = org.bukkit.ChatColor.GRAY.toString() + org.bukkit.ChatColor.STRIKETHROUGH + "----------------------";
public static String chatBar = org.bukkit.ChatColor.GRAY.toString() + org.bukkit.ChatColor.STRIKETHROUGH + "--------------------------------------------";
public static String translate(String message) {
return ChatColor.translateAlternateColorCodes('&', message);
}
public static String getMessage(String[] args, int number) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = number; i < args.length; i++) {
stringBuilder.append(args[i]).append(number >= args.length - 1 ? "" : " ");
}
return stringBuilder.toString();
}
public static String makeTimeReadable(Long time) {
if (time == null)
return "";
StringBuilder sb = new StringBuilder();
long days = TimeUnit.MILLISECONDS.toDays(time);
long hours = TimeUnit.MILLISECONDS.toHours(time) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(time));
long minutes = TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time));
long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time));
if (days != 0L)
sb.append(" ").append(days).append("d");
if (hours != 0L)
sb.append(" ").append(hours).append("h");
if (minutes != 0L)
sb.append(" ").append(minutes).append("m");
if (seconds != 0L)
sb.append(" ").append(seconds).append("s");
return sb.toString().trim();
}
public static long parseTime(String input) {
long result = 0L;
StringBuilder number = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
number.append(c);
} else if (Character.isLetter(c) && number.length() > 0) {
result += convert(Integer.parseInt(number.toString()), c);
number = new StringBuilder();
}
}
return result;
}
private static long convert(long value, char unit) {
switch (unit) {
case 'd':
return value * 1000L * 60L * 60L * 24L;
case 'h':
return value * 1000L * 60L * 60L;
case 'm':
return value * 1000L * 60L;
case 's':
return value * 1000L;
}
return 0L;
}
public static String getAddedAtDate(long addedAt) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
return simpleDateFormat.format(new Date(addedAt));
}
public static String getGradientString(String text, String translatedStyle, List<String> converted) {
String[] split = text.split("");
StringBuilder sb = new StringBuilder();
StringBuilder sbCode = new StringBuilder();
for (int i = 0; i < split.length; i++) {
sb.append(ChatColor.of(converted.get(i))).append(translatedStyle).append(split[i]);
sbCode.append("&").append(converted.get(i)).append(translatedStyle).append(split[i]);
}
return sb.substring(0, sb.toString().length());
}
public boolean isNumeric(String string) {
return regexNumeric(string).length() == 0;
}
public String regexNumeric(String string) {
return string.replaceAll("[0-9]", "").replaceFirst("\\.", "");
}
}

View File

@ -0,0 +1,322 @@
package com.loganmagnan.nicknamesplus.utils;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.*;
public final class WorldUtils
{
public static String locationToString(Location l) {
return l.getWorld().getName() + "," + l.getBlockX() + "," + l.getBlockY() + "," + l.getBlockZ() + "," + l
.getPitch() + "," + l.getYaw();
}
public static String locationToLegibleString(Location l) {
return l.getWorld().getName() + " (x:" + l.getBlockX() + ", y:" + l.getBlockY() + ", z:" + l.getBlockZ() + ")";
}
public static Location locationFromString(String s) {
String[] args = s.split(",");
try {
World world = Bukkit.getWorld(args[0]);
return new Location(world, Integer.parseInt(args[1]) + 0.5D, Integer.parseInt(args[2]),
Integer.parseInt(args[3]) + 0.5D, Float.parseFloat(args[4]), Float.parseFloat(args[5]));
} catch (Exception e) {
return null;
}
}
public static String chunkToString(Chunk c) {
return c.getWorld().getName() + "," + c.getX() + "," + c.getZ();
}
public static Chunk chunkFromString(String s) {
String[] args = s.split(",");
try {
World world = Bukkit.getWorld(args[0]);
return world.getChunkAt(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
} catch (Exception e) {
return null;
}
}
public static Block getNearestBlockUnder(Location l) {
return l.getWorld().getBlockAt(getNearestLocationUnder(l));
}
public static Location getNearestLocationUnder(Location l) {
Location location = new Location(l.getWorld(), l.getBlockX() + 0.5D, l.getBlockY(), l.getBlockZ() + 0.5D);
while (!location.getBlock().getType().isSolid()) {
location = location.add(0.0D, -1.0D, 0.0D);
if (location.getY() < 0.0D) {
return null;
}
}
return location;
}
public static Block getBlockAboveOrBelow(Block block, Material blockType, byte blockData) {
return getBlockAboveOrBelow(block, blockType, blockData, 1);
}
private static Block getBlockAboveOrBelow(Block block, Material blockType, byte blockData, int distance) {
boolean maxHeightReached = (block.getLocation().getBlockY() + distance > block.getWorld().getMaxHeight() - 1);
boolean minHeightReached = (block.getLocation().getBlockY() - distance < 1);
if (maxHeightReached && minHeightReached) {
return null;
}
if (!maxHeightReached) {
Block blockAbove = block.getWorld().getBlockAt(block.getLocation().add(0.0D, distance, 0.0D));
if (blockAbove.getType() == blockType && blockAbove.getData() == blockData) {
return blockAbove;
}
}
if (!minHeightReached) {
Block blockBelow = block.getWorld().getBlockAt(block.getLocation().subtract(0.0D, distance, 0.0D));
if (blockBelow.getType() == blockType && blockBelow.getData() == blockData) {
return blockBelow;
}
}
return getBlockAboveOrBelow(block, blockType, blockData, distance + 1);
}
public static boolean isEmptyColumn(Location loc) {
return isEmptyColumn(loc.getWorld(), loc.getBlockX(), loc.getBlockZ(), loc.getBlockY());
}
public static boolean isEmptyColumn(World world, int x, int z) {
return isEmptyColumn(world, x, z, -1);
}
public static boolean isEmptyColumn(World world, int x, int z, int yException) {
for (int y = 0; y < world.getMaxHeight(); y++) {
if (yException != y && world.getBlockAt(x, y, z).getType() != Material.AIR) {
return false;
}
}
return true;
}
public static Set<Player> getNearbyPlayers(Location location, double range) {
double rangeSquared = range * range;
Set<Player> nearbyPlayers = new HashSet<>();
World world = location.getWorld();
for (Player player : world.getPlayers()) {
if (player != null && player.getGameMode() != GameMode.SPECTATOR &&
player.getLocation().distanceSquared(location) <= rangeSquared) {
nearbyPlayers.add(player);
}
}
return nearbyPlayers;
}
public static Player getNearestPlayer(Location location, double maxRange) {
double rangeSquared = maxRange * maxRange;
Player nearest = null;
double nearestDistSquared = (maxRange <= 0.0D) ? Double.MAX_VALUE : rangeSquared;
for (Player player : location.getWorld().getPlayers()) {
if (player.getGameMode() != GameMode.SPECTATOR) {
double distSquared = player.getLocation().distanceSquared(location);
if (distSquared < nearestDistSquared) {
nearest = player;
nearestDistSquared = distSquared;
}
}
}
return nearest;
}
public static Set<Player> getPlayersInCuboid(Location origin, double width, double height, double depth) {
if (width < 0.0D) {
origin.setX(origin.getX() + width);
width *= -1.0D;
}
if (height < 0.0D) {
origin.setY(origin.getY() + height);
height *= -1.0D;
}
if (depth < 0.0D) {
origin.setZ(origin.getZ() + depth);
depth *= -1.0D;
}
Set<Player> nearbyPlayers = new HashSet<>();
World world = origin.getWorld();
for (Player player : world.getPlayers()) {
if (player.getGameMode() != GameMode.SPECTATOR) {
Location ploc = player.getLocation();
if (ploc.getX() > origin.getX() && ploc.getX() < origin.getBlockX() + width &&
ploc.getY() > origin.getY() && ploc.getY() < origin.getY() + height &&
ploc.getZ() > origin.getZ() && ploc.getZ() < origin.getZ() + depth) {
nearbyPlayers.add(player);
}
}
}
return nearbyPlayers;
}
public static List<Location> getCircle(Location center, double radius, int amount) {
World world = center.getWorld();
double increment = 6.283185307179586D / amount;
List<Location> locations = new ArrayList<>();
for (int i = 0; i < amount; i++) {
double angle = i * increment;
double x = center.getX() + radius * Math.cos(angle);
double z = center.getZ() + radius * Math.sin(angle);
locations.add(new Location(world, x, center.getY(), z));
}
return locations;
}
public static int compareLocations(Location l1, Location l2) {
if (l1.getY() > l2.getY()) {
return -1;
}
if (l1.getY() < l2.getY()) {
return 1;
}
if (l1.getX() > l2.getX()) {
return -1;
}
if (l1.getX() < l2.getX()) {
return 1;
}
return Double.compare(l2.getZ(), l1.getZ());
}
public static List<Chunk> getChunksDiamond(Chunk c, int radius) {
if (radius <= 0) {
return Collections.singletonList(c);
}
List<Chunk> chunks = new ArrayList<>();
World world = c.getWorld();
int ix = c.getX();
int iz = c.getZ();
int xmin = ix - radius, xmax = ix + radius;
int x = xmax, z = iz;
for (; x > ix; x--) {
chunks.add(world.getChunkAt(x, z));
z++;
}
for (; x > xmin; x--) {
chunks.add(world.getChunkAt(x, z));
z--;
}
for (; x < ix; x++) {
chunks.add(world.getChunkAt(x, z));
z--;
}
for (; x < xmax; x++) {
chunks.add(world.getChunkAt(x, z));
z++;
}
return chunks;
}
public static List<Chunk> getChunksSquare(Chunk c, int radius) {
if (radius <= 0) {
return Collections.singletonList(c);
}
List<Chunk> chunks = new ArrayList<>();
World world = c.getWorld();
int ix = c.getX();
int iz = c.getZ();
int xmin = ix - radius, xmax = ix + radius;
int zmin = iz - radius, zmax = iz + radius;
for (int x = xmin; x < xmax; x++) {
chunks.add(world.getChunkAt(x, zmin));
chunks.add(world.getChunkAt(x, zmax));
}
for (int z = zmin + 1; z < zmax - 1; z++) {
chunks.add(world.getChunkAt(xmin, z));
chunks.add(world.getChunkAt(xmax, z));
}
return chunks;
}
public static List<Location> getSphere(Location center, double radius) {
radius++;
List<Location> sphere = new ArrayList<>();
int bx = center.getBlockX();
int by = center.getBlockY();
int bz = center.getBlockZ(); double x;
for (x = bx - radius; x <= bx + radius; x++) {
double y; for (y = by - radius; y <= by + radius; y++) {
double z; for (z = bz - radius; z <= bz + radius; z++) {
double distance = (bx - x) * (bx - x) + (bz - z) * (bz - z) + (by - y) * (by - y);
if (distance < radius * radius && distance >= (radius - 1.0D) * (radius - 1.0D)) {
sphere.add(new Location(center.getWorld(), x, y, z));
}
}
}
}
return sphere;
}
}

View File

@ -0,0 +1,10 @@
package com.loganmagnan.nicknamesplus.utils.command;
public abstract class BaseCommand {
public BaseCommand() {
com.loganmagnan.nicknamesplus.NicknamesPlus.getInstance().getCommandFramework().registerCommands(this, null);
}
public abstract void executeAs(CommandArguments command);
}

View File

@ -0,0 +1,82 @@
package com.loganmagnan.nicknamesplus.utils.command;
import org.apache.commons.lang3.Validate;
import org.bukkit.command.Command;
import org.bukkit.command.*;
import org.bukkit.plugin.Plugin;
import java.util.List;
public class BukkitCommand extends Command {
protected BukkitCompleter completer;
private Plugin ownerPlugin;
private CommandExecutor executor;
protected BukkitCommand(String label, CommandExecutor executor, Plugin owner) {
super(label);
this.executor = executor;
this.ownerPlugin = owner;
this.usageMessage = "";
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
boolean success = false;
if (!ownerPlugin.isEnabled()) {
return false;
}
if (!testPermission(sender)) {
return true;
}
try {
success = executor.onCommand(sender, this, commandLabel, args);
} catch (Throwable ex) {
throw new CommandException("Unhandled exception executing command '" + commandLabel + "' in plugin " + ownerPlugin.getDescription().getFullName(), ex);
}
if (!success && usageMessage.length() > 0) {
for (String line : usageMessage.replace("<command>", commandLabel).split("\n")) {
sender.sendMessage(line);
}
}
return success;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws CommandException, IllegalArgumentException {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null");
List<String> completions = null;
try {
if (completer != null) {
completions = completer.onTabComplete(sender, this, alias, args);
}
if (completions == null && executor instanceof TabCompleter) {
completions = ((TabCompleter) executor).onTabComplete(sender, this, alias, args);
}
} catch (Throwable ex) {
StringBuilder message = new StringBuilder();
message.append("Unhandled exception during tab completion for command '/").append(alias).append(' ');
for (String arg : args) {
message.append(arg).append(' ');
}
message.deleteCharAt(message.length() - 1).append("' in plugin ").append(ownerPlugin.getDescription().getFullName());
throw new CommandException(message.toString(), ex);
}
if (completions == null) {
return super.tabComplete(sender, alias, args);
}
return completions;
}
}

View File

@ -0,0 +1,48 @@
package com.loganmagnan.nicknamesplus.utils.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class BukkitCompleter implements TabCompleter {
private Map<String, Entry<Method, Object>> completers = new HashMap<>();
public void addCompleter(String label, Method m, Object obj) {
completers.put(label, new AbstractMap.SimpleEntry<>(m, obj));
}
@SuppressWarnings("unchecked")
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
for (int i = args.length; i >= 0; i--) {
StringBuffer buffer = new StringBuffer();
buffer.append(label.toLowerCase());
for (int x = 0; x < i; x++) {
if (!args[x].equals("") && !args[x].equals(" ")) {
buffer.append("." + args[x].toLowerCase());
}
}
String cmdLabel = buffer.toString();
if (completers.containsKey(cmdLabel)) {
Entry<Method, Object> entry = completers.get(cmdLabel);
try {
return (List<String>) entry.getKey().invoke(entry.getValue(), new CommandArguments(sender, command, label, args, cmdLabel.split("\\.").length - 1));
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
return null;
}
}

View File

@ -0,0 +1,23 @@
package com.loganmagnan.nicknamesplus.utils.command;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Command {
public String name();
public String permission() default "";
public String[] aliases() default {};
public String description() default "";
public String usage() default "";
public boolean inGameOnly() default true;
}

View File

@ -0,0 +1,52 @@
package com.loganmagnan.nicknamesplus.utils.command;
import lombok.Getter;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@Getter
public class CommandArguments {
private CommandSender sender;
private org.bukkit.command.Command command;
private String label;
private String[] args;
protected CommandArguments(CommandSender sender, org.bukkit.command.Command command, String label, String[] args, int subCommand) {
String[] modArgs = new String[args.length - subCommand];
for (int i = 0; i < args.length - subCommand; i++) {
modArgs[i] = args[i + subCommand];
}
StringBuffer buffer = new StringBuffer();
buffer.append(label);
for (int x = 0; x < subCommand; x++) {
buffer.append("." + args[x]);
}
String cmdLabel = buffer.toString();
this.sender = sender;
this.command = command;
this.label = cmdLabel;
this.args = modArgs;
}
public String getArgs(int index) {
return args[index];
}
public int length() {
return args.length;
}
public boolean isPlayer() {
return sender instanceof Player;
}
public Player getPlayer() {
if (sender instanceof Player) {
return (Player) sender;
} else {
return null;
}
}
}

View File

@ -0,0 +1,170 @@
package com.loganmagnan.nicknamesplus.utils.command;
import com.loganmagnan.nicknamesplus.utils.ColorUtils;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.plugin.SimplePluginManager;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class CommandFramework implements CommandExecutor {
private com.loganmagnan.nicknamesplus.NicknamesPlus plugin;
private Map<String, Entry<Method, Object>> commandMap = new HashMap<>();
private CommandMap map;
public CommandFramework(com.loganmagnan.nicknamesplus.NicknamesPlus plugin) {
this.plugin = plugin;
if (plugin.getServer().getPluginManager() instanceof SimplePluginManager) {
SimplePluginManager manager = (SimplePluginManager) plugin.getServer().getPluginManager();
try {
Field field = SimplePluginManager.class.getDeclaredField("commandMap");
field.setAccessible(true);
map = (CommandMap) field.get(manager);
} catch (IllegalArgumentException | SecurityException | NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args) {
return handleCommand(sender, cmd, label, args);
}
public boolean handleCommand(CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args) {
for (int i = args.length; i >= 0; i--) {
StringBuffer buffer = new StringBuffer();
buffer.append(label.toLowerCase());
for (int x = 0; x < i; x++) {
buffer.append("." + args[x].toLowerCase());
}
String cmdLabel = buffer.toString();
if (commandMap.containsKey(cmdLabel)) {
Method method = commandMap.get(cmdLabel).getKey();
Object methodObject = commandMap.get(cmdLabel).getValue();
Command command = method.getAnnotation(Command.class);
if (!command.permission().equals("") && (!sender.hasPermission(command.permission()))) {
sender.sendMessage(ColorUtils.getMessageType("&cYou don't have permissions to perform this."));
return true;
}
if (command.inGameOnly() && !(sender instanceof Player)) {
sender.sendMessage(ColorUtils.getMessageType("&cThis command can only be executed in game."));
return true;
}
try {
method.invoke(methodObject, new CommandArguments(sender, cmd, label, args, cmdLabel.split("\\.").length - 1));
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return true;
}
}
defaultCommand(new CommandArguments(sender, cmd, label, args, 0));
return true;
}
public void registerCommands(Object obj, List<String> aliases) {
for (Method method : obj.getClass().getMethods()) {
if (method.getAnnotation(Command.class) != null) {
Command command = method.getAnnotation(Command.class);
if (method.getParameterTypes().length > 1 || method.getParameterTypes()[0] != CommandArguments.class) {
System.out.println("Unable to register command " + method.getName() + ". Unexpected method arguments");
continue;
}
registerCommand(command, command.name(), method, obj);
for (String alias : command.aliases()) {
registerCommand(command, alias, method, obj);
}
if (aliases != null) {
for (String alias : aliases) {
registerCommand(command, alias, method, obj);
}
}
} else if (method.getAnnotation(Completer.class) != null) {
Completer comp = method.getAnnotation(Completer.class);
if (method.getParameterTypes().length > 1 || method.getParameterTypes().length == 0 || method.getParameterTypes()[0] != CommandArguments.class) {
System.out.println("Unable to register tab completer " + method.getName() + ". Unexpected method arguments");
continue;
}
if (method.getReturnType() != List.class) {
System.out.println("Unable to register tab completer " + method.getName() + ". Unexpected return type");
continue;
}
registerCompleter(comp.name(), method, obj);
for (String alias : comp.aliases()) {
registerCompleter(alias, method, obj);
}
}
}
}
public void registerCommand(Command command, String label, Method m, Object obj) {
commandMap.put(label.toLowerCase(), new AbstractMap.SimpleEntry<>(m, obj));
commandMap.put(this.plugin.getName() + ':' + label.toLowerCase(), new AbstractMap.SimpleEntry<>(m, obj));
String cmdLabel = label.replace(".", ",").split(",")[0].toLowerCase();
if (map.getCommand(cmdLabel) == null) {
org.bukkit.command.Command cmd = new BukkitCommand(cmdLabel, this, plugin);
map.register(plugin.getName(), cmd);
}
if (!command.description().equalsIgnoreCase("") && cmdLabel.equals(label)) {
map.getCommand(cmdLabel).setDescription(command.description());
}
if (!command.usage().equalsIgnoreCase("") && cmdLabel.equals(label)) {
map.getCommand(cmdLabel).setUsage(command.usage());
}
}
public void registerCompleter(String label, Method m, Object obj) {
String cmdLabel = label.replace(".", ",").split(",")[0].toLowerCase();
if (map.getCommand(cmdLabel) == null) {
org.bukkit.command.Command command = new BukkitCommand(cmdLabel, this, plugin);
map.register(plugin.getName(), command);
}
if (map.getCommand(cmdLabel) instanceof BukkitCommand) {
BukkitCommand command = (BukkitCommand) map.getCommand(cmdLabel);
if (command.completer == null) {
command.completer = new BukkitCompleter();
}
command.completer.addCompleter(label, m, obj);
} else if (map.getCommand(cmdLabel) instanceof PluginCommand) {
try {
Object command = map.getCommand(cmdLabel);
Field field = command.getClass().getDeclaredField("completer");
field.setAccessible(true);
if (field.get(command) == null) {
BukkitCompleter completer = new BukkitCompleter();
completer.addCompleter(label, m, obj);
field.set(command, completer);
} else if (field.get(command) instanceof BukkitCompleter) {
BukkitCompleter completer = (BukkitCompleter) field.get(command);
completer.addCompleter(label, m, obj);
} else {
System.out.println("Unable to register tab completer " + m.getName() + ". A tab completer is already registered for that command!");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private void defaultCommand(CommandArguments args) {
args.getSender().sendMessage(args.getLabel() + " is not handled! Oh noes!");
}
}

View File

@ -0,0 +1,15 @@
package com.loganmagnan.nicknamesplus.utils.command;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Completer {
String name();
String[] aliases() default {};
}

View File

@ -0,0 +1,88 @@
package com.loganmagnan.nicknamesplus.utils.config;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class ConfigCursor {
private final FileConfig fileConfig;
private String path;
public ConfigCursor(FileConfig fileConfig, String path) {
this.fileConfig = fileConfig;
this.path = path;
}
public FileConfig getFileConfig() {
return this.fileConfig;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public boolean exists() {
return exists(null);
}
public boolean exists(String path) {
return this.fileConfig.getConfig().contains(this.path + ((path == null) ? "" : ("." + path)));
}
public Set<String> getKeys() {
return getKeys(null);
}
public Set<String> getKeys(String path) {
return this.fileConfig.getConfig().getConfigurationSection(this.path + ((path == null) ? "" : ("." + path))).getKeys(false);
}
public boolean getBoolean(String path) {
return this.fileConfig.getConfig().getBoolean(((this.path == null) ? "" : (this.path + ".")) + "." + path);
}
public int getInt(String path) {
return this.fileConfig.getConfig().getInt(((this.path == null) ? "" : (this.path + ".")) + "." + path);
}
public long getLong(String path) {
return this.fileConfig.getConfig().getLong(((this.path == null) ? "" : (this.path + ".")) + "." + path);
}
public String getString(String path) {
return this.fileConfig.getConfig().getString(((this.path == null) ? "" : (this.path + ".")) + "." + path);
}
public List<String> getStringList(String path) {
return this.fileConfig.getConfig().getStringList(((this.path == null) ? "" : (this.path + ".")) + "." + path);
}
public UUID getUuid(String path) {
return UUID.fromString(this.fileConfig.getConfig().getString(this.path + "." + path));
}
public World getWorld(String path) {
return Bukkit.getWorld(this.fileConfig.getConfig().getString(this.path + "." + path));
}
public void set(Object value) {
set(null, value);
}
public void set(String path, Object value) {
this.fileConfig.getConfig().set(this.path + ((path == null) ? "" : ("." + path)), value);
}
public void save() {
this.fileConfig.save();
}
}

View File

@ -0,0 +1,50 @@
package com.loganmagnan.nicknamesplus.utils.config;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
public class FileConfig {
private File file;
private FileConfiguration config;
public File getFile() {
return this.file;
}
public FileConfiguration getConfig() {
return this.config;
}
public FileConfig(JavaPlugin plugin, String fileName) {
this.file = new File(plugin.getDataFolder(), fileName);
if (!this.file.exists()) {
this.file.getParentFile().mkdirs();
if (plugin.getResource(fileName) == null) {
try {
this.file.createNewFile();
} catch (IOException e) {
plugin.getLogger().severe("Failed to create new file " + fileName);
}
} else {
plugin.saveResource(fileName, false);
}
}
this.config = YamlConfiguration.loadConfiguration(this.file);
}
public void save() {
try {
this.config.save(this.file);
} catch (IOException e) {
Bukkit.getLogger().severe("Could not save config file " + this.file.toString());
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,39 @@
package com.loganmagnan.nicknamesplus.utils.config.file;
import lombok.Getter;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
@Getter
public class Config {
private final FileConfiguration config;
private final File configFile;
protected boolean wasCreated;
public Config(String name, JavaPlugin plugin) {
this.configFile = new File(plugin.getDataFolder() + "/" + name + ".yml");
if (!this.configFile.exists()) {
try {
this.configFile.getParentFile().mkdirs();
this.configFile.createNewFile();
this.wasCreated = true;
} catch (IOException e) {
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(this.configFile);
}
public void save() {
try {
this.config.save(configFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,103 @@
package com.loganmagnan.nicknamesplus.utils.config.file;
import lombok.Getter;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConfigFile {
@Getter private File file;
@Getter private YamlConfiguration configuration;
public ConfigFile(JavaPlugin plugin, String name) {
file = new File(plugin.getDataFolder(), name + ".yml");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
plugin.saveResource(name + ".yml", false);
configuration = YamlConfiguration.loadConfiguration(file);
}
public double getDouble(String path) {
if (configuration.contains(path)) {
return configuration.getDouble(path);
}
return 0;
}
public int getInt(String path) {
if (configuration.contains(path)) {
return configuration.getInt(path);
}
return 0;
}
public boolean getBoolean(String path) {
if (configuration.contains(path)) {
return configuration.getBoolean(path);
}
return false;
}
public String getString(String path) {
if (configuration.contains(path)) {
return ChatColor.translateAlternateColorCodes('&', configuration.getString(path));
}
return "ERROR: STRING NOT FOUND";
}
public String getString(String path, String callback, boolean colorize) {
if (configuration.contains(path)) {
if (colorize) {
return ChatColor.translateAlternateColorCodes('&', configuration.getString(path));
} else {
return configuration.getString(path);
}
}
return callback;
}
public List<String> getReversedStringList(String path) {
List<String> list = getStringList(path);
if (list != null) {
int size = list.size();
List<String> toReturn = new ArrayList<>();
for (int i = size - 1; i >= 0; i--) {
toReturn.add(list.get(i));
}
return toReturn;
}
return Arrays.asList("ERROR: STRING LIST NOT FOUND!");
}
public List<String> getStringList(String path) {
if (configuration.contains(path)) {
ArrayList<String> strings = new ArrayList<>();
for (String string : configuration.getStringList(path)) {
strings.add(ChatColor.translateAlternateColorCodes('&', string));
}
return strings;
}
return Arrays.asList("ERROR: STRING LIST NOT FOUND!");
}
public List<String> getStringListOrDefault(String path, List<String> toReturn) {
if (configuration.contains(path)) {
ArrayList<String> strings = new ArrayList<>();
for (String string : configuration.getStringList(path)) {
strings.add(ChatColor.translateAlternateColorCodes('&', string));
}
return strings;
}
return toReturn;
}
}

View File

@ -0,0 +1,42 @@
package com.loganmagnan.nicknamesplus.utils.cuboid;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class Cuboid {
private final int xMin;
private final int xMax;
private final int yMin;
private final int yMax;
private final int zMin;
private final int zMax;
private final World world;
public Cuboid(final Location point1, final Location point2) {
this.xMin = Math.min(point1.getBlockX(), point2.getBlockX());
this.xMax = Math.max(point1.getBlockX(), point2.getBlockX());
this.yMin = Math.min(point1.getBlockY(), point2.getBlockY());
this.yMax = Math.max(point1.getBlockY(), point2.getBlockY());
this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ());
this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ());
this.world = point1.getWorld();
}
private boolean contains(World world, int x, int y, int z) {
return world.getName().equals(this.world.getName()) && x >= xMin && x <= xMax && y >= yMin && y <= yMax && z >= zMin && z <= zMax;
}
private boolean contains(Location loc) {
return this.contains(loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public boolean isInside(Player player) {
return this.contains(player.getLocation());
}
}

View File

@ -0,0 +1,97 @@
package com.loganmagnan.nicknamesplus.utils.cuboid;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.util.Iterator;
public class CuboidBlockIterator implements Iterator<Block> {
private World world;
private int baseX;
private int baseY;
private int baseZ;
private int sizeX;
private int sizeY;
private int sizeZ;
private int x;
private int y;
private int z;
CuboidBlockIterator(World world, int x1, int y1, int z1, int x2, int y2, int z2) {
this.world = world;
this.baseX = x1;
this.baseY = y1;
this.baseZ = z1;
this.sizeX = Math.abs(x2 - x1) + 1;
this.sizeY = Math.abs(y2 - y1) + 1;
this.sizeZ = Math.abs(z2 - z1) + 1;
this.z = 0;
this.y = 0;
this.x = 0;
}
@Override
public boolean hasNext() {
return this.x < this.sizeX && this.y < this.sizeY && this.z < this.sizeZ;
}
@Override
public Block next() {
Block block = this.world.getBlockAt(this.baseX + this.x, this.baseY + this.y, this.baseZ + this.z);
if (++this.x >= this.sizeX) {
this.x = 0;
if (++this.y >= this.sizeY) {
this.y = 0;
++this.z;
}
}
return block;
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public World getWorld() {
return this.world;
}
public int getBaseX() {
return this.baseX;
}
public int getBaseY() {
return this.baseY;
}
public int getBaseZ() {
return this.baseZ;
}
public int getSizeX() {
return this.sizeX;
}
public int getSizeY() {
return this.sizeY;
}
public int getSizeZ() {
return this.sizeZ;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}

View File

@ -0,0 +1,46 @@
package com.loganmagnan.nicknamesplus.utils.cuboid;
public enum CuboidDirection {
NORTH, EAST, SOUTH, WEST,
UP, DOWN, HORIZONTAL, VERTICAL, BOTH,
UNKNOWN;
private CuboidDirection() {
}
public CuboidDirection opposite() {
switch (this) {
case NORTH: {
return SOUTH;
}
case EAST: {
return WEST;
}
case SOUTH: {
return NORTH;
}
case WEST: {
return EAST;
}
case HORIZONTAL: {
return VERTICAL;
}
case VERTICAL: {
return HORIZONTAL;
}
case UP: {
return DOWN;
}
case DOWN: {
return UP;
}
case BOTH: {
return BOTH;
}
}
return UNKNOWN;
}
}

View File

@ -0,0 +1,97 @@
package com.loganmagnan.nicknamesplus.utils.cuboid;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.Iterator;
public class CuboidLocationIterator implements Iterator<Location> {
private World world;
private int baseX;
private int baseY;
private int baseZ;
private int sizeX;
private int sizeY;
private int sizeZ;
private int x;
private int y;
private int z;
CuboidLocationIterator(World world, int x1, int y1, int z1, int x2, int y2, int z2) {
this.world = world;
this.baseX = x1;
this.baseY = y1;
this.baseZ = z1;
this.sizeX = Math.abs(x2 - x1) + 1;
this.sizeY = Math.abs(y2 - y1) + 1;
this.sizeZ = Math.abs(z2 - z1) + 1;
this.z = 0;
this.y = 0;
this.x = 0;
}
@Override
public boolean hasNext() {
return this.x < this.sizeX && this.y < this.sizeY && this.z < this.sizeZ;
}
@Override
public Location next() {
Location location = new Location(this.world, this.baseX + this.x, this.baseY + this.y, this.baseZ + this.z);
if (++this.x >= this.sizeX) {
this.x = 0;
if (++this.y >= this.sizeY) {
this.y = 0;
++this.z;
}
}
return location;
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public World getWorld() {
return this.world;
}
public int getBaseX() {
return this.baseX;
}
public int getBaseY() {
return this.baseY;
}
public int getBaseZ() {
return this.baseZ;
}
public int getSizeX() {
return this.sizeX;
}
public int getSizeY() {
return this.sizeY;
}
public int getSizeZ() {
return this.sizeZ;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}

View File

@ -0,0 +1,6 @@
COMMANDS:
RGB-NICK: # Permission node - nicknamesplus.command.rgbnick
VALID-CHAT-COLOR-CODE: "&cPlease use a valid chat color code"
VALID-HEX-COLOR-CODE: "&cPlease use a valid hex color code"
VALID-COLOR-CODE: "&cPlease use a valid color code"
RGB-NICKNAME-SET-TO: "&aSet RGB nickname to: %rgb-nickname%"

View File

@ -0,0 +1,5 @@
name: NicknamesPlus
author: Trixkz
version: 1.2
api-version: 1.13
main: com.loganmagnan.nicknamesplus.NicknamesPlus