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
* Increase hook delay to let ProtocolLib inject the listener
* 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
* 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.
@ -38,7 +38,7 @@
* Added missing add-premium-other message
* Upgrade to Java 8 -> Minimize file size
* 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 >
* Fix ProtocolSupport autoRegister
* Fix update username in FastLogin database after nameChange
@ -61,7 +61,7 @@
### 1.7.1
* Fix BungeeCord autoRegister (Fixes #46)
* Fix protocollsupport autoregister
* Fix ProtocolSupport auto-register
### 1.7
@ -175,7 +175,7 @@
* Removes the need of an Bukkit auth plugin if you use a bungeecord one
* Optimize performance and thread-safety
* 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
@ -185,19 +185,19 @@
### 0.5
* Added cracked command
* Added autologin - See config
* Added auto-login - See config
* Added config
* Added isRegistered API method
* Added forceRegister API method
* 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
### 0.4
* Added forward premium skin
* Added plugin support for protocolsupport
* Added plugin support for ProtocolSupport
### 0.3.2
@ -223,7 +223,7 @@
### 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"
* Reformat source code
* 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.PremiumCommand;
import com.github.games647.fastlogin.bukkit.listener.BukkitJoinListener;
import com.github.games647.fastlogin.bukkit.listener.BungeeCordListener;
import com.github.games647.fastlogin.bukkit.listener.JoinListener;
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.ProtocolLibListener;
import com.github.games647.fastlogin.bukkit.listener.protocolsupport.ProtocolSupportListener;
@ -66,7 +66,7 @@ public class FastLoginBukkit extends JavaPlugin implements PlatformPlugin<Comman
setServerStarted();
//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());
//register listeners on success
} 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
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
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) {
if (sender instanceof Player) {
notifyBungeeCord((Player) sender, target, activate, true);
if (sender instanceof PluginMessageRecipient) {
notifyBungeeCord((PluginMessageRecipient) sender, target, activate, true);
} else {
Player firstPlayer = Iterables.getFirst(getServer().getOnlinePlayers(), 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.metadata.Authenticated;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
@ -31,7 +32,7 @@ public class CrazyLoginHook implements AuthPlugin<Player> {
@Override
public boolean forceLogin(Player player) {
//not thread-safe operation
Future<LoginPlayerData> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> {
Future<Optional<LoginPlayerData>> future = Bukkit.getScheduler().callSyncMethod(crazyLoginPlugin, () -> {
LoginPlayerData playerData = crazyLoginPlugin.getPlayerData(player);
if (playerData != null) {
//mark the account as logged in
@ -56,17 +57,17 @@ public class CrazyLoginHook implements AuthPlugin<Player> {
playerData.addIP(ip);
player.setMetadata("Authenticated", new Authenticated(crazyLoginPlugin, player));
crazyLoginPlugin.unregisterDynamicHooks();
return playerData;
return Optional.of(playerData);
}
return null;
return Optional.empty();
});
try {
LoginPlayerData result = future.get();
if (result != null && result.isLoggedIn()) {
Optional<LoginPlayerData> result = future.get().filter(LoginPlayerData::isLoggedIn);
if (result.isPresent()) {
//SQL-Queries should run async
crazyLoginPlugin.getCrazyDatabase().saveWithoutPassword(result);
crazyLoginPlugin.getCrazyDatabase().saveWithoutPassword(result.get());
return true;
}
} 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
* 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";
@ -35,7 +35,7 @@ public class BungeeCordListener implements PluginMessageListener {
//null if whitelist is empty so bungeecord support is disabled
private final Set<UUID> proxyIds;
public BungeeCordListener(FastLoginBukkit plugin) {
public BungeeListener(FastLoginBukkit plugin) {
this.plugin = plugin;
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();
String id = '/' + address.getAddress().getHostAddress() + ':' + address.getPort();
if ("AUTO_LOGIN".equalsIgnoreCase(subchannel)) {
if ("AUTO_LOGIN".equalsIgnoreCase(subChannel)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
playerSession.setVerified(true);
plugin.getLoginSessions().put(id, playerSession);
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, () -> {
AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook();
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
* plugin can skip authentication.
*/
public class BukkitJoinListener implements Listener {
public class JoinListener implements Listener {
private static final long DELAY_LOGIN = 20L / 2;
private final FastLoginBukkit plugin;
public BukkitJoinListener(FastLoginBukkit plugin) {
public JoinListener(FastLoginBukkit plugin) {
this.plugin = plugin;
}

View File

@ -53,7 +53,7 @@ public class ForceLoginTask extends ForceLoginManagement<Player, CommandSender,
@Override
public boolean isOnline(Player player) {
try {
//the playerlist isn't thread-safe
//the player-list isn't thread-safe
return Bukkit.getScheduler().callSyncMethod(core.getPlugin(), player::isOnline).get();
} catch (InterruptedException | ExecutionException 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;
import com.github.games647.fastlogin.bungee.hooks.BungeeAuthHook;
import com.github.games647.fastlogin.bungee.listener.ConnectionListener;
import com.github.games647.fastlogin.bungee.listener.PluginMessageListener;
import com.github.games647.fastlogin.bungee.listener.ConnectListener;
import com.github.games647.fastlogin.bungee.listener.MessageListener;
import com.github.games647.fastlogin.core.mojang.MojangApiConnector;
import com.github.games647.fastlogin.core.shared.FastLoginCore;
import com.github.games647.fastlogin.core.shared.PlatformPlugin;
@ -38,8 +38,8 @@ public class FastLoginBungee extends Plugin implements PlatformPlugin<CommandSen
}
//events
getProxy().getPluginManager().registerListener(this, new ConnectionListener(this));
getProxy().getPluginManager().registerListener(this, new PluginMessageListener(this));
getProxy().getPluginManager().registerListener(this, new ConnectListener(this));
getProxy().getPluginManager().registerListener(this, new MessageListener(this));
//this is required to listen to messages from the server
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
* order to clear that the connection is online mode.
*/
public class ConnectionListener implements Listener {
public class ConnectListener implements Listener {
private final FastLoginBungee plugin;
public ConnectionListener(FastLoginBungee plugin) {
public ConnectListener(FastLoginBungee plugin) {
this.plugin = plugin;
}
@ -58,7 +58,7 @@ public class ConnectionListener implements Listener {
return;
}
//use the login event instead of the postlogin event in order to send the loginsuccess packet to the client
//use the login event instead of the post login event in order to send the login success packet to the client
//with the offline uuid this makes it possible to set the skin then
PendingConnection connection = loginEvent.getConnection();
InitialHandler initialHandler = (InitialHandler) connection;

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

View File

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

View File

@ -24,6 +24,7 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
@ -58,7 +59,7 @@ public class MojangApiConnector {
protected final Logger logger;
public MojangApiConnector(Logger logger, Collection<String> localAddresses, int rateLimit
, List<HostAndPort> proxies) {
, Iterable<HostAndPort> proxies) {
this.logger = logger;
this.rateLimit = Math.max(rateLimit, 600);
this.sslFactory = buildAddresses(logger, localAddresses);
@ -74,10 +75,10 @@ public class MojangApiConnector {
/**
* @return null on non-premium
*/
public UUID getPremiumUUID(String playerName) {
public Optional<UUID> getPremiumUUID(String playerName) {
if (!validNameMatcher.matcher(playerName).matches()) {
//check if it's a valid player name
return null;
return Optional.empty();
}
try {
@ -87,7 +88,7 @@ public class MojangApiConnector {
if (proxies.hasNext()) {
connection = getConnection(UUID_LINK + playerName, proxies.next());
} else {
return null;
return Optional.empty();
}
}
} else {
@ -98,7 +99,7 @@ public class MojangApiConnector {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line = reader.readLine();
return getUUIDFromJson(line);
return Optional.of(getUUIDFromJson(line));
}
} else if (connection.getResponseCode() == RATE_LIMIT_CODE) {
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);
}
return null;
return Optional.empty();
}
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.hooks.AuthPlugin;
import java.util.Optional;
import java.util.UUID;
import java.util.logging.Level;
@ -38,13 +39,13 @@ public abstract class JoinManagement<P extends C, C, S extends LoginSource> {
return;
}
UUID premiumUUID = null;
Optional<UUID> premiumUUID = Optional.empty();
if (config.get("nameChangeCheck", false) || config.get("autoRegister", false)) {
premiumUUID = core.getApiConnector().getPremiumUUID(username);
}
if (premiumUUID == null
|| (!checkNameChange(source, username, premiumUUID)
if (!premiumUUID.isPresent()
|| (!checkNameChange(source, username, premiumUUID.get())
&& !checkPremiumName(source, username, profile))) {
//nothing detected the player as premium -> start a cracked session
if (core.getConfig().get("switchMode", false)) {

View File

@ -30,7 +30,8 @@
<includes>
<include>${project.groupId}:*</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>
</includes>
</artifactSet>