1
0
Fork 0
mirror of https://github.com/xHyroM/lighteco.git synced 2024-11-10 01:18:07 +01:00

style: cleanup

This commit is contained in:
Jozef Steinhübl 2023-08-29 08:12:19 +02:00
parent eb62c51541
commit 75d80b0480
23 changed files with 129 additions and 104 deletions

View file

@ -9,6 +9,7 @@ import java.util.concurrent.CompletableFuture;
public interface UserManager {
@NonNull CompletableFuture<User> loadUser(@NonNull UUID uniqueId);
@NonNull CompletableFuture<User> loadUser(@NonNull UUID uniqueId, String username);
@NonNull CompletableFuture<Void> saveUser(@NonNull User user);

View file

@ -2,13 +2,14 @@ package dev.xhyrom.lighteco.api.storage;
import dev.xhyrom.lighteco.api.model.user.User;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public interface StorageProvider {
void init() throws Exception;
void shutdown() throws Exception;
@NonNull User loadUser(@NonNull UUID uniqueId) throws Exception;
// todo: look at this
@NonNull User loadUser(@NonNull UUID uniqueId, @Nullable String username) throws Exception;
void saveUser(@NonNull User user) throws Exception;
}

View file

@ -42,7 +42,7 @@ public class BukkitLightEcoBootstrap implements LightEcoBootstrap, LoaderBootstr
@Override
public void onDisable() {
this.plugin.disable();
}
public Server getServer() {

View file

@ -44,7 +44,11 @@ public class PayCommand implements Command {
this.manager.plugin.getUserManager().loadUser(target.getUniqueId())
.thenAcceptAsync(result -> {
String name = target.getName() != null ? target.getName() : args.getRaw("target");
String name = result.getUsername() == null ?
target.getName() != null
? target.getName()
: args.getRaw("target")
: result.getUsername();
result.setUsername(name);
this.manager.onPay(sender, currency, result, amount);

View file

@ -46,6 +46,6 @@ public class PlaceholderAPIExpansion extends PlaceholderExpansion {
return user.getBalance(currency).toPlainString();
}
return "lighteco";
return null;
}
}

View file

@ -16,7 +16,6 @@ public class BukkitConnectionListener implements Listener {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
@ -24,7 +23,7 @@ public class BukkitConnectionListener implements Listener {
}
try {
this.plugin.getStorage().loadUser(event.getUniqueId()).join();
this.plugin.getStorage().loadUser(event.getUniqueId(), event.getName()).join();
} catch (Exception e) {
this.plugin.getBootstrap().getLogger()
.error("Failed to load user data for %s (%s)", e, event.getName(), event.getUniqueId());

View file

@ -9,7 +9,6 @@ public class BukkitLogger implements PluginLogger {
this.logger = logger;
}
@Override
public void info(String message) {
this.logger.info(message);

View file

@ -20,7 +20,12 @@ public class ApiUserManager extends ApiAbstractManager<dev.xhyrom.lighteco.commo
@Override
public @NonNull CompletableFuture<User> loadUser(@NonNull UUID uniqueId) {
return this.plugin.getStorage().loadUser(uniqueId)
return loadUser(uniqueId, null);
}
@Override
public @NonNull CompletableFuture<User> loadUser(@NonNull UUID uniqueId, String username) {
return this.plugin.getStorage().loadUser(uniqueId, username)
.thenApply(ApiUserManager::wrap);
}

View file

@ -1,19 +1,18 @@
package dev.xhyrom.lighteco.common.config.storage;
import dev.xhyrom.lighteco.common.storage.StorageType;
import eu.okaeri.configs.OkaeriConfig;
import eu.okaeri.configs.annotation.Comment;
import eu.okaeri.configs.annotation.Variable;
public class StorageConfig extends OkaeriConfig {
@Comment("Storage provider.")
@Comment("Available providers: h2, sqlite")
public String provider = "h2";
@Comment("Available providers: h2, sqlite, mysql, mariadb")
public StorageType provider = StorageType.H2;
@Comment("Data storage settings.")
@Comment("You don't need to worry about this if you're using local database.")
public StorageDataConfig data = new StorageDataConfig();
@Variable("table-prefix")
@Comment("Table prefix.")
public String tablePrefix = "lighteco_";
}

View file

@ -2,6 +2,7 @@ package dev.xhyrom.lighteco.common.dependencies;
import lombok.Getter;
@Getter
public enum Dependency {
H2_DRIVER(
"com.h2database",
@ -29,10 +30,7 @@ public enum Dependency {
"42.6.0"
);
@Getter
private final String fullPath;
private final String groupId;
private final String artifactId;
private final String version;
private static final String MAVEN_FORMAT = "%s/%s/%s/%s-%s.jar";
@ -46,8 +44,6 @@ public enum Dependency {
version
);
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
}

View file

@ -3,7 +3,7 @@ package dev.xhyrom.lighteco.common.dependencies;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.MoreFiles;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import dev.xhyrom.lighteco.common.plugin.classpath.URLClassLoaderAccess;
import dev.xhyrom.lighteco.common.util.URLClassLoaderAccess;
import dev.xhyrom.lighteco.common.storage.StorageType;
import java.io.IOException;
@ -30,7 +30,6 @@ public class DependencyManagerImpl implements DependencyManager {
this.registry = new DependencyRegistry();
this.cacheDirectory = setupCacheDirectory(plugin);
this.classLoader = URLClassLoaderAccess.create((URLClassLoader) plugin.getBootstrap().getClass().getClassLoader());
System.out.println(this.classLoader);
}
@Override
@ -47,7 +46,7 @@ public class DependencyManagerImpl implements DependencyManager {
try {
loadDependency(dependency);
} catch (Exception e) {
new RuntimeException("Failed to load dependency " + dependency, e);
throw new RuntimeException("Failed to load dependency " + dependency, e);
} finally {
latch.countDown();
}
@ -70,14 +69,11 @@ public class DependencyManagerImpl implements DependencyManager {
this.loaded.put(dependency, file);
System.out.println("HHHH");
if (this.registry.shouldAutoLoad(dependency)) {
System.out.println("Loaded dependency " + dependency + " from " + file);
try {
this.classLoader.addURL(file.toUri().toURL());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to load dependency " + dependency, e);
}
}
}

View file

@ -13,6 +13,7 @@ public class DependencyRegistry {
.putAll(StorageType.H2, Dependency.H2_DRIVER)
.putAll(StorageType.MYSQL, Dependency.MYSQL_DRIVER)
.putAll(StorageType.MARIADB, Dependency.MARIADB_DRIVER)
.putAll(StorageType.POSTGRESQL, Dependency.POSTGRESQL_DRIVER)
.build();
public Set<Dependency> resolveStorageDependencies(Set<StorageType> types) {

View file

@ -23,7 +23,12 @@ public class StandardUserManager extends AbstractManager<UUID, User> implements
@Override
public CompletableFuture<User> loadUser(UUID uniqueId) {
return this.plugin.getStorage().loadUser(uniqueId);
return loadUser(uniqueId, null);
}
@Override
public CompletableFuture<User> loadUser(UUID uniqueId, String username) {
return this.plugin.getStorage().loadUser(uniqueId, username);
}
@Override

View file

@ -10,7 +10,9 @@ public interface UserManager extends Manager<UUID, User> {
CompletableFuture<Void> saveUser(User user);
CompletableFuture<Void> load();
CompletableFuture<User> loadUser(UUID uniqueId);
CompletableFuture<User> loadUser(UUID uniqueId, String username);
void invalidateCaches();
}

View file

@ -55,6 +55,10 @@ public abstract class AbstractLightEcoPlugin implements LightEcoPlugin {
this.registerApiOnPlatform(this.api);
}
public final void disable() {
this.storage.shutdown();
}
protected abstract void registerListeners();
protected abstract void setupManagers();

View file

@ -55,13 +55,25 @@ public class Storage {
}
}
public void shutdown() {
try {
this.provider.shutdown();
} catch (Exception e) {
throw new RuntimeException("Failed to shutdown storage provider", e);
}
}
public CompletableFuture<User> loadUser(UUID uniqueId) {
return loadUser(uniqueId, null);
}
public CompletableFuture<User> loadUser(UUID uniqueId, String username) {
User user = this.plugin.getUserManager().getIfLoaded(uniqueId);
if (user != null) {
return CompletableFuture.completedFuture(user);
}
return future(() -> this.provider.loadUser(uniqueId))
return future(() -> this.provider.loadUser(uniqueId, username))
.thenApply(apiUser -> this.plugin.getUserManager().getIfLoaded(apiUser.getUniqueId()));
}

View file

@ -20,12 +20,11 @@ public class StorageFactory {
}
public Set<StorageType> getRequiredTypes() {
return ImmutableSet.of(StorageType.parse(this.plugin.getConfig().storage.provider));
return ImmutableSet.of(this.plugin.getConfig().storage.provider);
}
public Storage get() {
// todo: use config
String provider = this.plugin.getConfig().storage.provider;
StorageType provider = this.plugin.getConfig().storage.provider;
Storage storage = new Storage(this.plugin, createProvider(provider));
storage.init();
@ -33,32 +32,26 @@ public class StorageFactory {
return storage;
}
private StorageProvider createProvider(String provider) {
switch (provider.toLowerCase()) {
case "memory":
return new MemoryStorageProvider(this.plugin);
case "h2":
return new SqlStorageProvider(
this.plugin,
new H2ConnectionFactory(this.plugin.getBootstrap().getDataDirectory().resolve("lighteco-h2").toAbsolutePath())
);
case "sqlite":
return new SqlStorageProvider(
this.plugin,
new SqliteConnectionFactory(this.plugin.getBootstrap().getDataDirectory().resolve("lighteco-sqlite.db"))
);
case "mysql":
return new SqlStorageProvider(
this.plugin,
new MySQLConnectionFactory(this.plugin.getConfig().storage.data)
);
case "mariadb":
return new SqlStorageProvider(
this.plugin,
new MariaDBConnectionFactory(this.plugin.getConfig().storage.data)
);
default:
throw new IllegalArgumentException("Unknown storage provider: " + provider);
}
private StorageProvider createProvider(StorageType type) {
return switch (type) {
case MEMORY -> new MemoryStorageProvider(this.plugin);
case H2 -> new SqlStorageProvider(
this.plugin,
new H2ConnectionFactory(this.plugin.getBootstrap().getDataDirectory().resolve("lighteco-h2").toAbsolutePath())
);
case SQLITE -> new SqlStorageProvider(
this.plugin,
new SqliteConnectionFactory(this.plugin.getBootstrap().getDataDirectory().resolve("lighteco-sqlite.db"))
);
case MYSQL -> new SqlStorageProvider(
this.plugin,
new MySQLConnectionFactory(this.plugin.getConfig().storage.data)
);
case MARIADB -> new SqlStorageProvider(
this.plugin,
new MariaDBConnectionFactory(this.plugin.getConfig().storage.data)
);
default -> throw new IllegalArgumentException("Unknown storage provider: " + type.name());
};
}
}

View file

@ -1,27 +1,12 @@
package dev.xhyrom.lighteco.common.storage;
import java.util.List;
import java.util.stream.Stream;
public enum StorageType {
MARIADB("MariaDB", "mariadb"),
MYSQL("MySQL", "mysql"),
MEMORY,
SQLITE("SQLite", "sqlite"),
H2("H2", "h2");
MARIADB,
MYSQL,
POSTGRESQL,
private final String name;
private final List<String> identifiers;
StorageType(String name, String... identifiers) {
this.name = name;
this.identifiers = List.of(identifiers);
}
public static StorageType parse(String name) {
return Stream.of(values())
.filter(type -> type.identifiers.contains(name.toLowerCase()))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown storage type: " + name));
}
SQLITE,
H2;
}

View file

@ -4,6 +4,7 @@ import dev.xhyrom.lighteco.api.model.user.User;
import dev.xhyrom.lighteco.api.storage.StorageProvider;
import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.HashMap;
import java.util.UUID;
@ -17,13 +18,16 @@ public class MemoryStorageProvider implements StorageProvider {
}
@Override
public void init() throws Exception {}
public void init() {}
@Override
public @NonNull User loadUser(@NonNull UUID uniqueId) {
public void shutdown() {}
@Override
public @NonNull User loadUser(@NonNull UUID uniqueId, @Nullable String username) {
this.simulateSlowDatabaseQuery();
return this.createUser(uniqueId, userDatabase.get(uniqueId));
return this.createUser(uniqueId, username, userDatabase.get(uniqueId));
}
@Override
@ -33,8 +37,10 @@ public class MemoryStorageProvider implements StorageProvider {
this.userDatabase.put(user.getUniqueId(), user);
}
private User createUser(UUID uniqueId, User data) {
private User createUser(UUID uniqueId, String username, User data) {
dev.xhyrom.lighteco.common.model.user.User user = this.plugin.getUserManager().getOrMake(uniqueId);
if (username != null)
user.setUsername(username);
return user.getProxy();
}

View file

@ -12,6 +12,11 @@ public enum SqlStatements {
"INSERT INTO {prefix}_users (uuid, currency_identifier, balance) VALUES (?1, ?2, ?3) ON CONFLICT (uuid, currency_identifier) DO UPDATE SET balance=?3;",
"INSERT INTO {prefix}_users (uuid, currency_identifier, balance) VALUES (?1, ?2, ?3) ON DUPLICATE KEY UPDATE balance=?3;",
"INSERT INTO {prefix}_users (uuid, currency_identifier, balance) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE balance=?;"
),
LOAD_WHOLE_USER(
"SELECT currency_identifier, balance FROM ( SELECT currency_identifier, balance FROM '{prefix}_users' WHERE uuid = ?1 UNION ALL SELECT currency_identifier, balance FROM '{prefix}_{context}_users' WHERE uuid = ?1 ) AS combined_currencies;",
"SELECT currency_identifier, balance FROM ( SELECT currency_identifier, balance FROM '{prefix}_users' WHERE uuid = ?1 UNION ALL SELECT currency_identifier, balance FROM '{prefix}_{context}_users' WHERE uuid = ?1 ) AS combined_currencies;",
"SELECT currency_identifier, balance FROM ( SELECT currency_identifier, balance FROM '{prefix}_users' WHERE uuid = ? UNION ALL SELECT currency_identifier, balance FROM '{prefix}_{context}_users' WHERE uuid = ? ) AS combined_currencies;"
);
public final String sqlite;

View file

@ -7,6 +7,7 @@ import dev.xhyrom.lighteco.common.plugin.LightEcoPlugin;
import dev.xhyrom.lighteco.common.storage.StorageType;
import dev.xhyrom.lighteco.common.storage.provider.sql.connection.ConnectionFactory;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.IOException;
import java.io.InputStream;
@ -18,10 +19,10 @@ import java.util.UUID;
import java.util.function.Function;
public class SqlStorageProvider implements StorageProvider {
private final String SAVE_USER_LOCAL_CURRENCY;
private final String SAVE_USER_GLOBAL_CURRENCY;
private static final String LOAD_WHOLE_USER = "SELECT currency_identifier, balance FROM ( SELECT currency_identifier, balance FROM '{prefix}_users' WHERE uuid = ? UNION ALL SELECT currency_identifier, balance FROM '{prefix}_{context}_users' WHERE uuid = ? ) AS combined_currencies;";
private static String SAVE_USER_LOCAL_CURRENCY;
private static String SAVE_USER_GLOBAL_CURRENCY;
private static String LOAD_WHOLE_USER;
private final LightEcoPlugin plugin;
private final ConnectionFactory connectionFactory;
private final Function<String, String> statementProcessor;
@ -36,8 +37,9 @@ public class SqlStorageProvider implements StorageProvider {
);
final StorageType implementationName = this.connectionFactory.getImplementationName();
this.SAVE_USER_LOCAL_CURRENCY = SqlStatements.SAVE_USER_LOCAL_CURRENCY.get(implementationName);
this.SAVE_USER_GLOBAL_CURRENCY = SqlStatements.SAVE_USER_GLOBAL_CURRENCY.get(implementationName);
SAVE_USER_LOCAL_CURRENCY = SqlStatements.SAVE_USER_LOCAL_CURRENCY.get(implementationName);
SAVE_USER_GLOBAL_CURRENCY = SqlStatements.SAVE_USER_GLOBAL_CURRENCY.get(implementationName);
LOAD_WHOLE_USER = SqlStatements.LOAD_WHOLE_USER.get(implementationName);
}
@Override
@ -67,9 +69,16 @@ public class SqlStorageProvider implements StorageProvider {
}
@Override
public @NonNull User loadUser(@NonNull UUID uniqueId) throws Exception {
public void shutdown() throws Exception {
this.connectionFactory.shutdown();
}
@Override
public @NonNull User loadUser(@NonNull UUID uniqueId, @Nullable String username) throws Exception {
String uniqueIdString = uniqueId.toString();
dev.xhyrom.lighteco.common.model.user.User user = this.plugin.getUserManager().getOrMake(uniqueId);
if (username != null)
user.setUsername(username);
try (Connection c = this.connectionFactory.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(this.statementProcessor.apply(LOAD_WHOLE_USER))) {

View file

@ -1,5 +1,12 @@
package dev.xhyrom.lighteco.common.plugin.classpath;
// Class loader access from LuckPerms
// https://github.com/LuckPerms/LuckPerms/blob/1790c0ad4744d31ea3e30eb87822b4f506de449b/common/src/main/java/me/lucko/luckperms/common/plugin/classpath/URLClassLoaderAccess.java
// Copyright (c) lucko (Luck) <lucko@lucko.me>
// Copyright (c) contributors
// MIT License
package dev.xhyrom.lighteco.common.util;
import dev.xhyrom.lighteco.common.util.exception.UnableToInjectException;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.reflect.Field;
@ -15,7 +22,9 @@ public abstract class URLClassLoaderAccess {
} else if (Unsafe.isSupported()) {
return new Unsafe(classLoader);
} else {
return Noop.INSTANCE;
throw new UnableToInjectException("LightEco is unable to inject dependencies into the plugin class loader.\n" +
"To fix this, please add '--add-opens java.base/java.lang=ALL-UNNAMED' to your JVM arguments." +
"If it still doesn't work, please report this on https://github.com/xHyroM/lighteco/issues");
}
}
@ -118,17 +127,4 @@ public abstract class URLClassLoaderAccess {
}
}
}
private static class Noop extends URLClassLoaderAccess {
private static final Noop INSTANCE = new Noop();
private Noop() {
super(null);
}
@Override
public void addURL(@NonNull URL url) {
throw new UnsupportedOperationException("Noop");
}
}
}

View file

@ -0,0 +1,7 @@
package dev.xhyrom.lighteco.common.util.exception;
public class UnableToInjectException extends RuntimeException {
public UnableToInjectException(String message) {
super(message);
}
}