refactor: 调整编译版本为1.8 使用lambda表达式和stream

Signed-off-by: 502647092 <admin@yumc.pw>
merge/1/MERGE
502647092 2017-02-04 14:34:58 +08:00
parent 04e113bff2
commit 8c6647f8ee
19 changed files with 180 additions and 237 deletions

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>pw.yumc</groupId>
<artifactId>YumCore</artifactId>
<version>1.6</version>
<version>1.7</version>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
@ -52,8 +52,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<repositories>
<repository>

View File

@ -1,6 +1,7 @@
package pw.yumc.YumCore.bukkit;
import java.io.File;
import java.util.Arrays;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -276,9 +277,7 @@ public class Log {
*
*/
public static void sender(CommandSender sender, String[] msg) {
for (String str : msg) {
sender(sender, str);
}
Arrays.stream(msg).forEach(str -> sender(sender, str));
}
/**

View File

@ -43,7 +43,7 @@ public class P {
try {
getInjectConfigMethod = instance.getClass().getMethod("get" + instance.getName() + "Config");
} catch (NoSuchMethodException e) {
Log.d(e);
Log.d("配置方法 get%sConfig 未找到 将返回getConfig 调用结果!", instance.getName());
}
}
@ -141,9 +141,7 @@ public class P {
if (!je.isDirectory()) {
for (final String dir : dirs) {
if (je.getName().startsWith(dir)) {
if (!new File(getDataFolder(), je.getName()).exists()) {
instance.saveResource(je.getName(), false);
}
instance.saveResource(je.getName(), false);
}
}
}

View File

@ -12,6 +12,7 @@ import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.simple.JSONObject;
import com.google.common.base.Charsets;
@ -133,22 +134,18 @@ public class C {
*
*/
public static void broadcast(final String message, final int times) {
Bukkit.getScheduler().runTaskAsynchronously(P.instance, new Runnable() {
new BukkitRunnable() {
int time = times;
@Override
public void run() {
int time = times;
do {
for (org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
send(player, message);
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
time--;
} while (time > 0);
C.Player.getOnlinePlayers().forEach(player -> send(player, message));
time--;
if (time <= 0) {
cancel();
}
}
});
}.runTaskTimerAsynchronously(P.instance, 0, 20);
}
/**
@ -162,25 +159,18 @@ public class C {
*
*/
public static void broadcast(final World world, final String message, final int times) {
Bukkit.getScheduler().runTaskAsynchronously(P.instance, new Runnable() {
new BukkitRunnable() {
int time = times;
@Override
public void run() {
int time = times;
do {
for (org.bukkit.entity.Player player : C.Player.getOnlinePlayers()) {
if (player.getWorld().getName().equalsIgnoreCase(world.getName())) {
send(player, message);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
time--;
} while (time > 0);
C.Player.getOnlinePlayers().stream().filter(player -> player.getWorld().getName().equalsIgnoreCase(world.getName())).forEach(player -> send(player, message));
time--;
if (time <= 0) {
cancel();
}
}
});
}.runTaskTimerAsynchronously(P.instance, 0, 20);
}
/**
@ -206,20 +196,18 @@ public class C {
*
*/
public static void send(final org.bukkit.entity.Player receivingPacket, final String msg, final int times) {
Bukkit.getScheduler().runTaskAsynchronously(P.instance, new Runnable() {
new BukkitRunnable() {
int time = times;
@Override
public void run() {
int time = times;
do {
send(receivingPacket, msg);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
time--;
} while (time > 0);
send(receivingPacket, msg);
time--;
if (time <= 0) {
cancel();
}
}
});
}.runTaskTimerAsynchronously(P.instance, 0, 20);
}
}
@ -369,11 +357,7 @@ public class C {
*
*/
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);
}
}
C.Player.getOnlinePlayers().stream().filter(player -> player.getWorld().getName().equalsIgnoreCase(world.getName())).forEach(player -> send(player, title, subtitle));
}
/**

View File

@ -1,14 +1,21 @@
package pw.yumc.YumCore.commands;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.bukkit.command.CommandSender;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.info.CommandInfo;
import pw.yumc.YumCore.commands.interfaces.HelpGenerator;
import pw.yumc.YumCore.commands.interfaces.HelpParse;
import java.util.*;
/**
*
*
@ -63,8 +70,8 @@ public class CommandHelp {
public CommandHelp(CommandInfo defCmd, Collection<? extends CommandInfo> list) {
this.defCmd = defCmd;
cmdlist = new LinkedList<>(list);
Collections.sort(cmdlist, new CommandNameComparator());
Collections.sort(cmdlist, new CommandComparator());
cmdlist.sort(new CommandNameComparator());
cmdlist.sort(new CommandComparator());
HELPPAGECOUNT = (int) Math.ceil((double) cmdlist.size() / LINES_PER_PAGE);
}

View File

@ -1,18 +1,23 @@
package pw.yumc.YumCore.commands;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.commands.annotation.Option;
import pw.yumc.YumCore.commands.exception.ParseException;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
/**
*
*
@ -275,11 +280,11 @@ public class CommandParse {
}
public void throwRange() {
throwRange(null);
throwRange("");
}
public void throwRange(String str) {
throw new ParseException(String.format(str == null ? "范围必须在 %s 到 %s 之间!" : str, min, max));
throw new ParseException(String.format(str.isEmpty() ? "范围必须在 %s 到 %s 之间!" : str, min, max));
}
}

View File

@ -3,7 +3,6 @@ package pw.yumc.YumCore.commands;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -110,10 +109,10 @@ public class CommandSub implements TabExecutor {
*/
private void buildCmdNameCache() {
cmdNameCache.clear();
for (CommandInfo cmd : cmds) {
cmds.forEach(cmd -> {
cmdNameCache.add(cmd.getName());
cmdNameCache.addAll(Arrays.asList(cmd.getCommand().aliases()));
}
});
cmdNameCache.add("help");
}
@ -156,12 +155,8 @@ public class CommandSub implements TabExecutor {
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);
}
}
C.Player.getOnlinePlayers().stream().filter(player -> (senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(player.getName(), lastWord)).forEach(
player -> matchedPlayers.add(player.getName()));
return matchedPlayers;
}
@ -208,11 +203,9 @@ public class CommandSub implements TabExecutor {
if (args.length == 1) {
StringUtil.copyPartialMatches(token, cmdNameCache, completions);
}
for (CommandTabInfo tab : tabs) {
StringUtil.copyPartialMatches(token, tab.execute(sender, token, args), completions);
}
tabs.forEach(tab -> StringUtil.copyPartialMatches(token, tab.execute(sender, token, args), completions));
StringUtil.copyPartialMatches(token, getPlayerTabComplete(sender, command, alias, args), completions);
Collections.sort(completions, String.CASE_INSENSITIVE_ORDER);
completions.sort(String.CASE_INSENSITIVE_ORDER);
return completions;
}

