Package refactoring

This commit is contained in:
Roman Zhuravlev 2023-08-11 19:33:20 +05:00
parent 6b74f1711f
commit ce184a16bf
22 changed files with 285 additions and 193 deletions

View file

@ -1,25 +1,39 @@
package org.zhdev;
package org.zhdev.varioutil;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class BukkitPlugin extends JavaPlugin {
public void registerCommand(String label, CommandExecutor executor, TabCompleter completer) {
public BukkitPlugin() {
super();
}
protected BukkitPlugin(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file);
}
public Command registerCommand(CommandExecutor executor, TabCompleter completer, String label) {
PluginCommand command = Bukkit.getPluginCommand(label);
if (command != null) {
command.setExecutor(executor);
command.setTabCompleter(completer);
}
return command;
}
public void registerCommand(String label, CommandExecutor executor) {
registerCommand(label, executor, this);
public Command registerCommand(CommandExecutor executor, String label) {
return registerCommand(executor, executor instanceof TabCompleter ? (TabCompleter) executor : this, label);
}
public void registerEvents(Listener listener) {

View file

@ -1,4 +1,4 @@
package org.zhdev;
package org.zhdev.varioutil;
import org.jetbrains.annotations.NotNull;

View file

@ -1,6 +1,6 @@
package org.zhdev.language;
package org.zhdev.varioutil.language;
import org.zhdev.util.StringUtils;
import org.zhdev.varioutil.util.StringUtils;
import java.util.HashMap;
import java.util.LinkedHashMap;
@ -15,7 +15,7 @@ public class Language {
return sectionKey + ':' + phraseKey;
}
String phrase = section.getOrDefault(phraseKey, phraseKey);
String phrase = section.get(phraseKey);
if (phrase == null) {
Map<String, Object> paramsMap = new LinkedHashMap<>(params.length / 2);
Object replacement = null;
@ -23,7 +23,7 @@ public class Language {
if (i % 2 == 0) {
replacement = params[i];
} else {
paramsMap.put(String.valueOf(params[i]), replacement);
paramsMap.put(String.valueOf(replacement), params[i]);
}
}
return sectionKey + ':' + phraseKey + ' ' + paramsMap;

View file

@ -1,6 +1,6 @@
package org.zhdev.reflection;
package org.zhdev.varioutil.reflection;
import org.zhdev.util.ReflectionUtils;
import org.zhdev.varioutil.util.ReflectionUtils;
import java.lang.reflect.Field;

View file

@ -1,6 +1,6 @@
package org.zhdev.reflection;
package org.zhdev.varioutil.reflection;
import org.zhdev.util.ReflectionUtils;
import org.zhdev.varioutil.util.ReflectionUtils;
import java.lang.reflect.Method;

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import java.util.Collection;
import java.util.function.Function;
@ -33,27 +33,27 @@ public class ArrayUtils {
}
public static <T> Byte[] mapToByte(T[] array, IntFunction<Byte[]> arrayConstructor) {
return map(array, arrayConstructor, NumberUtils::parseByte);
return map(array, arrayConstructor, StringUtils::parseByte);
}
public static <T> Short[] mapToShort(T[] array, IntFunction<Short[]> arrayConstructor) {
return map(array, arrayConstructor, NumberUtils::parseShort);
return map(array, arrayConstructor, StringUtils::parseShort);
}
public static <T> Integer[] mapToInteger(T[] array, IntFunction<Integer[]> arrayConstructor) {
return map(array, arrayConstructor, NumberUtils::parseInt);
return map(array, arrayConstructor, StringUtils::parseInt);
}
public static <T> Long[] mapToLong(T[] array, IntFunction<Long[]> arrayConstructor) {
return map(array, arrayConstructor, NumberUtils::parseLong);
return map(array, arrayConstructor, StringUtils::parseLong);
}
public static <T> Float[] mapToFloat(T[] array, IntFunction<Float[]> arrayConstructor) {
return map(array, arrayConstructor, NumberUtils::parseFloat);
return map(array, arrayConstructor, StringUtils::parseFloat);
}
public static <T> Double[] mapToDouble(T[] array, IntFunction<Double[]> arrayConstructor) {
return map(array, arrayConstructor, NumberUtils::parseDouble);
return map(array, arrayConstructor, StringUtils::parseDouble);
}
public static <C extends Collection<R>, T, R> C mapAndToCollection(T[] array, IntFunction<C> collectionConstructor, Function<T, R> function) {

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import java.util.Collection;
import java.util.List;
@ -34,27 +34,27 @@ public class CollectionUtils {
}
public static <C extends Collection<Byte>, T> C mapToByte(Collection<T> collection, IntFunction<C> collectionConstructor) {
return map(collection, collectionConstructor, NumberUtils::parseByte);
return map(collection, collectionConstructor, StringUtils::parseByte);
}
public static <C extends Collection<Short>, T> C mapToShort(Collection<T> collection, IntFunction<C> collectionConstructor) {
return map(collection, collectionConstructor, NumberUtils::parseShort);
return map(collection, collectionConstructor, StringUtils::parseShort);
}
public static <C extends Collection<Integer>, T> C mapToInteger(Collection<T> collection, IntFunction<C> collectionConstructor) {
return map(collection, collectionConstructor, NumberUtils::parseInt);
return map(collection, collectionConstructor, StringUtils::parseInt);
}
public static <C extends Collection<Long>, T> C mapToLong(Collection<T> collection, IntFunction<C> collectionConstructor) {
return map(collection, collectionConstructor, NumberUtils::parseLong);
return map(collection, collectionConstructor, StringUtils::parseLong);
}
public static <C extends Collection<Float>, T> C mapToFloat(Collection<T> collection, IntFunction<C> collectionConstructor) {
return map(collection, collectionConstructor, NumberUtils::parseFloat);
return map(collection, collectionConstructor, StringUtils::parseFloat);
}
public static <C extends Collection<Double>, T> C mapToDouble(Collection<T> collection, IntFunction<C> collectionConstructor) {
return map(collection, collectionConstructor, NumberUtils::parseDouble);
return map(collection, collectionConstructor, StringUtils::parseDouble);
}
public static <T, R> R[] mapAndToArray(Collection<T> collection, IntFunction<R[]> arrayConstructor, Function<T, R> function) {

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import java.time.*;
import java.time.format.DateTimeFormatter;

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
public class EnumUtils {
private static <T extends Enum<T>> T[] getValues(T eNum) {

View file

@ -1,7 +1,7 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import org.zhdev.reflection.FieldSearcher;
import org.zhdev.reflection.MethodSearcher;
import org.zhdev.varioutil.reflection.FieldSearcher;
import org.zhdev.varioutil.reflection.MethodSearcher;
import java.io.File;
import java.io.IOException;

View file

@ -1,9 +1,10 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
public class ResourceUtils {
public static InputStream getResource(String path, ClassLoader loader) {
@ -25,7 +26,7 @@ public class ResourceUtils {
return getResource(path, ResourceUtils.class.getClassLoader());
}
public static boolean saveResource(String resourcePath, File outFile, ClassLoader loader) throws IllegalStateException {
public static boolean saveResource(String resourcePath, Path outPath, ClassLoader loader) throws IllegalStateException {
if (resourcePath == null || resourcePath.equals("")) {
return false;
}
@ -36,14 +37,14 @@ public class ResourceUtils {
return false;
}
File parent = outFile.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
try {
if (!outFile.exists() || outFile.length() == 0) {
OutputStream stream = Files.newOutputStream(outFile.toPath());
Path parent = outPath.getParent();
if (parent != null && Files.notExists(parent)) {
Files.createDirectories(parent);
}
if (Files.notExists(outPath) || Files.size(outPath) == 0) {
OutputStream stream = Files.newOutputStream(outPath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
@ -54,14 +55,14 @@ public class ResourceUtils {
return true;
}
} catch (IOException e) {
throw new IllegalStateException("Could not save resource " + resourcePath + " to " + outFile, e);
throw new IllegalStateException("Could not save resource " + resourcePath + " to " + outPath, e);
}
return false;
}
public static boolean saveResource(String resourcePath, File outFile) throws IllegalStateException {
return saveResource(resourcePath, outFile);
public static boolean saveResource(String resourcePath, Path outPath) throws IllegalStateException {
return saveResource(resourcePath, outPath, ResourceUtils.class.getClassLoader());
}
}

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import java.util.ArrayList;
import java.util.Iterator;
@ -8,10 +8,12 @@ public class StringUtils {
public static String join(int beginIndex, int lastIndex, String delimiter, String lastDelimiter, String... elements) {
StringBuilder builder = new StringBuilder();
for (; beginIndex < elements.length; beginIndex++) {
if (beginIndex == lastIndex) {
builder.append(lastDelimiter);
} else {
builder.append(delimiter);
if (builder.length() > 0) {
if (beginIndex == lastIndex) {
builder.append(lastDelimiter);
} else {
builder.append(delimiter);
}
}
builder.append(elements[beginIndex]);
}
@ -262,4 +264,156 @@ public class StringUtils {
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
public static boolean isDigit(String input) {
for (int i = 0; i < input.length(); i++){
if (!Character.isDigit(input.charAt(i))) {
return false;
}
}
return true;
}
public static byte parseByte(String str, byte def) {
try {
return Byte.parseByte(str);
} catch (NumberFormatException e) {
return def;
}
}
public static short parseShort(String str, short def) {
try {
return Short.parseShort(str);
} catch (NumberFormatException e) {
return def;
}
}
public static int parseInt(String str, int def) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return def;
}
}
public static long parseLong(String str, long def) {
try {
return Long.parseLong(str);
} catch (NumberFormatException e) {
return def;
}
}
public static double parseFloat(String str, float def) {
try {
return Float.parseFloat(str);
} catch (NumberFormatException e) {
return def;
}
}
public static double parseDouble(String str, double def) {
try {
return Double.parseDouble(str);
} catch (NumberFormatException e) {
return def;
}
}
public static Byte parseByte(Object obj, Byte def) {
try {
return Byte.parseByte(String.valueOf(obj));
} catch (NumberFormatException e) {
return def;
}
}
public static Byte parseByte(Object obj) {
return parseByte(obj, null);
}
public static Short parseShort(Object obj, Short def) {
try {
return Short.parseShort(String.valueOf(obj));
} catch (NumberFormatException e) {
return def;
}
}
public static Short parseShort(Object obj) {
return parseShort(obj, null);
}
public static Integer parseInt(Object obj, Integer def) {
try {
return Integer.parseInt(String.valueOf(obj));
} catch (NumberFormatException e) {
return def;
}
}
public static Integer parseInt(Object obj) {
return parseInt(obj, null);
}
public static Long parseLong(Object obj, Long def) {
try {
return Long.parseLong(String.valueOf(obj));
} catch (NumberFormatException e) {
return def;
}
}
public static Long parseLong(Object obj) {
return parseLong(obj, null);
}
public static Float parseFloat(Object obj, Float def) {
try {
return Float.parseFloat(String.valueOf(obj));
} catch (NumberFormatException e) {
return def;
}
}
public static Float parseFloat(Object obj) {
return parseFloat(obj, null);
}
public static Double parseDouble(Object obj, Double def) {
try {
return Double.parseDouble(String.valueOf(obj));
} catch (NumberFormatException e) {
return def;
}
}
public static Double parseDouble(Object obj) {
return parseDouble(obj, null);
}
public static String inflect(long value, String var1, String var2, String var3, String var4) {
if (value == 0) {
return var4;
}
long r1;
if (value % 10 == 0 || (value / 10) % 10 == 1 || (r1 = value % 10) > 4) {
return var3;
} else if (r1 != 1) {
return var2;
} else {
return var1;
}
}
public static String inflect(long value, String var1, String var2, String var3) {
return inflect(value, var1, var2, var3, var3);
}
public static String inflect(long value, String var1, String var2) {
return inflect(value, var1, var2, var2);
}
}

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
@FunctionalInterface
public interface CheckedFunction<T, R, E extends Exception> {

View file

@ -1,4 +1,4 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
public class ConfigException extends RuntimeException {
public ConfigException() {

View file

@ -1,4 +1,4 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
import java.util.List;
import java.util.Map;

View file

@ -1,6 +1,6 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
class ConfigSectionNode {
final class ConfigSectionNode {
Object value;
String[] blockComments;
String[] inlineComments;

View file

@ -1,4 +1,4 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
import java.util.*;
import java.util.function.Function;

View file

@ -1,4 +1,4 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
@ -8,25 +8,24 @@ import org.yaml.snakeyaml.comments.CommentType;
import org.yaml.snakeyaml.nodes.*;
import org.yaml.snakeyaml.parser.ParserException;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class YamlConfig extends MapConfigSection implements Config {
protected static final String DEFAULT_KEY = "config.yml";
protected static final YamlConfigConstructor CONSTRUCTOR;
protected static final YamlConfigRepresenter REPRESENTER;
protected static final Yaml YAML;
protected final String key;
protected String[] headerComments;
protected String[] endComments;
public YamlConfig(String key) {
super(null);
super();
this.key = key;
}
@ -39,26 +38,6 @@ public class YamlConfig extends MapConfigSection implements Config {
return key;
}
@Override
public String[] getHeaderComments() {
return headerComments;
}
@Override
public String[] getEndComments() {
return endComments;
}
@Override
public void setHeaderComments(String... headerComments) {
this.headerComments = headerComments;
}
@Override
public void setEndComments(String... endComments) {
this.endComments = endComments;
}
private String[] createComments(List<CommentLine> lines) {
String[] comments = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
@ -68,9 +47,23 @@ public class YamlConfig extends MapConfigSection implements Config {
return comments;
}
protected Object constructHandle(Node keyNode, Node valueNode, String key, Object value) {
private List<CommentLine> createCommentLines(String[] comments, CommentType commentType) {
List<CommentLine> lines = new ArrayList<>(comments.length);
for (String comment : comments) {
lines.add(new CommentLine(null, null, comment.isEmpty() ? comment : " " + comment, commentType));
}
return lines;
}
protected Object constructHandle(MapConfigSection section, Node keyNode, Node valueNode, String key, Object value) {
if (valueNode instanceof MappingNode) {
MapConfigSection childSection = new MapConfigSection();
MapConfigSection childSection;
ConfigSectionNode oldNode = section.map.get(key);
if (oldNode == null || !(oldNode.value instanceof MapConfigSection)) {
childSection = new MapConfigSection();
} else {
childSection = (MapConfigSection) oldNode.value;
}
nodesToSections(childSection, (MappingNode) valueNode);
value = childSection;
}
@ -82,10 +75,12 @@ public class YamlConfig extends MapConfigSection implements Config {
for (NodeTuple tuple : node.getValue()) {
Node keyNode = tuple.getKeyNode();
Node valueNode = tuple.getValueNode();
String key = String.valueOf(CONSTRUCTOR.constructObject(keyNode));
Object value = constructHandle(keyNode, valueNode, key, CONSTRUCTOR.constructObject(valueNode));
Object value = constructHandle(section, keyNode, valueNode, key, CONSTRUCTOR.constructObject(valueNode));
ConfigSectionNode sectionNode = new ConfigSectionNode(value);
if (keyNode.getBlockComments() != null && keyNode.getBlockComments().size() > 0) {
sectionNode.blockComments = createComments(keyNode.getBlockComments());
}
@ -103,12 +98,6 @@ public class YamlConfig extends MapConfigSection implements Config {
try {
MappingNode node = (MappingNode) YAML.compose(reader);
if (node == null) return;
if (node.getBlockComments() != null && node.getBlockComments().size() > 0) {
headerComments = createComments(node.getBlockComments());
}
if (node.getEndComments() != null && node.getEndComments().size() > 0) {
endComments = createComments(node.getEndComments());
}
nodesToSections(this, node);
} catch (ParserException e) {
throw new ConfigException(e);
@ -116,39 +105,10 @@ public class YamlConfig extends MapConfigSection implements Config {
}
@Override
public void load(InputStream stream) {
load(new InputStreamReader(stream, StandardCharsets.UTF_8));
}
@Override
public void load(File file) throws IOException, ConfigException {
load(Files.newInputStream(file.toPath()));
}
@Override
public File load(String path) throws ConfigException {
File file = new File(path);
try {
if (file.exists()) load(file);
} catch (IOException e) {
throw new ConfigException(e);
}
return file;
}
@Override
public File load() throws ConfigException {
public Path load() throws ConfigException {
return load(key);
}
private List<CommentLine> createCommentLines(String[] comments, CommentType commentType) {
List<CommentLine> lines = new ArrayList<>(comments.length);
for (String comment : comments) {
lines.add(new CommentLine(null, null, comment.isEmpty() ? comment : " " + comment, commentType));
}
return lines;
}
protected Node representHandle(String key, Object value) {
Node valueNode;
if (value instanceof MapConfigSection) {
@ -181,60 +141,16 @@ public class YamlConfig extends MapConfigSection implements Config {
@Override
public void save(Writer writer) {
MappingNode node = sectionsToNodes(this);
node.setBlockComments(headerComments == null ? null : createCommentLines(headerComments, CommentType.BLOCK));
node.setEndComments(endComments == null ? null : createCommentLines(endComments, CommentType.BLOCK));
YAML.serialize(node, writer);
}
@Override
public void save(OutputStream stream) {
save(new OutputStreamWriter(stream, StandardCharsets.UTF_8));
}
@Override
public void save(File file) throws IOException {
save(Files.newOutputStream(file.toPath()));
}
@Override
public File save(String path) throws ConfigException {
File file = new File(path);
if (!file.exists()) {
File parent = file.getParentFile();
if (parent != null) parent.mkdirs();
try {
file.createNewFile();
save(file);
} catch (IOException e) {
throw new ConfigException(e);
}
}
return file;
}
@Override
public File save() throws ConfigException {
public Path save() throws ConfigException {
return save(key);
}
@Override
public File saveIfEmpty(String path) throws ConfigException {
File file = new File(path);
if (file.length() == 0) {
File parent = file.getParentFile();
if (parent != null) parent.mkdirs();
try {
file.createNewFile();
save(file);
} catch (IOException e) {
throw new ConfigException(e);
}
}
return file;
}
@Override
public File saveIfEmpty() throws ConfigException {
public Path saveIfEmpty() throws ConfigException {
return saveIfEmpty(key);
}
@ -255,4 +171,9 @@ public class YamlConfig extends MapConfigSection implements Config {
YAML = new Yaml(CONSTRUCTOR = new YamlConfigConstructor(loaderOptions), representer, dumperOptions, loaderOptions);
}
@Override
public String toString() {
return key;
}
}

View file

@ -1,10 +1,10 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.nodes.Node;
public class YamlConfigConstructor extends SafeConstructor {
final class YamlConfigConstructor extends SafeConstructor {
public YamlConfigConstructor(LoaderOptions loaderOptions) {
super(loaderOptions);
}

View file

@ -1,9 +1,9 @@
package org.zhdev.config;
package org.zhdev.varioutil.config;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.representer.Representer;
public class YamlConfigRepresenter extends Representer {
final class YamlConfigRepresenter extends Representer {
public YamlConfigRepresenter(DumperOptions options) {
super(options);
}

View file

@ -1,4 +1,4 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

View file

@ -1,11 +1,8 @@
package org.zhdev.util;
package org.zhdev.varioutil.util;
import org.zhdev.config.ConfigSection;
import org.zhdev.language.Language;
import org.zhdev.sql.H2SqlConnection;
import org.zhdev.sql.MySqlConnection;
import org.zhdev.sql.SqlConnection;
import org.zhdev.sql.SqliteConnection;
import org.zhdev.varioutil.config.ConfigSection;
import org.zhdev.varioutil.language.Language;
import org.zhdev.varioutil.sql.*;
import java.io.File;
import java.util.ArrayList;
@ -31,34 +28,39 @@ public class ConfigUtils {
addPhrases(language, config, s -> s);
}
public static SqlConnection createSqlConnection(ConfigSection config, String pathPrefix) {
String type = config.getString("type", "none").toLowerCase();
SqlConnection connection;
switch (type) {
public static ConnectionProvider createSqlConnectionProvider(ConfigSection config, String pathPrefix) {
String type = config.getString("type", "none");
ConnectionProvider provider;
switch (type.toLowerCase()) {
case "sqlite": {
String path = config.getString("path", "storage.db");
provider = new SqliteProvider(pathPrefix + File.separatorChar + path);
break;
}
case "h2": {
String path = config.getString("path", "storage.h2");
String username = config.getString("username");
String password = config.getString("password");
connection = new H2SqlConnection(File.separatorChar + path, username, password);
provider = new H2Provider(pathPrefix + File.separatorChar + path, username, password);
break;
}
case "mysql": {
String address = config.getString("address", "127.0.0.1");
pathPrefix = new File(pathPrefix).getAbsoluteFile().getName().replace(File.separator, "_").toLowerCase();
String dbname = config.getString("dbname", System.getProperty("user.home") + '_' + pathPrefix);
String dbname = config.getString("dbname", System.getProperty("user.home"));
String username = config.getString("username", System.getProperty("user.home"));
String password = config.getString("password");
boolean ssl = config.getBoolean("ssl", false);
connection = new MySqlConnection(address, dbname, username, password, ssl);
provider = new MysqlProvider(address, dbname, username, password, ssl);
break;
}
case "sqlite": {
String path = config.getString("path", "database.db");
connection = new SqliteConnection(pathPrefix + File.separatorChar + path);
case "none": {
provider = ConnectionProvider.NOT_ESTABLISHED;
break;
}
default: case "none": connection = SqlConnection.NOT_ESTABLISHED;
default: {
throw new SqlException("Unknown database driver: " + type);
}
}
return connection;
return provider;
}
}