From 7755a4ab3e59a52ddd5126b5abaa0463f181cdc2 Mon Sep 17 00:00:00 2001 From: filoghost Date: Fri, 26 Jun 2020 15:05:55 +0200 Subject: [PATCH] Use newer Java 7 File API where possible --- .../chestcommands/ChestCommands.java | 99 +++++++++++++------ .../config/yaml/PluginConfig.java | 81 ++++++++++----- .../config/yaml/SpecialConfig.java | 5 +- .../chestcommands/legacy/Upgrade.java | 16 +-- .../legacy/UpgradesDoneRegistry.java | 6 +- .../legacy/UpgradesExecutor.java | 31 +++--- .../legacy/upgrades/MenuUpgrade.java | 10 +- .../legacy/upgrades/PlaceholdersUpgrade.java | 27 +++-- .../legacy/upgrades/SettingsUpgrade.java | 10 +- 9 files changed, 177 insertions(+), 108 deletions(-) diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java b/Plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java index 17ddc28..e8df9ba 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/ChestCommands.java @@ -36,7 +36,6 @@ import me.filoghost.chestcommands.menu.settings.MenuSettings; import me.filoghost.chestcommands.parser.MenuParser; import me.filoghost.chestcommands.task.RefreshMenusTask; import me.filoghost.chestcommands.util.ErrorCollector; -import me.filoghost.chestcommands.util.FileUtils; import me.filoghost.chestcommands.util.Utils; import me.filoghost.updatechecker.UpdateChecker; import org.bstats.bukkit.MetricsLite; @@ -46,11 +45,17 @@ import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; -import java.io.File; import java.io.IOException; +import java.nio.file.FileVisitOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.stream.Stream; public class ChestCommands extends JavaPlugin { @@ -148,8 +153,13 @@ public class ChestCommands extends JavaPlugin { public ErrorCollector load() { ErrorCollector errors = new ErrorCollector(); menuManager.clear(); - boolean isFreshInstall = !getDataFolder().isDirectory(); - getDataFolder().mkdirs(); + boolean isFreshInstall = !Files.isDirectory(getDataPath()); + try { + Files.createDirectories(getDataPath()); + } catch (IOException e) { + errors.addError("Plugin failed to load, couldn't create data folder."); + return errors; + } try { new UpgradesExecutor(this).run(isFreshInstall); @@ -159,6 +169,7 @@ public class ChestCommands extends JavaPlugin { PluginConfig settingsYaml = getSettingsConfig(); try { + settingsYaml.createDefault(this); settingsYaml.load(); settings.load(settingsYaml); } catch (Throwable t) { @@ -167,6 +178,7 @@ public class ChestCommands extends JavaPlugin { PluginConfig langYaml = getLangConfig(); try { + langYaml.createDefault(this); langYaml.load(); lang.load(langYaml); } catch (Throwable t) { @@ -175,6 +187,7 @@ public class ChestCommands extends JavaPlugin { PluginConfig placeholdersYaml = getPlaceholdersConfig(); try { + placeholdersYaml.createDefault(this); placeholdersYaml.load(); placeholders.load(placeholdersYaml, errors); } catch (Throwable t) { @@ -182,16 +195,35 @@ public class ChestCommands extends JavaPlugin { } // Load the menus - File menusFolder = getMenusFolder(); + Path menusPath = getMenusPath(); - if (!menusFolder.isDirectory()) { - // Create the directory with the default menu - menusFolder.mkdirs(); - FileUtils.saveResourceSafe(this, "menu" + File.separator + "example.yml"); + if (!Files.isDirectory(menusPath)) { + // Create the menu folder with the example menu + try { + Files.createDirectories(menusPath); + } catch (IOException e) { + getLogger().log(Level.SEVERE, "Couldn't create \"" + menusPath.getFileName() + "\" folder"); + } + + PluginConfig exampleMenu = new PluginConfig(getDataPath(Paths.get("menu", "example.yml"))); + try { + exampleMenu.createDefault(this); + } catch (Throwable t) { + logConfigLoadException(exampleMenu, t); + } } - List menusList = getMenuConfigs(menusFolder); - for (PluginConfig menuConfig : menusList) { + List menuPaths; + + try { + menuPaths = getMenusPathList(); + } catch (IOException e) { + getLogger().log(Level.SEVERE, "Couldn't fetch files inside the folder \"" + getMenusPath().getFileName() + "\"", e); + menuPaths = Collections.emptyList(); + } + + for (Path menuFile : menuPaths) { + PluginConfig menuConfig = new PluginConfig(menuFile); try { menuConfig.load(); } catch (Throwable t) { @@ -232,36 +264,35 @@ public class ChestCommands extends JavaPlugin { } public PluginConfig getLangConfig() { - return new PluginConfig(this, "lang.yml"); + return new PluginConfig(getDataPath("lang.yml")); } public PluginConfig getSettingsConfig() { - return new PluginConfig(this, "config.yml"); + return new PluginConfig(getDataPath("config.yml")); } public PluginConfig getPlaceholdersConfig() { - return new PluginConfig(this, "custom-placeholders.yml"); + return new PluginConfig(getDataPath("custom-placeholders.yml")); } - public File getMenusFolder() { - return new File(getDataFolder(), "menu"); + public Path getMenusPath() { + return getDataPath("menu"); } /** - * Loads all the configuration files recursively into a list. + * Returns a list of YML menu files. */ - public List getMenuConfigs(File file) { - List list = new ArrayList<>(); - if (file.isDirectory()) { - for (File subFile : file.listFiles()) { - list.addAll(getMenuConfigs(subFile)); - } - } else if (file.isFile()) { - if (file.getName().endsWith(".yml")) { - list.add(new PluginConfig(this, file)); - } + public List getMenusPathList() throws IOException { + try (Stream paths = Files.walk(getMenusPath(), FileVisitOption.FOLLOW_LINKS)) { + return paths.filter(Files::isRegularFile) + .filter(this::isYmlPath) + .collect(Collectors.toList()); } - return list; + } + + + private boolean isYmlPath(Path path) { + return path.getFileName().toString().toLowerCase().endsWith(".yml"); } @@ -278,6 +309,18 @@ public class ChestCommands extends JavaPlugin { return instance; } + public Path getDataPath() { + return getDataFolder().toPath(); + } + + public Path getDataPath(Path path) { + return getDataPath().resolve(path); + } + + public Path getDataPath(String path) { + return getDataPath().resolve(path); + } + public MenuManager getMenuManager() { return menuManager; } diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/PluginConfig.java b/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/PluginConfig.java index 47e491c..5ffc8b5 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/PluginConfig.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/PluginConfig.java @@ -14,65 +14,92 @@ */ package me.filoghost.chestcommands.config.yaml; +import me.filoghost.chestcommands.ChestCommands; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import java.io.File; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; /** * A simple utility class to manage configurations with a file associated to them. */ public class PluginConfig extends YamlConfiguration { - private File file; - private Plugin plugin; + private final Path path; - public PluginConfig(Plugin plugin, File file) { - super(); - this.file = file; - this.plugin = plugin; + public PluginConfig(Path path) { + this.path = path; } - public PluginConfig(Plugin plugin, String name) { - this(plugin, new File(plugin.getDataFolder(), name)); + public Path getPath() { + return path; } - public void load() throws IOException, InvalidConfigurationException { + public void createDefault(ChestCommands plugin) throws IOException { + if (!path.startsWith(plugin.getDataPath())) { + throw new IOException("Config file " + path + " must be inside " + plugin.getDataPath()); + } - if (!file.isFile()) { - if (plugin.getResource(file.getName()) != null) { - plugin.saveResource(file.getName(), false); - } else { - if (file.getParentFile() != null) { - file.getParentFile().mkdirs(); + if (Files.exists(path)) { + return; + } + + if (path.getParent() != null) { + Files.createDirectories(path.getParent()); + } + + Path absoluteDataPath = plugin.getDataPath().toAbsolutePath(); + Path absoluteConfigPath = path.toAbsolutePath(); + + if (absoluteConfigPath.startsWith(absoluteDataPath)) { + Path relativeConfigPath = absoluteDataPath.relativize(absoluteConfigPath); + String defaultConfigURL = StreamSupport.stream(relativeConfigPath.spliterator(), false) + .map(Path::toString) + .collect(Collectors.joining("/")); + + try (InputStream defaultFile = plugin.getResource(defaultConfigURL)) { + if (defaultFile != null) { + Files.copy(defaultFile, path); + return; } - file.createNewFile(); } } + Files.createFile(path); + } + + public void load() throws IOException, InvalidConfigurationException { // To reset all the values when loading for (String section : this.getKeys(false)) { set(section, null); } - load(file); + + try (BufferedReader reader = Files.newBufferedReader(path)) { + load(reader); + } } public void save() throws IOException { - this.save(file); - } + if (path.getParent() != null) { + Files.createDirectories(path.getParent()); + } - public Plugin getPlugin() { - return plugin; - } + String data = saveToString(); - public File getFile() { - return file; + try (BufferedWriter writer = Files.newBufferedWriter(path)) { + writer.write(data); + } } public String getFileName() { - return file.getName(); + return path.getFileName().toString(); } } diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/SpecialConfig.java b/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/SpecialConfig.java index 36dda70..462331b 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/SpecialConfig.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/config/yaml/SpecialConfig.java @@ -14,6 +14,7 @@ */ package me.filoghost.chestcommands.config.yaml; +import me.filoghost.chestcommands.ChestCommands; import me.filoghost.chestcommands.util.FormatUtils; import java.io.IOException; @@ -54,7 +55,7 @@ public class SpecialConfig { if (defaultValue != null) { defaultValuesMap.put(configKey, defaultValue); } else { - config.getPlugin().getLogger().warning("The field " + field.getName() + " was not provided with a default value, please inform the developer."); + ChestCommands.getInstance().getLogger().warning("The field " + field.getName() + " was not provided with a default value, please inform the developer."); } } catch (Exception ex) { @@ -104,7 +105,7 @@ public class SpecialConfig { field.set(this, FormatUtils.addColors(config.getString(configKey))); // Always add colors } else { - config.getPlugin().getLogger().warning("Unknown field type: " + field.getType().getName() + " (" + field.getName() + "). Please inform the developer."); + ChestCommands.getInstance().getLogger().warning("Unknown field type: " + field.getType().getName() + " (" + field.getName() + "). Please inform the developer."); } } else { diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/Upgrade.java b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/Upgrade.java index 7f1d180..87092f3 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/Upgrade.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/Upgrade.java @@ -18,9 +18,9 @@ import me.filoghost.chestcommands.config.yaml.PluginConfig; import me.filoghost.chestcommands.util.Preconditions; import org.bukkit.configuration.InvalidConfigurationException; -import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -45,13 +45,13 @@ public abstract class Upgrade { try { createBackupFile(getOriginalFile()); } catch (IOException e) { - throw new UpgradeException("couldn't create backup of file \"" + getOriginalFile().getName() + "\"", e); + throw new UpgradeException("couldn't create backup of file \"" + getOriginalFile().getFileName() + "\"", e); } try { saveChanges(); } catch (IOException e) { - throw new UpgradeException("couldn't save upgraded file \"" + getUpgradedFile().getName() + "\"", e); + throw new UpgradeException("couldn't save upgraded file \"" + getUpgradedFile().getFileName() + "\"", e); } } @@ -68,16 +68,16 @@ public abstract class Upgrade { } } - private void createBackupFile(File file) throws IOException { + private void createBackupFile(Path path) throws IOException { String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm")); - String backupName = file.getName() + "_" + date + ".backup"; + String backupName = path.getFileName() + "_" + date + ".backup"; - Files.copy(file.toPath(), file.toPath().resolveSibling(backupName), StandardCopyOption.REPLACE_EXISTING); + Files.copy(path, path.resolveSibling(backupName), StandardCopyOption.REPLACE_EXISTING); } - public abstract File getOriginalFile(); + public abstract Path getOriginalFile(); - public abstract File getUpgradedFile(); + public abstract Path getUpgradedFile(); protected abstract void computeChanges() throws UpgradeException; diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java index 8dbd8fd..5639b25 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesDoneRegistry.java @@ -15,7 +15,6 @@ package me.filoghost.chestcommands.legacy; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -35,7 +34,7 @@ public class UpgradesDoneRegistry { this.upgradesDone = new HashSet<>(); if (Files.isRegularFile(saveFile)) { - try (Stream lines = Files.lines(saveFile, StandardCharsets.UTF_8)) { + try (Stream lines = Files.lines(saveFile)) { lines.filter(s -> !s.startsWith("#")) .forEach(upgradesDone::add); } @@ -65,7 +64,8 @@ public class UpgradesDoneRegistry { lines.add("# WARNING: manually editing this file is not recommended"); lines.add("#"); lines.addAll(upgradesDone); - Files.write(saveFile, lines, StandardCharsets.UTF_8); + Files.createDirectories(saveFile.getParent()); + Files.write(saveFile, lines); needSave = false; } } diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java index 9f10773..f765ff8 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/UpgradesExecutor.java @@ -21,7 +21,6 @@ import me.filoghost.chestcommands.legacy.upgrades.MenuUpgrade; import me.filoghost.chestcommands.legacy.upgrades.PlaceholdersUpgrade; import me.filoghost.chestcommands.legacy.upgrades.SettingsUpgrade; -import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; @@ -33,7 +32,7 @@ import java.util.stream.Collectors; public class UpgradesExecutor { private final ChestCommands plugin; - private List failedUpgrades; + private List failedUpgrades; private UpgradesDoneRegistry upgradesDoneRegistry; public UpgradesExecutor(ChestCommands plugin) { @@ -59,14 +58,19 @@ public class UpgradesExecutor { String legacyCommandSeparator = readLegacyCommandSeparator(); SettingsUpgrade settingsUpgrade = new SettingsUpgrade(plugin); - PlaceholdersUpgrade placeholdersUpgrade = new PlaceholdersUpgrade(plugin); - List menuUpgrades = getMenuConfigs().stream() - .map(menuConfig -> new MenuUpgrade(menuConfig, legacyCommandSeparator)) - .collect(Collectors.toList()); - runIfNecessary(UpgradeID.V4_CONFIG, settingsUpgrade); + + PlaceholdersUpgrade placeholdersUpgrade = new PlaceholdersUpgrade(plugin); runIfNecessary(UpgradeID.V4_PLACEHOLDERS, placeholdersUpgrade); - runIfNecessary(UpgradeID.V4_MENUS, menuUpgrades); + + try { + List menuUpgrades = plugin.getMenusPathList().stream() + .map(menuPath -> new MenuUpgrade(new PluginConfig(menuPath), legacyCommandSeparator)) + .collect(Collectors.toList()); + runIfNecessary(UpgradeID.V4_MENUS, menuUpgrades); + } catch (IOException e) { + failedUpgrades.add(plugin.getMenusPath()); + } } try { @@ -79,7 +83,7 @@ public class UpgradesExecutor { // Success only if no upgrade failed if (!failedUpgrades.isEmpty()) { String failedConversionFiles = failedUpgrades.stream() - .map(upgrade -> upgrade.getOriginalFile().getName()) + .map(Path::toString) .collect(Collectors.joining(", ")); throw new UpgradeExecutorException("Failed to automatically upgrade the following files: " + failedConversionFiles); } @@ -100,11 +104,6 @@ public class UpgradesExecutor { return legacyCommandSeparator; } - private List getMenuConfigs() { - File menusFolder = plugin.getMenusFolder(); - return plugin.getMenuConfigs(menusFolder); - } - private void runIfNecessary(UpgradeID upgradeID, Upgrade upgradeTask) { runIfNecessary(upgradeID, Collections.singletonList(upgradeTask)); @@ -124,12 +123,12 @@ public class UpgradesExecutor { if (modified) { plugin.getLogger().info( "Automatically upgraded configuration file \"" - + upgradeTask.getUpgradedFile().getName() + "\" with newer configuration nodes. " + + upgradeTask.getUpgradedFile().getFileName() + "\" with newer configuration nodes. " + "A backup of the old file has been saved."); } } catch (UpgradeException e) { failedAnyUpgrade = true; - failedUpgrades.add(upgradeTask); + failedUpgrades.add(upgradeTask.getOriginalFile()); logUpgradeException(upgradeTask, e); } } diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/MenuUpgrade.java b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/MenuUpgrade.java index 25d28a0..d173a73 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/MenuUpgrade.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/MenuUpgrade.java @@ -20,8 +20,8 @@ import me.filoghost.chestcommands.legacy.UpgradeException; import me.filoghost.chestcommands.util.Strings; import org.bukkit.configuration.ConfigurationSection; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -38,13 +38,13 @@ public class MenuUpgrade extends Upgrade { } @Override - public File getOriginalFile() { - return menuConfig.getFile(); + public Path getOriginalFile() { + return menuConfig.getPath(); } @Override - public File getUpgradedFile() { - return menuConfig.getFile(); + public Path getUpgradedFile() { + return menuConfig.getPath(); } @Override diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/PlaceholdersUpgrade.java b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/PlaceholdersUpgrade.java index 8d966fc..bc20117 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/PlaceholdersUpgrade.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/PlaceholdersUpgrade.java @@ -21,46 +21,43 @@ import me.filoghost.chestcommands.legacy.UpgradeException; import me.filoghost.chestcommands.util.Strings; import org.apache.commons.lang.StringEscapeUtils; -import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; public class PlaceholdersUpgrade extends Upgrade { private final PluginConfig newPlaceholdersConfig; - private final File oldPlaceholdersFile; - - private List lines; + private final Path oldPlaceholdersFile; public PlaceholdersUpgrade(ChestCommands plugin) { this.newPlaceholdersConfig = plugin.getPlaceholdersConfig(); - this.oldPlaceholdersFile = new File(plugin.getDataFolder(), "placeholders.yml"); + this.oldPlaceholdersFile = plugin.getDataPath("placeholders.yml"); } @Override - public File getOriginalFile() { + public Path getOriginalFile() { return oldPlaceholdersFile; } @Override - public File getUpgradedFile() { - return newPlaceholdersConfig.getFile(); + public Path getUpgradedFile() { + return newPlaceholdersConfig.getPath(); } @Override protected void computeChanges() throws UpgradeException { - if (!oldPlaceholdersFile.isFile()) { + if (!Files.isRegularFile(oldPlaceholdersFile)) { return; } // Do NOT load the new placeholder configuration from disk, as it should only contain placeholders imported from the old file - + List lines; try { - lines = Files.readAllLines(oldPlaceholdersFile.toPath(), StandardCharsets.UTF_8); + lines = Files.readAllLines(oldPlaceholdersFile); } catch (IOException e) { - throw new UpgradeException("couldn't read file \"" + oldPlaceholdersFile.getName() + "\"", e); + throw new UpgradeException("couldn't read file \"" + oldPlaceholdersFile.getFileName() + "\"", e); } for (String line : lines) { @@ -85,7 +82,9 @@ public class PlaceholdersUpgrade extends Upgrade { @Override protected void saveChanges() throws IOException { - oldPlaceholdersFile.delete(); + try { + Files.deleteIfExists(oldPlaceholdersFile); + } catch (IOException ignored) {} newPlaceholdersConfig.save(); } diff --git a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/SettingsUpgrade.java b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/SettingsUpgrade.java index 02ed720..f9b2eda 100644 --- a/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/SettingsUpgrade.java +++ b/Plugin/src/main/java/me/filoghost/chestcommands/legacy/upgrades/SettingsUpgrade.java @@ -20,8 +20,8 @@ import me.filoghost.chestcommands.config.yaml.PluginConfig; import me.filoghost.chestcommands.legacy.Upgrade; import me.filoghost.chestcommands.legacy.UpgradeException; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.Set; public class SettingsUpgrade extends Upgrade { @@ -39,13 +39,13 @@ public class SettingsUpgrade extends Upgrade { } @Override - public File getOriginalFile() { - return settingsConfig.getFile(); + public Path getOriginalFile() { + return settingsConfig.getPath(); } @Override - public File getUpgradedFile() { - return settingsConfig.getFile(); + public Path getUpgradedFile() { + return settingsConfig.getPath(); } @Override