Fix NPE in unban command

This commit is contained in:
Telesphoreo 2022-04-04 15:18:20 -05:00
parent 35d436bb61
commit c8a64cc9cb
8 changed files with 159 additions and 88 deletions

View File

@ -37,36 +37,26 @@ import org.bukkit.plugin.java.JavaPlugin;
@Setter
public class Plex extends JavaPlugin
{
public static final BuildProperties build = new BuildProperties();
private static Plex plugin;
public Config config;
public Config messages;
public Config indefBans;
public File modulesFolder;
private StorageType storageType = StorageType.SQLITE;
private SQLConnection sqlConnection;
private MongoConnection mongoConnection;
private RedisConnection redisConnection;
private MongoPlayerData mongoPlayerData;
private SQLPlayerData sqlPlayerData;
private ModuleManager moduleManager;
private RankManager rankManager;
private ServiceManager serviceManager;
private PunishmentManager punishmentManager;
private AdminList adminList;
private UpdateChecker updateChecker;
private String system;
public static final BuildProperties build = new BuildProperties();
public static Plex get()
{
return plugin;

View File

@ -25,7 +25,8 @@ import java.util.stream.Collectors;
* @see Admin
*/
public class AdminList extends PlexBase {
public class AdminList extends PlexBase
{
/**
* Key/Value storage, where the key is the unique ID of the admin
*/
@ -36,7 +37,8 @@ public class AdminList extends PlexBase {
*
* @param admin The admin object
*/
public void addToCache(Admin admin) {
public void addToCache(Admin admin)
{
admins.put(admin.getUuid(), admin);
}
@ -46,7 +48,8 @@ public class AdminList extends PlexBase {
* @param uuid The unique ID of the admin
* @see UUID
*/
public void removeFromCache(UUID uuid) {
public void removeFromCache(UUID uuid)
{
admins.remove(uuid);
}
@ -55,24 +58,32 @@ public class AdminList extends PlexBase {
*
* @return An array list of the names of every admin
*/
public List<String> getAllAdmins() {
public List<String> getAllAdmins()
{
List<String> admins = Lists.newArrayList();
if (plugin.getStorageType() == StorageType.MONGODB) {
if (plugin.getStorageType() == StorageType.MONGODB)
{
Datastore store = plugin.getMongoConnection().getDatastore();
Query<PlexPlayer> query = store.find(PlexPlayer.class);
admins.addAll(query.stream().filter(plexPlayer -> plexPlayer.getRankFromString().isAtLeast(Rank.ADMIN)).map(PlexPlayer::getName).collect(Collectors.toList()));
} else {
try (Connection con = plugin.getSqlConnection().getCon()) {
}
else
{
try (Connection con = plugin.getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE rank IN(?, ?, ?)");
statement.setString(1, Rank.ADMIN.name().toLowerCase());
statement.setString(2, Rank.SENIOR_ADMIN.name().toLowerCase());
statement.setString(3, Rank.EXECUTIVE.name().toLowerCase());
ResultSet set = statement.executeQuery();
while (set.next()) {
while (set.next())
{
admins.add(set.getString("name"));
}
} catch (SQLException throwables) {
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
@ -84,21 +95,27 @@ public class AdminList extends PlexBase {
*
* @return An array list of the names of every admin
*/
public List<PlexPlayer> getAllAdminPlayers() {
public List<PlexPlayer> getAllAdminPlayers()
{
List<PlexPlayer> plexPlayers = Lists.newArrayList();
if (plugin.getStorageType() == StorageType.MONGODB) {
if (plugin.getStorageType() == StorageType.MONGODB)
{
Datastore store = plugin.getMongoConnection().getDatastore();
Query<PlexPlayer> query = store.find(PlexPlayer.class);
return query.stream().toList().stream().filter(player -> plugin.getRankManager().isAdmin(player)).collect(Collectors.toList());
} else {
try (Connection con = plugin.getSqlConnection().getCon()) {
}
else
{
try (Connection con = plugin.getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE rank IN(?, ?, ?)");
statement.setString(1, Rank.ADMIN.name().toLowerCase());
statement.setString(2, Rank.SENIOR_ADMIN.name().toLowerCase());
statement.setString(3, Rank.EXECUTIVE.name().toLowerCase());
ResultSet set = statement.executeQuery();
while (set.next()) {
while (set.next())
{
String uuid = set.getString("uuid");
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
@ -107,7 +124,8 @@ public class AdminList extends PlexBase {
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>() {
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
PlexPlayer plexPlayer = new PlexPlayer(UUID.fromString(uuid));
@ -121,7 +139,9 @@ public class AdminList extends PlexBase {
plexPlayer.setCommandSpy(commandspy);
plexPlayers.add(plexPlayer);
}
} catch (SQLException throwables) {
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}

View File

@ -37,7 +37,7 @@ public class UnbanCMD extends PlexCommand
UUID targetUUID = PlexUtils.getFromName(args[0]);
PlexPlayer plexPlayer = getOfflinePlexPlayer(targetUUID);
if (!DataUtils.hasPlayedBefore(targetUUID))
if (targetUUID == null || !DataUtils.hasPlayedBefore(targetUUID))
{
throw new PlayerNotFoundException();
}

View File

@ -27,7 +27,10 @@ public class TabListener extends PlexListener
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null) return;
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@ -36,7 +39,10 @@ public class TabListener extends PlexListener
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null) return;
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
@ -45,7 +51,10 @@ public class TabListener extends PlexListener
{
PlexPlayer plexPlayer = event.getPlexPlayer();
Player player = event.getPlexPlayer().getPlayer();
if (player == null) return;
if (player == null)
{
return;
}
player.playerListName(Component.text(player.getName()).color(plugin.getRankManager().getColor(plexPlayer)));
}
}

View File

@ -4,6 +4,13 @@ import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.command.PlexCommand;
import dev.plex.listener.PlexListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
@ -12,17 +19,10 @@ import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
@Getter
@Setter(AccessLevel.MODULE)
public abstract class PlexModule {
public abstract class PlexModule
{
@Getter(AccessLevel.MODULE)
private final List<PlexCommand> commands = Lists.newArrayList();
@ -34,48 +34,61 @@ public abstract class PlexModule {
private File dataFolder;
private Logger logger;
public void load() {
public void load()
{
}
public void enable() {
public void enable()
{
}
public void disable() {
public void disable()
{
}
public void registerListener(PlexListener listener) {
public void registerListener(PlexListener listener)
{
listeners.add(listener);
}
public void unregisterListener(PlexListener listener) {
public void unregisterListener(PlexListener listener)
{
listeners.remove(listener);
HandlerList.unregisterAll(listener);
}
public void registerCommand(PlexCommand command) {
public void registerCommand(PlexCommand command)
{
commands.add(command);
}
public void unregisterCommand(PlexCommand command) {
public void unregisterCommand(PlexCommand command)
{
commands.remove(command);
}
public PlexCommand getCommand(String name) {
public PlexCommand getCommand(String name)
{
return commands.stream().filter(plexCommand -> plexCommand.getName().equalsIgnoreCase(name) || plexCommand.getAliases().stream().map(String::toLowerCase).toList().contains(name.toLowerCase(Locale.ROOT))).findFirst().orElse(null);
}
@Nullable
public InputStream getResource(@NotNull String filename) {
try {
public InputStream getResource(@NotNull String filename)
{
try
{
URL url = this.getClass().getClassLoader().getResource(filename);
if (url == null) {
if (url == null)
{
return null;
}
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
} catch (IOException ex) {
}
catch (IOException ex)
{
return null;
}
}

View File

@ -9,7 +9,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class CustomClassLoader extends URLClassLoader {
public class CustomClassLoader extends URLClassLoader
{
/*public CustomClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
for (URL url : urls) {
@ -17,25 +18,30 @@ public class CustomClassLoader extends URLClassLoader {
}
}*/
public CustomClassLoader(URL jarInJar, ClassLoader parent) {
public CustomClassLoader(URL jarInJar, ClassLoader parent)
{
super(new URL[]{extractJar(jarInJar)}, parent);
addURL(jarInJar);
}
static URL extractJar(URL jarInJar) throws RuntimeException {
static URL extractJar(URL jarInJar) throws RuntimeException
{
// get the jar-in-jar resource
if (jarInJar == null) {
if (jarInJar == null)
{
throw new RuntimeException("Could not locate jar-in-jar");
}
// create a temporary file
// on posix systems by default this is only read/writable by the process owner
Path path;
try {
try
{
path = Files.createTempFile("plex-jarinjar", ".jar.tmp");
} catch (IOException e) {
}
catch (IOException e)
{
throw new RuntimeException("Unable to create a temporary file", e);
}
@ -43,15 +49,21 @@ public class CustomClassLoader extends URLClassLoader {
path.toFile().deleteOnExit();
// copy the jar-in-jar to the temporary file path
try (InputStream in = jarInJar.openStream()) {
try (InputStream in = jarInJar.openStream())
{
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
}
catch (IOException e)
{
throw new RuntimeException("Unable to copy jar-in-jar to temporary path", e);
}
try {
try
{
return path.toUri().toURL();
} catch (MalformedURLException e) {
}
catch (MalformedURLException e)
{
throw new RuntimeException("Unable to get URL from path", e);
}
}

View File

@ -45,14 +45,16 @@ import org.jetbrains.annotations.Nullable;
//TODO: doesn't work
public class LibraryLoader {
public class LibraryLoader
{
private final Logger logger;
private final RepositorySystem repository;
private final DefaultRepositorySystemSession session;
private final List<RemoteRepository> repositories;
public LibraryLoader(@NotNull Logger logger) {
public LibraryLoader(@NotNull Logger logger)
{
this.logger = logger;
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
@ -64,9 +66,11 @@ public class LibraryLoader {
session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_FAIL);
session.setLocalRepositoryManager(repository.newLocalRepositoryManager(session, new LocalRepository("libraries")));
session.setTransferListener(new AbstractTransferListener() {
session.setTransferListener(new AbstractTransferListener()
{
@Override
public void transferStarted(@NotNull TransferEvent event) throws TransferCancelledException {
public void transferStarted(@NotNull TransferEvent event) throws TransferCancelledException
{
logger.log(Level.INFO, "Downloading {0}", event.getResource().getRepositoryUrl() + event.getResource().getResourceName());
}
});
@ -76,8 +80,10 @@ public class LibraryLoader {
}
@Nullable
public ClassLoader createLoader(@NotNull PlexModule module, @NotNull PlexModuleFile moduleFile) {
if (moduleFile.getLibraries().isEmpty()) {
public ClassLoader createLoader(@NotNull PlexModule module, @NotNull PlexModuleFile moduleFile)
{
if (moduleFile.getLibraries().isEmpty())
{
return null;
}
logger.log(Level.INFO, "Loading libraries for {0}", new Object[]{moduleFile.getName()});
@ -89,7 +95,8 @@ public class LibraryLoader {
List<Dependency> dependencies = new ArrayList<>();
List<Class<?>> classes = Lists.newArrayList();
List<File> files = Lists.newArrayList();
for (String library : moduleFile.getLibraries()) {
for (String library : moduleFile.getLibraries())
{
Artifact artifact = new DefaultArtifact(library);
Dependency dependency = new Dependency(artifact, null);
@ -97,20 +104,27 @@ public class LibraryLoader {
}
DependencyResult result;
try {
try
{
result = repository.resolveDependencies(session, new DependencyRequest(new CollectRequest((Dependency)null, dependencies, repositories), null));
} catch (DependencyResolutionException ex) {
}
catch (DependencyResolutionException ex)
{
throw new RuntimeException("Error resolving libraries", ex);
}
List<URL> jarFiles = new ArrayList<>();
for (ArtifactResult artifact : result.getArtifactResults()) {
for (ArtifactResult artifact : result.getArtifactResults())
{
File file = artifact.getArtifact().getFile();
files.add(file);
URL url;
try {
try
{
url = file.toURI().toURL();
} catch (MalformedURLException ex) {
}
catch (MalformedURLException ex)
{
throw new AssertionError(ex);
}
@ -167,21 +181,29 @@ public class LibraryLoader {
});
classes.forEach(clazz -> logger.log(Level.INFO, "Loading class {0}", new Object[]{clazz.getName()}));*/
jarFiles.forEach(url -> {
jarFiles.forEach(url ->
{
JarURLConnection connection;
try {
try
{
URL url2 = new URL("jar:" + url.toString() + "!/");
/*
connection = (JarURLConnection) url2.openConnection();
logger.log(Level.INFO, "Jar File: " + connection.getJarFileURL().toString());*/
} catch (IOException e) {
}
catch (IOException e)
{
e.printStackTrace();
}
});
return new URLClassLoader(files.stream().map(File::toURI).map(uri -> {
try {
return new URLClassLoader(files.stream().map(File::toURI).map(uri ->
{
try
{
return uri.toURL();
} catch (MalformedURLException e) {
}
catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
@ -216,21 +238,27 @@ public class LibraryLoader {
}*/
private ArrayList<String> getClassNamesFromJar(JarFile file) throws Exception {
private ArrayList<String> getClassNamesFromJar(JarFile file) throws Exception
{
ArrayList<String> classNames = new ArrayList<>();
try {
try
{
//Iterate through the contents of the jar file
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
//Pick file that has the extension of .class
if ((entry.getName().endsWith(".class"))) {
if ((entry.getName().endsWith(".class")))
{
String className = entry.getName().replaceAll("/", "\\.");
String myClass = className.substring(0, className.lastIndexOf('.'));
classNames.add(myClass);
}
}
} catch (Exception e) {
}
catch (Exception e)
{
throw new Exception("Error while getting class names from jar", e);
}
return classNames;

View File

@ -12,7 +12,6 @@ import dev.plex.util.PlexLog;
import dev.plex.util.PlexUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;