From abf85cf9605a929f0e48ffffb4cecfcd3e3f1dd4 Mon Sep 17 00:00:00 2001 From: portlek Date: Thu, 12 Dec 2019 15:54:28 +0300 Subject: [PATCH] update classes Former-commit-id: b990d7d5428f011a2e4b5260a6540405e4ec24c1 --- .../File/BukkitFileAPI/JSONConfiguration.java | 186 ++++++++++++++ .../JSONConfigurationOptions.java | 65 +++++ .../File/BukkitFileAPI/SerializableSet.java | 151 ++++++++++++ .../maxgamer/quickshop/File/FileEnvelope.java | 102 ++++++++ .../org/maxgamer/quickshop/File/IFile.java | 24 ++ .../org/maxgamer/quickshop/File/JSONFile.java | 72 ++++++ .../org/maxgamer/quickshop/File/XMLFile.java | 59 +++++ .../org/maxgamer/quickshop/File/YAMLFile.java | 68 ++++++ .../quickshop/Mock/MckFileConfiguration.java | 20 ++ .../org/maxgamer/quickshop/QuickShop.java | 1 - .../org/maxgamer/quickshop/Util/Copied.java | 37 +++ .../quickshop/Util/SerializationHelper.java | 146 +++++++++++ src/main/resources/config.yml | 4 +- .../maxgamer/quickshop/File/JSONFileTest.java | 26 ++ .../org/maxgamer/quickshop/QuickShopTest.java | 24 ++ src/test/resources/messages.json | 231 ++++++++++++++++++ src/test/resources/plugin.yml | 3 + 17 files changed, 1216 insertions(+), 3 deletions(-) create mode 100644 src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfiguration.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfigurationOptions.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/SerializableSet.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/IFile.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/JSONFile.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/XMLFile.java create mode 100644 src/main/java/org/maxgamer/quickshop/File/YAMLFile.java create mode 100644 src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java create mode 100644 src/main/java/org/maxgamer/quickshop/Util/Copied.java create mode 100644 src/main/java/org/maxgamer/quickshop/Util/SerializationHelper.java create mode 100644 src/test/java/org/maxgamer/quickshop/File/JSONFileTest.java create mode 100644 src/test/java/org/maxgamer/quickshop/QuickShopTest.java create mode 100644 src/test/resources/messages.json create mode 100644 src/test/resources/plugin.yml diff --git a/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfiguration.java b/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfiguration.java new file mode 100644 index 000000000..9e6501eaf --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfiguration.java @@ -0,0 +1,186 @@ +package org.maxgamer.quickshop.File.BukkitFileAPI; + +import com.google.gson.*; +import com.google.gson.internal.LinkedTreeMap; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang.StringEscapeUtils; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.jetbrains.annotations.NotNull; +import org.maxgamer.quickshop.Util.SerializationHelper; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.Reader; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; + +public final class JSONConfiguration extends FileConfiguration { + + protected static final String BLANK_CONFIG = "{}\n"; + + @NotNull + @Override + public String saveToString() { + final GsonBuilder gsonBuilder = new GsonBuilder(); + + if (options().prettyPrint()) { + gsonBuilder.setPrettyPrinting(); + } + + final Gson gson = gsonBuilder.create(); + final Object value = SerializationHelper.serialize(getValues(false)); + final String dump = StringEscapeUtils.unescapeJava(gson.toJson(value)); + + if (dump.equals(BLANK_CONFIG)) { + return ""; + } + + return dump; + } + + @Override + public void loadFromString(@NotNull String contents) throws InvalidConfigurationException { + if (contents.isEmpty()) { + return; + } + + final Map input; + + try { + final Gson gson = new GsonBuilder() + .registerTypeAdapter(new TypeToken>(){}.getType(), + new MapDeserializerDoubleAsIntFix()) + .create(); + input = gson.fromJson(contents, new TypeToken>(){}.getType()); + } catch (JsonSyntaxException e) { + throw new InvalidConfigurationException("Invalid JSON detected.", e); + } catch (ClassCastException e) { + throw new InvalidConfigurationException("Top level is not a Map.", e); + } + + if (input != null) { + convertMapsToSections(input, this); + } else { + throw new InvalidConfigurationException("An unknown error occurred while attempting to parse the json."); + } + } + + @NotNull + @Override + protected String buildHeader() { + return ""; + } + + protected void convertMapsToSections(@NotNull Map input, @NotNull ConfigurationSection section) { + final Object result = SerializationHelper.deserialize(input); + + if (result instanceof Map) { + input = (Map) result; + + for (Map.Entry entry : input.entrySet()) { + final String key = entry.getKey().toString(); + final Object value = entry.getValue(); + + if (value instanceof Map) { + convertMapsToSections((Map) value, section.createSection(key)); + } else { + section.set(key, value); + } + } + } else { + section.set("", result); + } + } + + @NotNull + @Override + public JSONConfigurationOptions options() { + if (options == null) { + options = new JSONConfigurationOptions(this); + } + + return (JSONConfigurationOptions) options; + } + + @NotNull + public static JSONConfiguration loadConfiguration(@NotNull File file) { + final JSONConfiguration config = new JSONConfiguration(); + + try { + config.load(file); + } catch (FileNotFoundException ignored) { + // ignored... + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } + + return config; + } + + @NotNull + public static JSONConfiguration loadConfiguration(@NotNull Reader reader) { + final JSONConfiguration config = new JSONConfiguration(); + + try { + config.load(reader); + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } + + return config; + } + + public static class MapDeserializerDoubleAsIntFix implements JsonDeserializer> { + + @Override @SuppressWarnings("unchecked") + public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return (Map) read(json); + } + + public Object read(JsonElement in) { + + if(in.isJsonArray()){ + List list = new ArrayList(); + JsonArray arr = in.getAsJsonArray(); + for (JsonElement anArr : arr) { + list.add(read(anArr)); + } + return list; + }else if(in.isJsonObject()){ + Map map = new LinkedTreeMap(); + JsonObject obj = in.getAsJsonObject(); + Set> entitySet = obj.entrySet(); + for(Map.Entry entry: entitySet){ + map.put(entry.getKey(), read(entry.getValue())); + } + return map; + }else if( in.isJsonPrimitive()){ + JsonPrimitive prim = in.getAsJsonPrimitive(); + if(prim.isBoolean()){ + return prim.getAsBoolean(); + }else if(prim.isString()){ + return prim.getAsString(); + }else if(prim.isNumber()){ + Number num = prim.getAsNumber(); + // here you can handle double int/long values + // and return any type you want + // this solution will transform 3.0 float to long values + if(Math.ceil(num.doubleValue()) == num.longValue()) + return num.longValue(); + else{ + return num.doubleValue(); + } + } + } + return null; + } + } +} diff --git a/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfigurationOptions.java b/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfigurationOptions.java new file mode 100644 index 000000000..b67684a5f --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/JSONConfigurationOptions.java @@ -0,0 +1,65 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +package org.maxgamer.quickshop.File.BukkitFileAPI; + +import org.bukkit.configuration.file.FileConfigurationOptions; +import org.jetbrains.annotations.NotNull; + +public class JSONConfigurationOptions extends FileConfigurationOptions { + + private boolean enablePrettyPrint = true; + + protected JSONConfigurationOptions(@NotNull final JSONConfiguration configuration) { + super(configuration); + } + + @Override + public JSONConfiguration configuration() { + return (JSONConfiguration) super.configuration(); + } + + @Override + public JSONConfigurationOptions copyDefaults(final boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public JSONConfigurationOptions pathSeparator(final char value) { + super.pathSeparator(value); + return this; + } + + @Override + public JSONConfigurationOptions header(final String value) { + super.header(value); + return this; + } + + @Override + public JSONConfigurationOptions copyHeader(final boolean value) { + super.copyHeader(value); + return this; + } + + /** + * Sets whether or not to pretty print the json output of the configuration. + * + * @param enable Whether or not pretty printing should be enabled. + * @return This object, for chaining. + */ + public JSONConfigurationOptions prettyPrint(final boolean enable) { + enablePrettyPrint = enable; + return this; + } + + /** + * Gets whether or not to pretty print the json output of the configuration. + * + * @return Whether or not to pretty print the json. + */ + public boolean prettyPrint() { + return enablePrettyPrint; + } +} diff --git a/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/SerializableSet.java b/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/SerializableSet.java new file mode 100644 index 000000000..2f565b618 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/BukkitFileAPI/SerializableSet.java @@ -0,0 +1,151 @@ +package org.maxgamer.quickshop.File.BukkitFileAPI; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; + +@SerializableAs("set") +public class SerializableSet implements Set, ConfigurationSerializable { + + @NotNull + private final Set backingSet; + + public SerializableSet(@NotNull Set backingSet) { + this.backingSet = backingSet; + } + + @SuppressWarnings("unchecked") + public SerializableSet(@NotNull Map serializedForm) { + Object o = serializedForm.get("contents"); + if (o instanceof List) { + backingSet = new HashSet((List) o); + } else { + backingSet = Collections.emptySet(); + } + } + + @SuppressWarnings("unchecked") + @Override + public Map serialize() { + Map serializedForm = new HashMap<>(backingSet.size()); + List contents = new ArrayList(backingSet); + serializedForm.put("contents", contents); + return serializedForm; + } + + @Override + public int size() { + return backingSet.size(); + } + + @Override + public boolean isEmpty() { + return backingSet.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return backingSet.contains(o); + } + + @NotNull + @Override + public Iterator iterator() { + return backingSet.iterator(); + } + + @NotNull + @Override + public Object[] toArray() { + return backingSet.toArray(); + } + + @NotNull + @Override + public Object[] toArray(@NotNull Object[] a) { + return backingSet.toArray(a); + } + + @SuppressWarnings("unchecked") + @Override + public boolean add(Object o) { + return backingSet.add(o); + } + + @Override + public boolean remove(Object o) { + return backingSet.remove(o); + } + + @SuppressWarnings("unchecked") + @Override + public boolean containsAll(@NotNull Collection c) { + return backingSet.containsAll(c); + } + + @SuppressWarnings("unchecked") + @Override + public boolean addAll(@NotNull Collection c) { + return backingSet.addAll(c); + } + + @SuppressWarnings("unchecked") + @Override + public boolean retainAll(@NotNull Collection c) { + return backingSet.retainAll(c); + } + + @SuppressWarnings("unchecked") + @Override + public boolean removeAll(@NotNull Collection c) { + return backingSet.removeAll(c); + } + + @Override + public void clear() { + backingSet.clear(); + } + + @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") + @Override + public boolean equals(Object o) { + return backingSet.equals(o); + } + + @Override + public int hashCode() { + return backingSet.hashCode(); + } + + @Override + public Spliterator spliterator() { + return backingSet.spliterator(); + } + + @SuppressWarnings("unchecked") + @Override + public boolean removeIf(Predicate filter) { + return backingSet.removeIf(filter); + } + + @Override + public Stream stream() { + return backingSet.stream(); + } + + @Override + public Stream parallelStream() { + return backingSet.parallelStream(); + } + + @SuppressWarnings("unchecked") + @Override + public void forEach(Consumer action) { + backingSet.forEach(action); + } +} diff --git a/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java b/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java new file mode 100644 index 000000000..ca1ffae00 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/FileEnvelope.java @@ -0,0 +1,102 @@ +package org.maxgamer.quickshop.File; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.Plugin; +import org.cactoos.io.InputOf; +import org.cactoos.io.InputStreamOf; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.maxgamer.quickshop.Mock.MckFileConfiguration; +import org.maxgamer.quickshop.Util.Copied; + +import java.io.File; +import java.io.InputStream; + +public abstract class FileEnvelope implements IFile { + + @NotNull + private final Plugin plugin; + + @NotNull + protected final File file; + + @NotNull + private final Copied copied; + + @NotNull + private final String resourcePath; + + protected final boolean loadDefault; + + @NotNull + protected FileConfiguration fileConfiguration = new MckFileConfiguration(); + + public FileEnvelope(@NotNull Plugin plugin, @NotNull File file, @NotNull String resourcePath, boolean loadDefault) { + this.plugin = plugin; + this.file = file; + this.copied = new Copied(file); + this.resourcePath = resourcePath; + this.loadDefault = loadDefault; + } + + @Override + public void create() { + if (file.exists()) { + reload(); + return; + } + + try { + final File parent = file.getParentFile(); + + if (parent != null) { + parent.mkdirs(); + } + + file.createNewFile(); + } catch (Exception exception) { + throw new RuntimeException(exception); + } + + if (loadDefault) { + copied.exec(getInputStream()); + } + + reload(); + } + + @NotNull + @Override + public InputStream getInputStream() { + return new InputStreamOf( + new InputOf( + plugin.getResource(resourcePath) + ) + ); + } + + @Override + public void save() { + try { + if (fileConfiguration instanceof MckFileConfiguration) { + reload(); + } + + fileConfiguration.save(file); + } catch (Exception exception) { + throw new RuntimeException(exception); + } + } + + @Nullable + @Override + public Object get(@NotNull String path) { + return fileConfiguration.get(path); + } + + @Override + public void set(@NotNull String path, @NotNull Object object) { + fileConfiguration.set(path, object); + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/File/IFile.java b/src/main/java/org/maxgamer/quickshop/File/IFile.java new file mode 100644 index 000000000..e30ee6a08 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/IFile.java @@ -0,0 +1,24 @@ +package org.maxgamer.quickshop.File; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.InputStream; + +public interface IFile { + + void create(); + + @NotNull + InputStream getInputStream(); + + void reload(); + + void save(); + + @Nullable + Object get(@NotNull String path); + + void set(@NotNull String path, @NotNull Object object); + +} diff --git a/src/main/java/org/maxgamer/quickshop/File/JSONFile.java b/src/main/java/org/maxgamer/quickshop/File/JSONFile.java new file mode 100644 index 000000000..e7e63668f --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/JSONFile.java @@ -0,0 +1,72 @@ +package org.maxgamer.quickshop.File; + +import org.bukkit.plugin.Plugin; +import org.cactoos.io.ReaderOf; +import org.jetbrains.annotations.NotNull; +import org.maxgamer.quickshop.File.BukkitFileAPI.JSONConfiguration; + +import java.io.File; +import java.nio.charset.StandardCharsets; + +public final class JSONFile extends FileEnvelope { + + public JSONFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath, + boolean loadDefault) { + super( + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + loadDefault + ); + } + + public JSONFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath) { + super( + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + true + ); + } + + public JSONFile(@NotNull final Plugin plugin, @NotNull final String resourcePath, @NotNull final String fileName) { + this( + plugin, + new File( + plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") + ? resourcePath + : "/" + resourcePath), + fileName.endsWith(".yml") ? fileName : fileName + ".yml" + ), + resourcePath.isEmpty() + ? fileName + : resourcePath.endsWith("/") + ? resourcePath + fileName + : resourcePath + "/" + fileName + ); + } + + public JSONFile(@NotNull final Plugin plugin, @NotNull final String fileName) { + this(plugin, "", fileName); + } + + @Override + public void reload() { + fileConfiguration = JSONConfiguration.loadConfiguration(file); + if (loadDefault) { + fileConfiguration.setDefaults( + JSONConfiguration.loadConfiguration( + new ReaderOf( + getInputStream(), + StandardCharsets.UTF_8 + ) + ) + ); + } + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/File/XMLFile.java b/src/main/java/org/maxgamer/quickshop/File/XMLFile.java new file mode 100644 index 000000000..5e092d089 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/XMLFile.java @@ -0,0 +1,59 @@ +package org.maxgamer.quickshop.File; + +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +import java.io.File; + +public final class XMLFile extends FileEnvelope { + + public XMLFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath, + boolean loadDefault) { + super( + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + loadDefault + ); + } + + public XMLFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath) { + super( + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + true + ); + } + + public XMLFile(@NotNull final Plugin plugin, @NotNull final String resourcePath, @NotNull final String fileName) { + this( + plugin, + new File( + plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") + ? resourcePath + : "/" + resourcePath), + fileName.endsWith(".yml") ? fileName : fileName + ".yml" + ), + resourcePath.isEmpty() + ? fileName + : resourcePath.endsWith("/") + ? resourcePath + fileName + : resourcePath + "/" + fileName + ); + } + + public XMLFile(@NotNull final Plugin plugin, @NotNull final String fileName) { + this(plugin, "", fileName); + } + + @Override + public void reload() { + + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java b/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java new file mode 100644 index 000000000..9d13c0ec2 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/File/YAMLFile.java @@ -0,0 +1,68 @@ +package org.maxgamer.quickshop.File; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.InputStreamReader; + +public final class YAMLFile extends FileEnvelope { + + public YAMLFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath, + boolean loadDefault) { + super( + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + loadDefault + ); + } + + public YAMLFile(@NotNull final Plugin plugin, @NotNull final File file, @NotNull final String resourcePath) { + super( + plugin, + file, + resourcePath.endsWith(".yml") + ? resourcePath + : resourcePath + ".yml", + true + ); + } + + public YAMLFile(@NotNull final Plugin plugin, @NotNull final String resourcePath, @NotNull final String fileName) { + this( + plugin, + new File( + plugin.getDataFolder().getAbsolutePath() + (resourcePath.startsWith("/") + ? resourcePath + : "/" + resourcePath), + fileName.endsWith(".yml") ? fileName : fileName + ".yml" + ), + resourcePath.isEmpty() + ? fileName + : resourcePath.endsWith("/") + ? resourcePath + fileName + : resourcePath + "/" + fileName + ); + } + + public YAMLFile(@NotNull final Plugin plugin, @NotNull final String fileName) { + this(plugin, "", fileName); + } + + @Override + public void reload() { + fileConfiguration = YamlConfiguration.loadConfiguration(file); + fileConfiguration.setDefaults( + YamlConfiguration.loadConfiguration( + new InputStreamReader( + getInputStream() + ) + ) + ); + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java b/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java new file mode 100644 index 000000000..741442cff --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/Mock/MckFileConfiguration.java @@ -0,0 +1,20 @@ +package org.maxgamer.quickshop.Mock; + +import org.bukkit.configuration.file.FileConfiguration; +import org.jetbrains.annotations.NotNull; + +public final class MckFileConfiguration extends FileConfiguration { + @NotNull + @Override + public String saveToString() { + return ""; + } + @Override + public void loadFromString(@NotNull String s) { + } + @NotNull + @Override + protected String buildHeader() { + return ""; + } +} diff --git a/src/main/java/org/maxgamer/quickshop/QuickShop.java b/src/main/java/org/maxgamer/quickshop/QuickShop.java index 1b60fd5f7..41eca2702 100644 --- a/src/main/java/org/maxgamer/quickshop/QuickShop.java +++ b/src/main/java/org/maxgamer/quickshop/QuickShop.java @@ -411,7 +411,6 @@ public class QuickShop extends JavaPlugin { sentryErrorReporter = new SentryErrorReporter(this); // loadEcon(); - /* Initalize the Utils */ itemMatcher = new ItemMatcher(this); Util.initialize(); diff --git a/src/main/java/org/maxgamer/quickshop/Util/Copied.java b/src/main/java/org/maxgamer/quickshop/Util/Copied.java new file mode 100644 index 000000000..100a5299a --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/Util/Copied.java @@ -0,0 +1,37 @@ +package org.maxgamer.quickshop.Util; + +import org.cactoos.Proc; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +public final class Copied implements Proc { + + @NotNull + private final File file; + + public Copied(@NotNull File file) { + this.file = file; + } + + @Override + public void exec(@NotNull InputStream inputStream) { + try(final OutputStream out = new FileOutputStream(file)) { + final byte[] buf = new byte[1024]; + int len; + + while((len = inputStream.read(buf)) > 0) { + out.write(buf, 0, len); + } + + out.close(); + inputStream.close(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/Util/SerializationHelper.java b/src/main/java/org/maxgamer/quickshop/Util/SerializationHelper.java new file mode 100644 index 000000000..b25d78a98 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/Util/SerializationHelper.java @@ -0,0 +1,146 @@ +package org.maxgamer.quickshop.Util; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.jetbrains.annotations.NotNull; +import org.maxgamer.quickshop.File.BukkitFileAPI.SerializableSet; +import org.yaml.snakeyaml.error.YAMLException; + +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * @author Jeremy Wood + * @version 6/14/2017 + */ +public class SerializationHelper { + + private static final Logger LOG = Logger.getLogger(SerializationHelper.class.getName()); + + public static Object serialize(@NotNull Object value) { + if (value instanceof Object[]) { + value = new ArrayList<>(Arrays.asList((Object[]) value)); + } + if (value instanceof Set && !(value instanceof SerializableSet)) { + value = new SerializableSet((Set) value); + } + if (value instanceof ConfigurationSection) { + return buildMap(((ConfigurationSection) value).getValues(false)); + } else if (value instanceof Map) { + return buildMap((Map) value); + } else if (value instanceof List) { + return buildList((List) value); + } else if (value instanceof ConfigurationSerializable) { + ConfigurationSerializable serializable = (ConfigurationSerializable) value; + Map values = new LinkedHashMap<>(); + values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); + values.putAll(serializable.serialize()); + return buildMap(values); + } else { + return value; + } + } + + /** + * Takes a Map and parses through the values, to ensure that, before saving, all objects are as appropriate as + * possible for storage in most data formats. + * + * Specifically it does the following: + * for Map: calls this method recursively on the Map before putting it in the returned Map. + * for List: calls {@link #buildList(java.util.Collection)} which functions similar to this method. + * for ConfigurationSection: gets the values as a map and calls this method recursively on the Map before putting + * it in the returned Map. + * for ConfigurationSerializable: add the {@link ConfigurationSerialization#SERIALIZED_TYPE_KEY} to a new Map + * along with the Map given by {@link org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()} + * and calls this method recursively on the new Map before putting it in the returned Map. + * for Everything else: stores it as is in the returned Map. + */ + @NotNull + private static Map buildMap(@NotNull final Map map) { + final Map result = new LinkedHashMap(map.size()); + try { + for (final Map.Entry entry : map.entrySet()) { + result.put(entry.getKey().toString(), serialize(entry.getValue())); + } + } catch (final Exception e) { + LOG.log(Level.WARNING, "Error while building configuration map.", e); + } + return result; + } + + /** + * Takes a Collection and parses through the values, to ensure that, before saving, all objects are as appropriate + * as possible for storage in most data formats. + * + * Specifically it does the following: + * for Map: calls {@link #buildMap(java.util.Map)} on the Map before adding to the returned list. + * for List: calls this method recursively on the List. + * for ConfigurationSection: gets the values as a map and calls {@link #buildMap(java.util.Map)} on the Map + * before adding to the returned list. + * for ConfigurationSerializable: add the {@link ConfigurationSerialization#SERIALIZED_TYPE_KEY} to a new Map + * along with the Map given by {@link org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()} + * and calls {@link #buildMap(java.util.Map)} on the new Map before adding to the returned list. + * for Everything else: stores it as is in the returned List. + */ + private static List buildList(@NotNull final Collection collection) { + final List result = new ArrayList(collection.size()); + try { + for (Object o : collection) { + result.add(serialize(o)); + } + } catch (Exception e) { + LOG.log(Level.WARNING, "Error while building configuration list.", e); + } + return result; + } + + /** + * Parses through the input map to deal with serialized objects a la {@link ConfigurationSerializable}. + * + * Called recursively first on Maps and Lists before passing the parsed input over to + * {@link ConfigurationSerialization#deserializeObject(java.util.Map)}. Basically this means it will deserialize + * the most nested objects FIRST and the top level object LAST. + */ + public static Object deserialize(@NotNull final Map input) { + final Map output = new LinkedHashMap(input.size()); + for (final Map.Entry e : input.entrySet()) { + if (e.getValue() instanceof Map) { + output.put(e.getKey().toString(), deserialize((Map) e.getValue())); + } else if (e.getValue() instanceof List) { + output.put(e.getKey().toString(), deserialize((List) e.getValue())); + } else { + output.put(e.getKey().toString(), e.getValue()); + } + } + if (output.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { + try { + return ConfigurationSerialization.deserializeObject(output); + } catch (IllegalArgumentException ex) { + throw new YAMLException("Could not deserialize object", ex); + } + } + return output; + } + + /** + * Parses through the input list to deal with serialized objects a la {@link ConfigurationSerializable}. + * + * Functions similarly to {@link #deserialize(java.util.Map)} but only for detecting lists within + * lists and maps within lists. + */ + private static Object deserialize(@NotNull final List input) { + final List output = new ArrayList(input.size()); + for (final Object o : input) { + if (o instanceof Map) { + output.add(deserialize((Map) o)); + } else if (o instanceof List) { + output.add(deserialize((List) o)); + } else { + output.add(o); + } + } + return output; + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index d5a7334c5..8005d2edb 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -130,7 +130,7 @@ limits: #By default, chests are added to this list. #This will only work for blocks which implement InventoryHolder #in other words, no enderchest shops, no shops on dirt blocks, etc. -#May cause unexpected behavior with some blocks... Eg don't make a +#May cause unexpected behavior with some blocks... Eg don't make a #shop on a hopper (It sucks the display item in) and furnace shops #allow players to put whatever item they want in all 3 slots and #dispenser shops aren't protected from redstone... Etc. @@ -280,7 +280,7 @@ shop: #Should we ignore the unlimited shop? ignore-unlimited: true -#List of items that can't be sold in shops. Anyone with quickshop.bypass. can bypass it +#List of items that can't be sold in shops. Anyone with quickshop.bypass. can bypass it blacklist: - Bedrock diff --git a/src/test/java/org/maxgamer/quickshop/File/JSONFileTest.java b/src/test/java/org/maxgamer/quickshop/File/JSONFileTest.java new file mode 100644 index 000000000..145caae76 --- /dev/null +++ b/src/test/java/org/maxgamer/quickshop/File/JSONFileTest.java @@ -0,0 +1,26 @@ +package org.maxgamer.quickshop.File; + +import be.seeseemelk.mockbukkit.MockBukkit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.maxgamer.quickshop.QuickShopTest; + +class JSONFileTest { + + private QuickShopTest plugin; + private IFile json; + + @BeforeEach + void setUp() { + MockBukkit.mock(); + plugin = MockBukkit.load(QuickShopTest.class); + json = new JSONFile(plugin, "messages"); + json.create(); + } + + @AfterEach + void tearDown() { + MockBukkit.unload(); + } + +} diff --git a/src/test/java/org/maxgamer/quickshop/QuickShopTest.java b/src/test/java/org/maxgamer/quickshop/QuickShopTest.java new file mode 100644 index 000000000..34836268c --- /dev/null +++ b/src/test/java/org/maxgamer/quickshop/QuickShopTest.java @@ -0,0 +1,24 @@ +package org.maxgamer.quickshop; + +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.plugin.java.JavaPluginLoader; + +import java.io.File; + +public final class QuickShopTest extends JavaPlugin { + + public QuickShopTest() { + super(); + } + + protected QuickShopTest(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { + super( + loader, + description, + new File("build"), + file + ); + } + +} diff --git a/src/test/resources/messages.json b/src/test/resources/messages.json new file mode 100644 index 000000000..f2c11970a --- /dev/null +++ b/src/test/resources/messages.json @@ -0,0 +1,231 @@ +{ + "shop-staff-cleared": "&aSuccessfully removed all staff for your shop.", + "failed-to-paste": "&cFailed to upload the data to Pastebin, Check your internet and try again. (See console for details)", + "chest-was-removed": "&cThe chest was removed.", + "thats-not-a-number": "&cInvalid number", + "shop-already-owned": "&cThat is already a shop.", + "buying-more-than-selling": "&cWARNING: You are buying items for more than you are selling them!", + "signs": { + "item": "{0}", + "selling": "Selling {0}", + "header": "&c{0}", + "price": "{0} each", + "unlimited": "Unlimited", + "buying": "Buying {0}" + }, + "price-too-high": "&c The shop price too high! You can't create one that is priced higher than {0}.", + "no-pending-action": "&cYou do not have any pending action", + "restricted-prices": "&cRestricted prices for {0}: min {1} , max {2}", + "not-a-number": "&cThere can only be number, but you input {0}", + "shop-purchase-cancelled": "&cCancelled Shop Purchase.", + "updatenotify": { + "onekeybuttontitle": "[OneKey Update]", + "remote-disable-warning": "&cThis version of QuickShop is marked disabled by remote server, that mean this version may have serious problem, get details from our SpigotMC page: {0}. This warning will appear and spam your console until you use other not disabled version to replace this one, doesn't effect your server running.", + "list": [ + "{0} is released, You are still using {1}!", + "Boom! New update {0} incoming, Update!", + "Surprise! {0} came out, you are on {1}", + "Looks like you need to update, {0} is released!", + "Ooops! {0} is now released, you are on {1}!", + "I promise, QS has been updated to {0}, why have you not updated?", + "Fixing and re... Sorry {0} is released!", + "Err! Nope, this is not an error, {0} has just been released!", + "OMG! {0} came out! Why are you still using {1}?", + "Todays News: QuickShop has been updated to {0}!", + "Plugin K.I.A, You should update to {0}!", + "Fuze is fuzeing update {0}, save update!", + "There is an update commander, {0} has just come out!", + "Look me style---{0} updated, your still using {1}", + "Ahhhhhhh! New update {0}! Update!", + "What U thinking? {0} has been released! Update!" + ], + "buttontitle": "[Update Now]", + "label": { + "lts": "[LTS]", + "bukkitdev": "[BukkitDev]", + "github": "[Github]", + "unstable": "[Unstable]", + "stable": "[Stable]", + "qualityverifyed": "[Quality]", + "spigotmc": "[SpigotMC]" + } + }, + "no-anythings-in-your-hand": "&cThere is nothing in your hand.", + "warn-to-paste": "&eCollecting data and uploading it to Pastebin, this may take a while. &c&lWarning&c, The data is kept public for one week, it may leak your server configuration and other sensitive information, make sure you only send it to your <rusted staff/developer.", + "the-owner-cant-afford-to-buy-from-you": "&cThat costs {0} but the owner only has {1}", + "menu": { + "sell-tax-self": "&aYou own this shop so you don't pay taxes.", + "this-shop-is-selling": "&aThis shop is &bSELLING&a items.", + "successful-purchase": "&aSuccessfully Purchased:", + "enchants": "&5Enchants", + "item-name-and-price": "&e{0} {1} &afor &e{2}", + "this-shop-is-buying": "&aThis shop is &dBUYING&a items.", + "effects": "&aEffects: &e{0}", + "owner": "&aOwner: {0}", + "total-value-of-chest": "&aTotal value of Chest: &e{0}", + "commands": { + "preview": "/qs silentpreview {0} {1} {2} {3}" + }, + "price-per": "&aPrice per &e{0} &a- &e{1}", + "space": "&aSpace: &e{0}", + "sell-tax": "&aYou paid &e{0} &ain taxes.", + "stored-enchants": "&5Stored Enchants", + "item": "&aItem: &e{0}", + "successfully-sold": "&aSuccessfully Sold:", + "preview": "&b[Preview Item]", + "damage-percent-remaining": "&e{0}% &aRemaining.", + "shop-information": "&aShop Information:", + "stock": "&aStock &e{0}" + }, + "player-bought-from-your-store": "&c{0} purchased {1} {2} from your store.", + "no-price-given": "&cPlease give a valid price.", + "booleanformat": { + "failed": "&c\u2718", + "success": "&a\u2714" + }, + "blacklisted-item": "&cThat item is blacklisted. You may not sell it", + "success-created-shop": "&aCreated shop.", + "shop-has-no-space": "&cThe shop only has room for {0} more {1}.", + "no-creative-break": "&cYou cannot break other players shops in creative mode. Use survival instead.", + "translation-version": "&c&lSupport Version: &b&lReremake", + "how-much-to-trade-for": "&aEnter how much you wish to trade one &e{0}&a for in chat.", + "shop-has-changed": "&cThe shop you tried to use has changed since you clicked it!", + "not-a-integer": "&cThere can only be integer, but you input {0}", + "success-change-owner-to-server": "&aSuccessfully set the shop owner to Server.", + "not-looking-at-shop": "&cNo QuickShop was found, you must be looking at one.", + "you-dont-have-that-many-items": "&cYou only have {0} {1}.", + "language-version": 24, + "shop-not-exist": "&cThere had no shop.", + "translation-country": "&c&lLanguage Zone: &b&lEnglish (en_US)", + "unknown-player": "&cTarget player doesn't exist, please check the username you typed.", + "you-cant-afford-to-change-price": "&cIt costs {0} to change the price in your shop.", + "negative-amount": "&cDerp, can't trade negative amounts", + "success-removed-shop": "&aShop removed.", + "how-many-sell": "&aEnter how many you wish to &dSELL&a in chat. You have &e{0}&a available. Enter &ball&a to sell them all.", + "you-cant-afford-a-new-shop": "&cIt costs {0} to create a new shop.", + "shop-creation-cancelled": "&cCancelled Shop Creation.", + "owner-bypass-check": "&eBypassed all checks, Trade successful! (You are shop owner)", + "tableformat": { + "left_half_line": "+--------------------", + "right_half_line": "--------------------+", + "full_line": "+---------------------------------------------------+", + "left_begin": "| " + }, + "shop-staff-deleted": "&aSuccessfully removed {0} from your shop staffs.", + "that-is-locked": "&cThat shop is locked.", + "no-nearby-shop": "&cNo shops matching {0} nearby.", + "you-cant-create-shop-in-there": "&cYou don't have permission to create a shop at this location.", + "shop-stock-too-low": "&cThe shop only has {0} {1} left", + "fee-charged-for-price-change": "&aYou pay &c{0}&a to change the price.", + "how-many-buy": "&aEnter how many you wish to &bBUY&a in chat. You can buy &e{0}&a. Enter &ball&a to buy them all.", + "failed-to-put-sign": "&cNot enough space around the shop to place the information sign.", + "controlpanel": { + "mode-buying-hover": "&eClick to convert the shop to be in the selling mode.", + "refill-hover": "&eClick to refill the shop.", + "empty-hover": "&eClick to clear the inventory of the shop.", + "price": "&aPrice: &b{0} &e[&d&lSet&e]", + "unlimited": "&aUnlimited: {0} &e[&d&lSwitch&e]", + "price-hover": "&eClick to set a new price for the shop.", + "setowner-hover": "&eClick to switch owner.", + "setowner": "&aOwner: &b{0} &e[&d&lChange&e]", + "unlimited-hover": "&eClick to toggle if the shop is unlimited.", + "mode-buying": "&aShop mode: &bBuying &e[&d&lSwitch&e]", + "refill": "&aRefill: Refill the shop items &e[&d&lOK&e]", + "mode-selling-hover": "&eClick to convert the shop to be in the buying mode.", + "commands": { + "sell": "/qs silentsell {0} {1} {2} {3}", + "buy": "/qs silentbuy {0} {1} {2} {3}", + "price": "/qs price [New Price]", + "unlimited": "/qs silentunlimited {0} {1} {2} {3}", + "remove": "/qs silentremove {0} {1} {2} {3}", + "setowner": "/qs setowner [Player]", + "refill": "/qs refill [Amount]", + "empty": "/qs silentempty {0} {1} {2} {3}" + }, + "remove": "&c&l[Remove Shop]", + "infomation": "&aShop Control Panel:", + "mode-selling": "&aShop mode: &bSelling &e[&d&lSwitch&e]", + "remove-hover": "&eClick to remove this shop.", + "empty": "&aEmpty: Remove shop all items &e[&d&lOK&e]" + }, + "permission-denied-3rd-party": "&cPermission denied: 3rd party plugin [{0}].", + "not-enough-space": "&cYou only have room for {0} more of that!", + "average-price-nearby": "&aAverage Price Nearby: &e{0}", + "not-allowed-to-create": "&cYou may not create a shop here.", + "price-too-cheap": "&cPrice must be greater than &e${0}", + "shop-removed-cause-ongoing-fee": "&cYou shop at {0} was removed cause you had no enough money to keep it!", + "player-sold-to-your-store": "&a{0} sold {1} {2} to your store.", + "no-enough-money-to-keep-shops": "&cYou didn't have enough money to keep your shops! All shops have now been removed...", + "shop-staff-added": "&aSuccessfully added {0} to your shop staffs.", + "nothing-to-flush": "&aYou had no new shop message.", + "empty-success": "&aEmpty success", + "flush-finished": "&aSuccessfully flushed the messages.", + "unknown-owner": "Unknown", + "bypassing-lock": "&cBypassing a QuickShop lock!", + "nearby-shop-this-way": "&aShop is {0} blocks away from you.", + "no-double-chests": "&cYou cannot create the DoubleChest shop.", + "shop-out-of-stock": "&5Your shop at {0}, {1}, {2}, has run out of {3}", + "purchase-failed": "&cPurchase failed: Internal Error, please contact the server administrator.", + "price-is-now": "&aThe shops new price is &e{0}", + "reached-maximum-can-create": "&cYou have already created a maximum of {0}/{1} shops!", + "no-permission": "&cYou do not have permission to do that.", + "shop-out-of-space": "&5Your shop at {0}, {1}, {2}, is now full.", + "player-bought-from-your-store-tax": "&c{0} purchased {1} {2} from your store, and you paid {3} in taxes.", + "no-permission-build": "&cYou can't build a shop here.", + "refill-success": "&aRefill success", + "translation-author": "&c&lTranslator: &b&lGhost_chu", + "break-shop-use-supertool": "&eYou can break the shop by using the SuperTool.", + "translation-contributors": "&c&lContributors: &b&lTimtower, Netherfoam, KaiNoMood and Mgazul", + "command": { + "toggle-unlimited": { + "limited": "&aShop is now limited", + "unlimited": "&aShop is now unlimited" + }, + "no-type-given": "&cUsage: /qs find ", + "description": { + "info": "&eShow QuickShop Statistics", + "buy": "&eConverts a shop to &dBUY&e mode", + "help": "&eShow QuickShop helps", + "price": "&eChanges the buy/selling price of one of your shops", + "unlimited": "&eMakes a shop unlimited", + "about": "&eShow QuickShop abouts", + "setowner": "&eChanges who owns a shop", + "owner": "&eChanges who owns a shop", + "refill": "&eAdds a given number of items to a shop", + "paste": "&eAuto upload server data to Pastebin", + "find": "&eLocates the nearest shop of a specific type.", + "staff": "&eManage your shop staffs", + "sell": "&eConverts a shop to &bSELL&e mode", + "supercreate": "&eCreate a shop bypass all protection checks", + "title": "&aQuickShop Help", + "create": "&eCreates a new shop at the target chest", + "remove": "&eRemove your looking the shop", + "reload": "&eReloads the config.yml for QuickShop", + "amount": "&eExecute for your actions with amount(For chat plugin issue)", + "clean": "&eRemoves all (loaded) shops with 0 stock", + "debug": "&eSwitch to developer mode", + "fetchmessage": "&eFetch unread shop message", + "empty": "&eRemoves all stock from a shop" + }, + "new-owner": "&aNew owner: &e{0}", + "now-buying": "&aNow &dBUYING&a &e{0}", + "now-selling": "&aNow &bSELLING &e{0}", + "no-owner-given": "&cNo owner given. Use &a/qs setowner &c", + "no-amount-given": "&cNo amount given. Use &a/qs refill &c", + "reloading": "&aReloading...", + "cleaning": "&aCleaning up shops with 0 stock...", + "now-nolonger-debuging": "&aSuccessfully switched to production mode, Reloading QuickShop...", + "cleaned": "&aCleaned &e{0}&a shops", + "now-debuging": "&aSuccessfully switched to developer mode, Reloading QuickShop...", + "wrong-args": "&cParameters don't match, use /qs help to check help" + }, + "no-price-change": "&cThat wouldn't result in a price change!", + "shops-arent-locked": "&cRemember, shops are NOT protected from theft! If you want to stop thieves, lock it with LWC, Lockette, etc!", + "admin-shop": "AdminShop", + "you-cant-afford-to-buy": "&cThat costs {0}, but you only have {1}", + "tabcomplete": { + "range": "[range]", + "amount": "[amount]", + "price": "[price]" + } +} \ No newline at end of file diff --git a/src/test/resources/plugin.yml b/src/test/resources/plugin.yml new file mode 100644 index 000000000..86bf7fbf0 --- /dev/null +++ b/src/test/resources/plugin.yml @@ -0,0 +1,3 @@ +name: QuickShopTest +main: org.maxgamer.quickshop.QuickShopTest +version: 1.0 \ No newline at end of file