1
0
mirror of https://e.coding.net/circlecloud/YumCore.git synced 2024-11-21 01:38:51 +00:00

refactor: 去除final

Signed-off-by: 502647092 <admin@yumc.pw>
This commit is contained in:
502647092 2016-10-12 01:14:57 +08:00
parent 2dd7257dea
commit 335cdeeaad
58 changed files with 1026 additions and 1019 deletions

View File

@ -6,7 +6,7 @@
<version>1.1</version>
<name>YumCore</name>
<build>
<finalName>${project.name}</finalName>
<Name>${project.name}</Name>
<resources>
<resource>
<directory>src/main/resources</directory>

View File

@ -37,8 +37,8 @@ public class L {
* if the world don't exists
* @see ConfigurationSerializable
*/
public static Location deserialize(final Map<String, Object> args) {
final World world = Bukkit.getWorld((String) args.get("world"));
public static Location deserialize(Map<String, Object> args) {
World world = Bukkit.getWorld((String) args.get("world"));
if (world == null) {
throw new IllegalArgumentException("unknown world");
}
@ -54,8 +54,8 @@ public class L {
* 地点
* @return Map
*/
public static Map<String, Object> serialize(final Location loc) {
final Map<String, Object> data = new LinkedHashMap<>();
public static Map<String, Object> serialize(Location loc) {
Map<String, Object> data = new LinkedHashMap<>();
data.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, Location.class.getName());
data.put("world", loc.getWorld().getName());
data.put("x", loc.getX());

View File

@ -17,8 +17,8 @@ import org.bukkit.command.CommandSender;
*/
public class Log {
private static boolean debug = new File(String.format("plugins%1$sYumCore%1$sdebug", File.separatorChar)).exists();
private static final Logger logger = P.instance.getLogger();
private static final CommandSender console = Bukkit.getConsoleSender();
private static Logger logger = P.instance.getLogger();
private static CommandSender console = Bukkit.getConsoleSender();
private static String prefix = String.format("§6[§b%s§6]§r ", P.instance.getName());
private Log() {
@ -37,7 +37,7 @@ public class Log {
* if a security manager exists and if
* the caller does not have LoggingPermission("control").
*/
public static void addHandler(final Handler handler) throws SecurityException {
public static void addHandler(Handler handler) throws SecurityException {
logger.addHandler(handler);
}
@ -47,7 +47,7 @@ public class Log {
* @param message
* Message to be displayed
*/
public static void console(final String message) {
public static void console(String message) {
console.sendMessage(prefix + message);
}
@ -59,7 +59,7 @@ public class Log {
* @param object
* 格式化参数
*/
public static void console(final String message, final Object... object) {
public static void console(String message, Object... object) {
console.sendMessage(prefix + String.format(message, object));
}
@ -69,8 +69,8 @@ public class Log {
* @param message
* Message to be displayed
*/
public static void console(final String[] msg) {
for (final String str : msg) {
public static void console(String[] msg) {
for (String str : msg) {
console(str);
}
}
@ -83,7 +83,7 @@ public class Log {
* @param object
* 参数
*/
public static void d(final String msg, final Object... object) {
public static void d(String msg, Object... object) {
debug(String.format(msg, object));
}
@ -93,7 +93,7 @@ public class Log {
* @param msg
* 消息
*/
public static void debug(final String msg) {
public static void debug(String msg) {
if (debug) {
logger.info("[DEBUG] " + msg);
}
@ -107,7 +107,7 @@ public class Log {
* @param object
* 参数
*/
public static void debug(final String msg, final Object... object) {
public static void debug(String msg, Object... object) {
if (debug) {
logger.log(Level.SEVERE, "[DEBUG] " + msg, object);
}
@ -121,7 +121,7 @@ public class Log {
* @param e
* 异常
*/
public static void debug(final String msg, final Throwable e) {
public static void debug(String msg, Throwable e) {
if (debug) {
logger.info("[DEBUG] " + msg);
e.printStackTrace();
@ -134,7 +134,7 @@ public class Log {
* @param e
* 异常
*/
public static void debug(final Throwable e) {
public static void debug(Throwable e) {
if (debug) {
e.printStackTrace();
}
@ -158,7 +158,7 @@ public class Log {
* @param msg
* The string message (or a key in the message catalog)
*/
public static void info(final String msg) {
public static void info(String msg) {
logger.info(msg);
}
@ -175,7 +175,7 @@ public class Log {
* @param msg
* The string message (or a key in the message catalog)
*/
public static void log(final Level level, final String msg) {
public static void log(Level level, String msg) {
logger.log(level, msg);
}
@ -194,7 +194,7 @@ public class Log {
* @param param1
* parameter to the message
*/
public static void log(final Level level, final String msg, final Object param1) {
public static void log(Level level, String msg, Object param1) {
logger.log(level, msg, param1);
}
@ -213,7 +213,7 @@ public class Log {
* @param params
* array of parameters to the message
*/
public static void log(final Level level, final String msg, final Object[] params) {
public static void log(Level level, String msg, Object[] params) {
logger.log(level, msg, params);
}
@ -237,7 +237,7 @@ public class Log {
* @param thrown
* Throwable associated with log message.
*/
public static void log(final Level level, final String msg, final Throwable thrown) {
public static void log(Level level, String msg, Throwable thrown) {
logger.log(level, msg, thrown);
}
@ -245,7 +245,7 @@ public class Log {
* @param prefix
* 插件前缀
*/
public static void setPrefix(final String prefix) {
public static void setPrefix(String prefix) {
Log.prefix = ChatColor.translateAlternateColorCodes('&', prefix);
}
@ -257,7 +257,7 @@ public class Log {
* @param msg
* The string message (or a key in the message catalog)
*/
public static void severe(final String msg) {
public static void severe(String msg) {
logger.severe(msg);
}
@ -269,7 +269,7 @@ public class Log {
* @param msg
* 消息
*/
public static void toSender(final CommandSender sender, final String msg) {
public static void toSender(CommandSender sender, String msg) {
sender.sendMessage(prefix + msg);
}
@ -283,7 +283,7 @@ public class Log {
* @param objs
* 参数
*/
public static void toSender(final CommandSender sender, final String msg, final Object... objs) {
public static void toSender(CommandSender sender, String msg, Object... objs) {
sender.sendMessage(prefix + String.format(msg, objs));
}
@ -295,8 +295,8 @@ public class Log {
* @param msg
* 消息
*/
public static void toSender(final CommandSender sender, final String[] msg) {
for (final String str : msg) {
public static void toSender(CommandSender sender, String[] msg) {
for (String str : msg) {
toSender(sender, str);
}
}
@ -309,7 +309,7 @@ public class Log {
* @param objects
* 参数
*/
public static void w(final String string, final Object... objects) {
public static void w(String string, Object... objects) {
logger.warning(String.format(string, objects));
}
@ -324,7 +324,7 @@ public class Log {
* @param msg
* The string message (or a key in the message catalog)
*/
public static void warning(final String msg) {
public static void warning(String msg) {
logger.warning(msg);
}

View File

@ -23,12 +23,12 @@ public class P {
public static JavaPlugin instance;
static {
final Object pluginClassLoader = P.class.getClassLoader();
Object pluginClassLoader = P.class.getClassLoader();
try {
final Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
field.setAccessible(true);
instance = (JavaPlugin) field.get(pluginClassLoader);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -39,7 +39,7 @@ public class P {
*
* @return 插件命令
*/
public static PluginCommand getCommand(final String name) {
public static PluginCommand getCommand(String name) {
return instance.getCommand(name);
}
@ -56,28 +56,28 @@ public class P {
/**
* @return 获得插件文件夹
*/
public static final File getDataFolder() {
public static File getDataFolder() {
return instance.getDataFolder();
}
/**
* @return 获得插件描述文件
*/
public static final PluginDescriptionFile getDescription() {
public static PluginDescriptionFile getDescription() {
return instance.getDescription();
}
/**
* @return 获得插件日志器
*/
public static final Logger getLogger() {
public static Logger getLogger() {
return instance.getLogger();
}
/**
* @return 插件名称
*/
public static final String getName() {
public static String getName() {
return instance.getName();
}
@ -94,7 +94,7 @@ public class P {
/**
* @return 插件是否已启用
*/
public static final boolean isEnabled() {
public static boolean isEnabled() {
return instance.isEnabled();
}

View File

@ -39,19 +39,19 @@ public class C {
static {
try {
version = getNMSVersion();
final boolean newversion = Integer.parseInt(version.split("_")[1]) > 7;
boolean newversion = Integer.parseInt(version.split("_")[1]) > 7;
nmsChatSerializer = Class.forName(a(newversion ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer"));
nmsIChatBaseComponent = Class.forName(a("IChatBaseComponent"));
packetType = Class.forName(a("PacketPlayOutChat"));
packetActions = Class.forName(a(newversion ? "PacketPlayOutTitle$EnumTitleAction" : "EnumTitleAction"));
packetTitle = Class.forName(a("PacketPlayOutTitle"));
final Class<?> typeCraftPlayer = Class.forName(b("entity.CraftPlayer"));
final Class<?> typeNMSPlayer = Class.forName(a("EntityPlayer"));
final Class<?> typePlayerConnection = Class.forName(a("PlayerConnection"));
Class<?> typeCraftPlayer = Class.forName(b("entity.CraftPlayer"));
Class<?> typeNMSPlayer = Class.forName(a("EntityPlayer"));
Class<?> typePlayerConnection = Class.forName(a("PlayerConnection"));
getHandle = typeCraftPlayer.getMethod("getHandle");
playerConnection = typeNMSPlayer.getField("playerConnection");
sendPacket = typePlayerConnection.getMethod("sendPacket", Class.forName(a("Packet")));
} catch (final Exception e) {
} catch (Exception e) {
Log.warning(C.class.getSimpleName() + " 兼容性工具初始化失败 可能造成部分功能不可用!");
Log.debug(e);
}
@ -60,11 +60,11 @@ public class C {
private C() {
}
public static String a(final String str) {
public static String a(String str) {
return "net.minecraft.server." + version + "." + str;
}
public static String b(final String str) {
public static String b(String str) {
return "org.bukkit.craftbukkit." + version + "." + str;
}
@ -87,8 +87,8 @@ public class C {
* @param message
* 需要发送的消息
*/
public static void broadcast(final String message) {
for (final org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
public static void broadcast(String message) {
for (org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
send(player, message);
}
}
@ -107,12 +107,12 @@ public class C {
public void run() {
int time = times;
do {
for (final org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
for (org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
send(player, message);
}
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
} catch (InterruptedException e) {
// Ignore
}
time--;
@ -137,14 +137,14 @@ public class C {
public void run() {
int time = times;
do {
for (final org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
for (org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
if (player.getWorld().getName().equalsIgnoreCase(world.getName())) {
send(player, message);
}
}
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
} catch (InterruptedException e) {
// Ignore
}
time--;
@ -162,19 +162,19 @@ public class C {
* @param msg
* ActionBar信息
*/
public static void send(final org.bukkit.entity.Player receivingPacket, final String msg) {
public static void send(org.bukkit.entity.Player receivingPacket, String msg) {
Object packet = null;
try {
final Object serialized = nmsChatSerializer.getMethod("a", String.class).invoke(null, "{\"text\":\"" + ChatColor.translateAlternateColorCodes('&', JSONObject.escape(msg)) + "\"}");
Object serialized = nmsChatSerializer.getMethod("a", String.class).invoke(null, "{\"text\":\"" + ChatColor.translateAlternateColorCodes('&', JSONObject.escape(msg)) + "\"}");
if (!version.contains("1_7")) {
packet = packetType.getConstructor(nmsIChatBaseComponent, byte.class).newInstance(serialized, (byte) 2);
} else {
packet = packetType.getConstructor(nmsIChatBaseComponent, int.class).newInstance(serialized, 2);
}
final Object player = getHandle.invoke(receivingPacket);
final Object connection = playerConnection.get(player);
Object player = getHandle.invoke(receivingPacket);
Object connection = playerConnection.get(player);
sendPacket.invoke(connection, packet);
} catch (final Exception ex) {
} catch (Exception ex) {
Log.debug("ActionBar发包错误 " + version, ex);
}
}
@ -198,7 +198,7 @@ public class C {
send(receivingPacket, msg);
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
} catch (InterruptedException e) {
// Ignore
}
time--;
@ -224,34 +224,34 @@ public class C {
// getOnlinePlayers start
getOnlinePlayers = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
if (getOnlinePlayers.getReturnType() != org.bukkit.entity.Player[].class) {
for (final Method method : Bukkit.class.getDeclaredMethods()) {
for (Method method : Bukkit.class.getDeclaredMethods()) {
if (method.getReturnType() == org.bukkit.entity.Player[].class && method.getName().endsWith("getOnlinePlayers")) {
getOnlinePlayers = method;
}
}
}
// getOnlinePlayers end
} catch (final Exception e) {
} catch (Exception e) {
Log.warning(Player.class.getSimpleName() + "兼容性工具初始化失败 可能造成部分功能不可用!");
}
try {
// getOfflinePlayer start
try {
gameProfileClass = Class.forName("net.minecraft.util.com.mojang.authlib.GameProfile");
} catch (final Exception e) {
} catch (Exception e) {
try {
gameProfileClass = Class.forName("com.mojang.authlib.GameProfile");
} catch (final Exception e1) {
} catch (Exception e1) {
}
}
gameProfileConstructor = gameProfileClass.getDeclaredConstructor(new Class[] { UUID.class, String.class });
gameProfileConstructor.setAccessible(true);
final Class<? extends Server> craftServer = Bukkit.getServer().getClass();
final Class<?> craftOfflinePlayer = Class.forName(craftServer.getName().replace("CraftServer", "CraftOfflinePlayer"));
Class<? extends Server> craftServer = Bukkit.getServer().getClass();
Class<?> craftOfflinePlayer = Class.forName(craftServer.getName().replace("CraftServer", "CraftOfflinePlayer"));
craftOfflinePlayerConstructor = craftOfflinePlayer.getDeclaredConstructor(new Class[] { craftServer, gameProfileClass });
craftOfflinePlayerConstructor.setAccessible(true);
// getOfflinePlayer end
} catch (final Exception e) {
} catch (Exception e) {
Log.debug(e);
}
}
@ -266,12 +266,12 @@ public class C {
* 玩家名称
* @return {@link OfflinePlayer}
*/
public static OfflinePlayer getOfflinePlayer(final String playerName) {
public static OfflinePlayer getOfflinePlayer(String playerName) {
try {
final Object gameProfile = gameProfileConstructor.newInstance(new Object[] { UUID.nameUUIDFromBytes(("OfflinePlayer:" + playerName).getBytes(Charsets.UTF_8)), playerName });
final Object offlinePlayer = craftOfflinePlayerConstructor.newInstance(new Object[] { Bukkit.getServer(), gameProfile });
Object gameProfile = gameProfileConstructor.newInstance(new Object[] { UUID.nameUUIDFromBytes(("OfflinePlayer:" + playerName).getBytes(Charsets.UTF_8)), playerName });
Object offlinePlayer = craftOfflinePlayerConstructor.newInstance(new Object[] { Bukkit.getServer(), gameProfile });
return (OfflinePlayer) offlinePlayer;
} catch (final Exception e) {
} catch (Exception e) {
return Bukkit.getOfflinePlayer(playerName);
}
}
@ -284,7 +284,7 @@ public class C {
public static Collection<? extends org.bukkit.entity.Player> getOnlinePlayers() {
try {
return Arrays.asList((org.bukkit.entity.Player[]) getOnlinePlayers.invoke(null));
} catch (final Exception e) {
} catch (Exception e) {
return Bukkit.getOnlinePlayers();
}
}
@ -302,8 +302,8 @@ public class C {
* @param subtitle
* 子标题
*/
public static void broadcast(final String title, final String subtitle) {
for (final org.bukkit.entity.Player player : Player.getOnlinePlayers()) {
public static void broadcast(String title, String subtitle) {
for (org.bukkit.entity.Player player : Player.getOnlinePlayers()) {
send(player, title, subtitle);
}
}
@ -322,8 +322,8 @@ public class C {
* @param fadeOutTime
* 淡出时间
*/
public static void broadcast(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) {
for (final org.bukkit.entity.Player player : Player.getOnlinePlayers()) {
public static void broadcast(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
for (org.bukkit.entity.Player player : Player.getOnlinePlayers()) {
send(player, title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
}
@ -338,8 +338,8 @@ public class C {
* @param subtitle
* 子标题
*/
public static void broadcast(final World world, final String title, final String subtitle) {
for (final org.bukkit.entity.Player player : Player.getOnlinePlayers()) {
public static void broadcast(World world, String title, String subtitle) {
for (org.bukkit.entity.Player player : Player.getOnlinePlayers()) {
if (player.getWorld().getName().equalsIgnoreCase(world.getName())) {
send(player, title, subtitle);
}
@ -354,12 +354,12 @@ public class C {
* @throws Exception
* 异常
*/
public static void reset(final org.bukkit.entity.Player recoverPlayer) throws Exception {
public static void reset(org.bukkit.entity.Player recoverPlayer) throws Exception {
// Send timings first
final Object player = getHandle.invoke(recoverPlayer);
final Object connection = playerConnection.get(player);
final Object[] actions = packetActions.getEnumConstants();
final Object packet = packetTitle.getConstructor(packetActions, nmsIChatBaseComponent).newInstance(actions[4], null);
Object player = getHandle.invoke(recoverPlayer);
Object connection = playerConnection.get(player);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle.getConstructor(packetActions, nmsIChatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
@ -373,7 +373,7 @@ public class C {
* @param subtitle
* 子标题
*/
public static void send(final org.bukkit.entity.Player receivingPacket, final String title, final String subtitle) {
public static void send(org.bukkit.entity.Player receivingPacket, String title, String subtitle) {
send(receivingPacket, title, subtitle, 1, 2, 1);
}
@ -393,19 +393,23 @@ public class C {
* @param fadeOutTime
* 淡出时间
*/
public static void send(final org.bukkit.entity.Player receivingPacket, final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) {
public static void send(org.bukkit.entity.Player receivingPacket, String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
if (packetTitle != null) {
try {
// First reset previous settings
reset(receivingPacket);
// Send timings first
final Object player = getHandle.invoke(receivingPacket);
final Object connection = playerConnection.get(player);
final Object[] actions = packetActions.getEnumConstants();
Object player = getHandle.invoke(receivingPacket);
Object connection = playerConnection.get(player);
Object[] actions = packetActions.getEnumConstants();
Object packet = null;
// Send if set
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1)) {
packet = packetTitle.getConstructor(packetActions, nmsIChatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null, fadeInTime * 20, stayTime * 20, fadeOutTime * 20);
packet = packetTitle.getConstructor(packetActions, nmsIChatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2],
null,
fadeInTime * 20,
stayTime * 20,
fadeOutTime * 20);
sendPacket.invoke(connection, packet);
}
// Send title
@ -418,7 +422,7 @@ public class C {
packet = packetTitle.getConstructor(packetActions, nmsIChatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
} catch (final Exception e) {
} catch (Exception e) {
Log.debug(e);
}
}

View File

@ -11,12 +11,12 @@ import org.bukkit.entity.Player;
* @author
*/
public class CommandArgument {
private final CommandSender sender;
private final Command command;
private final String alias;
private final String[] args;
private CommandSender sender;
private Command command;
private String alias;
private String[] args;
public CommandArgument(final CommandSender sender, final Command command, final String alias, final String[] args) {
public CommandArgument(CommandSender sender, Command command, String alias, String[] args) {
this.sender = sender;
this.command = command;
this.alias = alias;

View File

@ -27,24 +27,24 @@ public class CommandHelp {
/**
* 消息配置
*/
private final static String prefix = String.format("§6[§b%s§6] ", P.instance.getName());
private final static String commandNotFound = prefix + "§c当前插件未注册任何子命令!";
private final static String pageNotFound = prefix + "§c不存在的帮助页面 §b请输入 /%s help §e1-%s";
private final static String helpTitle = String.format("§6========= %s §6插件帮助列表=========", prefix);
private final static String helpBody = "§6/%1$s §a%2$s §e%3$s §6- §b%4$s";
private final static String helpFooter = "§6查看更多的帮助页面 §b请输入 /%s help §e1-%s";
private static String prefix = String.format("§6[§b%s§6] ", P.instance.getName());
private static String commandNotFound = prefix + "§c当前插件未注册任何子命令!";
private static String pageNotFound = prefix + "§c不存在的帮助页面 §b请输入 /%s help §e1-%s";
private static String helpTitle = String.format("§6========= %s §6插件帮助列表=========", prefix);
private static String helpBody = "§6/%1$s §a%2$s §e%3$s §6- §b%4$s";
private static String helpFooter = "§6查看更多的帮助页面 §b请输入 /%s help §e1-%s";
/**
* 帮助页面每页行数
*/
private final static int LINES_PER_PAGE = 7;
private static int LINES_PER_PAGE = 7;
/**
* 默认命令
*/
private final CommandInfo defCmd;
private CommandInfo defCmd;
/**
* 已排序的命令列表
*/
private final List<CommandInfo> cmdlist;
private List<CommandInfo> cmdlist;
/**
* 命令解析
*/
@ -52,11 +52,11 @@ public class CommandHelp {
/**
* 帮助页面数量
*/
private final int HELPPAGECOUNT;
private int HELPPAGECOUNT;
/**
* 帮助列表缓存
*/
private final Map<String, String[]> cacheHelp = new HashMap<>();
private Map<String, String[]> cacheHelp = new HashMap<>();
/**
* 命令帮助
@ -64,7 +64,7 @@ public class CommandHelp {
* @param list
* 子命令列表
*/
public CommandHelp(final Collection<? extends CommandInfo> list) {
public CommandHelp(Collection<? extends CommandInfo> list) {
this(null, list);
}
@ -76,7 +76,7 @@ public class CommandHelp {
* @param list
* 子命令列表
*/
public CommandHelp(final CommandInfo defCmd, final Collection<? extends CommandInfo> list) {
public CommandHelp(CommandInfo defCmd, Collection<? extends CommandInfo> list) {
this.defCmd = defCmd;
cmdlist = new LinkedList<>(list);
Collections.sort(cmdlist, new CommandComparator());
@ -92,10 +92,10 @@ public class CommandHelp {
* 命令
* @return 格式化后的字串
*/
public String formatCommand(final CommandInfo ci, final String label) {
final String aliases = Arrays.toString(ci.getCommand().aliases());
final String cmd = ci.getName() + (aliases.length() == 2 ? "" : "§7" + aliases);
final Help help = ci.getHelp();
public String formatCommand(CommandInfo ci, String label) {
String aliases = Arrays.toString(ci.getCommand().aliases());
String cmd = ci.getName() + (aliases.length() == 2 ? "" : "§7" + aliases);
Help help = ci.getHelp();
return String.format(helpBody, label, cmd, help.possibleArguments(), formatHelp(help.value()));
}
@ -106,7 +106,7 @@ public class CommandHelp {
* 参数
* @return 解析后的帮助
*/
public String formatHelp(final String value) {
public String formatHelp(String value) {
if (helpParse != null) {
return helpParse.parse(value);
}
@ -125,7 +125,7 @@ public class CommandHelp {
* @param args
* 参数
*/
public boolean send(final CommandSender sender, final Command command, final String label, final String[] args) {
public boolean send(CommandSender sender, Command command, String label, String[] args) {
if (this.HELPPAGECOUNT == 0) {
sender.sendMessage(commandNotFound);
return true;
@ -134,12 +134,12 @@ public class CommandHelp {
try {
page = Integer.parseInt(args[1]);
page = page == 0 ? 1 : page;
} catch (final Exception e) {
} catch (Exception e) {
// Ignore
}
final String helpkey = label + page;
String helpkey = label + page;
if (!cacheHelp.containsKey(helpkey)) {
final List<String> helpList = new LinkedList<>();
List<String> helpList = new LinkedList<>();
if (page > this.HELPPAGECOUNT || page < 1) {
// 帮助页面不存在
helpList.add(String.format(pageNotFound, label, HELPPAGECOUNT));
@ -149,8 +149,8 @@ public class CommandHelp {
if (page == 1 && defCmd != null) {
helpList.add(formatCommand(defCmd, label));
}
final int start = LINES_PER_PAGE * (page - 1);
final int end = start + LINES_PER_PAGE;
int start = LINES_PER_PAGE * (page - 1);
int end = start + LINES_PER_PAGE;
for (int i = start; i < end; i++) {
if (this.cmdlist.size() > i) {
// 帮助列表
@ -172,7 +172,7 @@ public class CommandHelp {
* @param helpParse
* 帮助解析器
*/
public void setHelpParse(final CommandHelpParse helpParse) {
public void setHelpParse(CommandHelpParse helpParse) {
this.helpParse = helpParse;
}
@ -184,7 +184,7 @@ public class CommandHelp {
*/
static class CommandComparator implements Comparator<CommandInfo> {
@Override
public int compare(final CommandInfo o1, final CommandInfo o2) {
public int compare(CommandInfo o1, CommandInfo o2) {
if (o1.getSort() > o2.getSort()) {
return 1;
} else if (o1.getSort() == o2.getSort()) {

View File

@ -40,24 +40,24 @@ import pw.yumc.YumCore.commands.interfaces.CommandHelpParse;
* @author
*/
public class CommandManager implements TabExecutor {
private final static String argumentTypeError = "注解命令方法 %s 位于 %s 的参数错误 第一个参数应实现 CommandSender 接口!";
private final static String returnTypeError = "注解命令补全 %s 位于 %s 的返回值错误 应实现 List 接口!";
private static String argumentTypeError = "注解命令方法 %s 位于 %s 的参数错误 第一个参数应实现 CommandSender 接口!";
private static String returnTypeError = "注解命令补全 %s 位于 %s 的返回值错误 应实现 List 接口!";
private static Constructor<PluginCommand> PluginCommandConstructor;
private static Map<String, Command> knownCommands;
private static Map<String, Plugin> lookupNames;
static {
try {
final PluginManager pluginManager = Bukkit.getPluginManager();
PluginManager pluginManager = Bukkit.getPluginManager();
final Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames");
Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames");
lookupNamesField.setAccessible(true);
lookupNames = (Map<String, Plugin>) lookupNamesField.get(pluginManager);
final Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap");
Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true);
final SimpleCommandMap commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
SimpleCommandMap commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
final Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true);
knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
@ -70,7 +70,7 @@ public class CommandManager implements TabExecutor {
/**
* 插件实例类
*/
private final static JavaPlugin plugin = P.instance;
private static JavaPlugin plugin = P.instance;
/**
* 默认命令
*/
@ -78,19 +78,19 @@ public class CommandManager implements TabExecutor {
/**
* 命令列表
*/
private final Set<CommandInfo> cmds = new HashSet<>();
private Set<CommandInfo> cmds = new HashSet<>();
/**
* Tab列表
*/
private final Set<CommandTabInfo> tabs = new HashSet<>();
private Set<CommandTabInfo> tabs = new HashSet<>();
/**
* 命令缓存列表
*/
private final Map<String, CommandInfo> cmdCache = new HashMap<>();
private Map<String, CommandInfo> cmdCache = new HashMap<>();
/**
* 命令名称缓存
*/
private final List<String> cmdNameCache = new ArrayList<>();
private List<String> cmdNameCache = new ArrayList<>();
/**
* 命令帮助
*/
@ -106,7 +106,7 @@ public class CommandManager implements TabExecutor {
* @param name
* 注册的命令
*/
public CommandManager(final String name) {
public CommandManager(String name) {
cmd = plugin.getCommand(name);
if (cmd == null) {
try {
@ -130,20 +130,20 @@ public class CommandManager implements TabExecutor {
* @param executor
* 命令执行类
*/
public CommandManager(final String name, final CommandExecutor... executor) {
public CommandManager(String name, CommandExecutor... executor) {
this(name);
register(executor);
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
if (defCmd != null) {
return defCmd.execute(new CommandArgument(sender, command, label, args));
}
return help.send(sender, command, label, args);
}
final String subcmd = args[0].toLowerCase();
String subcmd = args[0].toLowerCase();
if (subcmd.equalsIgnoreCase("help")) {
return help.send(sender, command, label, args);
}
@ -151,13 +151,13 @@ public class CommandManager implements TabExecutor {
}
@Override
public List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) {
final List<String> completions = new ArrayList<>();
final String token = args[args.length - 1];
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
List<String> completions = new ArrayList<>();
String token = args[args.length - 1];
if (args.length == 1) {
StringUtil.copyPartialMatches(args[0], cmdNameCache, completions);
} else if (args.length >= 2) {
for (final CommandTabInfo tab : tabs) {
for (CommandTabInfo tab : tabs) {
StringUtil.copyPartialMatches(token, tab.execute(sender, command, token, args), completions);
}
StringUtil.copyPartialMatches(token, getPlayerTabComplete(sender, command, alias, args), completions);
@ -172,10 +172,10 @@ public class CommandManager implements TabExecutor {
* @param clazzs
* 子命令处理类
*/
public void register(final CommandExecutor... clazzs) {
for (final CommandExecutor clazz : clazzs) {
final Method[] methods = clazz.getClass().getDeclaredMethods();
for (final Method method : methods) {
public void register(CommandExecutor... clazzs) {
for (CommandExecutor clazz : clazzs) {
Method[] methods = clazz.getClass().getDeclaredMethods();
for (Method method : methods) {
if (registerCommand(method, clazz)) {
continue;
}
@ -192,7 +192,7 @@ public class CommandManager implements TabExecutor {
* @param helpParse
* 帮助解析器
*/
public void setHelpParse(final CommandHelpParse helpParse) {
public void setHelpParse(CommandHelpParse helpParse) {
help.setHelpParse(helpParse);
}
@ -201,7 +201,7 @@ public class CommandManager implements TabExecutor {
*/
private void buildCmdNameCache() {
cmdNameCache.clear();
for (final CommandInfo cmd : cmds) {
for (CommandInfo cmd : cmds) {
cmdNameCache.add(cmd.getName());
cmdNameCache.addAll(Arrays.asList(cmd.getCommand().aliases()));
}
@ -215,9 +215,9 @@ public class CommandManager implements TabExecutor {
* 子命令
* @return 命令信息
*/
private CommandInfo getByCache(final String subcmd) {
private CommandInfo getByCache(String subcmd) {
if (!cmdCache.containsKey(subcmd)) {
for (final CommandInfo cmdinfo : cmds) {
for (CommandInfo cmdinfo : cmds) {
if (cmdinfo.isValid(subcmd)) {
cmdCache.put(subcmd, cmdinfo);
break;
@ -243,12 +243,12 @@ public class CommandManager implements TabExecutor {
* 数组
* @return 在线玩家数组
*/
private List<String> getPlayerTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) {
final String lastWord = args[args.length - 1];
final Player senderPlayer = sender instanceof Player ? (Player) sender : null;
final List<String> matchedPlayers = new ArrayList<>();
for (final Player player : C.Player.getOnlinePlayers()) {
final String name = player.getName();
private List<String> getPlayerTabComplete(CommandSender sender, Command command, String alias, String[] args) {
String lastWord = args[args.length - 1];
Player senderPlayer = sender instanceof Player ? (Player) sender : null;
List<String> matchedPlayers = new ArrayList<>();
for (Player player : C.Player.getOnlinePlayers()) {
String name = player.getName();
if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) {
matchedPlayers.add(name);
}
@ -265,8 +265,8 @@ public class CommandManager implements TabExecutor {
* 数组开始位置
* @return 转移后的数组字符串
*/
private String[] moveStrings(final String[] args, final int start) {
final String[] ret = new String[args.length - start];
private String[] moveStrings(String[] args, int start) {
String[] ret = new String[args.length - start];
System.arraycopy(args, start, ret, 0, ret.length);
return ret;
}
@ -280,10 +280,10 @@ public class CommandManager implements TabExecutor {
* 调用对象
* @return 是否成功
*/
private boolean registerCommand(final Method method, final CommandExecutor clazz) {
final CommandInfo ci = CommandInfo.parse(method, clazz);
private boolean registerCommand(Method method, CommandExecutor clazz) {
CommandInfo ci = CommandInfo.parse(method, clazz);
if (ci != null) {
final Class<?>[] params = method.getParameterTypes();
Class<?>[] params = method.getParameterTypes();
Log.d("命令 %s 参数类型: %s", ci.getName(), Arrays.toString(params));
if (params.length > 0 && params[0].isAssignableFrom(CommandSender.class)) {
if (method.getReturnType() == boolean.class) {
@ -308,8 +308,8 @@ public class CommandManager implements TabExecutor {
* 调用对象
* @return 是否成功
*/
private boolean registerTab(final Method method, final CommandExecutor clazz) {
final CommandTabInfo ti = CommandTabInfo.parse(method, clazz);
private boolean registerTab(Method method, CommandExecutor clazz) {
CommandTabInfo ti = CommandTabInfo.parse(method, clazz);
if (ti != null) {
if (method.getReturnType().equals(List.class)) {
tabs.add(ti);

View File

@ -92,7 +92,7 @@ public @interface Cmd {
UNKNOW("未知");
private String name;
private Executor(final String name) {
private Executor(String name) {
this.name = name;
}
@ -103,7 +103,7 @@ public @interface Cmd {
* 命令执行者
* @return {@link Executor}
*/
public static Executor valueOf(final CommandSender sender) {
public static Executor valueOf(CommandSender sender) {
if (sender instanceof Player) {
return Executor.PLAYER;
} else if (sender instanceof ConsoleCommandSender) {

View File

@ -2,21 +2,21 @@ package pw.yumc.YumCore.commands.exception;
/**
* 命令参数解析异常
*
*
* @author
* @since 2016年10月5日 下午5:15:43
*/
public class CommandArgumentException extends CommandException {
public CommandArgumentException(final Exception e) {
public CommandArgumentException(Exception e) {
super(e);
}
public CommandArgumentException(final String string) {
public CommandArgumentException(String string) {
super(string);
}
public CommandArgumentException(final String string, final Exception e) {
public CommandArgumentException(String string, Exception e) {
super(string, e);
}
}

View File

@ -8,15 +8,15 @@ package pw.yumc.YumCore.commands.exception;
*/
public class CommandException extends RuntimeException {
public CommandException(final Exception e) {
public CommandException(Exception e) {
super(e);
}
public CommandException(final String string) {
public CommandException(String string) {
super(string);
}
public CommandException(final String string, final Exception e) {
public CommandException(String string, Exception e) {
super(string, e);
}

View File

@ -8,15 +8,15 @@ package pw.yumc.YumCore.commands.exception;
*/
public class CommandParseException extends CommandException {
public CommandParseException(final Exception e) {
public CommandParseException(Exception e) {
super(e);
}
public CommandParseException(final String string) {
public CommandParseException(String string) {
super(string);
}
public CommandParseException(final String string, final Exception e) {
public CommandParseException(String string, Exception e) {
super(string, e);
}
}

View File

@ -28,26 +28,26 @@ import pw.yumc.YumCore.commands.exception.CommandParseException;
* @author
*/
public class CommandInfo {
public static final CommandInfo Unknow = new CommandInfo();
private static final String onlyExecutor = "§c当前命令仅允许 §b%s §c执行!";
private static final String losePerm = "§c你需要有 %s 的权限才能执行此命令!";
private static final String argErr = "§c参数错误: §4%s";
private static final String cmdErr = "§6错误原因: §4命令参数不正确!";
private static final String cmdUse = "§6使用方法: §e/%s %s %s";
private static final String cmdDes = "§6命令描述: §3%s";
private final Object origin;
private final Method method;
private final String name;
private final List<String> aliases;
private final List<Executor> executors;
private final String executorStr;
private final boolean async;
private final Cmd command;
private final Help help;
private final int sort;
private final CommandParse parse;
public static CommandInfo Unknow = new CommandInfo();
private static String onlyExecutor = "§c当前命令仅允许 §b%s §c执行!";
private static String losePerm = "§c你需要有 %s 的权限才能执行此命令!";
private static String argErr = "§c参数错误: §4%s";
private static String cmdErr = "§6错误原因: §4命令参数不正确!";
private static String cmdUse = "§6使用方法: §e/%s %s %s";
private static String cmdDes = "§6命令描述: §3%s";
private Object origin;
private Method method;
private String name;
private List<String> aliases;
private List<Executor> executors;
private String executorStr;
private boolean async;
private Cmd command;
private Help help;
private int sort;
private CommandParse parse;
public CommandInfo(final Method method, final Object origin, final Cmd command, final Help help, final boolean async, final int sort, final CommandParse parse) {
public CommandInfo(Method method, Object origin, Cmd command, Help help, boolean async, int sort, CommandParse parse) {
this.method = method;
this.origin = origin;
this.name = "".equals(command.value()) ? method.getName().toLowerCase() : command.value();
@ -84,20 +84,20 @@ public class CommandInfo {
* 源对象
* @return {@link CommandInfo}
*/
public static CommandInfo parse(final Method method, final Object origin) {
final Cmd command = method.getAnnotation(Cmd.class);
public static CommandInfo parse(Method method, Object origin) {
Cmd command = method.getAnnotation(Cmd.class);
if (command != null) {
final Help help = method.getAnnotation(Help.class);
final Async async = method.getAnnotation(Async.class);
final Sort sort = method.getAnnotation(Sort.class);
final CommandParse cp = CommandParse.get(method);
Help help = method.getAnnotation(Help.class);
Async async = method.getAnnotation(Async.class);
Sort sort = method.getAnnotation(Sort.class);
CommandParse cp = CommandParse.get(method);
return new CommandInfo(method, origin, command, help != null ? help : Help.DEFAULT, async != null, sort != null ? sort.value() : 50, cp);
}
return null;
}
@Override
public boolean equals(final Object obj) {
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
@ -119,12 +119,12 @@ public class CommandInfo {
return false;
}
if (check(cmdArgs)) {
final Runnable runnable = new Runnable() {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
method.invoke(origin, parse.parse(cmdArgs));
} catch (final CommandParseException | CommandArgumentException e) {
} catch (CommandParseException | CommandArgumentException e) {
Log.toSender(cmdArgs.getSender(), argErr, e.getMessage());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new CommandException(e);
@ -187,7 +187,7 @@ public class CommandInfo {
* 需验证命令
* @return 是否匹配
*/
public boolean isValid(final String cmd) {
public boolean isValid(String cmd) {
return name.equalsIgnoreCase(cmd) || aliases.contains(cmd);
}
@ -198,12 +198,12 @@ public class CommandInfo {
* 命令信息
* @return 是否验证通过
*/
private boolean check(final CommandArgument cmdArgs) {
final CommandSender sender = cmdArgs.getSender();
private boolean check(CommandArgument cmdArgs) {
CommandSender sender = cmdArgs.getSender();
return checkSender(sender) && checkArgs(sender, cmdArgs) && checkPerm(sender);
}
private boolean checkArgs(final CommandSender sender, final CommandArgument cmdArgs) {
private boolean checkArgs(CommandSender sender, CommandArgument cmdArgs) {
if (cmdArgs.getArgs().length < command.minimumArguments()) {
Log.toSender(sender, cmdErr);
Log.toSender(sender, String.format(cmdUse, cmdArgs.getAlias(), getName(), help.possibleArguments()));
@ -213,8 +213,8 @@ public class CommandInfo {
return true;
}
private boolean checkPerm(final CommandSender sender) {
final String perm = command.permission();
private boolean checkPerm(CommandSender sender) {
String perm = command.permission();
if (perm != null && !"".equals(perm) && !sender.hasPermission(perm)) {
Log.toSender(sender, String.format(losePerm, perm));
return false;
@ -222,7 +222,7 @@ public class CommandInfo {
return true;
}
private boolean checkSender(final CommandSender sender) {
private boolean checkSender(CommandSender sender) {
if (!executors.contains(Executor.ALL) && !executors.contains(Executor.valueOf(sender))) {
Log.toSender(sender, String.format(onlyExecutor, executorStr));
return false;
@ -230,9 +230,9 @@ public class CommandInfo {
return true;
}
private String eS(final List<Executor> executors) {
final StringBuilder str = new StringBuilder();
for (final Executor executor : executors) {
private String eS(List<Executor> executors) {
StringBuilder str = new StringBuilder();
for (Executor executor : executors) {
str.append(executor.getName());
str.append(", ");
}

View File

@ -19,10 +19,10 @@ import pw.yumc.YumCore.commands.exception.CommandException;
* @author
*/
public class CommandTabInfo {
private final Object origin;
private final Method method;
private Object origin;
private Method method;
public CommandTabInfo(final Method method, final Object origin) {
public CommandTabInfo(Method method, Object origin) {
this.method = method;
this.origin = origin;
}
@ -36,8 +36,8 @@ public class CommandTabInfo {
* 对象
* @return {@link CommandTabInfo}
*/
public static CommandTabInfo parse(final Method method, final Object origin) {
final Tab tab = method.getAnnotation(Tab.class);
public static CommandTabInfo parse(Method method, Object origin) {
Tab tab = method.getAnnotation(Tab.class);
if (tab != null) {
return new CommandTabInfo(method, origin);
}
@ -45,7 +45,7 @@ public class CommandTabInfo {
}
@Override
public boolean equals(final Object obj) {
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
@ -69,8 +69,8 @@ public class CommandTabInfo {
* @return Tab补全信息
*/
@SuppressWarnings("unchecked")
public List<String> execute(final CommandSender sender, final org.bukkit.command.Command command, final String label, final String[] args) {
final CommandArgument cmdArgs = new CommandArgument(sender, command, label, args);
public List<String> execute(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) {
CommandArgument cmdArgs = new CommandArgument(sender, command, label, args);
try {
return (List<String>) method.invoke(origin, cmdArgs);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {

View File

@ -36,20 +36,20 @@ import pw.yumc.YumCore.config.yaml.BukkitRepresenter;
* @author
*/
public abstract class AbstractConfig extends YamlConfiguration {
private static final String CONTENT_NOT_BE_NULL = "内容不能为 null";
private static final String TOP_KEY_MUST_BE_MAP = "顶层键值必须是Map.";
private static String CONTENT_NOT_BE_NULL = "内容不能为 null";
private static String TOP_KEY_MUST_BE_MAP = "顶层键值必须是Map.";
protected static final Charset UTF_8 = Charset.forName("UTF-8");
protected static Charset UTF_8 = Charset.forName("UTF-8");
protected static final String FILE_NOT_BE_NULL = "文件不能为 NULL";
protected static final String CREATE_NEW_CONFIG = "配置: 创建新的文件 %s ...";
protected static final String newLine = "\n";
protected static String FILE_NOT_BE_NULL = "文件不能为 NULL";
protected static String CREATE_NEW_CONFIG = "配置: 创建新的文件 %s ...";
protected static String newLine = "\n";
protected static Plugin plugin = P.instance;
protected final DumperOptions yamlOptions = new DumperOptions();
protected final Representer yamlRepresenter = new BukkitRepresenter();
protected final Yaml yamlz = new Yaml(new BukkitConstructor(), yamlRepresenter, yamlOptions);
protected DumperOptions yamlOptions = new DumperOptions();
protected Representer yamlRepresenter = new BukkitRepresenter();
protected Yaml yamlz = new Yaml(new BukkitConstructor(), yamlRepresenter, yamlOptions);
/**
* 配置文件内容MAP
@ -69,16 +69,16 @@ public abstract class AbstractConfig extends YamlConfiguration {
}
@Override
public void load(final File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, FILE_NOT_BE_NULL);
final FileInputStream stream = new FileInputStream(file);
FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, UTF_8));
}
@Override
public void load(final Reader reader) throws IOException, InvalidConfigurationException {
final BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
final StringBuilder builder = new StringBuilder();
public void load(Reader reader) throws IOException, InvalidConfigurationException {
BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
try {
String line;
while ((line = input.readLine()) != null) {
@ -92,16 +92,16 @@ public abstract class AbstractConfig extends YamlConfiguration {
}
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
public void loadFromString(String contents) throws InvalidConfigurationException {
Validate.notNull(contents, CONTENT_NOT_BE_NULL);
try {
contentsMap = (Map) yamlz.load(contents);
} catch (final YAMLException e) {
} catch (YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (final ClassCastException e) {
} catch (ClassCastException e) {
throw new InvalidConfigurationException(TOP_KEY_MUST_BE_MAP);
}
final String header = parseHeader(contents);
String header = parseHeader(contents);
if (header.length() > 0) {
options().header(header);
}
@ -111,14 +111,14 @@ public abstract class AbstractConfig extends YamlConfiguration {
}
@Override
public void save(final File file) throws IOException {
public void save(File file) throws IOException {
Validate.notNull(file, FILE_NOT_BE_NULL);
Files.createParentDirs(file);
if (!file.exists()) {
file.createNewFile();
Log.info(String.format(CREATE_NEW_CONFIG, file.toPath()));
}
final Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8);
Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8);
try {
writer.write(data);
} finally {
@ -131,7 +131,7 @@ public abstract class AbstractConfig extends YamlConfiguration {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final String header = buildHeader();
String header = buildHeader();
String dump = yamlz.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";

View File

@ -10,23 +10,23 @@ import org.yaml.snakeyaml.DumperOptions;
public class CommentConfig extends AbstractConfig {
// 新增保留注释字段
protected static final String commentPrefixSymbol = "'注释 ";
protected static final String commentSuffixSymbol = "': 注释";
protected static String commentPrefixSymbol = "'注释 ";
protected static String commentSuffixSymbol = "': 注释";
protected static final String fromRegex = "( {0,})(#.*)";
protected static final Pattern fromPattern = Pattern.compile(fromRegex);
protected static String fromRegex = "( {0,})(#.*)";
protected static Pattern fromPattern = Pattern.compile(fromRegex);
protected static final String toRegex = "( {0,})(- ){0,}" + "(" + commentPrefixSymbol + ")" + "(#.*)" + "(" + commentSuffixSymbol + ")";
protected static final Pattern toPattern = Pattern.compile(toRegex);
protected static String toRegex = "( {0,})(- ){0,}" + "(" + commentPrefixSymbol + ")" + "(#.*)" + "(" + commentSuffixSymbol + ")";
protected static Pattern toPattern = Pattern.compile(toRegex);
protected static final Pattern countSpacePattern = Pattern.compile("( {0,})(- ){0,}(.*)");
protected static Pattern countSpacePattern = Pattern.compile("( {0,})(- ){0,}(.*)");
protected static final int commentSplitWidth = 90;
protected static int commentSplitWidth = 90;
private static String[] split(final String string, final int partLength) {
final String[] array = new String[string.length() / partLength + 1];
private static String[] split(String string, int partLength) {
String[] array = new String[string.length() / partLength + 1];
for (int i = 0; i < array.length; i++) {
final int beginIndex = i * partLength;
int beginIndex = i * partLength;
int endIndex = beginIndex + partLength;
if (endIndex > string.length()) {
endIndex = string.length();
@ -37,15 +37,15 @@ public class CommentConfig extends AbstractConfig {
}
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
final String[] parts = contents.split(newLine);
final List<String> lastComments = new ArrayList<>();
final StringBuilder builder = new StringBuilder();
for (final String part : parts) {
public void loadFromString(String contents) throws InvalidConfigurationException {
String[] parts = contents.split(newLine);
List<String> lastComments = new ArrayList<>();
StringBuilder builder = new StringBuilder();
for (String part : parts) {
Matcher matcher = fromPattern.matcher(part);
if (matcher.find()) {
final String originComment = matcher.group(2);
final String[] splitComments = split(originComment, commentSplitWidth);
String originComment = matcher.group(2);
String[] splitComments = split(originComment, commentSplitWidth);
for (int i = 0; i < splitComments.length; i++) {
String comment = splitComments[i];
if (i == 0) {
@ -57,7 +57,7 @@ public class CommentConfig extends AbstractConfig {
} else {
matcher = countSpacePattern.matcher(part);
if (matcher.find() && !lastComments.isEmpty()) {
for (final String comment : lastComments) {
for (String comment : lastComments) {
builder.append(matcher.group(1));
builder.append(this.checkNull(matcher.group(2)));
builder.append(commentPrefixSymbol);
@ -79,16 +79,16 @@ public class CommentConfig extends AbstractConfig {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final String header = buildHeader();
String header = buildHeader();
String dump = yamlz.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
final String contents = header + dump;
final StringBuilder savcontent = new StringBuilder();
final String[] parts = contents.split(newLine);
String contents = header + dump;
StringBuilder savcontent = new StringBuilder();
String[] parts = contents.split(newLine);
for (String part : parts) {
final Matcher matcher = toPattern.matcher(part);
Matcher matcher = toPattern.matcher(part);
if (matcher.find() && matcher.groupCount() == 5) {
part = this.checkNull(matcher.group(1)) + matcher.group(4);
}
@ -106,7 +106,7 @@ public class CommentConfig extends AbstractConfig {
* 检查字符串
* @return 返回非null字符串
*/
private String checkNull(final String string) {
private String checkNull(String string) {
return string == null ? "" : string;
}
}

View File

@ -32,26 +32,26 @@ import pw.yumc.YumCore.bukkit.Log;
*/
@SuppressWarnings({ "unchecked" })
public class FileConfig extends AbstractConfig {
protected static final String VERSION = "Version";
protected static String VERSION = "Version";
private static final char ALT_COLOR_CHAR = '&';
private static final String DEFAULT = "config.yml";
private static final String DATA_FORMANT = "yyyyMMddHHmmss";
private static final String CONFIG_BACKUP = "配置: %s 已备份为 %s !";
private static final String CONFIG_UPDATED = "配置: %s 升级成功 版本 %s !";
private static final String CONFIG_OVERRIDE = "配置: %s 将覆盖原有字段数据...";
private static final String CONFIG_NOT_FOUND = "配置: 文件 %s 不存在!";
private static final String CONFIG_READ_ERROR = "配置: %s 读取错误...";
private static final String CONFIG_SAVE_ERROR = "配置: %s 保存错误...";
private static final String CONFIG_UPDATE_WARN = "配置: %s 版本 %s 过低 正在升级到 %s ...";
private static final String CONFIG_CREATE_ERROR = "配置: %s 创建失败...";
private static final String CONFIG_FORMAT_ERROR = "配置: %s 格式错误...";
private static final String CONFIG_BACKUP_ERROR = "配置: %s 备份失败 异常: %s !";
private static final String CONFIG_UPDATE_VALUE = "配置: 更新字段 %s 的值为 %s ...";
private static final String CONFIG_BACKUP_AND_RESET = "配置: %s 格式错误 已备份为 %s 并恢复默认配置!";
private static final String CONFIG_NOT_FOUND_IN_JAR = "配置: 从插件内部未找到预置的 %s 文件!";
private static final String CONFIG_READ_COMMENT_ERROR = "配置: 读取文件注释信息失败!";
private static final String STREAM_NOT_BE_NULL = "数据流不能为 NULL";
private static char ALT_COLOR_CHAR = '&';
private static String DEFAULT = "config.yml";
private static String DATA_FORMANT = "yyyyMMddHHmmss";
private static String CONFIG_BACKUP = "配置: %s 已备份为 %s !";
private static String CONFIG_UPDATED = "配置: %s 升级成功 版本 %s !";
private static String CONFIG_OVERRIDE = "配置: %s 将覆盖原有字段数据...";
private static String CONFIG_NOT_FOUND = "配置: 文件 %s 不存在!";
private static String CONFIG_READ_ERROR = "配置: %s 读取错误...";
private static String CONFIG_SAVE_ERROR = "配置: %s 保存错误...";
private static String CONFIG_UPDATE_WARN = "配置: %s 版本 %s 过低 正在升级到 %s ...";
private static String CONFIG_CREATE_ERROR = "配置: %s 创建失败...";
private static String CONFIG_FORMAT_ERROR = "配置: %s 格式错误...";
private static String CONFIG_BACKUP_ERROR = "配置: %s 备份失败 异常: %s !";
private static String CONFIG_UPDATE_VALUE = "配置: 更新字段 %s 的值为 %s ...";
private static String CONFIG_BACKUP_AND_RESET = "配置: %s 格式错误 已备份为 %s 并恢复默认配置!";
private static String CONFIG_NOT_FOUND_IN_JAR = "配置: 从插件内部未找到预置的 %s 文件!";
private static String CONFIG_READ_COMMENT_ERROR = "配置: 读取文件注释信息失败!";
private static String STREAM_NOT_BE_NULL = "数据流不能为 NULL";
protected File file;
@ -70,7 +70,7 @@ public class FileConfig extends AbstractConfig {
* @param file
* 配置文件名称
*/
public FileConfig(final File file) {
public FileConfig(File file) {
Validate.notNull(file, FILE_NOT_BE_NULL);
init(file);
}
@ -83,7 +83,7 @@ public class FileConfig extends AbstractConfig {
* @param filename
* 配置文件名称
*/
public FileConfig(final File parent, final String filename) {
public FileConfig(File parent, String filename) {
init(new File(parent, filename), true);
}
@ -93,7 +93,7 @@ public class FileConfig extends AbstractConfig {
* @param stream
* 数据流
*/
public FileConfig(final InputStream stream) {
public FileConfig(InputStream stream) {
init(stream);
}
@ -103,7 +103,7 @@ public class FileConfig extends AbstractConfig {
* @param filename
* 配置文件名称
*/
public FileConfig(final String filename) {
public FileConfig(String filename) {
init(new File(plugin.getDataFolder(), filename), true);
}
@ -115,7 +115,7 @@ public class FileConfig extends AbstractConfig {
* @param filename
* 配置文件名称
*/
public FileConfig(final String parent, final String filename) {
public FileConfig(String parent, String filename) {
init(new File(parent, filename), true);
}
@ -130,7 +130,7 @@ public class FileConfig extends AbstractConfig {
* 对象
* @return {@link FileConfig}
*/
public <E> FileConfig addToList(final String path, final E obj) {
public <E> FileConfig addToList(String path, E obj) {
List<E> l = (List<E>) this.getList(path);
if (null == l) {
l = new ArrayList<>();
@ -148,7 +148,7 @@ public class FileConfig extends AbstractConfig {
* 字符串
* @return {@link FileConfig}
*/
public FileConfig addToStringList(final String path, final String obj) {
public FileConfig addToStringList(String path, String obj) {
addToStringList(path, obj, true);
return this;
}
@ -164,7 +164,7 @@ public class FileConfig extends AbstractConfig {
* 是否允许重复
* @return {@link FileConfig}
*/
public FileConfig addToStringList(final String path, final String obj, final boolean allowrepeat) {
public FileConfig addToStringList(String path, String obj, boolean allowrepeat) {
List<String> l = this.getStringList(path);
if (null == l) {
l = new ArrayList<>();
@ -183,12 +183,12 @@ public class FileConfig extends AbstractConfig {
* 待转码的List
* @return 颜色转码后的文本
*/
public List<String> getColorList(final List<String> cfgmsg) {
final List<String> message = new ArrayList<>();
public List<String> getColorList(List<String> cfgmsg) {
List<String> message = new ArrayList<>();
if (cfgmsg == null) {
return Collections.emptyList();
}
for (final String msg : cfgmsg) {
for (String msg : cfgmsg) {
message.add(ChatColor.translateAlternateColorCodes('&', msg));
}
return message;
@ -210,7 +210,7 @@ public class FileConfig extends AbstractConfig {
*
* @return {@link Location}
*/
public Location getLocation(final String key) {
public Location getLocation(String key) {
return getLocation(key, null);
}
@ -223,8 +223,8 @@ public class FileConfig extends AbstractConfig {
* 默认地点
* @return {@link Location}
*/
public Location getLocation(final String path, final Location def) {
final Object val = get(path, def);
public Location getLocation(String path, Location def) {
Object val = get(path, def);
return val instanceof Location ? (Location) val : def;
}
@ -235,7 +235,7 @@ public class FileConfig extends AbstractConfig {
* 配置路径
* @return 颜色转码后的文本
*/
public String getMessage(final String path) {
public String getMessage(String path) {
return getMessage(path, null);
}
@ -248,7 +248,7 @@ public class FileConfig extends AbstractConfig {
* 默认文本
* @return 颜色转码后的文本
*/
public String getMessage(final String path, final String def) {
public String getMessage(String path, String def) {
String message = this.getString(path, def);
if (message != null) {
message = ChatColor.translateAlternateColorCodes('&', message);
@ -263,8 +263,8 @@ public class FileConfig extends AbstractConfig {
* 配置路径
* @return 颜色转码后的文本
*/
public List<String> getMessageList(final String path) {
final List<String> cfgmsg = this.getStringList(path);
public List<String> getMessageList(String path) {
List<String> cfgmsg = this.getStringList(path);
if (cfgmsg == null) {
return Collections.emptyList();
}
@ -281,16 +281,16 @@ public class FileConfig extends AbstractConfig {
* 配置路径
* @return 字符串数组
*/
public String[] getStringArray(final String path) {
public String[] getStringArray(String path) {
return this.getStringList(path).toArray(new String[0]);
}
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
public void loadFromString(String contents) throws InvalidConfigurationException {
try {
commentConfig = new CommentConfig();
commentConfig.loadFromString(contents);
} catch (final Exception e) {
} catch (Exception e) {
Log.debug(CONFIG_READ_COMMENT_ERROR);
commentConfig = null;
}
@ -306,17 +306,17 @@ public class FileConfig extends AbstractConfig {
* 旧版本
* @return 是否需要更新
*/
public boolean needUpdate(final String newver, final String oldver) {
public boolean needUpdate(String newver, String oldver) {
if (newver == null) {
return false;
}
if (oldver == null) {
return true;
}
final String[] va1 = newver.split("\\.");// 注意此处为正则匹配不能用"."
final String[] va2 = oldver.split("\\.");
String[] va1 = newver.split("\\.");// 注意此处为正则匹配不能用"."
String[] va2 = oldver.split("\\.");
int idx = 0;
final int minLength = Math.min(va1.length, va2.length);// 取最小长度值
int minLength = Math.min(va1.length, va2.length);// 取最小长度值
int diff = 0;
while (idx < minLength
&& (diff = va1[idx].length() - va2[idx].length()) == 0// 先比较长度
@ -348,8 +348,8 @@ public class FileConfig extends AbstractConfig {
* 对象
* @return {@link FileConfig}
*/
public <E> FileConfig removeFromList(final String path, final E obj) {
final List<E> l = (List<E>) this.getList(path);
public <E> FileConfig removeFromList(String path, E obj) {
List<E> l = (List<E>) this.getList(path);
if (null != l) {
l.remove(obj);
}
@ -365,8 +365,8 @@ public class FileConfig extends AbstractConfig {
* 对象
* @return {@link FileConfig}
*/
public FileConfig removeFromStringList(final String path, final String obj) {
final List<String> l = this.getStringList(path);
public FileConfig removeFromStringList(String path, String obj) {
List<String> l = this.getStringList(path);
if (null != l) {
l.remove(obj);
}
@ -383,7 +383,7 @@ public class FileConfig extends AbstractConfig {
try {
this.save(file);
return true;
} catch (final IOException e) {
} catch (IOException e) {
Log.warning(String.format(CONFIG_SAVE_ERROR, file.getName()));
e.printStackTrace();
return false;
@ -391,7 +391,7 @@ public class FileConfig extends AbstractConfig {
}
@Override
public void save(final File file) throws IOException {
public void save(File file) throws IOException {
Validate.notNull(file, FILE_NOT_BE_NULL);
if (commentConfig != null) {
data = commentConfig.saveToString();
@ -402,7 +402,7 @@ public class FileConfig extends AbstractConfig {
}
@Override
public void set(final String path, final Object value) {
public void set(String path, Object value) {
if (commentConfig != null) {
commentConfig.set(path, value);
}
@ -415,9 +415,9 @@ public class FileConfig extends AbstractConfig {
private void saveFromJar() {
if (plugin != null && file != null) {
try {
final String filename = file.getName();
final InputStream filestream = plugin.getResource(file.getName());
final String errFileName = this.getErrName(filename);
String filename = file.getName();
InputStream filestream = plugin.getResource(file.getName());
String errFileName = this.getErrName(filename);
file.renameTo(new File(file.getParent(), errFileName));
if (filestream == null) {
file.createNewFile();
@ -425,7 +425,7 @@ public class FileConfig extends AbstractConfig {
plugin.saveResource(filename, true);
}
Log.warning(String.format(CONFIG_BACKUP_AND_RESET, filename, errFileName));
} catch (final IOException | IllegalArgumentException e) {
} catch (IOException | IllegalArgumentException e) {
throw new IllegalArgumentException(e);
}
} else {
@ -439,14 +439,14 @@ public class FileConfig extends AbstractConfig {
* @param oldcfg
* 配置文件
*/
protected void backupConfig(final FileConfig oldcfg) {
final String filename = oldcfg.getConfigName();
protected void backupConfig(FileConfig oldcfg) {
String filename = oldcfg.getConfigName();
try {
final String newCfgName = this.getBakName(filename);
final File newcfg = new File(file.getParent(), newCfgName);
String newCfgName = this.getBakName(filename);
File newcfg = new File(file.getParent(), newCfgName);
oldcfg.save(newcfg);
Log.warning(String.format(CONFIG_BACKUP, filename, newCfgName));
} catch (final IOException e) {
} catch (IOException e) {
Log.warning(String.format(CONFIG_BACKUP_ERROR, filename, e.getMessage()));
Log.debug(oldcfg.getConfigName(), e);
}
@ -458,9 +458,9 @@ public class FileConfig extends AbstractConfig {
* @param file
* 配置文件
*/
protected void check(final File file) {
final String filename = file.getName();
final InputStream stream = plugin.getResource(filename);
protected void check(File file) {
String filename = file.getName();
InputStream stream = plugin.getResource(filename);
try {
if (!file.exists()) {
file.getParentFile().mkdirs();
@ -473,23 +473,23 @@ public class FileConfig extends AbstractConfig {
if (stream == null) {
return;
}
final FileConfig newcfg = new FileConfig(stream);
final FileConfig oldcfg = new FileConfig(file);
FileConfig newcfg = new FileConfig(stream);
FileConfig oldcfg = new FileConfig(file);
if (needUpdate(newcfg, oldcfg)) {
backupConfig(oldcfg);
updateConfig(newcfg, oldcfg).save(file);
}
}
} catch (final IOException e) {
} catch (IOException e) {
Log.warning(String.format(CONFIG_CREATE_ERROR, filename));
}
}
protected String getBakName(final String cfgname) {
protected String getBakName(String cfgname) {
return cfgname + "." + getStringDate(DATA_FORMANT) + ".bak";
}
protected String getErrName(final String cfgname) {
protected String getErrName(String cfgname) {
return cfgname + "." + getStringDate(DATA_FORMANT) + ".err";
}
@ -502,7 +502,7 @@ public class FileConfig extends AbstractConfig {
if (format == null) {
format = "yyyy-MM-dd HH:mm:ss";
}
final Date currentTime = new Date();
Date currentTime = new Date();
return new SimpleDateFormat(format).format(currentTime);
}
@ -513,7 +513,7 @@ public class FileConfig extends AbstractConfig {
* 配置文件
* @return FileConfig
*/
protected FileConfig init(final File file) {
protected FileConfig init(File file) {
init(file, false);
return this;
}
@ -527,7 +527,7 @@ public class FileConfig extends AbstractConfig {
* 是否检查文件
* @return FileConfig
*/
protected FileConfig init(final File file, final boolean check) {
protected FileConfig init(File file, boolean check) {
Validate.notNull(file, FILE_NOT_BE_NULL);
this.file = file;
if (check) {
@ -535,7 +535,7 @@ public class FileConfig extends AbstractConfig {
}
try {
init(new FileInputStream(file));
} catch (final FileNotFoundException e) {
} catch (FileNotFoundException e) {
Log.debug(String.format(CONFIG_NOT_FOUND, file.toPath()));
}
return this;
@ -548,18 +548,18 @@ public class FileConfig extends AbstractConfig {
* 输入流
* @return FileConfig
*/
protected FileConfig init(final InputStream stream) {
protected FileConfig init(InputStream stream) {
Validate.notNull(stream, STREAM_NOT_BE_NULL);
try {
this.load(new InputStreamReader(stream, UTF_8));
} catch (final InvalidConfigurationException | IllegalArgumentException ex) {
} catch (InvalidConfigurationException | IllegalArgumentException ex) {
if (file == null) {
throw new IllegalArgumentException(ex);
}
Log.warning(String.format(CONFIG_FORMAT_ERROR, file.getName()));
Log.warning(ex.getMessage());
saveFromJar();
} catch (final IOException ex) {
} catch (IOException ex) {
if (file == null) {
throw new IllegalStateException(ex);
}
@ -577,7 +577,7 @@ public class FileConfig extends AbstractConfig {
* 旧配置文件
* @return 是否需要升级
*/
protected boolean needUpdate(final FileConfig newcfg, final FileConfig oldcfg) {
protected boolean needUpdate(FileConfig newcfg, FileConfig oldcfg) {
return needUpdate(newcfg.getString(VERSION), oldcfg.getString(VERSION));
}
@ -590,7 +590,7 @@ public class FileConfig extends AbstractConfig {
* 旧配置文件
* @return 更新以后的配置文件
*/
protected FileConfig updateConfig(final FileConfig newCfg, final FileConfig oldCfg) {
protected FileConfig updateConfig(FileConfig newCfg, FileConfig oldCfg) {
return updateConfig(newCfg, oldCfg, false);
}
@ -605,11 +605,11 @@ public class FileConfig extends AbstractConfig {
* 是否强制更新
* @return 更新以后的配置文件
*/
protected FileConfig updateConfig(final FileConfig newCfg, final FileConfig oldCfg, final boolean force) {
final String filename = oldCfg.getConfigName();
final String newver = newCfg.getString(VERSION);
final String oldver = oldCfg.getString(VERSION);
final Set<String> oldConfigKeys = oldCfg.getKeys(true);
protected FileConfig updateConfig(FileConfig newCfg, FileConfig oldCfg, boolean force) {
String filename = oldCfg.getConfigName();
String newver = newCfg.getString(VERSION);
String oldver = oldCfg.getString(VERSION);
Set<String> oldConfigKeys = oldCfg.getKeys(true);
Log.warning(String.format(CONFIG_UPDATE_WARN, filename, oldver, newver));
// 保留版本字段 不更新
oldConfigKeys.remove(VERSION);
@ -619,8 +619,8 @@ public class FileConfig extends AbstractConfig {
oldConfigKeys.removeAll(newCfg.getKeys(true));
}
// 复制旧的数据
for (final String string : oldConfigKeys) {
final Object var = oldCfg.get(string);
for (String string : oldConfigKeys) {
Object var = oldCfg.get(string);
if (var != null && !(var instanceof MemorySection)) {
Log.debug(String.format(CONFIG_UPDATE_VALUE, string, var));
newCfg.set(string, var);

View File

@ -23,7 +23,7 @@ public class PlayerConfig extends FileConfig {
* @param player
* 玩家
*/
public PlayerConfig(final File dir, final Player player) {
public PlayerConfig(File dir, Player player) {
super(dir, player.getName() + ".yml");
}
@ -33,7 +33,7 @@ public class PlayerConfig extends FileConfig {
* @param player
* 玩家
*/
public PlayerConfig(final Player player) {
public PlayerConfig(Player player) {
this(player.getName());
}
@ -43,7 +43,7 @@ public class PlayerConfig extends FileConfig {
* @param playername
* 玩家名称
*/
public PlayerConfig(final String playername) {
public PlayerConfig(String playername) {
super(new File(plugin.getDataFolder(), CONFIG_FOLDER), playername + ".yml");
}
}

View File

@ -14,11 +14,11 @@ import pw.yumc.YumCore.config.FileConfig;
* @author
*/
public class RemoteConfig extends FileConfig {
public RemoteConfig(final String url) throws MalformedURLException, IOException {
public RemoteConfig(String url) throws MalformedURLException, IOException {
this(new URL(url));
}
public RemoteConfig(final URL url) throws IOException {
public RemoteConfig(URL url) throws IOException {
super(url.openStream());
}
@ -29,10 +29,10 @@ public class RemoteConfig extends FileConfig {
* 配置文件地址
* @return {@link FileConfig}
*/
public static FileConfig getConfig(final String url) {
public static FileConfig getConfig(String url) {
try {
return new RemoteConfig(url);
} catch (final IOException e) {
} catch (IOException e) {
Log.debug("获取远程配置文件失败!", e);
return null;
}
@ -49,11 +49,11 @@ public class RemoteConfig extends FileConfig {
* 默认值
* @return 插件信息
*/
public static String getYamlTag(final String url, final String tag, final String def) {
public static String getYamlTag(String url, String tag, String def) {
String result = def;
try {
result = getConfig(url).getString(tag);
} catch (final NullPointerException e) {
} catch (NullPointerException e) {
// Ignore
}
return result;

View File

@ -7,11 +7,11 @@ import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.config.FileConfig;
public class YumConfig {
protected static final String REMOTEFILECENTER = "http://data.yumc.pw/config/";
protected static final String DataFolder = "plugins" + File.separatorChar + "YumCore";
protected static String REMOTEFILECENTER = "http://data.yumc.pw/config/";
protected static String DataFolder = "plugins" + File.separatorChar + "YumCore";
private static final String fromYumc = "配置 %s 来自 YUMC 数据中心...";
private static final String createError = "从 YUMC 数据中心下载配置 %s 失败...";
private static String fromYumc = "配置 %s 来自 YUMC 数据中心...";
private static String createError = "从 YUMC 数据中心下载配置 %s 失败...";
private YumConfig() {
}
@ -23,8 +23,8 @@ public class YumConfig {
* 本地文件名称
* @return {@link FileConfig}
*/
public static FileConfig getLocal(final String filename) {
final File file = new File(DataFolder, filename);
public static FileConfig getLocal(String filename) {
File file = new File(DataFolder, filename);
return new FileConfig(file);
}
@ -35,11 +35,11 @@ public class YumConfig {
* 配置文件地址
* @return {@link FileConfig}
*/
public static FileConfig getRemote(final String url) {
public static FileConfig getRemote(String url) {
FileConfig config = null;
try {
config = new RemoteConfig(REMOTEFILECENTER + url);
} catch (final IOException e) {
} catch (IOException e) {
Log.debug(e);
}
Log.info(String.format(config == null ? createError : fromYumc, url));

View File

@ -23,12 +23,12 @@ import pw.yumc.YumCore.config.annotation.Nullable;
* @author
*/
public abstract class AbstractInjectConfig {
private static final String INJECT_TYPE_ERROR = "配置节点 %s 数据类型不匹配 应该为: %s 但实际为: %s!";
private static final String INJECT_ERROR = "自动注入配置失败 可能造成插件运行错误 %s: %s!";
private static final String DATE_PARSE_ERROR = "配置节点 {0} 日期解析失败 格式应该为: {1} 但输入值为: {2}!";
private static final String PATH_NOT_FOUND = "配置节点 %s 丢失 将使用默认值!";
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
private static String INJECT_TYPE_ERROR = "配置节点 %s 数据类型不匹配 应该为: %s 但实际为: %s!";
private static String INJECT_ERROR = "自动注入配置失败 可能造成插件运行错误 %s: %s!";
private static String DATE_PARSE_ERROR = "配置节点 {0} 日期解析失败 格式应该为: {1} 但输入值为: {2}!";
private static String PATH_NOT_FOUND = "配置节点 %s 丢失 将使用默认值!";
private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
private ConfigurationSection config;
/**
@ -37,7 +37,7 @@ public abstract class AbstractInjectConfig {
* @param config
* 配置区
*/
public void inject(final ConfigurationSection config) {
public void inject(ConfigurationSection config) {
inject(config, false);
}
@ -49,17 +49,17 @@ public abstract class AbstractInjectConfig {
* @param save
* 是否为保存
*/
public void inject(final ConfigurationSection config, final boolean save) {
public void inject(ConfigurationSection config, boolean save) {
if (config == null) {
Log.w("尝试%s ConfigurationSection 为 Null 的数据!", save ? "保存" : "读取");
return;
}
this.config = config;
for (final Field field : getClass().getDeclaredFields()) {
for (Field field : getClass().getDeclaredFields()) {
if (Modifier.isTransient(field.getModifiers()) || field.getType().isPrimitive()) {
continue;
}
final ConfigNode node = field.getAnnotation(ConfigNode.class);
ConfigNode node = field.getAnnotation(ConfigNode.class);
String path = field.getName();
if (node != null && !node.value().isEmpty()) {
path = node.value();
@ -79,7 +79,7 @@ public abstract class AbstractInjectConfig {
* @param config
* 配置文件区
*/
public ConfigurationSection save(final ConfigurationSection config) {
public ConfigurationSection save(ConfigurationSection config) {
inject(config, true);
return config;
}
@ -94,7 +94,7 @@ public abstract class AbstractInjectConfig {
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
private void applyDefault(final Field field, Object value) throws IllegalArgumentException, IllegalAccessException {
private void applyDefault(Field field, Object value) throws IllegalArgumentException, IllegalAccessException {
switch (field.getType().getName()) {
case "java.util.List":
value = new ArrayList<>();
@ -122,7 +122,7 @@ public abstract class AbstractInjectConfig {
* @throws NoSuchMethodException
* @throws SecurityException
*/
private Object convertType(final Class<?> type, final String path, final Object value) throws ParseException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
private Object convertType(Class<?> type, String path, Object value) throws ParseException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
switch (type.getName()) {
case "java.util.Date":
return df.parse((String) value);
@ -152,7 +152,7 @@ public abstract class AbstractInjectConfig {
* @throws NoSuchMethodException
* @throws SecurityException
*/
private Object hanldeDefault(final Class<?> field, final String path, final Object value) throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
private Object hanldeDefault(Class<?> field, String path, Object value) throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
if (InjectConfigurationSection.class.isAssignableFrom(field)) {
if (config.isConfigurationSection(path)) {
return field.getConstructor(ConfigurationSection.class).newInstance(config.getConfigurationSection(path));
@ -179,8 +179,8 @@ public abstract class AbstractInjectConfig {
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
private void hanldeValue(final String path, final Field field, Object value) throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException, ParseException {
final Class<?> type = field.getType();
private void hanldeValue(String path, Field field, Object value) throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException, ParseException {
Class<?> type = field.getType();
if (!type.equals(value.getClass())) {
value = convertType(type, path, value);
}
@ -199,7 +199,7 @@ public abstract class AbstractInjectConfig {
* @param field
* 字段
*/
protected void setConfig(final String path, final Field field) {
protected void setConfig(String path, Field field) {
try {
config.set(path, field.get(this));
} catch (IllegalArgumentException | IllegalAccessException e) {
@ -216,10 +216,10 @@ public abstract class AbstractInjectConfig {
* @param field
* 字段
*/
protected void setField(final String path, final Field field) {
protected void setField(String path, Field field) {
Object value = config.get(path);
try {
final Default def = field.getAnnotation(Default.class);
Default def = field.getAnnotation(Default.class);
if (value == null && def != null) {
value = def.value();
}
@ -231,12 +231,12 @@ public abstract class AbstractInjectConfig {
return;
}
hanldeValue(path, field, value);
} catch (final IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
Log.w(INJECT_TYPE_ERROR, path, field.getType().getName(), value.getClass().getName());
Log.debug(ex);
} catch (final ParseException e) {
} catch (ParseException e) {
Log.w(DATE_PARSE_ERROR, path, DATE_FORMAT, value);
} catch (final InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException | IllegalAccessException ex) {
} catch (InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException | IllegalAccessException ex) {
Log.w(INJECT_ERROR, ex.getClass().getName(), ex.getMessage());
Log.debug(ex);
}

View File

@ -17,16 +17,16 @@ public abstract class InjectConfig extends AbstractInjectConfig {
this(new FileConfig());
}
public InjectConfig(final File file) {
public InjectConfig(File file) {
this(new FileConfig(file));
}
public InjectConfig(final FileConfig config) {
public InjectConfig(FileConfig config) {
this.config = config;
inject(config);
}
public InjectConfig(final String name) {
public InjectConfig(String name) {
this(new FileConfig(name));
}

View File

@ -10,7 +10,7 @@ import org.bukkit.configuration.ConfigurationSection;
*/
public abstract class InjectConfigurationSection extends AbstractInjectConfig {
public InjectConfigurationSection(final ConfigurationSection config) {
public InjectConfigurationSection(ConfigurationSection config) {
inject(config);
}
@ -20,7 +20,7 @@ public abstract class InjectConfigurationSection extends AbstractInjectConfig {
* @param config
* 配置区
*/
public void reload(final ConfigurationSection config) {
public void reload(ConfigurationSection config) {
inject(config);
}
}

View File

@ -29,21 +29,21 @@ public class BukkitConstructor extends YamlConstructor {
private class ConstructCustomObject extends ConstructYamlMap {
@Override
public Object construct(final Node node) {
public Object construct(Node node) {
if (node.isTwoStepsConstruction()) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
final Map<?, ?> raw = (Map<?, ?>) super.construct(node);
Map<?, ?> raw = (Map<?, ?>) super.construct(node);
if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
final Map<String, Object> typed = new LinkedHashMap<>(raw.size());
for (final Map.Entry<?, ?> entry : raw.entrySet()) {
Map<String, Object> typed = new LinkedHashMap<>(raw.size());
for (Map.Entry<?, ?> entry : raw.entrySet()) {
typed.put(entry.getKey().toString(), entry.getValue());
}
// 自定义解析部分
final String key = raw.get(ConfigurationSerialization.SERIALIZED_TYPE_KEY).toString();
String key = raw.get(ConfigurationSerialization.SERIALIZED_TYPE_KEY).toString();
if (constructor.containsKey(key)) {
try {
return constructor.get(key).invoke(null, typed);
@ -55,7 +55,7 @@ public class BukkitConstructor extends YamlConstructor {
// Bukkit自动解析
try {
return ConfigurationSerialization.deserializeObject(typed);
} catch (final IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
throw new YAMLException("Could not deserialize object", ex);
}
}
@ -64,7 +64,7 @@ public class BukkitConstructor extends YamlConstructor {
}
@Override
public void construct2ndStep(final Node node, final Object object) {
public void construct2ndStep(Node node, Object object) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
}

View File

@ -13,7 +13,7 @@ public class BukkitRepresenter extends YamlRepresenter {
public class RepresentLocation extends RepresentMap {
@Override
public Node representData(final Object data) {
public Node representData(Object data) {
return super.representData(L.serialize((Location) data));
}
}

View File

@ -38,7 +38,7 @@ public class L10N {
* 物品实体
* @return 物品名称
*/
public static final String getFullName(final ItemStack i) {
public static String getFullName(ItemStack i) {
return getItemName(getItemType(i)) + (i.hasItemMeta() && i.getItemMeta().hasDisplayName() ? "§r(" + i.getItemMeta().getDisplayName() + "§r)" : "");
}
@ -49,7 +49,7 @@ public class L10N {
* 物品实体
* @return 物品名称
*/
public static final String getItemName(final ItemStack i) {
public static String getItemName(ItemStack i) {
return getItemName(getItemType(i));
}
@ -60,7 +60,7 @@ public class L10N {
* 物品实体
* @return 物品名称
*/
public static final String getName(final ItemStack i) {
public static String getName(ItemStack i) {
return i.hasItemMeta() && i.getItemMeta().hasDisplayName() ? i.getItemMeta().getDisplayName() : getItemName(getItemType(i));
}
@ -80,7 +80,7 @@ public class L10N {
* 物品类型名称
* @return 物品名称
*/
private static final String getItemName(final String iname) {
private static String getItemName(String iname) {
String aname = content.get(iname);
if (aname == null) {
aname = iname;
@ -99,13 +99,13 @@ public class L10N {
* 物品实体
* @return 物品类型
*/
private static final String getItemType(final ItemStack i) {
private static String getItemType(ItemStack i) {
String name = i.getType().name();
String dura = "";
if (i.getType() == Material.MONSTER_EGG) {
name = ((SpawnEgg) i.getData()).getSpawnedType().name();
} else {
final int dur = i.getDurability();
int dur = i.getDurability();
dura = (i.getMaxStackSize() != 1 && dur != 0) ? Integer.toString(dur) : "";
}
return (name + (dura.isEmpty() ? "" : "-" + dura)).toUpperCase();
@ -120,8 +120,8 @@ public class L10N {
@Override
public void run() {
try {
final Map<String, String> local = YumConfig.getLocal(CONFIG_NAME).getContentMap();
final Map<String, String> remote = YumConfig.getRemote(CONFIG_NAME).getContentMap();
Map<String, String> local = YumConfig.getLocal(CONFIG_NAME).getContentMap();
Map<String, String> remote = YumConfig.getRemote(CONFIG_NAME).getContentMap();
if (local != null) {
Log.info("本地汉化文件词条数量: " + local.size());
content.putAll(local);
@ -131,7 +131,7 @@ public class L10N {
content.putAll(remote);
}
Log.info("本地化工具初始化完毕...");
} catch (final Exception e) {
} catch (Exception e) {
Log.warning(String.format("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage()));
Log.debug(CONFIG_NAME, e);
}

View File

@ -29,10 +29,10 @@ public class EntityKit {
private static Field _fgoalSelector;
private static Field _ftargetSelector;
private final static Class<?> _cControllerMove = MinecraftReflection.getMinecraftClass("ControllerMove");
private final static Class<?> _cPathEntity = MinecraftReflection.getMinecraftClass("PathEntity");
private final static Class<?> _cEntityInsentient = MinecraftReflection.getMinecraftClass("EntityInsentient");
private final static Class<?> _cPathfinderGoalSelector = MinecraftReflection.getMinecraftClass("PathfinderGoalSelector");
private static Class<?> _cControllerMove = MinecraftReflection.getMinecraftClass("ControllerMove");
private static Class<?> _cPathEntity = MinecraftReflection.getMinecraftClass("PathEntity");
private static Class<?> _cEntityInsentient = MinecraftReflection.getMinecraftClass("EntityInsentient");
private static Class<?> _cPathfinderGoalSelector = MinecraftReflection.getMinecraftClass("PathfinderGoalSelector");
private static Method _mPlayerList_MoveToWorld = null;
private static Method _mPlayerConnection_Teleport = null;
@ -49,9 +49,9 @@ public class EntityKit {
ReflectUtil.getMethodByNameAndParams(_cEntityInsentient, "getControllerMove");
ReflectUtil.getDeclaredMethodByParams(_cControllerMove, double.class, double.class, double.class, double.class).get(0);
final Class<?> cc = MinecraftReflection.getMinecraftClass("NavigationAbstract");
for (final Method method : cc.getDeclaredMethods()) {
final Class<?>[] parmeters = method.getParameterTypes();
Class<?> cc = MinecraftReflection.getMinecraftClass("NavigationAbstract");
for (Method method : cc.getDeclaredMethods()) {
Class<?>[] parmeters = method.getParameterTypes();
switch (parmeters.length) {
case 1: {
if (parmeters[0] == double.class) {
@ -73,7 +73,7 @@ public class EntityKit {
}
}
}
} catch (final Exception ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
try {
@ -86,7 +86,7 @@ public class EntityKit {
Location.class,
Boolean.TYPE)
.get(0);
} catch (final Exception ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
}
@ -98,9 +98,9 @@ public class EntityKit {
* 实体ID
* @return 实体
*/
public static Entity getEntityById(final int entityId) {
for (final World world : Bukkit.getWorlds()) {
for (final Entity entity : world.getEntities()) {
public static Entity getEntityById(int entityId) {
for (World world : Bukkit.getWorlds()) {
for (Entity entity : world.getEntities()) {
if (entity.getEntityId() == entityId) {
return entity;
}
@ -116,7 +116,7 @@ public class EntityKit {
* 实体
* @return 结果
*/
public static boolean inWater(final Entity ent) {
public static boolean inWater(Entity ent) {
return ent.getLocation().getBlock().getTypeId() == 8 || ent.getLocation().getBlock().getTypeId() == 9;
}
@ -127,11 +127,11 @@ public class EntityKit {
* 实体
* @return 是否隐藏
*/
public static boolean isInvisible(final Entity entity) {
final Object ent = ReflectUtil.getHandle(entity);
public static boolean isInvisible(Entity entity) {
Object ent = ReflectUtil.getHandle(entity);
try {
return (boolean) ent.getClass().getMethod("isInvisible").invoke(ent);
} catch (final Exception e) {
} catch (Exception e) {
}
return false;
}
@ -143,7 +143,7 @@ public class EntityKit {
* 实体
* @return 结果
*/
public static boolean isOnGround(final Entity ent) {
public static boolean isOnGround(Entity ent) {
return ent.isOnGround();
}
@ -154,7 +154,7 @@ public class EntityKit {
* 实体
* @return 结果
*/
public static boolean isSilence(final Entity entity) {
public static boolean isSilence(Entity entity) {
return WrappedDataWatcher.getEntityWatcher(entity).getByte(4) == 1;
}
@ -165,7 +165,7 @@ public class EntityKit {
* 实体
* @return 结果
*/
public static boolean onBlock(final Entity entity) {
public static boolean onBlock(Entity entity) {
// Side Standing
double xMod = entity.getLocation().getX() % 1;
if (entity.getLocation().getX() < 0) {
@ -209,7 +209,7 @@ public class EntityKit {
}
// Fences/Walls
final Material beneath = entity.getLocation().add(x, -1.5, z).getBlock().getType();
Material beneath = entity.getLocation().add(x, -1.5, z).getBlock().getType();
if (entity.getLocation().getY() % 0.5 == 0 && (beneath == Material.FENCE || beneath == Material.FENCE_GATE || beneath == Material.NETHER_FENCE || beneath == Material.COBBLE_WALL)) {
return true;
}
@ -226,14 +226,14 @@ public class EntityKit {
* 实体名称
* @return {@link EntityType}
*/
public static EntityType parseEntityType(final String str) {
public static EntityType parseEntityType(String str) {
EntityType type = null;
if (str != null) {
type = EntityType.fromName(str);
if (type == null) {
try {
type = EntityType.valueOf(str.toUpperCase());
} catch (final Exception e) {
} catch (Exception e) {
}
}
}
@ -246,20 +246,20 @@ public class EntityKit {
* @param entity
* 实体
*/
public static void removeGoalSelectors(final Entity entity) {
public static void removeGoalSelectors(Entity entity) {
try {
if (_fgoalSelector == null) {
_fgoalSelector = _cEntityInsentient.getDeclaredField("goalSelector");
_fgoalSelector.setAccessible(true);
}
final Object creature = ReflectUtil.getHandle(entity);
Object creature = ReflectUtil.getHandle(entity);
if (_cEntityInsentient.isInstance(creature)) {
final Object world = ReflectUtil.getHandle(entity.getWorld());
final Object methodProfiler = world.getClass().getField("methodProfiler").get(world);
final Object goalSelector = _cPathfinderGoalSelector.getConstructor(methodProfiler.getClass()).newInstance(methodProfiler);
Object world = ReflectUtil.getHandle(entity.getWorld());
Object methodProfiler = world.getClass().getField("methodProfiler").get(world);
Object goalSelector = _cPathfinderGoalSelector.getConstructor(methodProfiler.getClass()).newInstance(methodProfiler);
_fgoalSelector.set(creature, goalSelector);
}
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -272,11 +272,11 @@ public class EntityKit {
* @param invisible
* 是否隐藏
*/
public static void setInvisible(final Entity entity, final boolean invisible) {
final Object ent = ReflectUtil.getHandle(entity);
public static void setInvisible(Entity entity, boolean invisible) {
Object ent = ReflectUtil.getHandle(entity);
try {
ent.getClass().getMethod("setInvisible", boolean.class).invoke(ent, invisible);
} catch (final Exception e) {
} catch (Exception e) {
}
}
@ -288,9 +288,9 @@ public class EntityKit {
* @param silence
* 是否静默
*/
public static void setSilence(final Entity entity, final boolean silence) {
final byte value = (byte) (silence ? 1 : 0);
final WrappedDataWatcher watcher = WrappedDataWatcher.getEntityWatcher(entity);
public static void setSilence(Entity entity, boolean silence) {
byte value = (byte) (silence ? 1 : 0);
WrappedDataWatcher watcher = WrappedDataWatcher.getEntityWatcher(entity);
watcher.setObject(4, value);
}
@ -300,26 +300,26 @@ public class EntityKit {
* @param entity
* @param to
*/
public static void teleportQuietly(final Entity entity, final Location to) {
public static void teleportQuietly(Entity entity, Location to) {
if (!(entity instanceof Player)) {
entity.teleport(to);
} else {
if (entity.getWorld().equals(to.getWorld())) {
final Object playerConnection = MinecraftFields.getPlayerConnection((Player) entity);
Object playerConnection = MinecraftFields.getPlayerConnection((Player) entity);
if (_mPlayerConnection_Teleport == null) {
_mPlayerConnection_Teleport = ReflectUtil.getMethodByNameAndParams(playerConnection.getClass(), "teleport", Location.class);
}
try {
_mPlayerConnection_Teleport.invoke(playerConnection, to);
} catch (final Exception ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
final Object toWorldServer = ReflectUtil.getHandle(to.getWorld());
final Object server = ReflectUtil.getHandle(Bukkit.getServer());
Object toWorldServer = ReflectUtil.getHandle(to.getWorld());
Object server = ReflectUtil.getHandle(Bukkit.getServer());
if (_fWorldServer_dimension == null) {
for (final Field field : ReflectUtil.getFieldByType(toWorldServer.getClass(), Integer.TYPE)) {
final int modifier = field.getModifiers();
for (Field field : ReflectUtil.getFieldByType(toWorldServer.getClass(), Integer.TYPE)) {
int modifier = field.getModifiers();
if (Modifier.isFinal(modifier) && Modifier.isPublic(modifier)) {
_fWorldServer_dimension = field;
}
@ -327,7 +327,7 @@ public class EntityKit {
}
try {
_mPlayerList_MoveToWorld.invoke(server, ReflectUtil.getHandle(entity), (int) _fWorldServer_dimension.get(toWorldServer), true, to, true);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -347,7 +347,7 @@ public class EntityKit {
* @param groundBoost
* 当实体在地上的时候会稍微抬起一些
*/
public static void velocity(final Entity ent, final double speed, final double yAdd, final double yMax, final boolean groundBoost) {
public static void velocity(Entity ent, double speed, double yAdd, double yMax, boolean groundBoost) {
velocity(ent, ent.getLocation().getDirection(), speed, false, 0.0D, yAdd, yMax, groundBoost);
}
@ -370,7 +370,7 @@ public class EntityKit {
* @param groundBoost
* 当实体在地上的时候会稍微抬起一些
*/
public static void velocity(final Entity ent, final Vector vec, final double speed, final boolean ySet, final double yBase, final double yAdd, final double yMax, final boolean groundBoost) {
public static void velocity(Entity ent, Vector vec, double speed, boolean ySet, double yBase, double yAdd, double yMax, boolean groundBoost) {
if ((Double.isNaN(vec.getX())) || (Double.isNaN(vec.getY())) || (Double.isNaN(vec.getZ())) || (vec.length() == 0.0D)) {
return;
}
@ -395,19 +395,19 @@ public class EntityKit {
ent.setVelocity(vec);
}
public static void walkTo(final Entity entity, final Location location) {
public static void walkTo(Entity entity, Location location) {
if (entity == null || location == null) {
return;
}
final Object nmsEntityEntity = ReflectUtil.getHandle(entity);
Object nmsEntityEntity = ReflectUtil.getHandle(entity);
if (!_cEntityInsentient.isInstance(nmsEntityEntity)) {
entity.teleport(location);
return;
}
try {
final Object oFollowerNavigation = _mGetNavigation.invoke(nmsEntityEntity);
Object oFollowerNavigation = _mGetNavigation.invoke(nmsEntityEntity);
final Object path = _mA3.invoke(oFollowerNavigation, location.getX(), location.getY(), location.getZ());
Object path = _mA3.invoke(oFollowerNavigation, location.getX(), location.getY(), location.getZ());
if (path != null) {
_mA2.invoke(oFollowerNavigation, path, 1D);
_mA1.invoke(oFollowerNavigation, 2D);
@ -415,7 +415,7 @@ public class EntityKit {
if (location.distance(entity.getLocation()) > 20) {
entity.teleport(location);
}
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}

View File

@ -1,5 +1,5 @@
/**
* Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com).
* Copyright (c) 2011-2015, James Zhan 詹波 (j@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,8 +40,8 @@ public class HashKit {
* 数字比特
* @return 种子字串
*/
public static String generateSalt(final int numberOfBytes) {
final byte[] salt = new byte[numberOfBytes];
public static String generateSalt(int numberOfBytes) {
byte[] salt = new byte[numberOfBytes];
random.nextBytes(salt);
return toHex(salt);
}
@ -55,20 +55,20 @@ public class HashKit {
* 字符串
* @return 加密后的字符串
*/
public static String hash(final String algorithm, final String srcStr) {
public static String hash(String algorithm, String srcStr) {
try {
final StringBuilder result = new StringBuilder();
final MessageDigest md = MessageDigest.getInstance(algorithm);
final byte[] bytes = md.digest(srcStr.getBytes("utf-8"));
for (final byte b : bytes) {
final String hex = Integer.toHexString(b & 0xFF);
StringBuilder result = new StringBuilder();
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] bytes = md.digest(srcStr.getBytes("utf-8"));
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
result.append("0");
}
result.append(hex);
}
return result.toString();
} catch (final Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@ -80,7 +80,7 @@ public class HashKit {
* 字符串
* @return 加密后的字符串
*/
public static String md5(final String srcStr) {
public static String md5(String srcStr) {
return hash("MD5", srcStr);
}
@ -91,7 +91,7 @@ public class HashKit {
* 字符串
* @return 加密后的字符串
*/
public static String sha1(final String srcStr) {
public static String sha1(String srcStr) {
return hash("SHA-1", srcStr);
}
@ -102,7 +102,7 @@ public class HashKit {
* 字符串
* @return 加密后的字符串
*/
public static String sha256(final String srcStr) {
public static String sha256(String srcStr) {
return hash("SHA-256", srcStr);
}
@ -113,7 +113,7 @@ public class HashKit {
* 字符串
* @return 加密后的字符串
*/
public static String sha384(final String srcStr) {
public static String sha384(String srcStr) {
return hash("SHA-384", srcStr);
}
@ -124,7 +124,7 @@ public class HashKit {
* 字符串
* @return 加密后的字符串
*/
public static String sha512(final String srcStr) {
public static String sha512(String srcStr) {
return hash("SHA-512", srcStr);
}
@ -135,10 +135,10 @@ public class HashKit {
* Byte数组
* @return 字符串
*/
private static String toHex(final byte[] bytes) {
final StringBuilder result = new StringBuilder();
for (final byte b : bytes) {
final String hex = Integer.toHexString(b & 0xFF);
private static String toHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
result.append("0");
}

View File

@ -1,5 +1,5 @@
/**
* Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com).
* Copyright (c) 2011-2015, James Zhan 詹波 (j@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -46,14 +46,14 @@ import javax.net.ssl.X509TrustManager;
*/
public class HttpKit {
private static final String GET = "GET";
private static String GET = "GET";
private static final String POST = "POST";
private static String POST = "POST";
private static final String CHARSET = "UTF-8";
private static String CHARSET = "UTF-8";
private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit.TrustAnyHostnameVerifier();
private static SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
private static TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit.TrustAnyHostnameVerifier();
private HttpKit() {
}
@ -65,7 +65,7 @@ public class HttpKit {
* 网址
* @return 网页HTML
*/
public static String get(final String url) {
public static String get(String url) {
return get(url, null, null);
}
@ -78,7 +78,7 @@ public class HttpKit {
* 查询参数
* @return 网页HTML
*/
public static String get(final String url, final Map<String, String> queryParas) {
public static String get(String url, Map<String, String> queryParas) {
return get(url, queryParas, null);
}
@ -93,13 +93,13 @@ public class HttpKit {
* 头信息
* @return 网页HTML
*/
public static String get(final String url, final Map<String, String> queryParas, final Map<String, String> headers) {
public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) {
HttpURLConnection conn = null;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers);
conn.connect();
return readResponseString(conn);
} catch (final Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
@ -119,7 +119,7 @@ public class HttpKit {
* 数据
* @return 网页HTML
*/
public static String post(final String url, final Map<String, String> queryParas, final String data) {
public static String post(String url, Map<String, String> queryParas, String data) {
return post(url, queryParas, data, null);
}
@ -136,19 +136,19 @@ public class HttpKit {
* 头信息
* @return 网页HTML
*/
public static String post(final String url, final Map<String, String> queryParas, final String data, final Map<String, String> headers) {
public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
HttpURLConnection conn = null;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
conn.connect();
final OutputStream out = conn.getOutputStream();
OutputStream out = conn.getOutputStream();
out.write(data.getBytes(CHARSET));
out.flush();
out.close();
return readResponseString(conn);
} catch (final Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
@ -166,7 +166,7 @@ public class HttpKit {
* 查询参数
* @return 网页HTML
*/
public static String post(final String url, final String data) {
public static String post(String url, String data) {
return post(url, null, data, null);
}
@ -181,7 +181,7 @@ public class HttpKit {
* 头信息
* @return 网页HTML
*/
public static String post(final String url, final String data, final Map<String, String> headers) {
public static String post(String url, String data, Map<String, String> headers) {
return post(url, null, data, headers);
}
@ -194,12 +194,12 @@ public class HttpKit {
* 参数
* @return 构建后的地址
*/
private static String buildUrlWithQueryString(final String url, final Map<String, String> queryParas) {
private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
if (queryParas == null || queryParas.isEmpty()) {
return url;
}
final StringBuilder sb = new StringBuilder(url);
StringBuilder sb = new StringBuilder(url);
boolean isFirst;
if (url.indexOf("?") == -1) {
isFirst = true;
@ -208,19 +208,19 @@ public class HttpKit {
isFirst = false;
}
for (final Entry<String, String> entry : queryParas.entrySet()) {
for (Entry<String, String> entry : queryParas.entrySet()) {
if (isFirst) {
isFirst = false;
} else {
sb.append("&");
}
final String key = entry.getKey();
String key = entry.getKey();
String value = entry.getValue();
if (StrKit.notBlank(value)) {
try {
value = URLEncoder.encode(value, CHARSET);
} catch (final UnsupportedEncodingException e) {
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@ -244,9 +244,9 @@ public class HttpKit {
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
private static HttpURLConnection getHttpConnection(final String url, final String method, final Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
final URL _url = new URL(url);
final HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
URL _url = new URL(url);
HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
@ -263,7 +263,7 @@ public class HttpKit {
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (headers != null && !headers.isEmpty()) {
for (final Entry<String, String> entry : headers.entrySet()) {
for (Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
@ -278,11 +278,11 @@ public class HttpKit {
*/
private static SSLSocketFactory initSSLSocketFactory() {
try {
final TrustManager[] tm = { new HttpKit.TrustAnyTrustManager() };
final SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
TrustManager[] tm = { new HttpKit.TrustAnyTrustManager() };
SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
return sslContext.getSocketFactory();
} catch (final Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@ -294,24 +294,24 @@ public class HttpKit {
* HTTP连接
* @return 字符串
*/
private static String readResponseString(final HttpURLConnection conn) {
final StringBuilder sb = new StringBuilder();
private static String readResponseString(HttpURLConnection conn) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
try {
inputStream = conn.getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (final Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (final IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
@ -326,7 +326,7 @@ public class HttpKit {
*/
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(final String hostname, final SSLSession session) {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
@ -339,11 +339,11 @@ public class HttpKit {
*/
private static class TrustAnyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override

View File

@ -17,7 +17,7 @@ import pw.yumc.YumCore.bukkit.P;
* @author
*/
public class PKit {
private static final Map<ClassLoader, Plugin> pluginMap = new HashMap<>();
private static Map<ClassLoader, Plugin> pluginMap = new HashMap<>();
/**
* 关闭插件
@ -32,7 +32,7 @@ public class PKit {
* @param msg
* 关闭提示
*/
public static void disable(final String msg) {
public static void disable(String msg) {
Log.warning(msg);
disable();
}
@ -53,15 +53,15 @@ public class PKit {
* 堆栈
* @return 操作插件
*/
public static Plugin getOperatePlugin(final StackTraceElement[] stacktrace) {
public static Plugin getOperatePlugin(StackTraceElement[] stacktrace) {
collectPlugin();
for (final StackTraceElement element : stacktrace) {
for (StackTraceElement element : stacktrace) {
try {
final ClassLoader loader = Class.forName(element.getClassName(), false, PKit.class.getClassLoader()).getClassLoader();
ClassLoader loader = Class.forName(element.getClassName(), false, PKit.class.getClassLoader()).getClassLoader();
if (pluginMap.containsKey(loader)) {
return pluginMap.get(loader);
}
} catch (final ClassNotFoundException ex) {
} catch (ClassNotFoundException ex) {
}
}
return null;
@ -74,7 +74,7 @@ public class PKit {
* 任务
* @return Bukkit 任务 {@link BukkitTask}
*/
public static BukkitTask runTask(final Runnable run) {
public static BukkitTask runTask(Runnable run) {
return Bukkit.getScheduler().runTask(P.instance, run);
}
@ -85,7 +85,7 @@ public class PKit {
* 任务
* @return Bukkit 任务 {@link BukkitTask}
*/
public static BukkitTask runTaskAsync(final Runnable run) {
public static BukkitTask runTaskAsync(Runnable run) {
return Bukkit.getScheduler().runTaskAsynchronously(P.instance, run);
}
@ -98,7 +98,7 @@ public class PKit {
* 延时多久
* @return Bukkit 任务 {@link BukkitTask}
*/
public static BukkitTask runTaskLater(final Runnable run, final long delay) {
public static BukkitTask runTaskLater(Runnable run, long delay) {
return Bukkit.getScheduler().runTaskLater(P.instance, run, delay);
}
@ -111,7 +111,7 @@ public class PKit {
* 延时多久
* @return Bukkit 任务 {@link BukkitTask}
*/
public static BukkitTask runTaskLaterAsync(final Runnable run, final long delay) {
public static BukkitTask runTaskLaterAsync(Runnable run, long delay) {
return Bukkit.getScheduler().runTaskLaterAsynchronously(P.instance, run, delay);
}
@ -126,7 +126,7 @@ public class PKit {
* 任务间隔
* @return Bukkit 任务 {@link BukkitTask}
*/
public static BukkitTask runTaskTimer(final Runnable run, final long delay, final long timer) {
public static BukkitTask runTaskTimer(Runnable run, long delay, long timer) {
return Bukkit.getScheduler().runTaskTimer(P.instance, run, delay, timer);
}
@ -141,7 +141,7 @@ public class PKit {
* 任务间隔
* @return Bukkit 任务 {@link BukkitTask}
*/
public static BukkitTask runTaskTimerAsync(final Runnable run, final long delay, final long timer) {
public static BukkitTask runTaskTimerAsync(Runnable run, long delay, long timer) {
return Bukkit.getScheduler().runTaskTimerAsynchronously(P.instance, run, delay, timer);
}
@ -152,7 +152,7 @@ public class PKit {
* 任务
* @return 任务ID
*/
public static int scheduleTask(final Runnable run) {
public static int scheduleTask(Runnable run) {
return Bukkit.getScheduler().scheduleSyncDelayedTask(P.instance, run);
}
@ -167,7 +167,7 @@ public class PKit {
* 执行间隔
* @return 任务ID
*/
public static int scheduleTask(final Runnable run, final long delay, final long timer) {
public static int scheduleTask(Runnable run, long delay, long timer) {
return Bukkit.getScheduler().scheduleSyncRepeatingTask(P.instance, run, delay, timer);
}
@ -177,7 +177,7 @@ public class PKit {
private static void collectPlugin() {
if (Bukkit.getPluginManager().getPlugins().length != pluginMap.keySet().size() - 1) {
pluginMap.clear();
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
pluginMap.put(plugin.getClass().getClassLoader(), plugin);
}
pluginMap.remove(PKit.class.getClassLoader());

View File

@ -12,7 +12,7 @@ import org.bukkit.ChatColor;
* @since 2016年9月14日 上午1:02:23
*/
public class StrKit {
private static final String EMPTY = "";
private static String EMPTY = "";
private StrKit() {
}
@ -22,7 +22,7 @@ public class StrKit {
* 源字串
* @return 颜色转化后的字串
*/
public static String color(final String string) {
public static String color(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
}
@ -35,7 +35,7 @@ public class StrKit {
* 数组开始位置
* @return 转移后的数组字符串
*/
public static String consolidateStrings(final String[] args, final int start) {
public static String consolidateStrings(String[] args, int start) {
String ret = args[start];
if (args.length > start + 1) {
for (int i = start + 1; i < args.length; i++) {
@ -69,12 +69,12 @@ public class StrKit {
* if originals contains a null element.
* <b>Note: the collection may be modified before this is thrown</b>
*/
public static <T extends Collection<? super String>> T copyPartialMatches(final String token, final Iterable<String> originals, final T collection) throws UnsupportedOperationException, IllegalArgumentException {
public static <T extends Collection<? super String>> T copyPartialMatches(String token, Iterable<String> originals, T collection) throws UnsupportedOperationException, IllegalArgumentException {
Validate.notNull(token, "Search token cannot be null");
Validate.notNull(collection, "Collection cannot be null");
Validate.notNull(originals, "Originals cannot be null");
for (final String string : originals) {
for (String string : originals) {
if (startsWithIgnoreCase(string, token)) {
collection.add(string);
}
@ -88,7 +88,7 @@ public class StrKit {
* 字串
* @return 是否为空字串
*/
public static boolean isBlank(final String str) {
public static boolean isBlank(String str) {
return str == null || str.isEmpty();
}
@ -99,7 +99,7 @@ public class StrKit {
* 数组
* @return 字符串
*/
public static String join(final Object[] arr) {
public static String join(Object[] arr) {
return join(arr, EMPTY);
}
@ -112,9 +112,9 @@ public class StrKit {
* 分割符
* @return 字符串
*/
public static String join(final Object[] arr, final String split) {
final StringBuffer str = new StringBuffer();
for (final Object s : arr) {
public static String join(Object[] arr, String split) {
StringBuffer str = new StringBuffer();
for (Object s : arr) {
str.append(s.toString());
str.append(split);
}
@ -126,7 +126,7 @@ public class StrKit {
* 字串
* @return 是否不为空字串
*/
public static boolean notBlank(final String str) {
public static boolean notBlank(String str) {
return str != null && !str.isEmpty();
}
@ -146,7 +146,7 @@ public class StrKit {
* @throws IllegalArgumentException
* if string is null
*/
public static boolean startsWithIgnoreCase(final String string, final String prefix) throws IllegalArgumentException, NullPointerException {
public static boolean startsWithIgnoreCase(String string, String prefix) throws IllegalArgumentException, NullPointerException {
Validate.notNull(string, "Cannot check a null string for a match");
if (string.length() < prefix.length()) {
return false;
@ -200,7 +200,7 @@ public class StrKit {
* @return substring from start position to end positon,
* <code>null</code> if null String input
*/
public static String substring(final String str, int start, int end) {
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}

View File

@ -23,7 +23,7 @@ public class ZipKit {
* 名称
* @return
*/
public static String getRealName(final String name) {
public static String getRealName(String name) {
return new File(name).getName();
}
@ -37,7 +37,7 @@ public class ZipKit {
* @throws IOException
* IO异常
*/
public static void unzip(final File zipFile, final File destPath) throws ZipException, IOException {
public static void unzip(File zipFile, File destPath) throws ZipException, IOException {
unzip(zipFile, destPath, null);
}
@ -53,12 +53,12 @@ public class ZipKit {
* @throws IOException
* IO异常
*/
public static void unzip(final File zipFile, final File destPath, final String ext) throws ZipException, IOException {
final ZipFile zipObj = new ZipFile(zipFile);
final Enumeration<? extends ZipEntry> e = zipObj.entries();
public static void unzip(File zipFile, File destPath, String ext) throws ZipException, IOException {
ZipFile zipObj = new ZipFile(zipFile);
Enumeration<? extends ZipEntry> e = zipObj.entries();
while (e.hasMoreElements()) {
final ZipEntry entry = e.nextElement();
final File destinationFilePath = new File(destPath, getRealName(entry.getName()));
ZipEntry entry = e.nextElement();
File destinationFilePath = new File(destPath, getRealName(entry.getName()));
if (entry.isDirectory() || (ext != null && !destinationFilePath.getName().endsWith(ext))) {
continue;
}

View File

@ -24,7 +24,7 @@ public class MailAPI {
* 内容
* @return 是否发送成功
*/
public static boolean send(final HostAndPort smtp, final String from, final String to, final String subject, final String content) {
public static boolean send(HostAndPort smtp, String from, String to, String subject, String content) {
return send(smtp, from, to, subject, content, null, null);
}
@ -47,7 +47,7 @@ public class MailAPI {
* 密码
* @return 是否发送成功
*/
public static boolean send(final HostAndPort smtp, final String from, final String to, final String subject, final String content, final String username, final String password) {
public static boolean send(HostAndPort smtp, String from, String to, String subject, String content, String username, String password) {
return send(smtp, from, null, to, subject, content, username, password);
}
@ -72,7 +72,7 @@ public class MailAPI {
* 密码
* @return 是否发送成功
*/
public static boolean send(final HostAndPort smtp, final String from, final String fromName, final String to, final String subject, final String content, final String username, final String password) {
public static boolean send(HostAndPort smtp, String from, String fromName, String to, String subject, String content, String username, String password) {
return send(smtp, from, fromName, to, null, subject, content, username, password);
}
@ -99,7 +99,7 @@ public class MailAPI {
* 密码
* @return 是否发送成功
*/
public static boolean send(final HostAndPort smtp, final String from, final String fromName, final String to, final String copyto, final String subject, final String content, final String username, final String password) {
public static boolean send(HostAndPort smtp, String from, String fromName, String to, String copyto, String subject, String content, String username, String password) {
return send(smtp, from, fromName, to, copyto, subject, content, null, username, password);
}
@ -128,7 +128,7 @@ public class MailAPI {
* 密码
* @return 是否发送成功
*/
public static boolean send(final HostAndPort smtp, final String from, final String fromName, final String to, final String copyto, final String subject, final String content, final String[] filename, final String username, final String password) {
public static boolean send(HostAndPort smtp, String from, String fromName, String to, String copyto, String subject, String content, String[] filename, String username, String password) {
return XMail.send(smtp, from, fromName, to, copyto, subject, content, filename, username, password, true);
}
}

View File

@ -28,16 +28,16 @@ public class MailAuthenticator extends Authenticator {
* @param password
* 密码
*/
public MailAuthenticator(final String username, final String password) {
public MailAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
public void setPassword(final String password) {
public void setPassword(String password) {
this.password = password;
}
public void setUsername(final String username) {
public void setUsername(String username) {
this.username = username;
}

View File

@ -13,7 +13,7 @@ class SimpleMail {
private String from = null;
private Address sender;
public SimpleMail(final String subject, final Object content) {
public SimpleMail(String subject, Object content) {
this.subject = subject;
this.content = content;
}
@ -53,19 +53,19 @@ class SimpleMail {
*
* @param content
*/
public void setContent(final Object content) {
public void setContent(Object content) {
this.content = content;
}
public void setFrom(final String from) {
public void setFrom(String from) {
this.from = from;
}
public void setSender(final Address sender) {
public void setSender(Address sender) {
this.sender = sender;
}
public void setSentDate(final Date date) {
public void setSentDate(Date date) {
this.sentDate = date;
}
@ -74,7 +74,7 @@ class SimpleMail {
*
* @param subject
*/
public void setSubject(final String subject) {
public void setSubject(String subject) {
this.subject = subject;
}

View File

@ -20,7 +20,7 @@ public class SimpleMailSender {
/**
* 发送邮件的props文件
*/
private final transient Properties props = System.getProperties();
private transient Properties props = System.getProperties();
/**
* 邮件服务器登录验证
@ -40,9 +40,9 @@ public class SimpleMailSender {
* @param password
* 发送邮件的密码
*/
public SimpleMailSender(final String username, final String password) {
public SimpleMailSender(String username, String password) {
// 通过邮箱地址解析出smtp服务器对大多数邮箱都管用
final String smtpHostName = "smtp." + username.split("@")[1];
String smtpHostName = "smtp." + username.split("@")[1];
init(smtpHostName, username, password);
}
@ -56,7 +56,7 @@ public class SimpleMailSender {
* @param password
* 发送邮件的密码
*/
public SimpleMailSender(final String smtpHostName, final String username, final String password) {
public SimpleMailSender(String smtpHostName, String username, String password) {
init(username, password, smtpHostName);
}
@ -70,9 +70,9 @@ public class SimpleMailSender {
* @throws AddressException
* @throws MessagingException
*/
public void send(final SimpleMail mail, final String... recipients) throws AddressException, MessagingException {
public void send(SimpleMail mail, String... recipients) throws AddressException, MessagingException {
// 创建mime类型邮件
final MimeMessage message = new MimeMessage(session);
MimeMessage message = new MimeMessage(session);
// 设置发信人
if (mail.getFrom() != null) {
message.setFrom(new InternetAddress(mail.getFrom()));
@ -80,8 +80,8 @@ public class SimpleMailSender {
message.setFrom(new InternetAddress(authenticator.getUsername()));
}
// 设置收件人们
final int num = recipients.length;
final InternetAddress[] addresses = new InternetAddress[num];
int num = recipients.length;
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
addresses[i] = new InternetAddress(recipients[i]);
}
@ -112,7 +112,7 @@ public class SimpleMailSender {
* @throws AddressException
* @throws MessagingException
*/
public void send(final String subject, final Object content, final String... recipients) throws AddressException, MessagingException {
public void send(String subject, Object content, String... recipients) throws AddressException, MessagingException {
this.send(new SimpleMail(subject, content), recipients);
}
@ -126,7 +126,7 @@ public class SimpleMailSender {
* @param smtpHostName
* SMTP主机地址
*/
private void init(final String smtpHostName, final String username, final String password) {
private void init(String smtpHostName, String username, String password) {
// 初始化props
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHostName);

View File

@ -26,8 +26,8 @@ public class XMail {
private static boolean autoRegister = true;
private static final HashMap<String, DataContentHandler> handlers = new HashMap<>();
private static final DataContentHandlerFactory defaultDataContentHandlerFactory;
private static HashMap<String, DataContentHandler> handlers = new HashMap<>();
private static DataContentHandlerFactory defaultDataContentHandlerFactory;
static {
// todo
// activation.jar
@ -43,8 +43,8 @@ public class XMail {
handlers.put("image/jpeg", new com.sun.mail.handlers.image_jpeg());
defaultDataContentHandlerFactory = new DataContentHandlerFactory() {
@Override
public DataContentHandler createDataContentHandler(final String type) {
final DataContentHandler handler = handlers.get(type);
public DataContentHandler createDataContentHandler(String type) {
DataContentHandler handler = handlers.get(type);
if (handler != null) {
return handler;
}
@ -54,7 +54,7 @@ public class XMail {
};
}
public static void addDataContentHandler(final String type, final DataContentHandler handler) {
public static void addDataContentHandler(String type, DataContentHandler handler) {
handlers.put(type, handler);
}
@ -66,7 +66,7 @@ public class XMail {
try {
DataHandler.setDataContentHandlerFactory(defaultDataContentHandlerFactory);
return true;
} catch (final Exception e) {
} catch (Exception e) {
}
return false;
}
@ -98,19 +98,19 @@ public class XMail {
* 是否需要验证
* @return 是否发送成功
*/
public static boolean send(final HostAndPort smtp, final String from, String fromName, final String to, final String copyto, final String subject, final String content, final String[] filename, final String username, final String password, final boolean needAuth) {
public static boolean send(HostAndPort smtp, String from, String fromName, String to, String copyto, String subject, String content, String[] filename, final String username, final String password, boolean needAuth) {
try {
if (isAutoRegister()) {
unregisterDefaultDataContentHandlerFactory();
registerDefaultDataContentHandlerFactory();
}
final Properties props = new Properties();
Properties props = new Properties();
props.put("mail.smtp.host", smtp.getHostText());
props.put("mail.smtp.port", smtp.getPort());
props.put("mail.smtp.socketFactory.port", smtp.getPort());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", needAuth);
final Session mailSession = Session.getInstance(props, new Authenticator() {
Session mailSession = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
@ -120,31 +120,31 @@ public class XMail {
if (fromName == null) {
fromName = from;
}
final MimeMessage mimeMsg = new MimeMessage(mailSession);
MimeMessage mimeMsg = new MimeMessage(mailSession);
mimeMsg.setSubject(subject);
final MimeMultipart mp = new MimeMultipart();
MimeMultipart mp = new MimeMultipart();
if (content != null) {
try {
final BodyPart bp = new MimeBodyPart();
BodyPart bp = new MimeBodyPart();
bp.setContent("" + content, "text/html;charset=GBK");
mp.addBodyPart(bp);
} catch (final Exception e) {
} catch (Exception e) {
System.err.println("设置邮件正文时发生错误!" + e);
return false;
}
}
if (filename != null) {
for (final String file : filename) {
for (String file : filename) {
try {
final BodyPart bp = new MimeBodyPart();
final FileDataSource fileds = new FileDataSource(file);
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(file);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
} catch (final Exception e) {
} catch (Exception e) {
System.err.println("增加邮件附件:" + file + "发生错误!" + e);
}
}
@ -156,10 +156,10 @@ public class XMail {
// 设置发信人
try {
mimeMsg.setFrom(new InternetAddress(from, fromName));
} catch (final Exception e) {
} catch (Exception e) {
mimeMsg.setFrom(new InternetAddress(from));
}
} catch (final Exception e) {
} catch (Exception e) {
System.err.println("设置发信人发生错误!");
e.printStackTrace();
return false;
@ -167,7 +167,7 @@ public class XMail {
try {
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
} catch (final Exception e) {
} catch (Exception e) {
System.err.println("设置接收人发生错误!");
e.printStackTrace();
return false;
@ -178,10 +178,10 @@ public class XMail {
// 设置抄送人
try {
mimeMsg.setFrom(new InternetAddress(from, fromName));
} catch (final Exception e) {
} catch (Exception e) {
mimeMsg.setFrom(new InternetAddress(from));
}
} catch (final Exception e) {
} catch (Exception e) {
System.err.println("设置抄送人发生错误!");
e.printStackTrace();
}
@ -194,7 +194,7 @@ public class XMail {
Transport.send(mimeMsg);
return true;
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isAutoRegister()) {
@ -204,18 +204,18 @@ public class XMail {
return false;
}
public static void setAutoRegister(final boolean autoRegister) {
public static void setAutoRegister(boolean autoRegister) {
XMail.autoRegister = autoRegister;
}
public static Object unregisterDefaultDataContentHandlerFactory() {
try {
final Field field = DataHandler.class.getDeclaredField("factory");
Field field = DataHandler.class.getDeclaredField("factory");
field.setAccessible(true);
final Object object = field.get(null);
Object object = field.get(null);
field.set(null, null);
return object;
} catch (final Exception e) {
} catch (Exception e) {
}
return null;
}

View File

@ -14,11 +14,11 @@ import java.util.List;
* @author
*/
public class PasteContent {
private final static String errN = "异常名称: %s";
private final static String errM = "异常说明: %s";
private final static String errInfo = "简易错误信息如下:";
private final static String errStackTrace = " 位于 %s.%s(%s:%s)";
private final List<String> TEXT = new ArrayList<>();
private static String errN = "异常名称: %s";
private static String errM = "异常说明: %s";
private static String errInfo = "简易错误信息如下:";
private static String errStackTrace = " 位于 %s.%s(%s:%s)";
private List<String> TEXT = new ArrayList<>();
/**
* 添加文件
@ -28,7 +28,7 @@ public class PasteContent {
* @throws IOException
* IO异常
*/
public void addFile(final File file) throws IOException {
public void addFile(File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException("文件不得为Null!");
}
@ -41,7 +41,7 @@ public class PasteContent {
* @param str
*
*/
public void addLine(final String str) {
public void addLine(String str) {
this.TEXT.add(str);
}
@ -51,7 +51,7 @@ public class PasteContent {
* @param str
*
*/
public void addLines(final List<String> str) {
public void addLines(List<String> str) {
this.TEXT.addAll(str);
}
@ -61,7 +61,7 @@ public class PasteContent {
* @param e
* 异常
*/
public void addThrowable(final Throwable e) {
public void addThrowable(Throwable e) {
Throwable temp = e;
while (temp.getCause() != null) {
temp = temp.getCause();
@ -69,15 +69,15 @@ public class PasteContent {
TEXT.add(String.format(errN, e.getClass().getName()));
TEXT.add(String.format(errM, e.getMessage()));
TEXT.add(errInfo);
for (final StackTraceElement ste : e.getStackTrace()) {
for (StackTraceElement ste : e.getStackTrace()) {
TEXT.add(String.format(errStackTrace, ste.getClassName(), ste.getMethodName(), ste.getFileName(), ste.getLineNumber() < 0 ? "未知" : ste.getLineNumber()));
}
}
@Override
public String toString() {
final StringBuilder text = new StringBuilder();
for (final String str : TEXT) {
StringBuilder text = new StringBuilder();
for (String str : TEXT) {
text.append(str + '\n');
}
return text.toString();

View File

@ -14,7 +14,7 @@ public enum PasteFormat {
String format;
private PasteFormat(final String format) {
private PasteFormat(String format) {
this.format = format;
}

View File

@ -5,39 +5,40 @@ import java.net.HttpURLConnection;
import java.net.URL;
public class PasteXcode {
private final static String POST_URL = "http://paste.xcode.ro/";
private static String POST_URL = "http://paste.xcode.ro/";
public static void main(final String[] args) {
final PasteXcode p = new PasteXcode();
final PasteContent paste = new PasteContent();
public static void main(String[] args) {
PasteXcode p = new PasteXcode();
PasteContent paste = new PasteContent();
paste.addLine("异常提交测试!");
paste.addThrowable(new Throwable());
System.out.println(p.post(paste));;
System.out.println(p.post(paste));
;
}
public String post(final PasteContent content) {
public String post(PasteContent content) {
return post("YumCore", PasteFormat.JAVA, content);
}
public String post(final String name, final PasteFormat format, final PasteContent content) {
public String post(String name, PasteFormat format, PasteContent content) {
String result = "Failed to post!";
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(POST_URL).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(POST_URL).openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setInstanceFollowRedirects(false);
connection.setDoOutput(true);
final OutputStream outputStream = connection.getOutputStream();
final byte[] outByte = String.format("paste_user=%s&paste_lang=%s&paste_data=%s&paste_submit=Paste&paste_expire=0", name, format.toString(), content.toString()).getBytes();
OutputStream outputStream = connection.getOutputStream();
byte[] outByte = String.format("paste_user=%s&paste_lang=%s&paste_data=%s&paste_submit=Paste&paste_expire=0", name, format.toString(), content.toString()).getBytes();
outputStream.write(outByte);
outputStream.flush();
outputStream.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
result = connection.getHeaderField("Location");
}
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
return result;

View File

@ -8,41 +8,42 @@ import java.net.URL;
import java.net.URLEncoder;
public class Pastebin {
private final static String POST_URL = "http://pastebin.com/api/api_post.php";
private final String API_KEY;
private static String POST_URL = "http://pastebin.com/api/api_post.php";
private String API_KEY;
public Pastebin() {
this.API_KEY = "0e7d92011945cbcc1e884ab6e3e75e69";
}
public Pastebin(final String API_KEY) {
public Pastebin(String API_KEY) {
this.API_KEY = API_KEY;
}
public static void main(final String[] args) {
final Pastebin p = new Pastebin();
final PasteContent paste = new PasteContent();
public static void main(String[] args) {
Pastebin p = new Pastebin();
PasteContent paste = new PasteContent();
paste.addLine("异常提交测试!");
paste.addThrowable(new Throwable());
System.out.println(p.post(paste));;
System.out.println(p.post(paste));
;
}
public String post(final PasteContent content) {
public String post(PasteContent content) {
return post("", PasteFormat.JAVA, Pastebin.Private.UNLISTED, content);
}
public String post(final String name, final PasteFormat format, final Pastebin.Private level, final PasteContent content) {
public String post(String name, PasteFormat format, Pastebin.Private level, PasteContent content) {
String result = "Failed to post!";
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(POST_URL).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(POST_URL).openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setInstanceFollowRedirects(false);
connection.setDoOutput(true);
final OutputStream outputStream = connection.getOutputStream();
final byte[] outByte = ("api_option=paste&api_dev_key="
OutputStream outputStream = connection.getOutputStream();
byte[] outByte = ("api_option=paste&api_dev_key="
+ URLEncoder.encode(this.API_KEY, "utf-8")
+ "&api_paste_code="
+ URLEncoder.encode(content.toString(), "utf-8")
@ -59,8 +60,8 @@ public class Pastebin {
outputStream.write(outByte);
outputStream.flush();
outputStream.close();
final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final StringBuffer request = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer request = new StringBuffer();
String temp;
while ((temp = br.readLine()) != null) {
request.append(temp);
@ -71,7 +72,7 @@ public class Pastebin {
if (!result.contains("http://")) {
result = "Failed to post! (returned result: " + result;
}
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
return result;
@ -84,7 +85,7 @@ public class Pastebin {
int level;
private Private(final int level) {
private Private(int level) {
this.level = level;
}

View File

@ -16,13 +16,13 @@ import org.json.simple.JSONValue;
* @author
*/
public class StickyNotes {
private final static String DOMAIN = "http://paste.yumc.pw";
private final static String POST_URL = DOMAIN + "/api/json/create";
private final static String VIEW_URL = DOMAIN + "/%s/%s";
private static String DOMAIN = "http://paste.yumc.pw";
private static String POST_URL = DOMAIN + "/api/json/create";
private static String VIEW_URL = DOMAIN + "/%s/%s";
public static void main(final String[] args) {
final StickyNotes p = new StickyNotes();
final PasteContent paste = new PasteContent();
public static void main(String[] args) {
StickyNotes p = new StickyNotes();
PasteContent paste = new PasteContent();
paste.addLine("异常提交测试!");
paste.addThrowable(new Throwable());
System.out.println(p.post(StickyNotes.Expire.HalfHour, paste));
@ -35,7 +35,7 @@ public class StickyNotes {
* 内容
* @return 地址
*/
public String post(final PasteContent content) {
public String post(PasteContent content) {
return post("YumCore-" + System.currentTimeMillis(), PasteFormat.JAVA, StickyNotes.Expire.Never, content);
}
@ -48,7 +48,7 @@ public class StickyNotes {
* 内容
* @return 地址
*/
public String post(final StickyNotes.Expire expire, final PasteContent content) {
public String post(StickyNotes.Expire expire, PasteContent content) {
return post("YumCore-" + System.currentTimeMillis(), PasteFormat.JAVA, expire, content);
}
@ -65,7 +65,7 @@ public class StickyNotes {
* 内容
* @return 地址
*/
public String post(final String title, final PasteFormat format, final StickyNotes.Expire expire, final PasteContent content) {
public String post(String title, PasteFormat format, StickyNotes.Expire expire, PasteContent content) {
return post(title, format.toString(), expire.getExpire(), content.toString());
}
@ -82,23 +82,23 @@ public class StickyNotes {
* 内容
* @return 地址
*/
public String post(final String title, final String format, final int expire, final String content) {
public String post(String title, String format, int expire, String content) {
String result = "Failed to post!";
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(POST_URL).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(POST_URL).openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setInstanceFollowRedirects(false);
connection.setDoOutput(true);
final OutputStream outputStream = connection.getOutputStream();
final byte[] outByte = String.format("title=%s&language=%s&expire=%s&data=%s", title, format, expire, content).getBytes();
OutputStream outputStream = connection.getOutputStream();
byte[] outByte = String.format("title=%s&language=%s&expire=%s&data=%s", title, format, expire, content).getBytes();
outputStream.write(outByte);
outputStream.flush();
outputStream.close();
final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final StringBuilder request = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder request = new StringBuilder();
String temp;
while ((temp = br.readLine()) != null) {
request.append(temp);
@ -111,7 +111,7 @@ public class StickyNotes {
return object.get("error").toString();
}
return String.format(VIEW_URL, object.get("id"), object.get("hash"));
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
return result;
@ -134,7 +134,7 @@ public class StickyNotes {
int expire;
private Expire(final int expire) {
private Expire(int expire) {
this.expire = expire;
}

View File

@ -38,7 +38,7 @@ public class SignKit extends ProtocolLibBase {
static {
try {
GameMode.SPECTATOR.name();
} catch (final Exception e) {
} catch (Exception e) {
newVer = false;
}
}
@ -52,9 +52,9 @@ public class SignKit extends ProtocolLibBase {
* 木牌内容
* @throws InvocationTargetException
*/
public static void open(final Player player, final String[] lines) throws InvocationTargetException {
final Location loc = player.getLocation();
final int x = loc.getBlockX(), y = 0, z = loc.getBlockZ();
public static void open(Player player, String[] lines) throws InvocationTargetException {
Location loc = player.getLocation();
int x = loc.getBlockX(), y = 0, z = loc.getBlockZ();
if (newVer) {
// Set
PacketContainer packet = manager.createPacket(Server.BLOCK_CHANGE);
@ -66,7 +66,8 @@ public class SignKit extends ProtocolLibBase {
packet = manager.createPacket(Server.UPDATE_SIGN);
packet.getBlockPositionModifier().write(0, new BlockPosition(x, y, z));
packet.getChatComponentArrays().write(0,
new WrappedChatComponent[] { WrappedChatComponent.fromText(lines[0]), WrappedChatComponent.fromText(lines[1]), WrappedChatComponent.fromText(lines[2]), WrappedChatComponent.fromText(lines[3]) });
new WrappedChatComponent[] { WrappedChatComponent.fromText(lines[0]), WrappedChatComponent.fromText(lines[1]), WrappedChatComponent.fromText(lines[2]),
WrappedChatComponent.fromText(lines[3]) });
manager.sendServerPacket(player, packet);
@ -108,12 +109,12 @@ public class SignKit extends ProtocolLibBase {
* @author
*/
public static class SignUpdateEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Player player;
private final String[] lines;
private static HandlerList handlers = new HandlerList();
private Player player;
private String[] lines;
private boolean cancel = false;
public SignUpdateEvent(final Player player, final String[] lines) {
public SignUpdateEvent(Player player, String[] lines) {
this.player = player;
this.lines = lines;
}
@ -157,7 +158,7 @@ public class SignKit extends ProtocolLibBase {
* @see org.bukkit.event.Cancellable#setCancelled(boolean)
*/
@Override
public void setCancelled(final boolean cancel) {
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
@ -176,25 +177,25 @@ public class SignKit extends ProtocolLibBase {
}
@Override
public void onPacketReceiving(final PacketEvent event) {
final Player player = event.getPlayer();
final PacketContainer packet = event.getPacket();
final List<String> lines = new ArrayList<>();
public void onPacketReceiving(PacketEvent event) {
Player player = event.getPlayer();
PacketContainer packet = event.getPacket();
List<String> lines = new ArrayList<>();
if (newVer) {
final WrappedChatComponent[] input1_8 = packet.getChatComponentArrays().read(0);
for (final WrappedChatComponent wrappedChatComponent : input1_8) {
WrappedChatComponent[] input1_8 = packet.getChatComponentArrays().read(0);
for (WrappedChatComponent wrappedChatComponent : input1_8) {
lines.add(subString(wrappedChatComponent.getJson()));
}
} else {
final String[] input = packet.getStringArrays().getValues().get(0);
String[] input = packet.getStringArrays().getValues().get(0);
lines.addAll(Arrays.asList(input));
}
final SignUpdateEvent sue = new SignUpdateEvent(player, lines.toArray(new String[0]));
SignUpdateEvent sue = new SignUpdateEvent(player, lines.toArray(new String[0]));
Bukkit.getPluginManager().callEvent(sue);
event.setCancelled(sue.isCancelled());
}
private String subString(final String string) {
private String subString(String string) {
return string.substring(1, string.length() - 1);
}
}

View File

@ -18,7 +18,7 @@ public class VaultChat extends VaultBase {
private static Chat chat;
static {
final RegisteredServiceProvider<Chat> rsp = Bukkit.getServer().getServicesManager().getRegistration(Chat.class);
RegisteredServiceProvider<Chat> rsp = Bukkit.getServer().getServicesManager().getRegistration(Chat.class);
if (rsp == null || (chat = rsp.getProvider()) == null) {
PKit.disable("已加载 Vault 但是未找到聊天相关插件 停止加载...");
} else {
@ -42,7 +42,7 @@ public class VaultChat extends VaultBase {
* 玩家实体
* @return 玩家称号
*/
public static String getPlayerPrefix(final Player player) {
public static String getPlayerPrefix(Player player) {
return chat.getPlayerPrefix(player);
}
@ -54,7 +54,7 @@ public class VaultChat extends VaultBase {
* @param prefix
* 玩家称号
*/
public static void setPlayerPrefix(final Player player, final String prefix) {
public static void setPlayerPrefix(Player player, String prefix) {
chat.setPlayerPrefix(player, prefix);
}
}

View File

@ -19,7 +19,7 @@ public class VaultEconomy extends VaultBase {
private static Economy economy;
static {
final RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null || (economy = rsp.getProvider()) == null) {
PKit.disable("已加载 Vault 但是未找到经济相关插件 停止加载...");
} else {
@ -36,7 +36,7 @@ public class VaultEconomy extends VaultBase {
* 数量
* @return {@link EconomyResponse}
*/
public static EconomyResponse add(final OfflinePlayer oPlayer, final double amont) {
public static EconomyResponse add(OfflinePlayer oPlayer, double amont) {
return economy.depositPlayer(oPlayer, amont);
}
@ -58,7 +58,7 @@ public class VaultEconomy extends VaultBase {
* 数量
* @return 是否
*/
public static boolean had(final OfflinePlayer oPlayer, final double amont) {
public static boolean had(OfflinePlayer oPlayer, double amont) {
return economy.has(oPlayer, amont);
}
@ -71,7 +71,7 @@ public class VaultEconomy extends VaultBase {
* 数量
* @return {@link EconomyResponse}
*/
public static EconomyResponse remove(final OfflinePlayer oPlayer, final double amont) {
public static EconomyResponse remove(OfflinePlayer oPlayer, double amont) {
return economy.withdrawPlayer(oPlayer, amont);
}
}

View File

@ -18,7 +18,7 @@ public class VaultPermission extends VaultBase {
private static Permission permission;
static {
final RegisteredServiceProvider<Permission> rsp = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
RegisteredServiceProvider<Permission> rsp = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
if (rsp == null || (permission = rsp.getProvider()) == null) {
PKit.disable("已加载 Vault 但是未找到权限相关插件 停止加载...");
} else {
@ -35,7 +35,7 @@ public class VaultPermission extends VaultBase {
* 权限
* @return 结果
*/
public static boolean add(final Player player, final String perm) {
public static boolean add(Player player, String perm) {
return permission.playerAdd(player, perm);
}
@ -46,7 +46,7 @@ public class VaultPermission extends VaultBase {
* 玩家
* @return 权限组
*/
public static String getGroup(final Player player) {
public static String getGroup(Player player) {
return permission.getPrimaryGroup(player);
}
@ -68,7 +68,7 @@ public class VaultPermission extends VaultBase {
* 权限
* @return 结果
*/
public static boolean has(final Player player, final String perm) {
public static boolean has(Player player, String perm) {
return permission.has(player, perm);
}
@ -81,7 +81,7 @@ public class VaultPermission extends VaultBase {
* 权限
* @return 结果
*/
public static boolean remove(final Player player, final String perm) {
public static boolean remove(Player player, String perm) {
return permission.playerRemove(player, perm);
}
}

View File

@ -28,7 +28,7 @@ import pw.yumc.YumCore.sql.core.SQLiteCore;
*
*/
public class DataBase {
private final DataBaseCore dataBaseCore;
private DataBaseCore dataBaseCore;
/**
* 初始化数据库管理
@ -36,12 +36,12 @@ public class DataBase {
* @param core
* 数据库核心
*/
public DataBase(final DataBaseCore core) {
public DataBase(DataBaseCore core) {
this.dataBaseCore = core;
}
public static DataBase create(final Plugin plugin, final ConfigurationSection dbConfig) {
final ConfigurationSection cfg = dbConfig.getConfigurationSection("MySQL");
public static DataBase create(Plugin plugin, ConfigurationSection dbConfig) {
ConfigurationSection cfg = dbConfig.getConfigurationSection("MySQL");
if (dbConfig.getString("FileSystem").equalsIgnoreCase("MySQL")) {
plugin.getLogger().info("已启用MySQL保存数据,开始连接数据库...");
return new DataBase(new MySQLCore(cfg));
@ -58,7 +58,7 @@ public class DataBase {
try {
this.dataBaseCore.getConnection().close();
return true;
} catch (final SQLException e) {
} catch (SQLException e) {
Log.debug("数据库链接关闭失败!", e);
return false;
}
@ -75,21 +75,21 @@ public class DataBase {
* 接受数据的数据库核心
* @return 是否转换成功
*/
public boolean copyTo(final DataBaseCore db) {
public boolean copyTo(DataBaseCore db) {
try {
final String src = this.dataBaseCore.getConnection().getMetaData().getURL();
final String des = db.getConnection().getMetaData().getURL();
String src = this.dataBaseCore.getConnection().getMetaData().getURL();
String des = db.getConnection().getMetaData().getURL();
Log.info("开始从源 " + src + " 复制数据到 " + des + " ...");
ResultSet rs = this.dataBaseCore.getConnection().getMetaData().getTables(null, null, "%", null);
final List<String> tables = new LinkedList<>();
List<String> tables = new LinkedList<>();
while (rs.next()) {
tables.add(rs.getString("TABLE_NAME"));
}
info("源数据库中有 " + tables.size() + " 张数据表 ...");
rs.close();
int s = 0;
final long start = System.currentTimeMillis();
for (final String table : tables) {
long start = System.currentTimeMillis();
for (String table : tables) {
Log.info("开始复制源数据库中的表 " + table + " ...");
if (table.toLowerCase().startsWith("sqlite_autoindex_")) {
continue;
@ -104,10 +104,10 @@ public class DataBase {
}
query = query.substring(0, query.length() - 2) + ")";
final Connection con = db.getConnection();
Connection con = db.getConnection();
try {
con.setAutoCommit(false);
final PreparedStatement ps = con.prepareStatement(query);
PreparedStatement ps = con.prepareStatement(query);
long time = System.currentTimeMillis();
while (rs.next()) {
n++;
@ -119,7 +119,7 @@ public class DataBase {
try {
ps.executeBatch();
con.commit();
} catch (final SQLException e) {
} catch (SQLException e) {
info("#====================================================");
info("#数据复制区段(不是ID!) " + (n - 100) + "-" + n + " 出现错误...");
info("#错误信息如下: ");
@ -136,7 +136,7 @@ public class DataBase {
ps.executeBatch();
con.commit();
info("数据表 " + table + " 复制完成 共 " + n + " 条记录...");
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
} finally {
con.setAutoCommit(true);
@ -147,7 +147,7 @@ public class DataBase {
db.getConnection().close();
this.dataBaseCore.getConnection().close();
return true;
} catch (final SQLException e) {
} catch (SQLException e) {
return false;
}
}
@ -163,11 +163,11 @@ public class DataBase {
* -附加值
* @return 运行结果
*/
public boolean createTables(final String tableName, final KeyValue fields, final String Conditions) {
public boolean createTables(String tableName, KeyValue fields, String Conditions) {
try {
this.dataBaseCore.createTables(tableName, fields, Conditions);
return isTableExists(tableName);
} catch (final Exception e) {
} catch (Exception e) {
sqlerr("创建数据表 " + tableName + " 异常(内部方法)...", e);
return false;
}
@ -182,11 +182,11 @@ public class DataBase {
* 删除条件
* @return 受到影响的数据条目
*/
public int dbDelete(final String tableName, final KeyValue fields) {
final String sql = "DELETE FROM `" + tableName + "` WHERE " + fields.toWhereString();
public int dbDelete(String tableName, KeyValue fields) {
String sql = "DELETE FROM `" + tableName + "` WHERE " + fields.toWhereString();
try {
return this.dataBaseCore.update(sql);
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
return 0;
}
@ -201,11 +201,11 @@ public class DataBase {
* 选择条件
* @return 首个符合条件的结果
*/
public boolean dbExist(final String tableName, final KeyValue fields) {
final String sql = "SELECT * FROM " + tableName + " WHERE " + fields.toWhereString();
public boolean dbExist(String tableName, KeyValue fields) {
String sql = "SELECT * FROM " + tableName + " WHERE " + fields.toWhereString();
try {
return this.dataBaseCore.query(sql).next();
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
return false;
}
@ -220,11 +220,11 @@ public class DataBase {
* 带键值的
* @return 受到影响的数据条目
*/
public int dbInsert(final String tabName, final KeyValue fields) {
final String sql = "INSERT INTO `" + tabName + "` " + fields.toInsertString();
public int dbInsert(String tabName, KeyValue fields) {
String sql = "INSERT INTO `" + tabName + "` " + fields.toInsertString();
try {
return this.dataBaseCore.update(sql);
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
return 0;
}
@ -232,23 +232,23 @@ public class DataBase {
}
// @SuppressWarnings("unchecked")
// public <M> List<M> dbSelect(final Class<? extends Model<?>> model, final KeyValue selCondition) {
// final List<M> modellist = new ArrayList<>();
// final String sql = "SELECT " + toKeys(model) + " FROM `" + model.getAnnotation(Entity.class).name() + "`" + (selCondition == null ? "" : " WHERE " + selCondition.toWhereString());
// public <M> List<M> dbSelect( Class<? extends Model<?>> model, KeyValue selCondition) {
// List<M> modellist = new ArrayList<>();
// String sql = "SELECT " + toKeys(model) + " FROM `" + model.getAnnotation(Entity.class).name() + "`" + (selCondition == null ? "" : " WHERE " + selCondition.toWhereString());
// try {
// final ResultSet dbresult = this.dataBaseCore.execute(sql);
// ResultSet dbresult = this.dataBaseCore.execute(sql);
// while (dbresult.next()) {
// final M m = (M) model.newInstance();
// final Field[] fields = model.getDeclaredFields();
// for (final Field col : fields) {
// M m = (M) model.newInstance();
// Field[] fields = model.getDeclaredFields();
// for ( Field col : fields) {
// col.set(m, dbresult.getObject(col.getName()));
// }
// modellist.add(m);
// }
// } catch (final InstantiationException e) {
// } catch ( InstantiationException e) {
// info("模型类实例化失败!");
// e.printStackTrace();
// } catch (final Exception e) {
// } catch ( Exception e) {
// sqlerr(sql, e);
// }
// return modellist;
@ -265,19 +265,19 @@ public class DataBase {
* 选择条件
* @return 一个含有KeyValue的List列表
*/
public List<KeyValue> dbSelect(final String tableName, final KeyValue fields, final KeyValue selCondition) {
final String sql = "SELECT " + fields.toKeys() + " FROM `" + tableName + "`" + (selCondition == null ? "" : " WHERE " + selCondition.toWhereString());
final List<KeyValue> kvlist = new ArrayList<>();
public List<KeyValue> dbSelect(String tableName, KeyValue fields, KeyValue selCondition) {
String sql = "SELECT " + fields.toKeys() + " FROM `" + tableName + "`" + (selCondition == null ? "" : " WHERE " + selCondition.toWhereString());
List<KeyValue> kvlist = new ArrayList<>();
try {
final ResultSet dbresult = this.dataBaseCore.query(sql);
ResultSet dbresult = this.dataBaseCore.query(sql);
while (dbresult.next()) {
final KeyValue kv = new KeyValue();
for (final String col : fields.getKeys()) {
KeyValue kv = new KeyValue();
for (String col : fields.getKeys()) {
kv.add(col, dbresult.getString(col.toString()));
}
kvlist.add(kv);
}
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
}
return kvlist;
@ -294,19 +294,19 @@ public class DataBase {
* 读取的字段
* @return 一个含有KeyValue的List列表
*/
public List<KeyValue> dbSelect(final String tableName, final KeyValue selCondition, final String... fields) {
final String sql = "SELECT " + getKeys(fields) + " FROM `" + tableName + "`" + (selCondition == null ? "" : " WHERE " + selCondition.toWhereString());
final List<KeyValue> kvlist = new ArrayList<>();
public List<KeyValue> dbSelect(String tableName, KeyValue selCondition, String... fields) {
String sql = "SELECT " + getKeys(fields) + " FROM `" + tableName + "`" + (selCondition == null ? "" : " WHERE " + selCondition.toWhereString());
List<KeyValue> kvlist = new ArrayList<>();
try {
final ResultSet dbresult = this.dataBaseCore.query(sql);
ResultSet dbresult = this.dataBaseCore.query(sql);
while (dbresult.next()) {
final KeyValue kv = new KeyValue();
for (final String col : fields) {
KeyValue kv = new KeyValue();
for (String col : fields) {
kv.add(col, dbresult.getString(col.toString()));
}
kvlist.add(kv);
}
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
}
return kvlist;
@ -323,14 +323,14 @@ public class DataBase {
* 选择条件
* @return 首个符合条件的结果
*/
public String dbSelectFirst(final String tableName, final String fields, final KeyValue selConditions) {
final String sql = "SELECT " + fields + " FROM " + tableName + " WHERE " + selConditions.toWhereString() + " limit 1";
public String dbSelectFirst(String tableName, String fields, KeyValue selConditions) {
String sql = "SELECT " + fields + " FROM " + tableName + " WHERE " + selConditions.toWhereString() + " limit 1";
try {
final ResultSet dbresult = this.dataBaseCore.query(sql);
ResultSet dbresult = this.dataBaseCore.query(sql);
if (dbresult.next()) {
return dbresult.getString(fields);
}
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
}
return null;
@ -347,11 +347,11 @@ public class DataBase {
* 更新条件
* @return 受到影响的数据条目
*/
public int dbUpdate(final String tabName, final KeyValue fields, final KeyValue upCondition) {
final String sql = "UPDATE `" + tabName + "` SET " + fields.toUpdateString() + " WHERE " + upCondition.toWhereString();
public int dbUpdate(String tabName, KeyValue fields, KeyValue upCondition) {
String sql = "UPDATE `" + tabName + "` SET " + fields.toUpdateString() + " WHERE " + upCondition.toWhereString();
try {
return this.dataBaseCore.update(sql);
} catch (final Exception e) {
} catch (Exception e) {
sqlerr(sql, e);
return 0;
}
@ -373,9 +373,9 @@ public class DataBase {
* 字段数组
* @return 字段字符串
*/
public String getKeys(final String... fields) {
final StringBuilder sb = new StringBuilder();
for (final String string : fields) {
public String getKeys(String... fields) {
StringBuilder sb = new StringBuilder();
for (String string : fields) {
sb.append("`");
sb.append(string);
sb.append("`, ");
@ -383,17 +383,17 @@ public class DataBase {
return sb.toString().substring(0, sb.length() - 2);
}
public boolean isFieldExists(final String tableName, final KeyValue fields) {
final DatabaseMetaData dbm;
final ResultSet tables;
public boolean isFieldExists(String tableName, KeyValue fields) {
DatabaseMetaData dbm;
ResultSet tables;
try {
dbm = this.dataBaseCore.getConnection().getMetaData();
tables = dbm.getTables(null, null, tableName, null);
if (tables.next()) {
final ResultSet f = dbm.getColumns(null, null, tableName, fields.getKeys()[0]);
ResultSet f = dbm.getColumns(null, null, tableName, fields.getKeys()[0]);
return f.next();
}
} catch (final SQLException e) {
} catch (SQLException e) {
sqlerr("判断 表名:" + tableName + " 字段名:" + fields.getKeys()[0] + " 是否存在时出错!", e);
}
return false;
@ -406,12 +406,12 @@ public class DataBase {
* 表名
* @return 是否存在
*/
public boolean isTableExists(final String tableName) {
public boolean isTableExists(String tableName) {
try {
final DatabaseMetaData dbm = this.dataBaseCore.getConnection().getMetaData();
final ResultSet tables = dbm.getTables(null, null, tableName, null);
DatabaseMetaData dbm = this.dataBaseCore.getConnection().getMetaData();
ResultSet tables = dbm.getTables(null, null, tableName, null);
return tables.next();
} catch (final SQLException e) {
} catch (SQLException e) {
sqlerr("判断 表名:" + tableName + " 是否存在时出错!", e);
return false;
}
@ -423,15 +423,15 @@ public class DataBase {
* @param sqls
* SQL语句列表
*/
public void runSqlList(final Collection<String> sqls) {
final Connection con = getDataBaseCore().getConnection();
final long start = System.currentTimeMillis();
public void runSqlList(Collection<String> sqls) {
Connection con = getDataBaseCore().getConnection();
long start = System.currentTimeMillis();
try {
long time = System.currentTimeMillis();
con.setAutoCommit(false);
final Statement st = con.createStatement();
Statement st = con.createStatement();
int i = 0;
for (final String sql : sqls) {
for (String sql : sqls) {
st.addBatch(sql);
i++;
if (i % 100 == 0) {
@ -446,17 +446,17 @@ public class DataBase {
st.executeBatch();
con.commit();
info("执行SQL完毕 总计: " + sqls.size() + " 条 耗时: " + start + "ms!");
} catch (final SQLException e) {
} catch (SQLException e) {
try {
con.rollback();
sqlerr("执行SQL数组发生错误 数据已回滚...", e);
} catch (final SQLException e1) {
} catch (SQLException e1) {
sqlerr("执行SQL数组发生错误 警告! 数据回滚失败...", e1);
}
} finally {
try {
con.setAutoCommit(true);
} catch (final SQLException e) {
} catch (SQLException e) {
}
}
}
@ -469,7 +469,7 @@ public class DataBase {
* @param e
* 错误异常
*/
public void sqlerr(final String sql, final Exception e) {
public void sqlerr(String sql, Exception e) {
info("数据库操作出错: " + e.getMessage());
info("SQL查询语句: " + sql);
Log.debug(this.getClass().getName());
@ -485,14 +485,14 @@ public class DataBase {
return this.dataBaseCore.getConnection() != null;
}
private void info(final String info) {
private void info(String info) {
Log.info(info);
}
// private String toKeys(final Class<? extends Model<?>> model) {
// final Field[] fields = model.getDeclaredFields();
// final StringBuilder sb = new StringBuilder();
// for (final Field next : fields) {
// private String toKeys( Class<? extends Model<?>> model) {
// Field[] fields = model.getDeclaredFields();
// StringBuilder sb = new StringBuilder();
// for ( Field next : fields) {
// sb.append("`");
// sb.append(next.getName());
// sb.append("`, ");

View File

@ -28,7 +28,7 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL异常
*/
public abstract boolean createTables(final String tableName, final KeyValue fields, final String Conditions) throws SQLException;
public abstract boolean createTables(String tableName, KeyValue fields, String Conditions) throws SQLException;
/**
* 执行SQL语句
@ -39,10 +39,10 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL执行异常
*/
public boolean execute(final String sql) throws SQLException {
public boolean execute(String sql) throws SQLException {
debug(sql);
final Statement st = getStatement();
final boolean result = st.execute(sql);
Statement st = getStatement();
boolean result = st.execute(sql);
st.close();
return result;
}
@ -58,13 +58,13 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL执行异常
*/
public boolean execute(final String sql, final Object... obj) throws SQLException {
public boolean execute(String sql, Object... obj) throws SQLException {
debug(sql);
final PreparedStatement ps = prepareStatement(sql);
PreparedStatement ps = prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i + 1, obj[i]);
}
final boolean result = ps.execute(sql);
boolean result = ps.execute(sql);
ps.close();
return result;
}
@ -92,10 +92,10 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL查询异常
*/
public ResultSet query(final String sql) throws SQLException {
public ResultSet query(String sql) throws SQLException {
debug(sql);
final Statement st = getStatement();
final ResultSet result = st.executeQuery(sql);
Statement st = getStatement();
ResultSet result = st.executeQuery(sql);
return result;
}
@ -108,10 +108,10 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL执行异常
*/
public int update(final String sql) throws SQLException {
public int update(String sql) throws SQLException {
debug(sql);
final Statement st = getStatement();
final int result = st.executeUpdate(sql);
Statement st = getStatement();
int result = st.executeUpdate(sql);
st.close();
return result;
}
@ -127,13 +127,13 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL执行异常
*/
public int update(final String sql, final Object[] obj) throws SQLException {
public int update(String sql, Object[] obj) throws SQLException {
debug(sql);
final PreparedStatement ps = prepareStatement(sql);
PreparedStatement ps = prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i + 1, obj[i]);
}
final int result = ps.executeUpdate(sql);
int result = ps.executeUpdate(sql);
ps.close();
return result;
}
@ -144,7 +144,7 @@ public abstract class DataBaseCore {
* @param warn
* 警告消息
*/
public void warn(final String warn) {
public void warn(String warn) {
Log.warning(warn);
}
@ -154,7 +154,7 @@ public abstract class DataBaseCore {
* @param sql
* SQL语句
*/
private void debug(final String sql) {
private void debug(String sql) {
Log.debug("[SQL] " + sql);
}
@ -178,7 +178,7 @@ public abstract class DataBaseCore {
* @throws SQLException
* SQL执行异常
*/
protected PreparedStatement prepareStatement(final String sql) throws SQLException {
protected PreparedStatement prepareStatement(String sql) throws SQLException {
return getConnection().prepareStatement(sql);
}
}

View File

@ -14,7 +14,7 @@ import java.util.Map.Entry;
*/
public class KeyValue {
private final Map<Object, Object> keyvalues = new HashMap<>();
private Map<Object, Object> keyvalues = new HashMap<>();
/**
* 数据库键值管理类
@ -30,7 +30,7 @@ public class KeyValue {
* @param value
*
*/
public KeyValue(final String key, final Object value) {
public KeyValue(String key, Object value) {
add(key, value);
}
@ -43,7 +43,7 @@ public class KeyValue {
*
* @return {@link KeyValue}
*/
public KeyValue add(final String key, final Object value) {
public KeyValue add(String key, Object value) {
this.keyvalues.put(key, value);
return this;
}
@ -64,8 +64,8 @@ public class KeyValue {
* 查询的键
* @return
*/
public String getString(final String key) {
final Object obj = this.keyvalues.get(key);
public String getString(String key) {
Object obj = this.keyvalues.get(key);
return obj == null ? "" : obj.toString();
}
@ -75,8 +75,8 @@ public class KeyValue {
* @return 所有的值
*/
public Object[] getValues() {
final List<Object> keys = new ArrayList<>();
for (final Entry<Object, Object> next : this.keyvalues.entrySet()) {
List<Object> keys = new ArrayList<>();
for (Entry<Object, Object> next : this.keyvalues.entrySet()) {
keys.add(next.getValue());
}
return keys.toArray(new Object[0]);
@ -97,8 +97,8 @@ public class KeyValue {
* @return 数据表创建SQL语句
*/
public String toCreateString() {
final StringBuilder sb = new StringBuilder();
for (final Entry<Object, Object> next : this.keyvalues.entrySet()) {
StringBuilder sb = new StringBuilder();
for (Entry<Object, Object> next : this.keyvalues.entrySet()) {
sb.append("`");
sb.append(next.getKey());
sb.append("` ");
@ -116,7 +116,7 @@ public class KeyValue {
public String toInsertString() {
String ks = "";
String vs = "";
for (final Entry<Object, Object> next : this.keyvalues.entrySet()) {
for (Entry<Object, Object> next : this.keyvalues.entrySet()) {
ks += "`" + next.getKey() + "`, ";
vs += "'" + next.getValue() + "', ";
}
@ -127,8 +127,8 @@ public class KeyValue {
* @return 转换为键列
*/
public String toKeys() {
final StringBuilder sb = new StringBuilder();
for (final Object next : this.keyvalues.keySet()) {
StringBuilder sb = new StringBuilder();
for (Object next : this.keyvalues.keySet()) {
sb.append("`");
sb.append(next);
sb.append("`, ");
@ -147,8 +147,8 @@ public class KeyValue {
* @return 更新SQL语句
*/
public String toUpdateString() {
final StringBuilder sb = new StringBuilder();
for (final Entry<Object, Object> next : this.keyvalues.entrySet()) {
StringBuilder sb = new StringBuilder();
for (Entry<Object, Object> next : this.keyvalues.entrySet()) {
sb.append("`");
sb.append(next.getKey());
sb.append("`='");
@ -164,8 +164,8 @@ public class KeyValue {
* @return 查询SQL语句
*/
public String toWhereString() {
final StringBuilder sb = new StringBuilder();
for (final Entry<Object, Object> next : this.keyvalues.entrySet()) {
StringBuilder sb = new StringBuilder();
for (Entry<Object, Object> next : this.keyvalues.entrySet()) {
sb.append("`");
sb.append(next.getKey());
sb.append("`='");

View File

@ -14,10 +14,10 @@ import org.bukkit.configuration.ConfigurationSection;
* @author
*/
public class MySQLCore extends DataBaseCore {
private static final String driverName = "com.mysql.jdbc.Driver";
private static String driverName = "com.mysql.jdbc.Driver";
private Connection connection;
private final Properties info;
private final String url;
private Properties info;
private String url;
/**
* 初始化连接信息
@ -25,7 +25,7 @@ public class MySQLCore extends DataBaseCore {
* @param cfg
* 配置节点
*/
public MySQLCore(final ConfigurationSection cfg) {
public MySQLCore(ConfigurationSection cfg) {
this(cfg.getString("ip", "127.0.0.1"), cfg.getInt("port", 3306), cfg.getString("database", "minecraft"), cfg.getString("username", "root"), cfg.getString("password", ""));
}
@ -43,7 +43,7 @@ public class MySQLCore extends DataBaseCore {
* @param password
* 密码
*/
public MySQLCore(final String host, final int port, final String dbname, final String username, final String password) {
public MySQLCore(String host, int port, String dbname, String username, String password) {
this.info = new Properties();
this.info.put("autoReconnect", "true");
this.info.put("user", username);
@ -53,7 +53,7 @@ public class MySQLCore extends DataBaseCore {
this.url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;
try {
Class.forName(driverName).newInstance();
} catch (final Exception e) {
} catch (Exception e) {
warn("数据库初始化失败 请检查驱动 " + driverName + " 是否存在!");
}
}
@ -72,8 +72,8 @@ public class MySQLCore extends DataBaseCore {
* SQL异常
*/
@Override
public boolean createTables(final String tableName, final KeyValue fields, final String Conditions) throws SQLException {
final String sql = "CREATE TABLE IF NOT EXISTS `%s` ( %s %s ) ENGINE = InnoDB DEFAULT CHARSET=UTF8";
public boolean createTables(String tableName, KeyValue fields, String Conditions) throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS `%s` ( %s %s ) ENGINE = InnoDB DEFAULT CHARSET=UTF8";
return execute(String.format(sql, tableName, fields.toCreateString(), Conditions == null ? "" : ", " + Conditions));
}
@ -85,7 +85,7 @@ public class MySQLCore extends DataBaseCore {
}
this.connection = DriverManager.getConnection(this.url, this.info);
return this.connection;
} catch (final SQLException e) {
} catch (SQLException e) {
warn("数据库操作出错: " + e.getMessage());// 得到出错信息
warn("登录URL: " + this.url); // 发生错误时将连接数据库信息打印出来
warn("登录账户: " + this.info.getProperty("user"));

View File

@ -16,9 +16,9 @@ import org.bukkit.plugin.Plugin;
* @author
*/
public class SQLiteCore extends DataBaseCore {
private static final String driverName = "org.sqlite.JDBC";
private static String driverName = "org.sqlite.JDBC";
private Connection connection;
private final File dbFile;
private File dbFile;
/**
* 初始化连接信息
@ -26,20 +26,20 @@ public class SQLiteCore extends DataBaseCore {
* @param dbFile
* 数据库文件
*/
public SQLiteCore(final File dbFile) {
public SQLiteCore(File dbFile) {
this.dbFile = dbFile;
if (this.dbFile.exists()) {
// So we need a new connection
try {
this.dbFile.createNewFile();
} catch (final IOException e) {
} catch (IOException e) {
warn("数据库文件 " + dbFile.getAbsolutePath() + " 创建失败!");
e.printStackTrace();
}
}
try {
Class.forName(driverName).newInstance();
} catch (final Exception e) {
} catch (Exception e) {
warn("数据库初始化失败 请检查驱动 " + driverName + " 是否存在!");
e.printStackTrace();
}
@ -53,7 +53,7 @@ public class SQLiteCore extends DataBaseCore {
* @param cfg
* 配置信息
*/
public SQLiteCore(final Plugin plugin, final ConfigurationSection cfg) {
public SQLiteCore(Plugin plugin, ConfigurationSection cfg) {
this(plugin, cfg.getString("database"));
}
@ -65,20 +65,20 @@ public class SQLiteCore extends DataBaseCore {
* @param filename
* 文件名称
*/
public SQLiteCore(final Plugin plugin, final String filename) {
public SQLiteCore(Plugin plugin, String filename) {
this.dbFile = new File(plugin.getDataFolder(), filename + ".db");
if (this.dbFile.exists()) {
// So we need a new connection
try {
this.dbFile.createNewFile();
} catch (final IOException e) {
} catch (IOException e) {
warn("数据库文件 " + this.dbFile.getAbsolutePath() + " 创建失败!");
e.printStackTrace();
}
}
try {
Class.forName(driverName).newInstance();
} catch (final Exception e) {
} catch (Exception e) {
warn("数据库初始化失败 请检查驱动 " + driverName + " 是否存在!");
e.printStackTrace();
}
@ -90,13 +90,13 @@ public class SQLiteCore extends DataBaseCore {
* @param filepath
* 文件路径
*/
public SQLiteCore(final String filepath) {
public SQLiteCore(String filepath) {
this(new File(filepath));
}
@Override
public boolean createTables(final String tableName, final KeyValue fields, final String Conditions) throws SQLException {
final String sql = "CREATE TABLE IF NOT EXISTS `%s` ( %s %s )";
public boolean createTables(String tableName, KeyValue fields, String Conditions) throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS `%s` ( %s %s )";
return execute(String.format(sql, tableName, fields.toCreateString().replace("AUTO_INCREMENT", "AUTOINCREMENT"), Conditions == null ? "" : " , " + Conditions));
}
@ -116,7 +116,7 @@ public class SQLiteCore extends DataBaseCore {
}
this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.dbFile);
return this.connection;
} catch (final SQLException e) {
} catch (SQLException e) {
warn("数据库操作出错: " + e.getMessage());// 得到出错信息
warn("数据库文件: " + this.dbFile.getAbsolutePath()); // 发生错误时将连接数据库信息打印出来
return null;

View File

@ -39,17 +39,17 @@ public class Statistics {
/**
* 统计系统版本
*/
private final static int REVISION = 10;
private static int REVISION = 10;
/**
* 统计插件基础配置文件
*/
private final static File configfile = new File(String.format("plugins%1$sPluginHelper%1$sconfig.yml", File.separatorChar));
private static File configfile = new File(String.format("plugins%1$sPluginHelper%1$sconfig.yml", File.separatorChar));
/**
* UTF-8编码
*/
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static Charset UTF_8 = Charset.forName("UTF-8");
/**
* getOnlinePlayers方法
@ -65,14 +65,14 @@ public class Statistics {
try {
getOnlinePlayers = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
if (getOnlinePlayers.getReturnType() != Player[].class) {
for (final Method method : Bukkit.class.getDeclaredMethods()) {
for (Method method : Bukkit.class.getDeclaredMethods()) {
if (method.getReturnType() == Player[].class && method.getName().endsWith("getOnlinePlayers")) {
getOnlinePlayers = method;
}
}
}
final Object pluginClassLoader = Statistics.class.getClassLoader();
final Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
Object pluginClassLoader = Statistics.class.getClassLoader();
Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
field.setAccessible(true);
plugin = (JavaPlugin) field.get(pluginClassLoader);
} catch (NoSuchMethodException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
@ -87,12 +87,12 @@ public class Statistics {
/**
* 调试模式
*/
private final boolean debug;
private boolean debug;
/**
* 唯一服务器编码
*/
private final String guid;
private String guid;
/**
* 线程任务
@ -115,7 +115,7 @@ public class Statistics {
}
config = YamlConfiguration.loadConfiguration(configfile);
initFile(config);
} catch (final IOException e) {
} catch (IOException e) {
}
this.guid = config.getString("guid");
this.debug = config.getBoolean("debug", false);
@ -132,12 +132,12 @@ public class Statistics {
* @return 所代表远程资源的响应结果
* @throws IOException
*/
public static String postData(final String url, final String param) throws IOException {
public static String postData(String url, String param) throws IOException {
PrintWriter out = null;
String result = "";
final URL realUrl = new URL(url);
URL realUrl = new URL(url);
// 打开和URL之间的连接
final URLConnection conn = realUrl.openConnection();
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Connection", "Keep-Alive");
@ -154,7 +154,7 @@ public class Statistics {
// flush输出流的缓冲
out.flush();
String response = "";
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), UTF_8));
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), UTF_8));
while ((response = reader.readLine()) != null) {
result += response;
}
@ -172,7 +172,7 @@ public class Statistics {
* 配置文件
* @throws IOException
*/
private static void initFile(final YamlConfiguration config) throws IOException {
private static void initFile(YamlConfiguration config) throws IOException {
if (config.getString("guid") == null) {
config.options().header("YUMC数据中心 http://www.yumc.pw 收集的数据仅用于统计插件使用情况").copyDefaults(true);
config.set("guid", UUID.randomUUID().toString());
@ -196,7 +196,7 @@ public class Statistics {
* @param msg
* 输出对象
*/
public void print(final String msg) {
public void print(String msg) {
if (debug) {
System.out.println("[Statistics] " + msg);
}
@ -220,7 +220,7 @@ public class Statistics {
public void run() {
try {
postPlugin();
} catch (final Throwable e) {
} catch (Throwable e) {
if (debug) {
e.printStackTrace();
}
@ -238,7 +238,7 @@ public class Statistics {
private int getOnlinePlayerNumber() {
try {
return ((Player[]) getOnlinePlayers.invoke(Bukkit.getServer())).length;
} catch (final Exception ex) {
} catch (Exception ex) {
return Bukkit.getOnlinePlayers().size();
}
}
@ -248,11 +248,11 @@ public class Statistics {
*/
private void postPlugin() throws IOException {
// 服务器数据获取
final PluginDescriptionFile description = plugin.getDescription();
final String pluginname = description.getName();
final String tmposarch = System.getProperty("os.arch");
PluginDescriptionFile description = plugin.getDescription();
String pluginname = description.getName();
String tmposarch = System.getProperty("os.arch");
final Map<String, Object> data = new HashMap<>();
Map<String, Object> data = new HashMap<>();
data.put("guid", guid);
data.put("server_version", Bukkit.getVersion());
data.put("server_port", Bukkit.getServer().getPort());
@ -267,24 +267,24 @@ public class Statistics {
data.put("auth_mode", Bukkit.getServer().getOnlineMode() ? 1 : 0);
data.put("java_version", System.getProperty("java.version"));
final String jsondata = "Info=" + JSONValue.toJSONString(data);
String jsondata = "Info=" + JSONValue.toJSONString(data);
final String url = String.format("http://api.yumc.pw/I/P/S/V/%s/P/%s", REVISION, URLEncoder.encode(pluginname, "UTF-8"));
String url = String.format("http://api.yumc.pw/I/P/S/V/%s/P/%s", REVISION, URLEncoder.encode(pluginname, "UTF-8"));
print("Plugin: " + pluginname + " Send Data To CityCraft Data Center");
print("Address: " + url);
print("Data: " + jsondata);
// 发送数据
final JSONObject result = (JSONObject) JSONValue.parse(postData(url, jsondata));
JSONObject result = (JSONObject) JSONValue.parse(postData(url, jsondata));
print("Plugin: " + pluginname + " Recover Data From CityCraft Data Center: " + result.get("info"));
}
public class StatisticsTimer implements Runnable {
private final LinkedList<Double> history = new LinkedList<>();
private LinkedList<Double> history = new LinkedList<>();
private transient long lastPoll = System.nanoTime();
public double getAverageTPS() {
double avg = 0.0D;
for (final Double f : history) {
for (Double f : history) {
avg += f.doubleValue();
}
return avg / history.size();
@ -292,12 +292,12 @@ public class Statistics {
@Override
public void run() {
final long startTime = System.nanoTime();
final long timeSpent = (startTime - lastPoll) / 1000;
long startTime = System.nanoTime();
long timeSpent = (startTime - lastPoll) / 1000;
if (history.size() > 10) {
history.removeFirst();
}
final double ttps = 2.0E7D / (timeSpent == 0 ? 1 : timeSpent);
double ttps = 2.0E7D / (timeSpent == 0 ? 1 : timeSpent);
if (ttps <= 21.0D) {
history.add(ttps);
}

View File

@ -30,15 +30,15 @@ public abstract class ItemSerialize {
}
}
public static String $(final ItemStack item) {
final String result = itemSerialize.parse(item);
public static String $(ItemStack item) {
String result = itemSerialize.parse(item);
Log.d("%s物品序列化结果: %s", itemSerialize.getName(), result);
return result;
}
public abstract String getName();
public abstract String parse(final ItemStack item);
public abstract String parse(ItemStack item);
static class Automatic extends ItemSerialize {
Method asNMSCopyMethod;
@ -47,18 +47,18 @@ public abstract class ItemSerialize {
String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
public Automatic() throws ClassNotFoundException, NoSuchMethodException, SecurityException {
final Class<?> cis = getOBCClass("inventory.CraftItemStack");
Class<?> cis = getOBCClass("inventory.CraftItemStack");
asNMSCopyMethod = cis.getMethod("asNMSCopy", ItemStack.class);
final Class<?> nmsItemStack = asNMSCopyMethod.getReturnType();
for (final Method method : nmsItemStack.getMethods()) {
final Class<?> rt = method.getReturnType();
Class<?> nmsItemStack = asNMSCopyMethod.getReturnType();
for (Method method : nmsItemStack.getMethods()) {
Class<?> rt = method.getReturnType();
if (method.getParameterTypes().length == 0 && "NBTTagCompound".equals(rt.getSimpleName())) {
nmsNBTTagCompound = rt;
}
}
for (final Method method : nmsItemStack.getMethods()) {
final Class<?>[] paras = method.getParameterTypes();
final Class<?> rt = method.getReturnType();
for (Method method : nmsItemStack.getMethods()) {
Class<?>[] paras = method.getParameterTypes();
Class<?> rt = method.getReturnType();
if (paras.length == 1 && "NBTTagCompound".equals(paras[0].getSimpleName()) && "NBTTagCompound".equals(rt.getSimpleName())) {
nmsSaveNBTMethod = method;
}
@ -70,12 +70,12 @@ public abstract class ItemSerialize {
return "Automatic";
}
public Class getOBCClass(final String cname) throws ClassNotFoundException {
public Class getOBCClass(String cname) throws ClassNotFoundException {
return Class.forName("org.bukkit.craftbukkit." + ver + "." + cname);
}
@Override
public String parse(final ItemStack item) {
public String parse(ItemStack item) {
try {
return nmsSaveNBTMethod.invoke(asNMSCopyMethod.invoke(null, item), nmsNBTTagCompound.newInstance()).toString();
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
@ -93,7 +93,7 @@ public abstract class ItemSerialize {
}
@Override
public String parse(final ItemStack item) {
public String parse(ItemStack item) {
return serialize(item);
}
@ -104,8 +104,8 @@ public abstract class ItemSerialize {
* 物品属性
* @return 获取显示序列化
*/
private String getDisplay(final ItemMeta im) {
final StringBuilder display = new StringBuilder();
private String getDisplay(ItemMeta im) {
StringBuilder display = new StringBuilder();
display.append("{");
if (im.hasDisplayName()) {
display.append(String.format("Name:\"%s\",", im.getDisplayName()));
@ -113,7 +113,7 @@ public abstract class ItemSerialize {
if (im.hasLore()) {
display.append("Lore:[");
int i = 0;
for (final String line : im.getLore()) {
for (String line : im.getLore()) {
display.append(String.format("%s:\"%s\",", i, new JsonBuilder(line).toString()));
i++;
}
@ -132,9 +132,9 @@ public abstract class ItemSerialize {
* 附魔集合
* @return 获得附魔序列化
*/
private String getEnch(final Set<Entry<Enchantment, Integer>> set) {
final StringBuilder enchs = new StringBuilder();
for (final Map.Entry<Enchantment, Integer> ench : set) {
private String getEnch(Set<Entry<Enchantment, Integer>> set) {
StringBuilder enchs = new StringBuilder();
for (Map.Entry<Enchantment, Integer> ench : set) {
enchs.append(String.format("{id:%s,lvl:%s},", ench.getKey().getId(), ench.getValue()));
}
enchs.deleteCharAt(enchs.length() - 1);
@ -148,8 +148,8 @@ public abstract class ItemSerialize {
* 物品属性
* @return 获得属性序列化
*/
private String getTag(final ItemMeta im) {
final StringBuilder meta = new StringBuilder("{");
private String getTag(ItemMeta im) {
StringBuilder meta = new StringBuilder("{");
if (im.hasEnchants()) {
meta.append(String.format("ench:[%s],", getEnch(im.getEnchants().entrySet())));
}
@ -168,8 +168,8 @@ public abstract class ItemSerialize {
* {@link ItemStack}
* @return 物品字符串
*/
private String serialize(final ItemStack item) {
final StringBuilder json = new StringBuilder("{");
private String serialize(ItemStack item) {
StringBuilder json = new StringBuilder("{");
json.append(String.format("id:\"%s\",Damage:\"%s\"", item.getTypeId(), item.getDurability()));
if (item.getAmount() > 1) {
json.append(String.format(",Count:%s", item.getAmount()));

View File

@ -7,7 +7,7 @@ package pw.yumc.YumCore.tellraw;
* @author
*/
public class JsonBuilder {
public static final String[] REPLACEMENT_CHARS;
public static String[] REPLACEMENT_CHARS;
static {
REPLACEMENT_CHARS = new String[128];
for (int i = 0; i <= 0x1f; i++) {
@ -27,16 +27,16 @@ public class JsonBuilder {
json = new StringBuilder();
}
public JsonBuilder(final String string) {
public JsonBuilder(String string) {
this();
append(string);
}
public void append(final String value) {
public void append(String value) {
int last = 0;
final int length = value.length();
int length = value.length();
for (int i = 0; i < length; i++) {
final char c = value.charAt(i);
char c = value.charAt(i);
String replacement;
if (c < 128) {
replacement = REPLACEMENT_CHARS[c];

View File

@ -7,10 +7,10 @@ package pw.yumc.YumCore.tellraw;
* @author
*/
public class MessagePart {
private static final String TEXT_FORMAT = "\"text\":\"%s\"";
private static final String CLICK_FORMAT = "\"clickEvent\":{\"action\":\"%s\",\"value\":\"%s\"}";
private static final String HOVER_FORMAT = "\"hoverEvent\":{\"action\":\"%s\",\"value\":\"%s\"}";
private static final String INSERT_FORMAT = " \"insertion\":\"%s\"";
private static String TEXT_FORMAT = "\"text\":\"%s\"";
private static String CLICK_FORMAT = "\"clickEvent\":{\"action\":\"%s\",\"value\":\"%s\"}";
private static String HOVER_FORMAT = "\"hoverEvent\":{\"action\":\"%s\",\"value\":\"%s\"}";
private static String INSERT_FORMAT = " \"insertion\":\"%s\"";
/**
* 消息文本
*/
@ -40,7 +40,7 @@ public class MessagePart {
this("");
}
public MessagePart(final String text) {
public MessagePart(String text) {
this.text = text;
}
@ -57,7 +57,7 @@ public class MessagePart {
* @param str
* 流对象
*/
public void writeJson(final StringBuilder str) {
public void writeJson(StringBuilder str) {
str.append("{");
str.append(String.format(TEXT_FORMAT, new JsonBuilder(text)));
if (clickActionName != null) {

View File

@ -24,7 +24,7 @@ public class Tellraw {
static boolean isPaper = Bukkit.getVersion().contains("Paper");
List<MessagePart> messageParts = new ArrayList<>();
public Tellraw(final String text) {
public Tellraw(String text) {
messageParts.add(new MessagePart(text));
}
@ -44,7 +44,7 @@ public class Tellraw {
* 文本
* @return {@link Tellraw}
*/
public static Tellraw create(final String text) {
public static Tellraw create(String text) {
return new Tellraw(text);
}
@ -57,7 +57,7 @@ public class Tellraw {
* 参数
* @return {@link Tellraw}
*/
public static Tellraw create(final String text, final Object... objects) {
public static Tellraw create(String text, Object... objects) {
return new Tellraw(String.format(text, objects));
}
@ -65,7 +65,7 @@ public class Tellraw {
* 发送Tellraw公告
*/
public void broadcast() {
for (final Player player : C.Player.getOnlinePlayers()) {
for (Player player : C.Player.getOnlinePlayers()) {
send(player);
}
}
@ -79,7 +79,7 @@ public class Tellraw {
* 提示
* @return {@link Tellraw}
*/
public Tellraw cmd_tip(final String command, final String... tip) {
public Tellraw cmd_tip(String command, String... tip) {
return command(command).tip(tip);
}
@ -90,7 +90,7 @@ public class Tellraw {
* 命令
* @return {@link Tellraw}
*/
public Tellraw command(final String command) {
public Tellraw command(String command) {
return onClick("run_command", command);
}
@ -101,11 +101,11 @@ public class Tellraw {
* 文件路径
* @return {@link Tellraw}
*/
public Tellraw file(final String path) {
public Tellraw file(String path) {
return onClick("open_file", path);
}
public Tellraw insertion(final String data) {
public Tellraw insertion(String data) {
latest().insertionData = data;
return this;
}
@ -117,7 +117,7 @@ public class Tellraw {
* {@link ItemStack}
* @return {@link Tellraw}
*/
public Tellraw item(final ItemStack item) {
public Tellraw item(ItemStack item) {
return item(ItemSerialize.$(item));
}
@ -128,7 +128,7 @@ public class Tellraw {
* 物品Json串
* @return {@link Tellraw}
*/
public Tellraw item(final String json) {
public Tellraw item(String json) {
return onHover("show_item", json);
}
@ -139,7 +139,7 @@ public class Tellraw {
* 地址
* @return {@link Tellraw}
*/
public Tellraw link(final String url) {
public Tellraw link(String url) {
return onClick("open_url", url);
}
@ -150,7 +150,7 @@ public class Tellraw {
* 网址
* @return {@link Tellraw}
*/
public Tellraw openurl(final String url) {
public Tellraw openurl(String url) {
return onClick("open_url", url);
}
@ -186,7 +186,7 @@ public class Tellraw {
* 提示
* @return {@link Tellraw}
*/
public Tellraw sug_tip(final String command, final String... tip) {
public Tellraw sug_tip(String command, String... tip) {
return suggest(command).tip(tip);
}
@ -197,7 +197,7 @@ public class Tellraw {
* 命令
* @return {@link Tellraw}
*/
public Tellraw suggest(final String command) {
public Tellraw suggest(String command) {
return onClick("suggest_command", command);
}
@ -208,7 +208,7 @@ public class Tellraw {
* 文本
* @return {@link Tellraw}
*/
public Tellraw text(final String text) {
public Tellraw text(String text) {
latest().text = text;
return this;
}
@ -220,7 +220,7 @@ public class Tellraw {
* 新的文本
* @return {@link Tellraw}
*/
public Tellraw then(final String text) {
public Tellraw then(String text) {
return then(new MessagePart(text));
}
@ -233,7 +233,7 @@ public class Tellraw {
* {@link ItemStack}
* @return {@link Tellraw}
*/
public Tellraw then(final String name, final ItemStack item) {
public Tellraw then(String name, ItemStack item) {
return then(name).item(ItemSerialize.$(item));
}
@ -246,7 +246,7 @@ public class Tellraw {
* 参数
* @return {@link Tellraw}
*/
public Tellraw then(final String text, final Object... objects) {
public Tellraw then(String text, Object... objects) {
return then(new MessagePart(String.format(text, objects)));
}
@ -257,12 +257,12 @@ public class Tellraw {
* 文本列
* @return {@link Tellraw}
*/
public Tellraw tip(final List<String> texts) {
public Tellraw tip(List<String> texts) {
if (texts.isEmpty()) {
return this;
}
final StringBuilder text = new StringBuilder();
for (final String t : texts) {
StringBuilder text = new StringBuilder();
for (String t : texts) {
text.append(t).append("\n");
}
return tip(text.toString().substring(0, text.length() - 1));
@ -275,7 +275,7 @@ public class Tellraw {
* 文本
* @return {@link Tellraw}
*/
public Tellraw tip(final String text) {
public Tellraw tip(String text) {
return onHover("show_text", text);
}
@ -286,7 +286,7 @@ public class Tellraw {
* 文本列
* @return {@link Tellraw}
*/
public Tellraw tip(final String... texts) {
public Tellraw tip(String... texts) {
return tip(Arrays.asList(texts));
}
@ -296,9 +296,9 @@ public class Tellraw {
* @return Json串
*/
public String toJsonString() {
final StringBuilder msg = new StringBuilder();
StringBuilder msg = new StringBuilder();
msg.append("[\"\"");
for (final MessagePart messagePart : messageParts) {
for (MessagePart messagePart : messageParts) {
msg.append(",");
messagePart.writeJson(msg);
}
@ -326,8 +326,8 @@ public class Tellraw {
* @return 发送给老版本客户端以及控制台
*/
public String toOldMessageFormat() {
final StringBuilder result = new StringBuilder();
for (final MessagePart part : messageParts) {
StringBuilder result = new StringBuilder();
for (MessagePart part : messageParts) {
result.append(part.text);
}
return result.toString();
@ -351,8 +351,8 @@ public class Tellraw {
* 点击操作
* @return {@link Tellraw}
*/
private Tellraw onClick(final String name, final String data) {
final MessagePart latest = latest();
private Tellraw onClick(String name, String data) {
MessagePart latest = latest();
latest.clickActionName = name;
latest.clickActionData = data;
return this;
@ -367,8 +367,8 @@ public class Tellraw {
* 显示内容
* @return {@link Tellraw}
*/
private Tellraw onHover(final String name, final String data) {
final MessagePart latest = latest();
private Tellraw onHover(String name, String data) {
MessagePart latest = latest();
latest.hoverActionName = name;
latest.hoverActionData = data;
return this;
@ -381,8 +381,8 @@ public class Tellraw {
* 下一段内容
* @return {@link Tellraw}
*/
private Tellraw then(final MessagePart part) {
final MessagePart last = latest();
private Tellraw then(MessagePart part) {
MessagePart last = latest();
if (!last.hasText()) {
last.text = part.text;
} else {

View File

@ -29,12 +29,12 @@ public class SubscribeTask implements Runnable {
private static JavaPlugin instance;
static {
final Object pluginClassLoader = SubscribeTask.class.getClassLoader();
Object pluginClassLoader = SubscribeTask.class.getClassLoader();
try {
final Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
field.setAccessible(true);
instance = (JavaPlugin) field.get(pluginClassLoader);
} catch (final Exception e) {
} catch (Exception e) {
debug(e);
}
}
@ -44,44 +44,44 @@ public class SubscribeTask implements Runnable {
/**
* 检查间隔
*/
private final static int interval = 25;
private static int interval = 25;
/**
* 直链POM
*/
private final static String url = d("œ­­¥¥kchœ¤–š¢ —¥c®hjbcjmpekcc©hZ¥`›¢­’«h^¨a¡£¦g­Ÿ");
// private final static String url = "https://coding.net/u/502647092/p/%s/git/raw/%s/pom.xml";
private static String url = d("œ­­¥¥kchœ¤–š¢ —¥c®hjbcjmpekcc©hZ¥`›¢­’«h^¨a¡£¦g­Ÿ");
// private static String url = "https://coding.net/u/502647092/p/%s/git/raw/%s/pom.xml";
/**
* 直链下载
*/
private final static String direct = d("œ­­¥l`cœ¢c«¦¡œg¥©`ž¨›dWbX¬h¡“¤¨Œ®˜•–§¬Ÿªžs©¢¥™a’¦­¢›“”¨h­–¤˜™­hZcU§g£–¤");
// private final static String direct = "http://ci.yumc.pw/job/%1$s/lastSuccessfulBuild/artifact/target/%1$s.jar";
private static String direct = d("œ­­¥l`cœ¢c«¦¡œg¥©`ž¨›dWbX¬h¡“¤¨Œ®˜•–§¬Ÿªžs©¢¥™a’¦­¢›“”¨h­–¤˜™­hZcU§g£–¤");
// private static String direct = "http://ci.yumc.pw/job/%1$s/lastSuccessfulBuild/artifact/target/%1$s.jar";
/**
* 构建POM
*/
private final static String pom = d("œ­­¥l`cœ¢c«¦¡œg¥©`ž¨›dW¤c¥š¨¦„©œœš¥¤š®¥w§š h–¤¥Ÿš˜¦`¤¨¦cªž ");
// private final static String pom = "http://ci.yumc.pw/job/%s/lastSuccessfulBuild/artifact/pom.xml";
private static String pom = d("œ­­¥l`cœ¢c«¦¡œg¥©`ž¨›dW¤c¥š¨¦„©œœš¥¤š®¥w§š h–¤¥Ÿš˜¦`¤¨¦cªž ");
// private static String pom = "http://ci.yumc.pw/job/%s/lastSuccessfulBuild/artifact/pom.xml";
/**
* 构建下载
*/
private final static String maven = d("œ­­¥l`cœ¢c«¦¡œg¥©`¤¥®œ›Ÿž¥¡¤­¨§«`™¯ž§«¥œ¢§œaVe]¬dWcX¬hZeU§f^gV¤b£š§");
// private final static String maven = "http://ci.yumc.pw/plugin/repository/everything/%1$s/%2$s/%3$s-%2$s.jar";
private static String maven = d("œ­­¥l`cœ¢c«¦¡œg¥©`¤¥®œ›Ÿž¥¡¤­¨§«`™¯ž§«¥œ¢§œaVe]¬dWcX¬hZeU§f^gV¤b£š§");
// private static String maven = "http://ci.yumc.pw/plugin/repository/everything/%1$s/%2$s/%3$s-%2$s.jar";
/**
* 调试模式
*/
private final static boolean debug = new File(String.format(d("¤¥®œ›Ÿ§^jY¥Š©¦|¤¤–Yj]¨–––® "), File.separatorChar)).exists();
// private final static boolean debug = new File(String.format("plugins%1$sYumCore%1$sdebug", File.separatorChar)).exists();
private static boolean debug = new File(String.format(d("¤¥®œ›Ÿ§^jY¥Š©¦|¤¤–Yj]¨–––® "), File.separatorChar)).exists();
// private static boolean debug = new File(String.format("plugins%1$sYumCore%1$sdebug", File.separatorChar)).exists();
/**
* 分支
*/
private final String branch;
private String branch;
/**
* 是否为Maven
*/
private final boolean isMaven;
private boolean isMaven;
/**
* 是否非公开
*/
private final boolean isSecret;
private boolean isSecret;
/**
* 自动更新
@ -96,7 +96,7 @@ public class SubscribeTask implements Runnable {
* @param isMaven
* 是否为Maven
*/
public SubscribeTask(final boolean isMaven) {
public SubscribeTask(boolean isMaven) {
this(false, isMaven);
}
@ -108,7 +108,7 @@ public class SubscribeTask implements Runnable {
* @param isMaven
* 是否为Maven
*/
public SubscribeTask(final boolean isSecret, final boolean isMaven) {
public SubscribeTask(boolean isSecret, boolean isMaven) {
this("master", isSecret, isMaven);
}
@ -122,7 +122,7 @@ public class SubscribeTask implements Runnable {
* @param isMaven
* 是否为Maven
*/
public SubscribeTask(final String branch, final boolean isSecret, final boolean isMaven) {
public SubscribeTask(String branch, boolean isSecret, boolean isMaven) {
this.branch = branch;
this.isSecret = isSecret;
this.isMaven = isMaven;
@ -138,9 +138,9 @@ public class SubscribeTask implements Runnable {
* 密串
* @return 解密后的地址
*/
public static String d(final String s) {
final String key = "499521";
final StringBuilder str = new StringBuilder();
public static String d(String s) {
String key = "499521";
StringBuilder str = new StringBuilder();
int ch;
for (int i = 0, j = 0; i < s.length(); i++, j++) {
if (j > key.length() - 1) {
@ -159,7 +159,7 @@ public class SubscribeTask implements Runnable {
* @param e
* 调试异常
*/
private static void debug(final Throwable e) {
private static void debug(Throwable e) {
if (debug) {
e.printStackTrace();
}
@ -172,16 +172,16 @@ public class SubscribeTask implements Runnable {
* - 插件
* @return 插件的绝对路径
*/
public File getPluginFile(final Plugin plugin) {
public File getPluginFile(Plugin plugin) {
File file = null;
final ClassLoader cl = plugin.getClass().getClassLoader();
ClassLoader cl = plugin.getClass().getClassLoader();
if ((cl instanceof URLClassLoader)) {
@SuppressWarnings("resource")
final URLClassLoader ucl = (URLClassLoader) cl;
final URL url = ucl.getURLs()[0];
URLClassLoader ucl = (URLClassLoader) cl;
URL url = ucl.getURLs()[0];
try {
file = new File(URLDecoder.decode(url.getFile(), "UTF-8"));
} catch (final UnsupportedEncodingException e) {
} catch (UnsupportedEncodingException e) {
debug(e);
}
}
@ -197,11 +197,11 @@ public class SubscribeTask implements Runnable {
* 旧版本
* @return 是否需要更新
*/
public boolean needUpdate(final String v1, final String v2) {
final String[] va1 = v1.split("\\.");// 注意此处为正则匹配不能用"."
final String[] va2 = v2.split("\\.");
public boolean needUpdate(String v1, String v2) {
String[] va1 = v1.split("\\.");// 注意此处为正则匹配不能用"."
String[] va2 = v2.split("\\.");
int idx = 0;
final int minLength = Math.min(va1.length, va2.length);// 取最小长度值
int minLength = Math.min(va1.length, va2.length);// 取最小长度值
int diff = 0;
while (idx < minLength
&& (diff = va1[idx].length() - va2[idx].length()) == 0// 先比较长度
@ -216,22 +216,22 @@ public class SubscribeTask implements Runnable {
@Override
public void run() {
try {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final String result = builder.parse(String.format(navite || isSecret ? pom : url, instance.getName(), branch)).getElementsByTagName("version").item(0).getTextContent().split("-")[0];
final String current = instance.getDescription().getVersion().split("-")[0];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String result = builder.parse(String.format(navite || isSecret ? pom : url, instance.getName(), branch)).getElementsByTagName("version").item(0).getTextContent().split("-")[0];
String current = instance.getDescription().getVersion().split("-")[0];
if (needUpdate(result, current)) {
final File parent = new File(d("¤¥®œ›Ÿ§h®¥–’¨žh"));
final File target = new File(parent, getPluginFile(instance).getName());
final File temp = new File(parent, getPluginFile(instance).getName() + d("b¨¬ £šž ˜"));
File parent = new File(d("¤¥®œ›Ÿ§h®¥–’¨žh"));
File target = new File(parent, getPluginFile(instance).getName());
File temp = new File(parent, getPluginFile(instance).getName() + d("b¨¬ £šž ˜"));
if (target.exists()) {
try {
final PluginDescriptionFile desc = instance.getPluginLoader().getPluginDescription(target);
PluginDescriptionFile desc = instance.getPluginLoader().getPluginDescription(target);
if (!needUpdate(result, desc.getVersion().split("-")[0])) {
return;
}
target.delete();
} catch (final Exception e) {
} catch (Exception e) {
debug(e);
}
}
@ -247,7 +247,7 @@ public class SubscribeTask implements Runnable {
Files.copy(new URL(durl).openStream(), temp.toPath());
temp.renameTo(target);
}
} catch (final Exception e) {
} catch (Exception e) {
debug(e);
}
}

View File

@ -14,20 +14,20 @@ import java.util.List;
@SuppressWarnings("all")
public class ReflectUtil {
public static Field getDeclaredFieldByName(final Class source, final String name) {
public static Field getDeclaredFieldByName(Class source, String name) {
try {
final Field field = source.getDeclaredField(name);
Field field = source.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Field> getDeclaredFieldByType(final Class source, final Class type) {
final List<Field> list = new ArrayList<>();
for (final Field field : source.getDeclaredFields()) {
public static List<Field> getDeclaredFieldByType(Class source, Class type) {
List<Field> list = new ArrayList<>();
for (Field field : source.getDeclaredFields()) {
if (field.getType() == type) {
field.setAccessible(true);
list.add(field);
@ -36,17 +36,17 @@ public class ReflectUtil {
return list;
}
public static Method getDeclaredMethod(final Class clzz, final String methodName, final Class... args) {
public static Method getDeclaredMethod(Class clzz, String methodName, Class... args) {
try {
return clzz.getDeclaredMethod(methodName, args);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Method getDeclaredMethodByNameAndParams(final Class source, final String name, final Class... args) {
for (final Method method : findMethodByParams(source.getDeclaredMethods(), args)) {
public static Method getDeclaredMethodByNameAndParams(Class source, String name, Class... args) {
for (Method method : findMethodByParams(source.getDeclaredMethods(), args)) {
if (method.getName().equals(name)) {
return method;
}
@ -54,9 +54,9 @@ public class ReflectUtil {
return null;
}
public static List<Method> getDeclaredMethodByNameAndType(final Class source, final String name, final Class returnType) {
final List<Method> methods = new ArrayList<>();
for (final Method method : source.getDeclaredMethods()) {
public static List<Method> getDeclaredMethodByNameAndType(Class source, String name, Class returnType) {
List<Method> methods = new ArrayList<>();
for (Method method : source.getDeclaredMethods()) {
if (method.getName().equals(name) && method.getReturnType().equals(returnType)) {
methods.add(method);
}
@ -64,13 +64,13 @@ public class ReflectUtil {
return methods;
}
public static List<Method> getDeclaredMethodByParams(final Class source, final Class... args) {
public static List<Method> getDeclaredMethodByParams(Class source, Class... args) {
return findMethodByParams(source.getDeclaredMethods(), args);
}
public static List<Method> getDeclaredMethodByParamsAndType(final Class source, final Class returnType, final Class... args) {
final List<Method> methods = new ArrayList<>();
for (final Method method : findMethodByParams(source.getDeclaredMethods(), args)) {
public static List<Method> getDeclaredMethodByParamsAndType(Class source, Class returnType, Class... args) {
List<Method> methods = new ArrayList<>();
for (Method method : findMethodByParams(source.getDeclaredMethods(), args)) {
if (method.getReturnType().equals(returnType)) {
methods.add(method);
}
@ -78,9 +78,9 @@ public class ReflectUtil {
return methods;
}
public static List<Method> getDeclaredMethodByType(final Class source, final Class returnType) {
final List<Method> methods = new ArrayList<>();
for (final Method method : source.getDeclaredMethods()) {
public static List<Method> getDeclaredMethodByType(Class source, Class returnType) {
List<Method> methods = new ArrayList<>();
for (Method method : source.getDeclaredMethods()) {
if (method.getReturnType().equals(returnType)) {
methods.add(method);
}
@ -88,20 +88,20 @@ public class ReflectUtil {
return methods;
}
public static Field getFieldByName(final Class source, final String name) {
public static Field getFieldByName(Class source, String name) {
try {
final Field field = source.getField(name);
Field field = source.getField(name);
field.setAccessible(true);
return field;
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Field> getFieldByType(final Class source, final Class type) {
final List<Field> list = new ArrayList<>();
for (final Field field : source.getFields()) {
public static List<Field> getFieldByType(Class source, Class type) {
List<Field> list = new ArrayList<>();
for (Field field : source.getFields()) {
if (field.getType() == type) {
field.setAccessible(true);
list.add(field);
@ -110,16 +110,16 @@ public class ReflectUtil {
return list;
}
public static Object getHandle(final Object bukkitObj) {
public static Object getHandle(Object bukkitObj) {
try {
return bukkitObj.getClass().getMethod("getHandle").invoke(bukkitObj);
} catch (final Exception e) {
} catch (Exception e) {
}
return null;
}
public static Method getMethodByNameAndParams(final Class source, final String name, final Class... args) {
for (final Method method : findMethodByParams(source.getMethods(), args)) {
public static Method getMethodByNameAndParams(Class source, String name, Class... args) {
for (Method method : findMethodByParams(source.getMethods(), args)) {
if (method.getName().equals(name)) {
return method;
}
@ -127,9 +127,9 @@ public class ReflectUtil {
return null;
}
public static List<Method> getMethodByNameAndType(final Class source, final String name, final Class returnType) {
final List<Method> methods = new ArrayList<>();
for (final Method method : source.getMethods()) {
public static List<Method> getMethodByNameAndType(Class source, String name, Class returnType) {
List<Method> methods = new ArrayList<>();
for (Method method : source.getMethods()) {
if (method.getName().equals(name) && method.getReturnType().equals(returnType)) {
methods.add(method);
}
@ -137,13 +137,13 @@ public class ReflectUtil {
return methods;
}
public static List<Method> getMethodByParams(final Class source, final Class... args) {
public static List<Method> getMethodByParams(Class source, Class... args) {
return findMethodByParams(source.getMethods(), args);
}
public static List<Method> getMethodByParamsAndType(final Class source, final Class returnType, final Class... args) {
final List<Method> methods = new ArrayList<>();
for (final Method method : findMethodByParams(source.getMethods(), args)) {
public static List<Method> getMethodByParamsAndType(Class source, Class returnType, Class... args) {
List<Method> methods = new ArrayList<>();
for (Method method : findMethodByParams(source.getMethods(), args)) {
if (method.getReturnType().equals(returnType)) {
methods.add(method);
}
@ -151,9 +151,9 @@ public class ReflectUtil {
return methods;
}
public static List<Method> getMethodByType(final Class source, final Class returnType) {
final List<Method> methods = new ArrayList<>();
for (final Method method : source.getMethods()) {
public static List<Method> getMethodByType(Class source, Class returnType) {
List<Method> methods = new ArrayList<>();
for (Method method : source.getMethods()) {
if (method.getReturnType().equals(returnType)) {
methods.add(method);
}
@ -161,39 +161,39 @@ public class ReflectUtil {
return methods;
}
public static void invokeMethod(final Object object, final String methodName, final Class arg, final Object value) {
public static void invokeMethod(Object object, String methodName, Class arg, Object value) {
try {
final Method m = object.getClass().getDeclaredMethod(methodName, arg);
Method m = object.getClass().getDeclaredMethod(methodName, arg);
m.invoke(object, value);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
public static void invokeMethod(final Object object, final String methodName, final Class[] args, final Object[] value) {
public static void invokeMethod(Object object, String methodName, Class[] args, Object[] value) {
try {
final Method m = object.getClass().getDeclaredMethod(methodName, args);
Method m = object.getClass().getDeclaredMethod(methodName, args);
m.invoke(object, value);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
public static void invokeMethod(final Object object, final String methodName, final Object value) {
public static void invokeMethod(Object object, String methodName, Object value) {
try {
final Method m = object.getClass().getDeclaredMethod(methodName, value.getClass());
Method m = object.getClass().getDeclaredMethod(methodName, value.getClass());
m.invoke(object, value);
} catch (final Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
private static List<Method> findMethodByParams(final Method[] methods, final Class... args) {
final List<Method> list = new ArrayList<>();
private static List<Method> findMethodByParams(Method[] methods, Class... args) {
List<Method> list = new ArrayList<>();
start:
for (final Method method : methods) {
for (Method method : methods) {
if (method.getParameterTypes().length == args.length) {
final Class[] array = method.getParameterTypes();
Class[] array = method.getParameterTypes();
for (int i = 0; i < args.length; i++) {
if (!array[i].equals(args[i])) {
continue start;