Make use of the awesome Java 8 features

This commit is contained in:
games647
2016-09-16 17:40:42 +02:00
parent 31d6b67381
commit 17c2099bf1
15 changed files with 85 additions and 114 deletions

View File

@ -10,6 +10,7 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.stream.Stream;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
@ -48,9 +49,7 @@ public class EncryptionUtil {
private static byte[] digestOperation(String algo, byte[]... content) {
try {
MessageDigest messagedigest = MessageDigest.getInstance(algo);
for (byte[] data : content) {
messagedigest.update(data);
}
Stream.of(content).forEach(messagedigest::update);
return messagedigest.digest();
} catch (NoSuchAlgorithmException nosuchalgorithmexception) {

View File

@ -37,9 +37,10 @@ public class CrackedCommand implements CommandExecutor {
}
} else {
//todo: load async if
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName());
PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName());
if (profile.isPremium()) {
sender.sendMessage(plugin.getCore().getMessage("remove-premium"));
profile.setPremium(false);
profile.setUuid(null);
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
@ -72,7 +73,7 @@ public class CrackedCommand implements CommandExecutor {
}
} else {
//todo: load async
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]);
PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]);
if (profile == null) {
sender.sendMessage("Error occured");
return;

View File

@ -53,7 +53,7 @@ public class PremiumCommand implements CommandExecutor {
plugin.getCore().getPendingConfirms().remove(id);
//todo: load async
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName());
PlayerProfile profile = plugin.getCore().getStorage().loadProfile(sender.getName());
if (profile.isPremium()) {
sender.sendMessage(plugin.getCore().getMessage("already-exists"));
} else {
@ -89,7 +89,7 @@ public class PremiumCommand implements CommandExecutor {
}
} else {
//todo: load async
final PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]);
PlayerProfile profile = plugin.getCore().getStorage().loadProfile(args[0]);
if (profile == null) {
sender.sendMessage(plugin.getCore().getMessage("player-unknown"));
return;

View File

@ -29,10 +29,10 @@ public class CrazyLoginHook implements AuthPlugin<Player> {
private final PlayerListener playerListener = getListener();
@Override
public boolean forceLogin(final Player player) {
public boolean forceLogin(Player player) {
//not thread-safe operation
Future<LoginPlayerData> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> {
LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player.getName());
LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player);
if (playerData != null) {
//mark the account as logged in
playerData.setLoggedIn(true);

View File

@ -24,11 +24,10 @@ public class RoyalAuthHook implements AuthPlugin<Player> {
private final RoyalAuth royalAuthPlugin = (RoyalAuth) Bukkit.getPluginManager().getPlugin("RoyalAuth");
@Override
public boolean forceLogin(final Player player) {
//not thread-safe
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(royalAuthPlugin, () -> {
AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player);
public boolean forceLogin(Player player) {
AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player);
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(royalAuthPlugin, () -> {
//https://github.com/RoyalDev/RoyalAuth/blob/master/src/main/java/org/royaldev/royalauth/commands/CmdLogin.java#L62
//not thread-safe
authPlayer.login();
@ -56,11 +55,8 @@ public class RoyalAuthHook implements AuthPlugin<Player> {
AuthPlayer authPlayer = AuthPlayer.getAuthPlayer(player);
boolean registerSuccess = authPlayer.setPassword(password, Config.passwordHashType);
if (registerSuccess) {
//login in the player after registration
return forceLogin(player);
}
return false;
//login in the player after registration
return registerSuccess && forceLogin(player);
}
}

View File

@ -25,7 +25,7 @@ public class xAuthHook implements AuthPlugin<Player> {
protected final xAuth xAuthPlugin = xAuth.getPlugin();
@Override
public boolean forceLogin(final Player player) {
public boolean forceLogin(Player player) {
//not thread-safe
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(xAuthPlugin, () -> {
xAuthPlayer xAuthPlayer = xAuthPlugin.getPlayerManager().getPlayer(player);
@ -56,7 +56,7 @@ public class xAuthHook implements AuthPlugin<Player> {
}
@Override
public boolean forceRegister(final Player player, final String password) {
public boolean forceRegister(Player player, final String password) {
//not thread-safe
Future<Boolean> future = Bukkit.getScheduler().callSyncMethod(xAuthPlugin, () -> {
xAuthPlayer xAuthPlayer = xAuthPlugin.getPlayerManager().getPlayer(player);
@ -73,13 +73,8 @@ public class xAuthHook implements AuthPlugin<Player> {
});
try {
boolean success = future.get();
if (success) {
//login in the player after registration
return forceLogin(player);
}
return false;
//login in the player after registration
return future.get() && forceLogin(player);
} catch (InterruptedException | ExecutionException ex) {
xAuthPlugin.getLogger().log(Level.SEVERE, "Failed to forceLogin", ex);
return false;

View File

@ -5,7 +5,6 @@ import com.github.games647.fastlogin.bukkit.FastLoginBukkit;
import com.github.games647.fastlogin.bukkit.tasks.ForceLoginTask;
import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import com.google.common.base.Charsets;
import com.google.common.collect.Sets;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
@ -16,6 +15,7 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -42,7 +42,7 @@ public class BungeeCordListener implements PluginMessageListener {
}
@Override
public void onPluginMessageReceived(String channel, final Player player, byte[] message) {
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
if (!channel.equals(plugin.getName())) {
return;
}
@ -69,7 +69,7 @@ public class BungeeCordListener implements PluginMessageListener {
//fail if BungeeCord support is disabled (id = null)
if (proxyIds.contains(sourceId)) {
final String id = '/' + checkedPlayer.getAddress().getAddress().getHostAddress() + ':'
String id = '/' + checkedPlayer.getAddress().getAddress().getHostAddress() + ':'
+ checkedPlayer.getAddress().getPort();
if ("AUTO_LOGIN".equalsIgnoreCase(subchannel)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
@ -105,19 +105,8 @@ public class BungeeCordListener implements PluginMessageListener {
whitelistFile.createNewFile();
}
Set<UUID> ids = Sets.newHashSet();
List<String> lines = Files.readLines(whitelistFile, Charsets.UTF_8);
for (String line : lines) {
if (line == null || line.trim().isEmpty()) {
continue;
}
UUID uuid = UUID.fromString(line.trim());
ids.add(uuid);
}
return ids;
return lines.stream().map(String::trim).map(UUID::fromString).collect(Collectors.toSet());
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to create file for Proxy whitelist", ex);
} catch (Exception ex) {

View File

@ -42,17 +42,18 @@ public class LoginSkinApplyListener implements Listener {
Collection<BukkitLoginSession> sessions = plugin.getSessions().values();
for (BukkitLoginSession session : sessions) {
if (session.getUsername().equals(player.getName())) {
applySkin(player, session);
String signature = session.getSkinSignature();
String skinData = session.getEncodedSkinData();
applySkin(player, skinData, signature);
break;
}
}
}
}
private void applySkin(Player player, BukkitLoginSession session) {
private void applySkin(Player player, String skinData, String signature) {
WrappedGameProfile gameProfile = WrappedGameProfile.fromPlayer(player);
String skinData = session.getEncodedSkinData();
String signature = session.getSkinSignature();
if (skinData != null && signature != null) {
WrappedSignedProperty skin = WrappedSignedProperty.fromValues("textures", skinData, signature);
try {

View File

@ -56,6 +56,11 @@ public class VerifyResponseTask implements Runnable {
verifyResponse(session);
}
} finally {
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
}
@ -90,11 +95,6 @@ public class VerifyResponseTask implements Runnable {
, "Player {0} ({1}) tried to log in with an invalid session ServerId: {2}"
, session.getUsername(), fromPlayer.getAddress(), serverId);
}
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
}
private void setPremiumUUID(UUID premiumUUID) {
@ -169,10 +169,6 @@ public class VerifyResponseTask implements Runnable {
}
kickPlayer(packetEvent.getPlayer(), kickReason);
//cancel the event in order to prevent the server receiving an invalid packet
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
}
private void kickPlayer(Player player, String reason) {

View File

@ -43,6 +43,7 @@ public class DelayedAuthHook implements Runnable {
List<Class<? extends AuthPlugin<Player>>> supportedHooks = Lists.newArrayList(AuthMeHook.class
, CrazyLoginHook.class, LogItHook.class, LoginSecurityHook.class, UltraAuthHook.class
, xAuthHook.class);
for (Class<? extends AuthPlugin<Player>> clazz : supportedHooks) {
String pluginName = clazz.getSimpleName().replace("Hook", "");
//uses only member classes which uses AuthPlugin interface (skip interfaces)

View File

@ -1,18 +1,17 @@
package com.github.games647.fastlogin.bungee;
import com.github.games647.fastlogin.core.shared.FastLoginCore;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -24,13 +23,7 @@ import net.md_5.bungee.config.YamlConfiguration;
public class BungeeCore extends FastLoginCore<ProxiedPlayer> {
private static Map<String, Object> generateConfigMap(Configuration config) {
Map<String, Object> configMap = Maps.newHashMap();
Collection<String> keys = config.getKeys();
keys.forEach(key -> {
configMap.put(key, config.get(key));
});
return configMap;
return config.getKeys().stream().collect(Collectors.toMap(key -> key, key -> config.get(key)));
}
private final FastLoginBungee plugin;

View File

@ -1,6 +1,5 @@
package com.github.games647.fastlogin.bungee;
import com.github.games647.fastlogin.bungee.FastLoginBungee;
import com.github.games647.fastlogin.core.AuthStorage;
import com.github.games647.fastlogin.core.importer.ImportPlugin;

View File

@ -38,52 +38,56 @@ public class PluginMessageListener implements Listener {
//check if the message is sent from the server
if (Server.class.isAssignableFrom(pluginMessageEvent.getSender().getClass())) {
readMessage(pluginMessageEvent);
//so that we can safely process this in the background
byte[] data = Arrays.copyOf(pluginMessageEvent.getData(), pluginMessageEvent.getData().length);
ProxiedPlayer forPlayer = (ProxiedPlayer) pluginMessageEvent.getReceiver();
ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> {
readMessage(forPlayer, data);
});
}
}
private void readMessage(PluginMessageEvent pluginMessageEvent) {
//so that we can safely process this in the background
byte[] data = Arrays.copyOf(pluginMessageEvent.getData(), pluginMessageEvent.getData().length);
ProxiedPlayer forPlayer = (ProxiedPlayer) pluginMessageEvent.getReceiver();
private void readMessage(ProxiedPlayer forPlayer, byte[] data) {
ByteArrayDataInput dataInput = ByteStreams.newDataInput(data);
String subchannel = dataInput.readUTF();
if ("ON".equals(subchannel)) {
String playerName = dataInput.readUTF();
ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> {
ByteArrayDataInput dataInput = ByteStreams.newDataInput(data);
String subchannel = dataInput.readUTF();
if ("ON".equals(subchannel)) {
String playerName = dataInput.readUTF();
if (playerName.equals(forPlayer.getName()) && plugin.getConfig().getBoolean("premium-warning")
&& !plugin.getCore().getPendingConfirms().contains(forPlayer.getUniqueId())) {
String message = plugin.getCore().getMessage("premium-warning");
forPlayer.sendMessage(TextComponent.fromLegacyText(message));
plugin.getCore().getPendingConfirms().add(forPlayer.getUniqueId());
return;
}
plugin.getCore().getPendingConfirms().remove(forPlayer.getUniqueId());
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, true);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("OFF".equals(subchannel)) {
String playerName = dataInput.readUTF();
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, false);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("SUCCESS".equals(subchannel)) {
if (forPlayer.getPendingConnection().isOnlineMode()) {
//bukkit module successfully received and force logged in the user
//update only on success to prevent corrupt data
BungeeLoginSession loginSession = plugin.getSession().get(forPlayer.getPendingConnection());
PlayerProfile playerProfile = loginSession.getProfile();
loginSession.setRegistered(true);
if (!loginSession.isAlreadySaved()) {
playerProfile.setPremium(true);
plugin.getCore().getStorage().save(playerProfile);
loginSession.setAlreadySaved(true);
}
}
if (playerName.equals(forPlayer.getName()) && plugin.getConfig().getBoolean("premium-warning")
&& !plugin.getCore().getPendingConfirms().contains(forPlayer.getUniqueId())) {
String message = plugin.getCore().getMessage("premium-warning");
forPlayer.sendMessage(TextComponent.fromLegacyText(message));
plugin.getCore().getPendingConfirms().add(forPlayer.getUniqueId());
return;
}
});
plugin.getCore().getPendingConfirms().remove(forPlayer.getUniqueId());
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, true);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("OFF".equals(subchannel)) {
String playerName = dataInput.readUTF();
AsyncToggleMessage task = new AsyncToggleMessage(plugin, forPlayer, playerName, false);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("SUCCESS".equals(subchannel)) {
onSuccessMessage(forPlayer);
}
}
private void onSuccessMessage(ProxiedPlayer forPlayer) {
if (forPlayer.getPendingConnection().isOnlineMode()) {
//bukkit module successfully received and force logged in the user
//update only on success to prevent corrupt data
BungeeLoginSession loginSession = plugin.getSession().get(forPlayer.getPendingConnection());
PlayerProfile playerProfile = loginSession.getProfile();
loginSession.setRegistered(true);
if (!loginSession.isAlreadySaved()) {
playerProfile.setPremium(true);
plugin.getCore().getStorage().save(playerProfile);
loginSession.setAlreadySaved(true);
}
}
}
}

View File

@ -42,12 +42,9 @@ public abstract class FastLoginCore<P> {
builder.maximumSize(maxSize);
}
return builder.build(new CacheLoader<K, V>() {
@Override
public V load(K key) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
});
return builder.build(CacheLoader.from(() -> {
throw new UnsupportedOperationException();
}));
}
public static UUID parseId(String withoutDashes) {

View File

@ -62,7 +62,7 @@ public abstract class MojangApiConnector {
try {
InetAddress address = InetAddress.getByName(localAddress);
if (!address.isAnyLocalAddress()) {
logger.log(Level.WARNING, "Submitted IP-Address is not local", address);
logger.log(Level.WARNING, "Submitted IP-Address is not local {0}", address);
continue;
}