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.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter; import org.bukkit.command.TabCompleter;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class BukkitPlugin extends JavaPlugin { 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); PluginCommand command = Bukkit.getPluginCommand(label);
if (command != null) { if (command != null) {
command.setExecutor(executor); command.setExecutor(executor);
command.setTabCompleter(completer); command.setTabCompleter(completer);
} }
return command;
} }
public void registerCommand(String label, CommandExecutor executor) { public Command registerCommand(CommandExecutor executor, String label) {
registerCommand(label, executor, this); return registerCommand(executor, executor instanceof TabCompleter ? (TabCompleter) executor : this, label);
} }
public void registerEvents(Listener listener) { public void registerEvents(Listener listener) {

View file

@ -1,4 +1,4 @@
package org.zhdev; package org.zhdev.varioutil;
import org.jetbrains.annotations.NotNull; 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.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -15,7 +15,7 @@ public class Language {
return sectionKey + ':' + phraseKey; return sectionKey + ':' + phraseKey;
} }
String phrase = section.getOrDefault(phraseKey, phraseKey); String phrase = section.get(phraseKey);
if (phrase == null) { if (phrase == null) {
Map<String, Object> paramsMap = new LinkedHashMap<>(params.length / 2); Map<String, Object> paramsMap = new LinkedHashMap<>(params.length / 2);
Object replacement = null; Object replacement = null;
@ -23,7 +23,7 @@ public class Language {
if (i % 2 == 0) { if (i % 2 == 0) {
replacement = params[i]; replacement = params[i];
} else { } else {
paramsMap.put(String.valueOf(params[i]), replacement); paramsMap.put(String.valueOf(replacement), params[i]);
} }
} }
return sectionKey + ':' + phraseKey + ' ' + paramsMap; 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; 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; 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.Collection;
import java.util.function.Function; import java.util.function.Function;
@ -33,27 +33,27 @@ public class ArrayUtils {
} }
public static <T> Byte[] mapToByte(T[] array, IntFunction<Byte[]> arrayConstructor) { 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) { 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) { 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) { 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) { 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) { 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) { 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.Collection;
import java.util.List; 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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.*;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;

View file

@ -1,4 +1,4 @@
package org.zhdev.util; package org.zhdev.varioutil.util;
public class EnumUtils { public class EnumUtils {
private static <T extends Enum<T>> T[] getValues(T eNum) { 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.varioutil.reflection.FieldSearcher;
import org.zhdev.reflection.MethodSearcher; import org.zhdev.varioutil.reflection.MethodSearcher;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;

View file

@ -1,9 +1,10 @@
package org.zhdev.util; package org.zhdev.varioutil.util;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path;
public class ResourceUtils { public class ResourceUtils {
public static InputStream getResource(String path, ClassLoader loader) { public static InputStream getResource(String path, ClassLoader loader) {
@ -25,7 +26,7 @@ public class ResourceUtils {
return getResource(path, ResourceUtils.class.getClassLoader()); 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("")) { if (resourcePath == null || resourcePath.equals("")) {
return false; return false;
} }
@ -36,14 +37,14 @@ public class ResourceUtils {
return false; return false;
} }
File parent = outFile.getParentFile(); try {
if (parent != null && !parent.exists()) { Path parent = outPath.getParent();
parent.mkdirs(); if (parent != null && Files.notExists(parent)) {
Files.createDirectories(parent);
} }
try { if (Files.notExists(outPath) || Files.size(outPath) == 0) {
if (!outFile.exists() || outFile.length() == 0) { OutputStream stream = Files.newOutputStream(outPath);
OutputStream stream = Files.newOutputStream(outFile.toPath());
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int len; int len;
while ((len = in.read(buf)) > 0) { while ((len = in.read(buf)) > 0) {
@ -54,14 +55,14 @@ public class ResourceUtils {
return true; return true;
} }
} catch (IOException e) { } 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; return false;
} }
public static boolean saveResource(String resourcePath, File outFile) throws IllegalStateException { public static boolean saveResource(String resourcePath, Path outPath) throws IllegalStateException {
return saveResource(resourcePath, outFile); 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.ArrayList;
import java.util.Iterator; import java.util.Iterator;
@ -8,11 +8,13 @@ public class StringUtils {
public static String join(int beginIndex, int lastIndex, String delimiter, String lastDelimiter, String... elements) { public static String join(int beginIndex, int lastIndex, String delimiter, String lastDelimiter, String... elements) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (; beginIndex < elements.length; beginIndex++) { for (; beginIndex < elements.length; beginIndex++) {
if (builder.length() > 0) {
if (beginIndex == lastIndex) { if (beginIndex == lastIndex) {
builder.append(lastDelimiter); builder.append(lastDelimiter);
} else { } else {
builder.append(delimiter); builder.append(delimiter);
} }
}
builder.append(elements[beginIndex]); builder.append(elements[beginIndex]);
} }
return builder.toString(); return builder.toString();
@ -262,4 +264,156 @@ public class StringUtils {
chars[0] = Character.toUpperCase(chars[0]); chars[0] = Character.toUpperCase(chars[0]);
return new String(chars); 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 @FunctionalInterface
public interface CheckedFunction<T, R, E extends Exception> { 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 class ConfigException extends RuntimeException {
public ConfigException() { public ConfigException() {

View file

@ -1,4 +1,4 @@
package org.zhdev.config; package org.zhdev.varioutil.config;
import java.util.List; import java.util.List;
import java.util.Map; 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; Object value;
String[] blockComments; String[] blockComments;
String[] inlineComments; String[] inlineComments;

View file

@ -1,4 +1,4 @@
package org.zhdev.config; package org.zhdev.varioutil.config;
import java.util.*; import java.util.*;
import java.util.function.Function; 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.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.LoaderOptions;
@ -8,25 +8,24 @@ import org.yaml.snakeyaml.comments.CommentType;
import org.yaml.snakeyaml.nodes.*; import org.yaml.snakeyaml.nodes.*;
import org.yaml.snakeyaml.parser.ParserException; import org.yaml.snakeyaml.parser.ParserException;
import java.io.*; import java.io.Reader;
import java.nio.charset.StandardCharsets; import java.io.Writer;
import java.nio.file.Files; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class YamlConfig extends MapConfigSection implements Config { public class YamlConfig extends MapConfigSection implements Config {
protected static final String DEFAULT_KEY = "config.yml";
protected static final YamlConfigConstructor CONSTRUCTOR; protected static final YamlConfigConstructor CONSTRUCTOR;
protected static final YamlConfigRepresenter REPRESENTER; protected static final YamlConfigRepresenter REPRESENTER;
protected static final Yaml YAML; protected static final Yaml YAML;
protected final String key; protected final String key;
protected String[] headerComments;
protected String[] endComments;
public YamlConfig(String key) { public YamlConfig(String key) {
super(null); super();
this.key = key; this.key = key;
} }
@ -39,26 +38,6 @@ public class YamlConfig extends MapConfigSection implements Config {
return key; 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) { private String[] createComments(List<CommentLine> lines) {
String[] comments = new String[lines.size()]; String[] comments = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) { for (int i = 0; i < lines.size(); i++) {
@ -68,9 +47,23 @@ public class YamlConfig extends MapConfigSection implements Config {
return comments; 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) { 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); nodesToSections(childSection, (MappingNode) valueNode);
value = childSection; value = childSection;
} }
@ -82,10 +75,12 @@ public class YamlConfig extends MapConfigSection implements Config {
for (NodeTuple tuple : node.getValue()) { for (NodeTuple tuple : node.getValue()) {
Node keyNode = tuple.getKeyNode(); Node keyNode = tuple.getKeyNode();
Node valueNode = tuple.getValueNode(); Node valueNode = tuple.getValueNode();
String key = String.valueOf(CONSTRUCTOR.constructObject(keyNode)); 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); ConfigSectionNode sectionNode = new ConfigSectionNode(value);
if (keyNode.getBlockComments() != null && keyNode.getBlockComments().size() > 0) { if (keyNode.getBlockComments() != null && keyNode.getBlockComments().size() > 0) {
sectionNode.blockComments = createComments(keyNode.getBlockComments()); sectionNode.blockComments = createComments(keyNode.getBlockComments());
} }
@ -103,12 +98,6 @@ public class YamlConfig extends MapConfigSection implements Config {
try { try {
MappingNode node = (MappingNode) YAML.compose(reader); MappingNode node = (MappingNode) YAML.compose(reader);
if (node == null) return; 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); nodesToSections(this, node);
} catch (ParserException e) { } catch (ParserException e) {
throw new ConfigException(e); throw new ConfigException(e);
@ -116,39 +105,10 @@ public class YamlConfig extends MapConfigSection implements Config {
} }
@Override @Override
public void load(InputStream stream) { public Path load() throws ConfigException {
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 {
return load(key); 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) { protected Node representHandle(String key, Object value) {
Node valueNode; Node valueNode;
if (value instanceof MapConfigSection) { if (value instanceof MapConfigSection) {
@ -181,60 +141,16 @@ public class YamlConfig extends MapConfigSection implements Config {
@Override @Override
public void save(Writer writer) { public void save(Writer writer) {
MappingNode node = sectionsToNodes(this); 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); YAML.serialize(node, writer);
} }
@Override @Override
public void save(OutputStream stream) { public Path save() throws ConfigException {
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 {
return save(key); return save(key);
} }
@Override @Override
public File saveIfEmpty(String path) throws ConfigException { public Path saveIfEmpty() 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 {
return saveIfEmpty(key); return saveIfEmpty(key);
} }
@ -255,4 +171,9 @@ public class YamlConfig extends MapConfigSection implements Config {
YAML = new Yaml(CONSTRUCTOR = new YamlConfigConstructor(loaderOptions), representer, dumperOptions, loaderOptions); 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.LoaderOptions;
import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Node;
public class YamlConfigConstructor extends SafeConstructor { final class YamlConfigConstructor extends SafeConstructor {
public YamlConfigConstructor(LoaderOptions loaderOptions) { public YamlConfigConstructor(LoaderOptions loaderOptions) {
super(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.DumperOptions;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
public class YamlConfigRepresenter extends Representer { final class YamlConfigRepresenter extends Representer {
public YamlConfigRepresenter(DumperOptions options) { public YamlConfigRepresenter(DumperOptions options) {
super(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.Matcher;
import java.util.regex.Pattern; 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.varioutil.config.ConfigSection;
import org.zhdev.language.Language; import org.zhdev.varioutil.language.Language;
import org.zhdev.sql.H2SqlConnection; import org.zhdev.varioutil.sql.*;
import org.zhdev.sql.MySqlConnection;
import org.zhdev.sql.SqlConnection;
import org.zhdev.sql.SqliteConnection;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
@ -31,34 +28,39 @@ public class ConfigUtils {
addPhrases(language, config, s -> s); addPhrases(language, config, s -> s);
} }
public static SqlConnection createSqlConnection(ConfigSection config, String pathPrefix) { public static ConnectionProvider createSqlConnectionProvider(ConfigSection config, String pathPrefix) {
String type = config.getString("type", "none").toLowerCase(); String type = config.getString("type", "none");
SqlConnection connection; ConnectionProvider provider;
switch (type) { switch (type.toLowerCase()) {
case "sqlite": {
String path = config.getString("path", "storage.db");
provider = new SqliteProvider(pathPrefix + File.separatorChar + path);
break;
}
case "h2": { case "h2": {
String path = config.getString("path", "storage.h2"); String path = config.getString("path", "storage.h2");
String username = config.getString("username"); String username = config.getString("username");
String password = config.getString("password"); String password = config.getString("password");
connection = new H2SqlConnection(File.separatorChar + path, username, password); provider = new H2Provider(pathPrefix + File.separatorChar + path, username, password);
break; break;
} }
case "mysql": { case "mysql": {
String address = config.getString("address", "127.0.0.1"); 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"));
String dbname = config.getString("dbname", System.getProperty("user.home") + '_' + pathPrefix);
String username = config.getString("username", System.getProperty("user.home")); String username = config.getString("username", System.getProperty("user.home"));
String password = config.getString("password"); String password = config.getString("password");
boolean ssl = config.getBoolean("ssl", false); boolean ssl = config.getBoolean("ssl", false);
connection = new MySqlConnection(address, dbname, username, password, ssl); provider = new MysqlProvider(address, dbname, username, password, ssl);
break; break;
} }
case "sqlite": { case "none": {
String path = config.getString("path", "database.db"); provider = ConnectionProvider.NOT_ESTABLISHED;
connection = new SqliteConnection(pathPrefix + File.separatorChar + path);
break; break;
} }
default: case "none": connection = SqlConnection.NOT_ESTABLISHED; default: {
} throw new SqlException("Unknown database driver: " + type);
return connection; }
}
return provider;
} }
} }