View File

@ -1,7 +1,15 @@
package pw.yumc.YumCore.commands.info;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.bukkit.P;
import pw.yumc.YumCore.commands.CommandParse;
@ -10,14 +18,11 @@ import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Cmd.Executor;
import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.annotation.Sort;
import pw.yumc.YumCore.commands.exception.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import pw.yumc.YumCore.commands.exception.ArgumentException;
import pw.yumc.YumCore.commands.exception.CommandException;
import pw.yumc.YumCore.commands.exception.ParseException;
import pw.yumc.YumCore.commands.exception.PermissionException;
import pw.yumc.YumCore.commands.exception.SenderException;
/**
*
@ -122,16 +127,13 @@ public class CommandInfo {
public boolean execute(final CommandSender sender, final String label, final String[] args) {
if (method == null) { return false; }
check(sender, label, args);
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
method.invoke(origin, parse.parse(sender, label, args));
} catch (ParseException | ArgumentException e) {
Log.sender(sender, argErr, e.getMessage());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new CommandException(e);
}
Runnable runnable = () -> {
try {
method.invoke(origin, parse.parse(sender, label, args));
} catch (ParseException | ArgumentException e) {
Log.sender(sender, argErr, e.getMessage());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new CommandException(e);
}
};
if (async) {

View File

@ -53,23 +53,20 @@ public class I18N {
*
*/
private static void load() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Map<String, String> local = YumConfig.getLocal(LANG).getContentMap();
Map<String, String> remote = YumConfig.getRemote(LANG).getContentMap();
if (local != null) {
content.putAll(local);
}
if (remote != null) {
content.putAll(remote);
}
Log.i("本地化工具初始化完毕...");
} catch (Exception e) {
Log.w("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage());
Log.d(LANG, e);
new Thread(() -> {
try {
Map<String, String> local = YumConfig.getLocal(LANG).getContentMap();
Map<String, String> remote = YumConfig.getRemote(LANG).getContentMap();
if (local != null) {
content.putAll(local);
}
if (remote != null) {
content.putAll(remote);
}
Log.i("本地化工具初始化完毕...");
} catch (Exception e) {
Log.w("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage());
Log.d(LANG, e);
}
}).start();
}

View File

@ -115,25 +115,22 @@ public class L10N {
*
*/
private static void load() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Map<String, String> local = YumConfig.getLocal(CONFIG_NAME).getContentMap();
if (local != null) {
Log.i("本地汉化文件词条数量: " + local.size());
content.putAll(local);
}
Map<String, String> remote = YumConfig.getRemote(CONFIG_NAME).getContentMap();
if (remote != null) {
Log.i("远程汉化文件词条数量: " + remote.size());
content.putAll(remote);
}
Log.i("本地化工具初始化完毕...");
} catch (Exception e) {
Log.w("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage());
Log.d(CONFIG_NAME, e);
new Thread(() -> {
try {
Map<String, String> local = YumConfig.getLocal(CONFIG_NAME).getContentMap();
if (local != null) {
Log.i("本地汉化文件词条数量: " + local.size());
content.putAll(local);
}
Map<String, String> remote = YumConfig.getRemote(CONFIG_NAME).getContentMap();
if (remote != null) {
Log.i("远程汉化文件词条数量: " + remote.size());
content.putAll(remote);
}
Log.i("本地化工具初始化完毕...");
} catch (Exception e) {
Log.w("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage());
Log.d(CONFIG_NAME, e);
}
}).start();
}

View File

@ -14,7 +14,7 @@ public class ExKit {
*
*/
public static void throwException(final Throwable exception) {
ExKit.<RuntimeException> throwExceptionT(exception);
ExKit.throwExceptionT(exception);
}
/**
@ -29,6 +29,6 @@ public class ExKit {
*/
@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwExceptionT(final Throwable exception) throws T {
throw (T) exception;
if (exception != null) { throw (T) exception; }
}
}

View File

@ -9,7 +9,12 @@ import javax.activation.DataContentHandler;
import javax.activation.DataContentHandlerFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
@ -36,14 +41,11 @@ public class XMail {
handlers.put("message/rfc822", new com.sun.mail.handlers.message_rfc822());
handlers.put("image/gif", new com.sun.mail.handlers.image_gif());
handlers.put("image/jpeg", new com.sun.mail.handlers.image_jpeg());
defaultDataContentHandlerFactory = new DataContentHandlerFactory() {
@Override
public DataContentHandler createDataContentHandler(String type) {
DataContentHandler handler = handlers.get(type);
if (handler != null) { return handler; }
System.out.println("************* Unknown Type: " + type + " *************");
return null;
}
defaultDataContentHandlerFactory = type -> {
DataContentHandler handler = handlers.get(type);
if (handler != null) { return handler; }
System.out.println("************* Unknown Type: " + type + " *************");
return null;
};
}

View File

@ -55,8 +55,7 @@ public class ServerInfo {
* @return
*/
public boolean fetchData() {
try {
Socket socket = new Socket();
try (Socket socket = new Socket()) {
OutputStream outputStream;
DataOutputStream dataOutputStream;
InputStream inputStream;

View File

@ -1,6 +1,12 @@
package pw.yumc.YumCore.reflect;
import java.lang.reflect.*;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
@ -283,34 +289,31 @@ public class Reflect {
*/
public <P> P as(final Class<P> proxyType) {
final boolean isMap = (object instanceof Map);
final InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final String name = method.getName();
final InvocationHandler handler = (proxy, method, args) -> {
final String name = method.getName();
// Actual method name matches always come first
try {
return on(object).call(name, args).get();
}
// Actual method name matches always come first
try {
return on(object).call(name, args).get();
}
// [#14] Simulate POJO behaviour on wrapped map objects
catch (final ReflectException e) {
if (isMap) {
final Map<String, Object> map = (Map<String, Object>) object;
final int length = (args == null ? 0 : args.length);
// [#14] Simulate POJO behaviour on wrapped map objects
catch (final ReflectException e) {
if (isMap) {
final Map<String, Object> map = (Map<String, Object>) object;
final int length = (args == null ? 0 : args.length);
if (length == 0 && name.startsWith("get")) {
return map.get(property(name.substring(3)));
} else if (length == 0 && name.startsWith("is")) {
return map.get(property(name.substring(2)));
} else if (length == 1 && name.startsWith("set")) {
map.put(property(name.substring(3)), args[0]);
return null;
}
if (length == 0 && name.startsWith("get")) {
return map.get(property(name.substring(3)));
} else if (length == 0 && name.startsWith("is")) {
return map.get(property(name.substring(2)));
} else if (length == 1 && name.startsWith("set")) {
map.put(property(name.substring(3)), args[0]);
return null;
}
throw e;
}
throw e;
}
};

View File

@ -263,29 +263,6 @@ public class DataBase {
return kvlist;
}
// @SuppressWarnings("unchecked")
// 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 {
// ResultSet dbresult = this.dataBaseCore.execute(sql);
// while (dbresult.next()) {
// M m = (M) model.newInstance();
// Field[] fields = model.getDeclaredFields();
// for ( Field col : fields) {
// col.set(m, dbresult.getObject(col.getName()));
// }
// modellist.add(m);
// }
// } catch ( InstantiationException e) {
// info("模型类实例化失败!");
// e.printStackTrace();
// } catch ( Exception e) {
// sqlerr(sql, e);
// }
// return modellist;
// }
/**
*
*
@ -500,16 +477,4 @@ public class DataBase {
return DataBase.create(P.instance, config.getConfigurationSection(path));
}
}
// 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("`, ");
// }
// return sb.toString().substring(0, sb.length() - 2);
// }
}

View File

@ -54,7 +54,7 @@ public class KeyValue {
* @return
*/
public String[] getKeys() {
return this.keyvalues.keySet().toArray(new String[0]);
return this.keyvalues.keySet().toArray(new String[] {});
}
/**
@ -79,7 +79,7 @@ public class KeyValue {
for (Entry<Object, Object> next : this.keyvalues.entrySet()) {
keys.add(next.getValue());
}
return keys.toArray(new Object[0]);
return keys.toArray(new Object[keys.size()]);
}
/**

View File

@ -3,17 +3,11 @@
*/
package pw.yumc.YumCore.statistic;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
@ -25,6 +19,16 @@ import java.util.LinkedList;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/**
* Yum
*
@ -209,15 +213,12 @@ public class Statistics {
// 开启TPS统计线程
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, timer, 0, 20);
// 开启发送数据线程
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
postPlugin();
} catch (Throwable e) {
if (debug) {
e.printStackTrace();
}
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, () -> {
try {
postPlugin();
} catch (Throwable e) {
if (debug) {
e.printStackTrace();
}
}
}, 50, 25 * 1200);

View File

@ -268,9 +268,7 @@ public class Tellraw implements Cloneable {
public Tellraw tip(List<String> texts) {
if (texts.isEmpty()) { return this; }
StringBuilder text = new StringBuilder();
for (String t : texts) {
text.append(t).append("\n");
}
texts.forEach(t -> text.append(t).append("\n"));
return tip(text.toString().substring(0, text.length() - 1));
}
@ -344,9 +342,7 @@ public class Tellraw implements Cloneable {
*/
public String toOldMessageFormat() {
StringBuilder result = new StringBuilder();
for (MessagePart part : messageParts) {
result.append(part.text);
}
messageParts.forEach(part -> result.append(part.text));
return result.toString();
}

View File

@ -135,12 +135,7 @@ public class SubscribeTask implements Runnable, Listener {
public void onJoin(PlayerJoinEvent e) {
final Player player = e.getPlayer();
if (player.isOp() && updateFile.isUpdated()) {
Bukkit.getScheduler().runTaskLater(instance, new Runnable() {
@Override
public void run() {
versionInfo.notify(player);
}
}, 10);
Bukkit.getScheduler().runTaskLater(instance, () -> versionInfo.notify(player), 10);
}
}