Use Optionals for nullable values

This commit is contained in:
games647
2017-09-24 19:50:42 +02:00
parent e6c23a4bb5
commit 1f917f3a8d
13 changed files with 55 additions and 55 deletions

View File

@ -20,7 +20,7 @@
* Minor cleanup using inspections + Https * Minor cleanup using inspections + Https
* Increase hook delay to let ProtocolLib inject the listener * Increase hook delay to let ProtocolLib inject the listener
* Drop support for old AuthMe API + Add support for new AuthMe API * Drop support for old AuthMe API + Add support for new AuthMe API
* Remove ebean util usage to make it compatible with 1.12 * Remove eBean util usage to make it compatible with 1.12
* Do not try to hook into a plugin if auth plugin hook is already set using the FastLogin API * Do not try to hook into a plugin if auth plugin hook is already set using the FastLogin API
* Automatically register accounts if they are not in the auth plugin database but in the FastLogin database * Automatically register accounts if they are not in the auth plugin database but in the FastLogin database
* Update BungeeAuth dependency and use the new API. Please update your plugin if you still use the old one. * Update BungeeAuth dependency and use the new API. Please update your plugin if you still use the old one.
@ -38,7 +38,7 @@
* Added missing add-premium-other message * Added missing add-premium-other message
* Upgrade to Java 8 -> Minimize file size * Upgrade to Java 8 -> Minimize file size
* Refactored/Cleaned up a lot of code * Refactored/Cleaned up a lot of code
* [API] Deprecated platform specific authplugin. Please use AuthPlugin< platform specific player type > * [API] Deprecated platform specific auth-plugin. Please use AuthPlugin< platform specific player type >
* [API] Deprecated bukkit's password generator. Please use PasswordGenerator< platform specific player type > * [API] Deprecated bukkit's password generator. Please use PasswordGenerator< platform specific player type >
* Fix ProtocolSupport autoRegister * Fix ProtocolSupport autoRegister
* Fix update username in FastLogin database after nameChange * Fix update username in FastLogin database after nameChange
@ -61,7 +61,7 @@
### 1.7.1 ### 1.7.1
* Fix BungeeCord autoRegister (Fixes #46) * Fix BungeeCord autoRegister (Fixes #46)
* Fix protocollsupport autoregister * Fix ProtocolSupport auto-register
### 1.7 ### 1.7
@ -175,7 +175,7 @@
* Removes the need of an Bukkit auth plugin if you use a bungeecord one * Removes the need of an Bukkit auth plugin if you use a bungeecord one
* Optimize performance and thread-safety * Optimize performance and thread-safety
* Fixed BungeeCord support * Fixed BungeeCord support
* Changed config option autologin to autoregister to clarify the usage * Changed config option auto-login to auto-register to clarify the usage
### 0.6 ### 0.6
@ -185,19 +185,19 @@
### 0.5 ### 0.5
* Added cracked command * Added cracked command
* Added autologin - See config * Added auto-login - See config
* Added config * Added config
* Added isRegistered API method * Added isRegistered API method
* Added forceRegister API method * Added forceRegister API method
* Fixed CrazyLogin player data restore -> Fixes memory leaks with this plugin * Fixed CrazyLogin player data restore -> Fixes memory leaks with this plugin
* Fixed premium name check to protocolsupport * Fixed premium name check to ProtocolSupport
* Improved permissions management * Improved permissions management
### 0.4 ### 0.4
* Added forward premium skin * Added forward premium skin
* Added plugin support for protocolsupport * Added plugin support for ProtocolSupport
### 0.3.2 ### 0.3.2
@ -223,7 +223,7 @@
### 0.2.3 ### 0.2.3
* Remove useless AuthMe forcelogin code * Remove useless AuthMe force-login code
* Send a kick message to the client instead of just "Disconnect" * Send a kick message to the client instead of just "Disconnect"
* Reformat source code * Reformat source code
* Fix thread safety for fake start packets (Bukkit.getOfflinePlayer doesn't look like to be thread-safe) * Fix thread safety for fake start packets (Bukkit.getOfflinePlayer doesn't look like to be thread-safe)

View File

@ -2,8 +2,8 @@ package com.github.games647.fastlogin.bukkit;
import com.github.games647.fastlogin.bukkit.commands.CrackedCommand; import com.github.games647.fastlogin.bukkit.commands.CrackedCommand;
import com.github.games647.fastlogin.bukkit.commands.PremiumCommand; import com.github.games647.fastlogin.bukkit.commands.PremiumCommand;
import com.github.games647.fastlogin.bukkit.listener.BukkitJoinListener; import com.github.games647.fastlogin.bukkit.listener.JoinListener;
import com.github.games647.fastlogin.bukkit.listener.BungeeCordListener; import com.github.games647.fastlogin.bukkit.listener.BungeeListener;
import com.github.games647.fastlogin.bukkit.listener.protocollib.LoginSkinApplyListener; import com.github.games647.fastlogin.bukkit.listener.protocollib.LoginSkinApplyListener;
import com.github.games647.fastlogin.bukkit.listener.protocollib.ProtocolLibListener; import com.github.games647.fastlogin.bukkit.listener.protocollib.ProtocolLibListener;
import com.github.games647.fastlogin.bukkit.listener.protocolsupport.ProtocolSupportListener; import com.github.games647.fastlogin.bukkit.listener.protocolsupport.ProtocolSupportListener;
@ -66,7 +66,7 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
setServerStarted(); setServerStarted();
//check for incoming messages from the bungeecord version of this plugin //check for incoming messages from the bungeecord version of this plugin
getServer().getMessenger().registerIncomingPluginChannel(this, getName(), new BungeeCordListener(this)); getServer().getMessenger().registerIncomingPluginChannel(this, getName(), new BungeeListener(this));
getServer().getMessenger().registerOutgoingPluginChannel(this, getName()); getServer().getMessenger().registerOutgoingPluginChannel(this, getName());
//register listeners on success //register listeners on success
} else { } else {
@ -93,7 +93,7 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
//delay dependency setup because we load the plugin very early where plugins are initialized yet //delay dependency setup because we load the plugin very early where plugins are initialized yet
getServer().getScheduler().runTaskLater(this, new DelayedAuthHook(this), 5L); getServer().getScheduler().runTaskLater(this, new DelayedAuthHook(this), 5L);
getServer().getPluginManager().registerEvents(new BukkitJoinListener(this), this); getServer().getPluginManager().registerEvents(new JoinListener(this), this);
//register commands using a unique name //register commands using a unique name
getCommand("premium").setExecutor(new PremiumCommand(this)); getCommand("premium").setExecutor(new PremiumCommand(this));
@ -122,8 +122,8 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
} }
public void sendBungeeActivateMessage(CommandSender sender, String target, boolean activate) { public void sendBungeeActivateMessage(CommandSender sender, String target, boolean activate) {
if (sender instanceof Player) { if (sender instanceof PluginMessageRecipient) {
notifyBungeeCord((Player) sender, target, activate, true); notifyBungeeCord((PluginMessageRecipient) sender, target, activate, true);
} else { } else {
Player firstPlayer = Iterables.getFirst(getServer().getOnlinePlayers(), null); Player firstPlayer = Iterables.getFirst(getServer().getOnlinePlayers(), null);
if (firstPlayer == null) { if (firstPlayer == null) {

View File

@ -8,6 +8,7 @@ import de.st_ddt.crazylogin.databases.CrazyLoginDataDatabase;
import de.st_ddt.crazylogin.listener.PlayerListener; import de.st_ddt.crazylogin.listener.PlayerListener;
import de.st_ddt.crazylogin.metadata.Authenticated; import de.st_ddt.crazylogin.metadata.Authenticated;
import java.util.Optional;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.logging.Level; import java.util.logging.Level;
@ -31,7 +32,7 @@ public class CrazyLoginHook implements AuthPlugin<Player> {
@Override @Override
public boolean forceLogin(Player player) { public boolean forceLogin(Player player) {
//not thread-safe operation //not thread-safe operation
Future<LoginPlayerData> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> { Future<Optional<LoginPlayerData>> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> {
LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player); LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player);
if (playerData != null) { if (playerData != null) {
//mark the account as logged in //mark the account as logged in
@ -56,17 +57,17 @@ public class CrazyLoginHook implements AuthPlugin<Player> {
playerData.addIP(ip); playerData.addIP(ip);
player.setMetadata("Authenticated", new Authenticated(crazyLoginPlugin, player)); player.setMetadata("Authenticated", new Authenticated(crazyLoginPlugin, player));
crazyLoginPlugin.unregisterDynamicHooks(); crazyLoginPlugin.unregisterDynamicHooks();
return playerData; return Optional.of(playerData);
} }
return null; return Optional.empty();
}); });
try { try {
LoginPlayerData result = future.get(); Optional<LoginPlayerData> result = future.get().filter(LoginPlayerData::isLoggedIn);
if (result != null && result.isLoggedIn()) { if (result.isPresent()) {
//SQL-Queries should run async //SQL-Queries should run async
crazyLoginPlugin.getCrazyDatabase().saveWithoutPassword(result); crazyLoginPlugin.getCrazyDatabase().saveWithoutPassword(result.get());
return true; return true;
} }
} catch (InterruptedException | ExecutionException ex) { } catch (InterruptedException | ExecutionException ex) {

View File

@ -27,7 +27,7 @@ import org.bukkit.plugin.messaging.PluginMessageListener;
* This class also receives the plugin message from the bungeecord version of this plugin in order to get notified if * This class also receives the plugin message from the bungeecord version of this plugin in order to get notified if
* the connection is in online mode. * the connection is in online mode.
*/ */
public class BungeeCordListener implements PluginMessageListener { public class BungeeListener implements PluginMessageListener {
private static final String FILE_NAME = "proxy-whitelist.txt"; private static final String FILE_NAME = "proxy-whitelist.txt";
@ -35,7 +35,7 @@ public class BungeeCordListener implements PluginMessageListener {
//null if whitelist is empty so bungeecord support is disabled //null if whitelist is empty so bungeecord support is disabled
private final Set<UUID> proxyIds; private final Set<UUID> proxyIds;
public BungeeCordListener(FastLoginBukkit plugin) { public BungeeListener(FastLoginBukkit plugin) {
this.plugin = plugin; this.plugin = plugin;
this.proxyIds = loadBungeeCordIds(); this.proxyIds = loadBungeeCordIds();
} }
@ -70,15 +70,15 @@ public class BungeeCordListener implements PluginMessageListener {
} }
} }
private void readMessage(Player checkedPlayer, String subchannel, String playerName, Player player) { private void readMessage(Player checkedPlayer, String subChannel, String playerName, Player player) {
InetSocketAddress address = checkedPlayer.getAddress(); InetSocketAddress address = checkedPlayer.getAddress();
String id = '/' + address.getAddress().getHostAddress() + ':' + address.getPort(); String id = '/' + address.getAddress().getHostAddress() + ':' + address.getPort();
if ("AUTO_LOGIN".equalsIgnoreCase(subchannel)) { if ("AUTO_LOGIN".equalsIgnoreCase(subChannel)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true); BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
playerSession.setVerified(true); playerSession.setVerified(true);
plugin.getLoginSessions().put(id, playerSession); plugin.getLoginSessions().put(id, playerSession);
Bukkit.getScheduler().runTaskAsynchronously(plugin, new ForceLoginTask(plugin.getCore(), player)); Bukkit.getScheduler().runTaskAsynchronously(plugin, new ForceLoginTask(plugin.getCore(), player));
} else if ("AUTO_REGISTER".equalsIgnoreCase(subchannel)) { } else if ("AUTO_REGISTER".equalsIgnoreCase(subChannel)) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook(); AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook();
try { try {

View File

@ -17,13 +17,13 @@ import org.bukkit.event.player.PlayerQuitEvent;
* This listener tells authentication plugins if the player has a premium account and we checked it successfully. So the * This listener tells authentication plugins if the player has a premium account and we checked it successfully. So the
* plugin can skip authentication. * plugin can skip authentication.
*/ */
public class BukkitJoinListener implements Listener { public class JoinListener implements Listener {
private static final long DELAY_LOGIN = 20L / 2; private static final long DELAY_LOGIN = 20L / 2;
private final FastLoginBukkit plugin; private final FastLoginBukkit plugin;
public BukkitJoinListener(FastLoginBukkit plugin) { public JoinListener(FastLoginBukkit plugin) {
this.plugin = plugin; this.plugin = plugin;
} }

View File

@ -53,7 +53,7 @@ public class ForceLoginTask extends ForceLoginManagement<Player, CommandSender,
@Override @Override
public boolean isOnline(Player player) { public boolean isOnline(Player player) {
try { try {
//the playerlist isn't thread-safe //the player-list isn't thread-safe
return Bukkit.getScheduler().callSyncMethod(core.getPlugin(), player::isOnline).get(); return Bukkit.getScheduler().callSyncMethod(core.getPlugin(), player::isOnline).get();
} catch (InterruptedException | ExecutionException ex) { } catch (InterruptedException | ExecutionException ex) {
core.getPlugin().getLogger().log(Level.SEVERE, "Failed to perform thread-safe online check", ex); core.getPlugin().getLogger().log(Level.SEVERE, "Failed to perform thread-safe online check", ex);

View File

@ -1,8 +1,8 @@
package com.github.games647.fastlogin.bungee; package com.github.games647.fastlogin.bungee;
import com.github.games647.fastlogin.bungee.hooks.BungeeAuthHook; import com.github.games647.fastlogin.bungee.hooks.BungeeAuthHook;
import com.github.games647.fastlogin.bungee.listener.ConnectionListener; import com.github.games647.fastlogin.bungee.listener.ConnectListener;
import com.github.games647.fastlogin.bungee.listener.PluginMessageListener; import com.github.games647.fastlogin.bungee.listener.MessageListener;
import com.github.games647.fastlogin.core.mojang.MojangApiConnector; import com.github.games647.fastlogin.core.mojang.MojangApiConnector;
import com.github.games647.fastlogin.core.shared.FastLoginCore; import com.github.games647.fastlogin.core.shared.FastLoginCore;
import com.github.games647.fastlogin.core.shared.PlatformPlugin; import com.github.games647.fastlogin.core.shared.PlatformPlugin;
@ -38,8 +38,8 @@ public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSen
} }
//events //events
getProxy().getPluginManager().registerListener(this, new ConnectionListener(this)); getProxy().getPluginManager().registerListener(this, new ConnectListener(this));
getProxy().getPluginManager().registerListener(this, new PluginMessageListener(this)); getProxy().getPluginManager().registerListener(this, new MessageListener(this));
//this is required to listen to messages from the server //this is required to listen to messages from the server
getProxy().registerChannel(getDescription().getName()); getProxy().registerChannel(getDescription().getName());

View File

@ -31,11 +31,11 @@ import net.md_5.bungee.event.EventPriority;
* plugin message to the Bukkit version of this plugin in * plugin message to the Bukkit version of this plugin in
* order to clear that the connection is online mode. * order to clear that the connection is online mode.
*/ */
public class ConnectionListener implements Listener { public class ConnectListener implements Listener {
private final FastLoginBungee plugin; private final FastLoginBungee plugin;
public ConnectionListener(FastLoginBungee plugin) { public ConnectListener(FastLoginBungee plugin) {
this.plugin = plugin; this.plugin = plugin;
} }

View File

@ -19,11 +19,11 @@ import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventHandler;
public class PluginMessageListener implements Listener { public class MessageListener implements Listener {
private final FastLoginBungee plugin; private final FastLoginBungee plugin;
public PluginMessageListener(FastLoginBungee plugin) { public MessageListener(FastLoginBungee plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@ -52,10 +52,10 @@ public class PluginMessageListener implements Listener {
FastLoginCore<ProxiedPlayer, CommandSender, FastLoginBungee> core = plugin.getCore(); FastLoginCore<ProxiedPlayer, CommandSender, FastLoginBungee> core = plugin.getCore();
ByteArrayDataInput dataInput = ByteStreams.newDataInput(data); ByteArrayDataInput dataInput = ByteStreams.newDataInput(data);
String subchannel = dataInput.readUTF(); String subChannel = dataInput.readUTF();
if ("SUCCESS".equals(subchannel)) { if ("SUCCESS".equals(subChannel)) {
onSuccessMessage(forPlayer); onSuccessMessage(forPlayer);
} else if ("ON".equals(subchannel)) { } else if ("ON".equals(subChannel)) {
String playerName = dataInput.readUTF(); String playerName = dataInput.readUTF();
boolean isPlayerSender = dataInput.readBoolean(); boolean isPlayerSender = dataInput.readBoolean();
@ -70,7 +70,7 @@ public class PluginMessageListener implements Listener {
core.getPendingConfirms().remove(forPlayer.getUniqueId()); core.getPendingConfirms().remove(forPlayer.getUniqueId());
Runnable task = new AsyncToggleMessage(core, forPlayer, playerName, true, isPlayerSender); Runnable task = new AsyncToggleMessage(core, forPlayer, playerName, true, isPlayerSender);
ProxyServer.getInstance().getScheduler().runAsync(plugin, task); ProxyServer.getInstance().getScheduler().runAsync(plugin, task);
} else if ("OFF".equals(subchannel)) { } else if ("OFF".equals(subChannel)) {
String playerName = dataInput.readUTF(); String playerName = dataInput.readUTF();
boolean isPlayerSender = dataInput.readBoolean(); boolean isPlayerSender = dataInput.readBoolean();

View File

@ -28,10 +28,6 @@ public class CommonUtil {
} }
public static UUID parseId(String withoutDashes) { public static UUID parseId(String withoutDashes) {
if (withoutDashes == null) {
return null;
}
return UUID.fromString(withoutDashes.substring(0, 8) return UUID.fromString(withoutDashes.substring(0, 8)
+ '-' + withoutDashes.substring(8, 12) + '-' + withoutDashes.substring(8, 12)
+ '-' + withoutDashes.substring(12, 16) + '-' + withoutDashes.substring(12, 16)

View File

@ -24,6 +24,7 @@ import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
@ -58,7 +59,7 @@ public class MojangApiConnector {
protected final Logger logger; protected final Logger logger;
public MojangApiConnector(Logger logger, Collection<String> localAddresses, int rateLimit public MojangApiConnector(Logger logger, Collection<String> localAddresses, int rateLimit
, List<HostAndPort> proxies) { , Iterable<HostAndPort> proxies) {
this.logger = logger; this.logger = logger;
this.rateLimit = Math.max(rateLimit, 600); this.rateLimit = Math.max(rateLimit, 600);
this.sslFactory = buildAddresses(logger, localAddresses); this.sslFactory = buildAddresses(logger, localAddresses);
@ -74,10 +75,10 @@ public class MojangApiConnector {
/** /**
* @return null on non-premium * @return null on non-premium
*/ */
public UUID getPremiumUUID(String playerName) { public Optional<UUID> getPremiumUUID(String playerName) {
if (!validNameMatcher.matcher(playerName).matches()) { if (!validNameMatcher.matcher(playerName).matches()) {
//check if it's a valid player name //check if it's a valid player name
return null; return Optional.empty();
} }
try { try {
@ -87,7 +88,7 @@ public class MojangApiConnector {
if (proxies.hasNext()) { if (proxies.hasNext()) {
connection = getConnection(UUID_LINK + playerName, proxies.next()); connection = getConnection(UUID_LINK + playerName, proxies.next());
} else { } else {
return null; return Optional.empty();
} }
} }
} else { } else {
@ -98,7 +99,7 @@ public class MojangApiConnector {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line = reader.readLine(); String line = reader.readLine();
return getUUIDFromJson(line); return Optional.of(getUUIDFromJson(line));
} }
} else if (connection.getResponseCode() == RATE_LIMIT_CODE) { } else if (connection.getResponseCode() == RATE_LIMIT_CODE) {
logger.info("RATE_LIMIT REACHED"); logger.info("RATE_LIMIT REACHED");
@ -112,7 +113,7 @@ public class MojangApiConnector {
logger.log(Level.SEVERE, "Failed to check if player has a paid account", ex); logger.log(Level.SEVERE, "Failed to check if player has a paid account", ex);
} }
return null; return Optional.empty();
} }
public boolean hasJoinedServer(LoginSession session, String serverId, InetSocketAddress ip) { public boolean hasJoinedServer(LoginSession session, String serverId, InetSocketAddress ip) {

View File

@ -3,6 +3,7 @@ package com.github.games647.fastlogin.core.shared;
import com.github.games647.fastlogin.core.PlayerProfile; import com.github.games647.fastlogin.core.PlayerProfile;
import com.github.games647.fastlogin.core.hooks.AuthPlugin; import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
@ -38,13 +39,13 @@ public abstract class JoinManagement<P extends C, C, S extends LoginSource> {
return; return;
} }
UUID premiumUUID = null; Optional<UUID> premiumUUID = Optional.empty();
if (config.get("nameChangeCheck", false) || config.get("autoRegister", false)) { if (config.get("nameChangeCheck", false) || config.get("autoRegister", false)) {
premiumUUID = core.getApiConnector().getPremiumUUID(username); premiumUUID = core.getApiConnector().getPremiumUUID(username);
} }
if (premiumUUID == null if (!premiumUUID.isPresent()
|| (!checkNameChange(source, username, premiumUUID) || (!checkNameChange(source, username, premiumUUID.get())
&& !checkPremiumName(source, username, profile))) { && !checkPremiumName(source, username, profile))) {
//nothing detected the player as premium -> start a cracked session //nothing detected the player as premium -> start a cracked session
if (core.getConfig().get("switchMode", false)) { if (core.getConfig().get("switchMode", false)) {

View File

@ -30,7 +30,8 @@
<includes> <includes>
<include>${project.groupId}:*</include> <include>${project.groupId}:*</include>
<include>com.zaxxer:HikariCP</include> <include>com.zaxxer:HikariCP</include>
<include>org.slf4j:*</include> <include>org.slf4j:slf4j-jdk14</include>
<include>org.slf4j:slf4j-api</include>
<include>net.md-5:bungeecord-config</include> <include>net.md-5:bungeecord-config</include>
</includes> </includes>
</artifactSet> </artifactSet>