From e506ab1bc96c6264a5d32b5f92483dca3cc5b5a4 Mon Sep 17 00:00:00 2001 From: Drashti Patel Date: Fri, 1 Mar 2024 23:05:55 -0400 Subject: [PATCH 1/4] Assignment 1 Submission --- pom.xml | 7 +++++ .../client/ui/utils/HintTextFieldTest.java | 29 ++++++++++++++++++ .../client/utils/UtilsLoggerTest.java | 30 +++++++++++++++++++ .../client/utils/UtilsRandomTest.java | 22 ++++++++++++++ .../client/utils/UtilsStringTest.java | 8 +++++ 5 files changed, 96 insertions(+) create mode 100644 src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java create mode 100644 src/test/java/com/osiris/autoplug/client/utils/UtilsRandomTest.java diff --git a/pom.xml b/pom.xml index 70fe30c2..1f5a6b00 100644 --- a/pom.xml +++ b/pom.xml @@ -81,6 +81,13 @@ 5.12.1 + + org.mockito + mockito-core + 3.12.4 + test + + com.github.Osiris-Team diff --git a/src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java b/src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java new file mode 100644 index 00000000..851e4367 --- /dev/null +++ b/src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java @@ -0,0 +1,29 @@ +package com.osiris.autoplug.client.ui.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.awt.Color; +import java.awt.event.FocusEvent; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +public class HintTextFieldTest { + + private HintTextField textField; + + @BeforeEach + public void setUp() { + textField = new HintTextField("Enter text here"); + } + + @Test + public void testTextIsClearedOnFocus() { + FocusEvent mockFocusEvent = Mockito.mock(FocusEvent.class); + textField.focusGained(mockFocusEvent); + assertEquals("", textField.getText()); + assertEquals(Color.BLACK, textField.getForeground()); + } + +} + diff --git a/src/test/java/com/osiris/autoplug/client/utils/UtilsLoggerTest.java b/src/test/java/com/osiris/autoplug/client/utils/UtilsLoggerTest.java index a4723a17..7e2ef693 100644 --- a/src/test/java/com/osiris/autoplug/client/utils/UtilsLoggerTest.java +++ b/src/test/java/com/osiris/autoplug/client/utils/UtilsLoggerTest.java @@ -8,16 +8,46 @@ package com.osiris.autoplug.client.utils; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; class UtilsLoggerTest { + @BeforeEach + void setUp() { + utilsLogger = new UtilsLogger(); + } + @Test void animatedPrintln() throws InterruptedException, IOException { UtilsLogger uLog = new UtilsLogger(); uLog.animatedPrintln("Thank you for installing AutoPlug!"); // DOESNT WORK IN INTELLIJ CONSOLE } + + + private UtilsLogger utilsLogger; + @Test + void testExpectInput() throws Exception{ + String expectedInput = "test"; + InputStream sysInBackup = System.in; + try { + String input = expectedInput + "\n"; + InputStream in = new ByteArrayInputStream(input.getBytes()); + System.setIn(in); + + String userInput = utilsLogger.expectInput(expectedInput); + + assertEquals(expectedInput, userInput); + } finally { + System.setIn(sysInBackup); + } + } + } \ No newline at end of file diff --git a/src/test/java/com/osiris/autoplug/client/utils/UtilsRandomTest.java b/src/test/java/com/osiris/autoplug/client/utils/UtilsRandomTest.java new file mode 100644 index 00000000..27652a60 --- /dev/null +++ b/src/test/java/com/osiris/autoplug/client/utils/UtilsRandomTest.java @@ -0,0 +1,22 @@ +package com.osiris.autoplug.client.utils; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class UtilsRandomTest { + + @Test + void testGenerateNewKey() { + UtilsRandom utilsRandom = new UtilsRandom(); + int length = 16; + + String key = utilsRandom.generateNewKey(length); + + assertNotNull(key); + assertEquals(length, key.length()); + + // Check if the generated key contains only alphanumeric characters + assertTrue(key.matches("[a-zA-Z0-9]+")); + } +} diff --git a/src/test/java/com/osiris/autoplug/client/utils/UtilsStringTest.java b/src/test/java/com/osiris/autoplug/client/utils/UtilsStringTest.java index c63e4134..69b95291 100644 --- a/src/test/java/com/osiris/autoplug/client/utils/UtilsStringTest.java +++ b/src/test/java/com/osiris/autoplug/client/utils/UtilsStringTest.java @@ -37,4 +37,12 @@ void splitBySpacesAndQuotes() throws Exception { " nogui"); assertEquals(6, l.size()); } + + @Test + void indexOf_singleOccurrence() { + UtilsString utilsString = new UtilsString(); + int result = utilsString.indexOf("Hello world!", 'o', 1); + assertEquals(4, result); + } + } \ No newline at end of file From 441b836089033b37e29a7c504944db635bc44781 Mon Sep 17 00:00:00 2001 From: Drashti Patel Date: Fri, 29 Mar 2024 14:28:44 -0300 Subject: [PATCH 2/4] Refactored code to resolve implementation code smells --- .../client/configs/UpdaterConfig.java | 8 +- .../autoplug/client/console/Commands.java | 136 +++++++++++------- .../autoplug/client/managers/FileManager.java | 26 ++-- .../client/managers/SyncFilesManager.java | 88 +++++++----- .../tasks/updater/mods/TaskModsUpdater.java | 2 +- .../updater/plugins/TaskPluginsUpdater.java | 12 +- 6 files changed, 164 insertions(+), 108 deletions(-) diff --git a/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java b/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java index 5c78307f..a4fd9774 100644 --- a/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java +++ b/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java @@ -54,14 +54,14 @@ public class UpdaterConfig extends MyYaml { public YamlSection plugins_updater_version; public YamlSection plugins_updater_async; public YamlSection plugins_updater_web_database; - public YamlSection plugins_updater_web_database_min_usages; + public YamlSection plugin_updater_min_usages; public YamlSection mods_updater; public YamlSection mods_updater_profile; public YamlSection mods_updater_path; public YamlSection mods_updater_version; public YamlSection mods_updater_async; - public YamlSection mods_update_check_name_for_mod_loader; + public YamlSection mods_loader_update_checkName; public UpdaterConfig() throws IOException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException, YamlWriterException { @@ -206,7 +206,7 @@ public UpdaterConfig() throws IOException, DuplicateKeyException, YamlReaderExce "Uses the AutoPlug-Web database to fill in missing plugin information.", "This option is only available for premium servers.", "Note that a server-key must be provided for this to work."); - plugins_updater_web_database_min_usages = put(name, "plugins-updater", "web-database", "min-usages").setDefValues("50").setComments( + plugin_updater_min_usages = put(name, "plugins-updater", "web-database", "min-usages").setDefValues("50").setComments( "The minimum amount of usages in servers a piece of information has to have to be used and deemed reliable."); put(name, "mods-updater").setCountTopLineBreaks(1); @@ -221,7 +221,7 @@ public UpdaterConfig() throws IOException, DuplicateKeyException, YamlReaderExce "Asynchronously checks for updates.", "Normally this should be faster than checking for updates synchronously, thus it should be enabled.", "The only downside of this is that your log file gets a bit messy."); - mods_update_check_name_for_mod_loader = put(name, "mods-updater", "check-name-for-mod-loader").setDefValues("false").setComments( + mods_loader_update_checkName = put(name, "mods-updater", "check-name-for-mod-loader").setDefValues("false").setComments( "Only relevant for determining if a curseforge mod release is forge or fabric.", "If enabled additionally checks the mod name to see if it contains fabric or forge."); diff --git a/src/main/java/com/osiris/autoplug/client/console/Commands.java b/src/main/java/com/osiris/autoplug/client/console/Commands.java index fdb23049..8a9ba507 100644 --- a/src/main/java/com/osiris/autoplug/client/console/Commands.java +++ b/src/main/java/com/osiris/autoplug/client/console/Commands.java @@ -8,6 +8,27 @@ package com.osiris.autoplug.client.console; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetAddress; +import java.net.URL; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.Scanner; + +import org.jetbrains.annotations.NotNull; + import com.osiris.autoplug.client.Main; import com.osiris.autoplug.client.Server; import com.osiris.autoplug.client.configs.UpdaterConfig; @@ -33,18 +54,14 @@ import com.osiris.autoplug.client.utils.UtilsMinecraft; import com.osiris.autoplug.client.utils.tasks.MyBThreadManager; import com.osiris.autoplug.client.utils.tasks.UtilsTasks; +import com.osiris.betterthread.exceptions.JLineLinkException; +import com.osiris.dyml.exceptions.DuplicateKeyException; +import com.osiris.dyml.exceptions.IllegalKeyException; +import com.osiris.dyml.exceptions.IllegalListException; +import com.osiris.dyml.exceptions.NotLoadedException; +import com.osiris.dyml.exceptions.YamlReaderException; +import com.osiris.dyml.exceptions.YamlWriterException; import com.osiris.jlib.logger.AL; -import org.jetbrains.annotations.NotNull; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.URL; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.*; /** * Listens for input started with . @@ -359,7 +376,7 @@ public static boolean installPlugin(String command) throws Exception { if(input.startsWith(repo)){ int bukkitId = Integer.parseInt(input.replace(repo, "").trim()); result = new ResourceFinder().findPluginByBukkitId(new MinecraftPlugin(new File(pluginsDir + "/" + tempName).getAbsolutePath(), - tempName, "0", "", 0, bukkitId, "")); + tempName, "0", "", 0, bukkitId, "")); } repo = "github"; if(input.startsWith(repo)){ @@ -381,7 +398,7 @@ public static boolean installPlugin(String command) throws Exception { result = new ResourceFinder().findPluginByModrinthId(plugin2, mcVersion); } /* - Nothing of the above worked thus do search by name + Nothing of the above worked thus do search by name */ if(!SearchResult.isMatchFound(result)){ plugin.setName(input.trim()); @@ -444,61 +461,78 @@ public static boolean installPlugin(String command) throws Exception { public static boolean installMod(String command) throws Exception { String input = command.replaceFirst("\\.install mod", "").replaceFirst("\\.im", "").trim(); - SearchResult result = null; String tempName = "NEW_MOD"; UpdaterConfig updaterConfig = new UpdaterConfig(); File modsDir = FileManager.convertRelativeToAbsolutePath(updaterConfig.mods_updater_path.asString()); - String mcVersion = updaterConfig.mods_updater_version.asString(); - if (mcVersion == null) mcVersion = Server.getMCVersion(); + if (mcVersion == null) + mcVersion = Server.getMCVersion(); + MinecraftMod mod = initializeMinecraftMod(modsDir, tempName, input); + if (mod != null) { + result = findMod(input, mod, mcVersion); + } - MinecraftMod mod = new MinecraftMod(new File(modsDir + "/" + tempName).getAbsolutePath(), tempName, "0", - "", "0", "0", ""); + if (!SearchResult.isMatchFound(result)) { + AL.warn("Failed to find mod, check the provided name for typos."); + return false; + } + File finalDest = downloadMod(modsDir, result, tempName); + AL.info("Installed to: " + finalDest); + return true; + } - String repo = "modrinth"; - if(input.startsWith(repo)) { + private static MinecraftMod initializeMinecraftMod(File modsDir, String tempName, String input) { + MinecraftMod mod = new MinecraftMod(new File(modsDir + "/" + tempName).getAbsolutePath(), tempName, "0", "", + "0", "0", ""); + String repo; + if (input.startsWith(repo = "modrinth")) { mod.modrinthId = input.replace(repo, "").trim(); - result = new ResourceFinder().findModByModrinthId(new InstalledModLoader(), - mod, mcVersion); - } - repo = "curseforge"; - if(input.startsWith(repo)) { + } else if (input.startsWith(repo = "curseforge")) { mod.curseforgeId = input.replace(repo, "").trim(); - result = new ResourceFinder().findModByCurseforgeId(new InstalledModLoader(), mod, - mcVersion, updaterConfig.mods_update_check_name_for_mod_loader.asBoolean()); - } - repo = "github"; - if(input.startsWith(repo)) { + } else if (input.startsWith(repo = "github")) { String[] split = input.replace(repo, "").trim().split(" "); if (!input.contains("/")) { AL.warn("The github format must be / (and optional )."); - return false; + return null; } mod.githubRepoName = (split[0]); - if(split.length >= 2) mod.githubAssetName = (split[1]); - else mod.githubAssetName = (split[0].split("/")[1]); - result = new ResourceFinder().findByGithubUrl(mod); - } - /* - Nothing of the above worked thus do search by name - */ - if(!SearchResult.isMatchFound(result)){ + if (split.length >= 2) + mod.githubAssetName = (split[1]); + else + mod.githubAssetName = (split[0].split("/")[1]); + } else { mod.setName(input.trim()); + } + return mod; + } - try { // SPIGOT - // TODO something similar for mods: result = new ResourceFinder().findUnknownSpigotPlugin(plugin); - } catch (Exception e) { - //AL.warn("Failed to find plugin named '"+plugin.getName()+"' at spigotmc.org.", e); - } - // TODO also search other repos + private static SearchResult findMod(String input, MinecraftMod mod, String mcVersion) + throws NotLoadedException, YamlReaderException, YamlWriterException, IOException, IllegalKeyException, + DuplicateKeyException, IllegalListException { + SearchResult result = null; + if (mod.modrinthId != null) { + result = new ResourceFinder().findModByModrinthId(new InstalledModLoader(), mod, mcVersion); + } else if (mod.curseforgeId != null) { + UpdaterConfig updaterConfig = new UpdaterConfig(); + result = new ResourceFinder().findModByCurseforgeId(new InstalledModLoader(), mod, mcVersion, + updaterConfig.mods_loader_update_checkName.asBoolean()); + } else if (mod.githubRepoName != null) { + result = new ResourceFinder().findByGithubUrl(mod); } + return result; + } - if (!SearchResult.isMatchFound(result)) { - AL.warn("Failed to find mod, check the provided name for typos."); - return false; + private static File downloadMod(File modsDir, SearchResult result, String tempName) + throws NotLoadedException, YamlReaderException, YamlWriterException, IOException, IllegalKeyException, + DuplicateKeyException, IllegalListException { + UpdaterConfig updaterConfig = new UpdaterConfig(); + MyBThreadManager myManager = null; + try { + myManager = new UtilsTasks().createManagerAndPrinter(); + } catch (JLineLinkException e) { + throw new RuntimeException(e); } - MyBThreadManager myManager = new UtilsTasks().createManagerAndPrinter(); File finalDest = new File(modsDir + "/" + result.mod.getName() + "-LATEST-[" + result.latestVersion + "].jar"); TaskModDownload task = new TaskModDownload("ModDownloader", myManager.manager, tempName, result.latestVersion, result.downloadUrl, result.mod.ignoreContentType, "AUTOMATIC", finalDest); @@ -512,9 +546,7 @@ public static boolean installMod(String command) throws Exception { new File(mod2.installationPath).getName().replace(tempName, mod2.getName())); } } - AL.info("Installed to: " + finalDest); - return true; + return finalDest; } - } diff --git a/src/main/java/com/osiris/autoplug/client/managers/FileManager.java b/src/main/java/com/osiris/autoplug/client/managers/FileManager.java index 6bff195d..76a338a9 100644 --- a/src/main/java/com/osiris/autoplug/client/managers/FileManager.java +++ b/src/main/java/com/osiris/autoplug/client/managers/FileManager.java @@ -8,10 +8,7 @@ package com.osiris.autoplug.client.managers; -import com.osiris.autoplug.client.utils.GD; -import com.osiris.jlib.logger.AL; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import static com.osiris.jprocesses2.util.OS.*; import java.io.File; import java.io.FileInputStream; @@ -24,7 +21,11 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import static com.osiris.jprocesses2.util.OS.isWindows; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.osiris.autoplug.client.utils.GD; +import com.osiris.jlib.logger.AL; /** * Search & find files! @@ -369,21 +370,28 @@ public FileVisitResult visitFile(Path path, @NotNull @Override public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { - - //Skip subdirectories of non main worki dirs and non matching dirs - if (!dir.toString().equals(GD.WORKING_DIR.toString()) && attrs.isDirectory() && !pathMatcher.matches(dir.getFileName())) { + if (shouldSkipDirectory(dir, attrs)) { return FileVisitResult.SKIP_SUBTREE; } else if (!dir.toString().equals(GD.WORKING_DIR.toString())) { - //Adds folders to list + // Adds folders to list queryFiles.add(new File(dir.toString())); return FileVisitResult.CONTINUE; } else { return FileVisitResult.CONTINUE; } + } + // Method to determine whether to skip the directory + private boolean shouldSkipDirectory(Path dir, BasicFileAttributes attrs) { + return !dir.equals(GD.WORKING_DIR) && attrs.isDirectory() && !matchesPattern(dir); + } + // Method to check if directory name matches a pattern + private boolean matchesPattern(Path dir) { + return pathMatcher.matches(dir.getFileName()); } + @NotNull @Override public FileVisitResult visitFileFailed(Path file, IOException exc) diff --git a/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java b/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java index d1661991..813a8a76 100644 --- a/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java +++ b/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java @@ -15,6 +15,7 @@ import com.osiris.jlib.logger.AL; import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.nio.file.StandardWatchEventKinds; @@ -26,68 +27,83 @@ public class SyncFilesManager { private static List lastFoldersToWatch = new ArrayList<>(); + public SyncFilesManager(SharedFilesConfig sharedFilesConfig) throws Exception { + clearPreviousWatchers(); + List foldersToWatch = initializeFoldersToWatch(sharedFilesConfig); + List filesToSendTo = initializeFilesToSendTo(sharedFilesConfig); + Consumer onFileChangeEvent = defineFileChangeEventHandler(filesToSendTo); + setUpDirectoryWatchers(foldersToWatch, onFileChangeEvent); + } + + private void clearPreviousWatchers() throws Exception { for (File folder : lastFoldersToWatch) { DirWatcher dirWatcher = DirWatcher.get(folder, false); dirWatcher.removeAllListeners(true); dirWatcher.close(); } + } + private List initializeFoldersToWatch(SharedFilesConfig sharedFilesConfig) throws Exception { List foldersToWatch = new ArrayList<>(); - for (String pathAsString : - sharedFilesConfig.copy_from.asStringList()) { + for (String pathAsString : sharedFilesConfig.copy_from.asStringList()) { if (pathAsString.startsWith("./")) foldersToWatch.add(FileManager.convertRelativeToAbsolutePath(pathAsString)); else throw new Exception("Wrongly formatted or absolute path: " + pathAsString); } + return foldersToWatch; + } + private List initializeFilesToSendTo(SharedFilesConfig sharedFilesConfig) throws Exception { List filesToSendTo = new ArrayList<>(); - //List ipsToSendTo = new ArrayList<>(); - for (String value : - sharedFilesConfig.send_to.asStringList()) { + for (String value : sharedFilesConfig.send_to.asStringList()) { if (value.startsWith("./")) filesToSendTo.add(FileManager.convertRelativeToAbsolutePath(value)); else if (value.contains("/") || value.contains("\\")) filesToSendTo.add(new File(value)); - // TODO else if (value.contains(".")) - // ipsToSendTo.add(value); else - throw new Exception("Failed to determine if '" + value + "' is absolute/relative path address."); //TODO or ipv4/ipv6 + throw new Exception("Failed to determine if '" + value + "' is an absolute/relative path address."); } + return filesToSendTo; + } - Consumer onFileChangeEvent = event -> { - // Determine relative path from file to server root - // Example: C:/Users/Server/plugins/AutoPlug.jar -> /plugins/AutoPlug.jar + private Consumer defineFileChangeEventHandler(List filesToSendTo) { + return event -> { String relPath = event.file.getAbsolutePath().replace(WORKING_DIR.getAbsolutePath(), ""); - if (event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_DELETE)) { - for (File receivingServerRootDir : - filesToSendTo) { - new File(receivingServerRootDir + relPath) - .delete(); - } - } else if (event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_MODIFY) - || event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_CREATE)) { - for (File receivingServerRootDir : - filesToSendTo) { - try { - File f = new File(receivingServerRootDir + relPath); - if (!f.getParentFile().exists()) f.getParentFile().mkdirs(); - if (!f.exists()) f.createNewFile(); - Files.copy(event.path, f.toPath(), StandardCopyOption.REPLACE_EXISTING); - } catch (Exception e) { - AL.warn(e); - } - } - } else - AL.warn("Failed to execute 'send-to' for event type '" + event.getWatchEventKind().name() + "' for file '" + event.file + "'!"); + handleFileChange(event, filesToSendTo, relPath); }; + } - for (File folder : - foldersToWatch) { - DirWatcher.get(folder, true).addListeners(onFileChangeEvent); - AL.debug(Main.class, "Watching 'copy-from' folder and sub-folders from: " + folder); + private void handleFileChange(FileEvent event, List filesToSendTo, String relPath) { + if (event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_DELETE)) { + filesToSendTo.forEach(receivingServerRootDir -> new File(receivingServerRootDir + relPath).delete()); + } else if (event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_MODIFY) + || event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_CREATE)) { + filesToSendTo.forEach(receivingServerRootDir -> { + try { + File f = new File(receivingServerRootDir + relPath); + if (!f.getParentFile().exists()) f.getParentFile().mkdirs(); + if (!f.exists()) f.createNewFile(); + Files.copy(event.path, f.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (Exception e) { + AL.warn(e); + } + }); + } else { + AL.warn("Unhandled event type: " + event.getWatchEventKind().name() + " for file: " + event.file); } + } + + private void setUpDirectoryWatchers(List foldersToWatch, Consumer onFileChangeEvent) { + foldersToWatch.forEach(folder -> { + try { + DirWatcher.get(folder, true).addListeners(onFileChangeEvent); + } catch (IOException e) { + throw new RuntimeException(e); + } + AL.debug(Main.class, "Watching 'copy-from' folder and sub-folders from: " + folder); + }); lastFoldersToWatch = foldersToWatch; } } diff --git a/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java b/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java index e3025138..ed2e0fed 100644 --- a/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java +++ b/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java @@ -203,7 +203,7 @@ public void runAtStart() throws Exception { sizeUnknownMods++; // MODRINTH OR CURSEFORGE MOD mod.ignoreContentType = true; // TODO temporary workaround for xamazon-json content type curseforge/bukkit issue: https://github.com/Osiris-Team/AutoPlug-Client/issues/109 String finalMcVersion = mcVersion; - activeFutures.add(executorService.submit(() -> new ResourceFinder().findByModrinthOrCurseforge(modLoader, mod, finalMcVersion, updaterConfig.mods_update_check_name_for_mod_loader.asBoolean()))); + activeFutures.add(executorService.submit(() -> new ResourceFinder().findByModrinthOrCurseforge(modLoader, mod, finalMcVersion, updaterConfig.mods_loader_update_checkName.asBoolean()))); } } catch (Exception e) { this.getWarnings().add(new BWarning(this, e, "Critical error while searching for update for '" + mod.getName() + "' mod!")); diff --git a/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java b/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java index 728e60ec..965c0f94 100644 --- a/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java +++ b/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java @@ -165,12 +165,12 @@ else if (e.getHttpErrorCode() == 404) { JsonObject result = Json.post(GD.OFFICIAL_WEBSITE + "api/minecraft-plugin-details", request).getAsJsonObject(); Type typeOfSet = new TypeToken>() { }.getType(); - Entry webSpigotId = getValidEntryWithMostUsages(gson.fromJson(result.get("spigotId").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); - Entry webBukkitId = getValidEntryWithMostUsages(gson.fromJson(result.get("bukkitId").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); - Entry webGithubRepoName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubRepoName").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); - Entry webGithubAssetName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubAssetName").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); - Entry webJenkinsProjectUrl = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsProjectUrl").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); - Entry webJenkinsArtifactName = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsArtifactName").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); + Entry webSpigotId = getValidEntryWithMostUsages(gson.fromJson(result.get("spigotId").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); + Entry webBukkitId = getValidEntryWithMostUsages(gson.fromJson(result.get("bukkitId").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); + Entry webGithubRepoName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubRepoName").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); + Entry webGithubAssetName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubAssetName").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); + Entry webJenkinsProjectUrl = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsProjectUrl").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); + Entry webJenkinsArtifactName = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsArtifactName").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); // Fill missing id information if (webSpigotId != null && (spigotId.asString() == null || spigotId.asInt() == 0)) From abcd281402d0cac25b1eec953f80b029716ac869 Mon Sep 17 00:00:00 2001 From: Drashti Patel Date: Sat, 30 Mar 2024 23:39:23 -0300 Subject: [PATCH 3/4] Updated Pull request with suggested changes --- .../client/configs/UpdaterConfig.java | 8 ++--- .../autoplug/client/console/Commands.java | 26 ++++------------- .../client/managers/SyncFilesManager.java | 7 ++++- .../tasks/updater/mods/TaskModsUpdater.java | 2 +- .../updater/plugins/TaskPluginsUpdater.java | 12 ++++---- .../client/ui/utils/HintTextFieldTest.java | 29 ------------------- 6 files changed, 23 insertions(+), 61 deletions(-) delete mode 100644 src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java diff --git a/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java b/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java index a4fd9774..5c78307f 100644 --- a/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java +++ b/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java @@ -54,14 +54,14 @@ public class UpdaterConfig extends MyYaml { public YamlSection plugins_updater_version; public YamlSection plugins_updater_async; public YamlSection plugins_updater_web_database; - public YamlSection plugin_updater_min_usages; + public YamlSection plugins_updater_web_database_min_usages; public YamlSection mods_updater; public YamlSection mods_updater_profile; public YamlSection mods_updater_path; public YamlSection mods_updater_version; public YamlSection mods_updater_async; - public YamlSection mods_loader_update_checkName; + public YamlSection mods_update_check_name_for_mod_loader; public UpdaterConfig() throws IOException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException, YamlWriterException { @@ -206,7 +206,7 @@ public UpdaterConfig() throws IOException, DuplicateKeyException, YamlReaderExce "Uses the AutoPlug-Web database to fill in missing plugin information.", "This option is only available for premium servers.", "Note that a server-key must be provided for this to work."); - plugin_updater_min_usages = put(name, "plugins-updater", "web-database", "min-usages").setDefValues("50").setComments( + plugins_updater_web_database_min_usages = put(name, "plugins-updater", "web-database", "min-usages").setDefValues("50").setComments( "The minimum amount of usages in servers a piece of information has to have to be used and deemed reliable."); put(name, "mods-updater").setCountTopLineBreaks(1); @@ -221,7 +221,7 @@ public UpdaterConfig() throws IOException, DuplicateKeyException, YamlReaderExce "Asynchronously checks for updates.", "Normally this should be faster than checking for updates synchronously, thus it should be enabled.", "The only downside of this is that your log file gets a bit messy."); - mods_loader_update_checkName = put(name, "mods-updater", "check-name-for-mod-loader").setDefValues("false").setComments( + mods_update_check_name_for_mod_loader = put(name, "mods-updater", "check-name-for-mod-loader").setDefValues("false").setComments( "Only relevant for determining if a curseforge mod release is forge or fabric.", "If enabled additionally checks the mod name to see if it contains fabric or forge."); diff --git a/src/main/java/com/osiris/autoplug/client/console/Commands.java b/src/main/java/com/osiris/autoplug/client/console/Commands.java index 8a9ba507..556b1aa2 100644 --- a/src/main/java/com/osiris/autoplug/client/console/Commands.java +++ b/src/main/java/com/osiris/autoplug/client/console/Commands.java @@ -14,19 +14,11 @@ import java.io.InputStreamReader; import java.net.InetAddress; import java.net.URL; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; +import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; -import java.util.Scanner; +import java.util.*; +import com.osiris.dyml.exceptions.*; import org.jetbrains.annotations.NotNull; import com.osiris.autoplug.client.Main; @@ -55,12 +47,6 @@ import com.osiris.autoplug.client.utils.tasks.MyBThreadManager; import com.osiris.autoplug.client.utils.tasks.UtilsTasks; import com.osiris.betterthread.exceptions.JLineLinkException; -import com.osiris.dyml.exceptions.DuplicateKeyException; -import com.osiris.dyml.exceptions.IllegalKeyException; -import com.osiris.dyml.exceptions.IllegalListException; -import com.osiris.dyml.exceptions.NotLoadedException; -import com.osiris.dyml.exceptions.YamlReaderException; -import com.osiris.dyml.exceptions.YamlWriterException; import com.osiris.jlib.logger.AL; /** @@ -470,7 +456,7 @@ public static boolean installMod(String command) throws Exception { mcVersion = Server.getMCVersion(); MinecraftMod mod = initializeMinecraftMod(modsDir, tempName, input); if (mod != null) { - result = findMod(input, mod, mcVersion); + result = findMod(mod, mcVersion); } if (!SearchResult.isMatchFound(result)) { @@ -507,7 +493,7 @@ private static MinecraftMod initializeMinecraftMod(File modsDir, String tempName return mod; } - private static SearchResult findMod(String input, MinecraftMod mod, String mcVersion) + private static SearchResult findMod(MinecraftMod mod, String mcVersion) throws NotLoadedException, YamlReaderException, YamlWriterException, IOException, IllegalKeyException, DuplicateKeyException, IllegalListException { SearchResult result = null; @@ -516,7 +502,7 @@ private static SearchResult findMod(String input, MinecraftMod mod, String mcVer } else if (mod.curseforgeId != null) { UpdaterConfig updaterConfig = new UpdaterConfig(); result = new ResourceFinder().findModByCurseforgeId(new InstalledModLoader(), mod, mcVersion, - updaterConfig.mods_loader_update_checkName.asBoolean()); + updaterConfig.mods_update_check_name_for_mod_loader.asBoolean()); } else if (mod.githubRepoName != null) { result = new ResourceFinder().findByGithubUrl(mod); } diff --git a/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java b/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java index 813a8a76..e5b25d1e 100644 --- a/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java +++ b/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java @@ -57,19 +57,24 @@ private List initializeFoldersToWatch(SharedFilesConfig sharedFilesConfig) private List initializeFilesToSendTo(SharedFilesConfig sharedFilesConfig) throws Exception { List filesToSendTo = new ArrayList<>(); + //List ipsToSendTo = new ArrayList<>(); for (String value : sharedFilesConfig.send_to.asStringList()) { if (value.startsWith("./")) filesToSendTo.add(FileManager.convertRelativeToAbsolutePath(value)); else if (value.contains("/") || value.contains("\\")) filesToSendTo.add(new File(value)); + // TODO else if (value.contains(".")) + // ipsToSendTo.add(value); else - throw new Exception("Failed to determine if '" + value + "' is an absolute/relative path address."); + throw new Exception("Failed to determine if '" + value + "' is an absolute/relative path address."); //TODO or ipv4/ipv6 } return filesToSendTo; } private Consumer defineFileChangeEventHandler(List filesToSendTo) { return event -> { + // Determine relative path from file to server root + // Example: C:/Users/Server/plugins/AutoPlug.jar -> /plugins/AutoPlug.jar String relPath = event.file.getAbsolutePath().replace(WORKING_DIR.getAbsolutePath(), ""); handleFileChange(event, filesToSendTo, relPath); }; diff --git a/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java b/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java index ed2e0fed..e3025138 100644 --- a/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java +++ b/src/main/java/com/osiris/autoplug/client/tasks/updater/mods/TaskModsUpdater.java @@ -203,7 +203,7 @@ public void runAtStart() throws Exception { sizeUnknownMods++; // MODRINTH OR CURSEFORGE MOD mod.ignoreContentType = true; // TODO temporary workaround for xamazon-json content type curseforge/bukkit issue: https://github.com/Osiris-Team/AutoPlug-Client/issues/109 String finalMcVersion = mcVersion; - activeFutures.add(executorService.submit(() -> new ResourceFinder().findByModrinthOrCurseforge(modLoader, mod, finalMcVersion, updaterConfig.mods_loader_update_checkName.asBoolean()))); + activeFutures.add(executorService.submit(() -> new ResourceFinder().findByModrinthOrCurseforge(modLoader, mod, finalMcVersion, updaterConfig.mods_update_check_name_for_mod_loader.asBoolean()))); } } catch (Exception e) { this.getWarnings().add(new BWarning(this, e, "Critical error while searching for update for '" + mod.getName() + "' mod!")); diff --git a/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java b/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java index 965c0f94..728e60ec 100644 --- a/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java +++ b/src/main/java/com/osiris/autoplug/client/tasks/updater/plugins/TaskPluginsUpdater.java @@ -165,12 +165,12 @@ else if (e.getHttpErrorCode() == 404) { JsonObject result = Json.post(GD.OFFICIAL_WEBSITE + "api/minecraft-plugin-details", request).getAsJsonObject(); Type typeOfSet = new TypeToken>() { }.getType(); - Entry webSpigotId = getValidEntryWithMostUsages(gson.fromJson(result.get("spigotId").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); - Entry webBukkitId = getValidEntryWithMostUsages(gson.fromJson(result.get("bukkitId").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); - Entry webGithubRepoName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubRepoName").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); - Entry webGithubAssetName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubAssetName").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); - Entry webJenkinsProjectUrl = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsProjectUrl").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); - Entry webJenkinsArtifactName = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsArtifactName").getAsString(), typeOfSet), updaterConfig.plugin_updater_min_usages.asInt()); + Entry webSpigotId = getValidEntryWithMostUsages(gson.fromJson(result.get("spigotId").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); + Entry webBukkitId = getValidEntryWithMostUsages(gson.fromJson(result.get("bukkitId").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); + Entry webGithubRepoName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubRepoName").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); + Entry webGithubAssetName = getValidEntryWithMostUsages(gson.fromJson(result.get("githubAssetName").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); + Entry webJenkinsProjectUrl = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsProjectUrl").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); + Entry webJenkinsArtifactName = getValidEntryWithMostUsages(gson.fromJson(result.get("jenkinsArtifactName").getAsString(), typeOfSet), updaterConfig.plugins_updater_web_database_min_usages.asInt()); // Fill missing id information if (webSpigotId != null && (spigotId.asString() == null || spigotId.asInt() == 0)) diff --git a/src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java b/src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java deleted file mode 100644 index 851e4367..00000000 --- a/src/test/java/com/osiris/autoplug/client/ui/utils/HintTextFieldTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.osiris.autoplug.client.ui.utils; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.awt.Color; -import java.awt.event.FocusEvent; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -public class HintTextFieldTest { - - private HintTextField textField; - - @BeforeEach - public void setUp() { - textField = new HintTextField("Enter text here"); - } - - @Test - public void testTextIsClearedOnFocus() { - FocusEvent mockFocusEvent = Mockito.mock(FocusEvent.class); - textField.focusGained(mockFocusEvent); - assertEquals("", textField.getText()); - assertEquals(Color.BLACK, textField.getForeground()); - } - -} - From 7db4d5e57cee255b5c64951cc1af85a6727683e8 Mon Sep 17 00:00:00 2001 From: Drashti Patel Date: Sat, 30 Mar 2024 23:51:26 -0300 Subject: [PATCH 4/4] Refactored code to increase maintainability --- .../client/configs/UpdaterConfig.java | 106 ++++++- .../autoplug/client/managers/FileManager.java | 265 +---------------- .../client/managers/FileSearcher.java | 266 ++++++++++++++++++ .../online/connections/ConFileManager.java | 57 +--- .../online/connections/FileSystemUtils.java | 57 ++++ .../updater/server/TaskServerUpdater.java | 100 +------ .../osiris/autoplug/client/ui/MainWindow.java | 60 +++- 7 files changed, 494 insertions(+), 417 deletions(-) create mode 100644 src/main/java/com/osiris/autoplug/client/managers/FileSearcher.java create mode 100644 src/main/java/com/osiris/autoplug/client/network/online/connections/FileSystemUtils.java diff --git a/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java b/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java index 5c78307f..e84ec784 100644 --- a/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java +++ b/src/main/java/com/osiris/autoplug/client/configs/UpdaterConfig.java @@ -9,12 +9,20 @@ package com.osiris.autoplug.client.configs; import com.osiris.autoplug.client.Main; +import com.osiris.autoplug.client.tasks.updater.TaskDownload; +import com.osiris.autoplug.client.tasks.updater.search.GithubSearch; +import com.osiris.autoplug.client.tasks.updater.search.JenkinsSearch; +import com.osiris.autoplug.client.tasks.updater.search.SearchResult; +import com.osiris.autoplug.client.tasks.updater.server.TaskServerUpdater; +import com.osiris.autoplug.client.utils.GD; import com.osiris.autoplug.client.utils.UpdateCheckerThread; import com.osiris.dyml.Yaml; import com.osiris.dyml.YamlSection; import com.osiris.dyml.exceptions.*; import com.osiris.jlib.logger.AL; +import org.apache.commons.io.FileUtils; +import java.io.File; import java.io.IOException; public class UpdaterConfig extends MyYaml { @@ -261,4 +269,100 @@ public Yaml validateValues() { } return this; } -} + + public void doAlternativeUpdatingLogic(TaskServerUpdater task) + throws YamlWriterException, IOException, InterruptedException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException { + SearchResult sr = null; + if (server_github_repo_name.asString() != null) { + sr = new GithubSearch().search(server_github_repo_name.asString(), + server_github_asset_name.asString(), + server_github_version.asString()); + if (sr.resultCode == 0) { + task.setStatus("Your server is on the latest version!"); + task.setSuccess(true); + return; + } + if (sr.resultCode == 1) { + doInstallDependingOnProfile(task, server_github_version, sr.latestVersion, sr.downloadUrl, sr.fileName); + } + } else { + sr = new JenkinsSearch().search(server_jenkins_project_url.asString(), + server_jenkins_artifact_name.asString(), + server_jenkins_build_id.asInt()); + + if (sr.resultCode == 0) { + task.setStatus("Your server is on the latest version!"); + task.setSuccess(true); + return; + } + if (sr.resultCode == 1) { + doInstallDependingOnProfile(task, server_jenkins_build_id, sr.latestVersion, sr.downloadUrl, sr.fileName); + } + } + } + + private void doInstallDependingOnProfile(TaskServerUpdater task, YamlSection version, String latestVersion, String downloadUrl, String onlineFileName) throws IOException, InterruptedException, YamlWriterException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException { + String profile = server_updater_profile.asString(); + File downloadsDir = GD.DOWNLOADS_DIR; + File serverExe = task.serverExe; + + if (profile.equals("NOTIFY")) { + task.setStatus("Update found (" + version.asString() + " -> " + latestVersion + ")!"); + } else if (profile.equals("MANUAL")) { + task.setStatus("Update found (" + version.asString() + " -> " + latestVersion + "), started download!"); + + // Download the file + File cache_dest = new File(downloadsDir.getAbsolutePath() + "/" + onlineFileName); + if (cache_dest.exists()) cache_dest.delete(); + cache_dest.createNewFile(); + TaskDownload download = new TaskDownload("ServerDownloader", task.getManager(), downloadUrl, cache_dest); + download.start(); + + while (true) { + Thread.sleep(500); // Wait until download is finished + if (download.isFinished()) { + if (download.isSuccess()) { + task.setStatus("Server update downloaded successfully."); + task.setSuccess(true); + } else { + task.setStatus("Server update failed!"); + task.setSuccess(false); + } + break; + } + } + } else { + task.setStatus("Update found (" + version.asString() + " -> " + latestVersion + "), started download!"); + + // Download the file + File cache_dest = new File(downloadsDir.getAbsolutePath() + "/" + onlineFileName); + if (cache_dest.exists()) cache_dest.delete(); + cache_dest.createNewFile(); + TaskDownload download = new TaskDownload("ServerDownloader", task.getManager(), downloadUrl, cache_dest); + download.start(); + + while (true) { + Thread.sleep(500); + if (download.isFinished()) { + if (download.isSuccess()) { + File final_dest = serverExe; + if (final_dest == null) + final_dest = new File(GD.WORKING_DIR + "/" + onlineFileName); + if (final_dest.exists()) final_dest.delete(); + final_dest.createNewFile(); + FileUtils.copyFile(cache_dest, final_dest); + task.setStatus("Server update was installed successfully (" + version.asString() + " -> " + latestVersion + ")!"); + version.setValues(latestVersion); + save(); + task.setSuccess(true); + } else { + task.setStatus("Server update failed!"); + task.setSuccess(false); + } + break; + } + } + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/osiris/autoplug/client/managers/FileManager.java b/src/main/java/com/osiris/autoplug/client/managers/FileManager.java index 76a338a9..a7fc1831 100644 --- a/src/main/java/com/osiris/autoplug/client/managers/FileManager.java +++ b/src/main/java/com/osiris/autoplug/client/managers/FileManager.java @@ -32,6 +32,8 @@ * TODO (Not tasty code. Rework needed!) */ public class FileManager { + private final FileSearcher fileSearcher = new FileSearcher(); + private final List queryFiles = new ArrayList<>(); @Nullable private File queryFile = null; @@ -51,7 +53,7 @@ public static File convertRelativeToAbsolutePath(@NotNull String shortPath) { public void deleteOldPlugin(String pl_name) { String searchPattern = "*" + pl_name + "**.jar"; //Find the file - findFileInPluginsDir(searchPattern); + FileSearcher.findFileInPluginsDir(searchPattern); //Delete the file if (!queryFile.delete()) { AL.warn(" [!] Couldn't remove old plugin jar at: " + queryFile.toPath() + " [!] "); @@ -68,7 +70,7 @@ public void deleteOldPlugin(String pl_name) { public List getAllPlugins() { String searchPattern = "*.jar"; //Find the file - findFilesInPluginsDir(searchPattern); + FileSearcher.findFilesInPluginsDir(searchPattern); return queryFiles; } @@ -77,7 +79,7 @@ public List getAllPlugins() { public List serverWorldsFolders() { String searchPattern = "*world*"; //Find the files - findFoldersInWorkingDir(searchPattern); + FileSearcher.findFoldersInWorkingDir(searchPattern); //Return the results return queryFiles; @@ -91,7 +93,7 @@ public List serverWorldsFolders() { public List serverFiles() { String searchPattern = "*"; //Find the files - findFilesInWorkingDir(searchPattern); + FileSearcher.findFilesInWorkingDir(searchPattern); //Return the results return queryFiles; @@ -100,9 +102,9 @@ public List serverFiles() { public File autoplugJar(File dirToSearch) { String searchPattern = "*.jar"; //Find the file - findAutoPlugJarFileInDir(searchPattern, dirToSearch); + fileSearcher.findAutoPlugJarFileInDir(searchPattern, dirToSearch); //Return the result file - return queryFile; + return fileSearcher.getQueryFile(); } /** @@ -212,53 +214,7 @@ public FileVisitResult preVisitDirectory(@NotNull Path path, BasicFileAttributes Files.walkFileTree(dirPath, visitor); return list; } - - private void findAutoPlugJarFileInDir(String searchPattern, File dirToSearch) { - - try { - final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); - - Files.walkFileTree(dirToSearch.toPath(), new SimpleFileVisitor() { - - @NotNull - @Override - public FileVisitResult visitFile(@NotNull Path path, - BasicFileAttributes attrs) throws IOException { - if (pathMatcher.matches(path.getFileName()) - && jarContainsAutoPlugProperties(path.toFile())) { - queryFile = new File(path.toString()); - return FileVisitResult.TERMINATE; - } - return FileVisitResult.CONTINUE; - } - - @NotNull - @Override - public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { - - if (!dir.toString().equals(dirToSearch.toString()) && attrs.isDirectory()) { - return FileVisitResult.SKIP_SUBTREE; - } else { - return FileVisitResult.CONTINUE; - } - } - - @NotNull - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - }); - - - } catch (IOException e) { - AL.warn(e); - } - - } - - private boolean jarContainsAutoPlugProperties(File jar) { + static boolean jarContainsAutoPlugProperties(File jar) { if (!jar.getName().endsWith(".jar")) return false; FileInputStream fis = null; ZipInputStream zis = null; @@ -303,207 +259,4 @@ private boolean jarContainsAutoPlugProperties(File jar) { } return false; } - - //Walks through files (skips AutoPlug.jar and all other subdirectories) and finds ALL files - private void findFilesInWorkingDir(String searchPattern) { - - try { - final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); - - Files.walkFileTree(GD.WORKING_DIR.toPath(), new SimpleFileVisitor() { - - @NotNull - @Override - public FileVisitResult visitFile(@NotNull Path path, - BasicFileAttributes attrs) throws IOException { - - if (pathMatcher.matches(path.getFileName())) { - //Adds files to list to return multiple files - queryFiles.add(new File(path.toString())); - return FileVisitResult.CONTINUE; - } - return FileVisitResult.CONTINUE; - } - - @NotNull - @Override - public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { - - if (!dir.toString().equals(GD.WORKING_DIR.toString()) && attrs.isDirectory()) { - return FileVisitResult.SKIP_SUBTREE; - } else { - return FileVisitResult.CONTINUE; - } - } - - @NotNull - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - }); - - - } catch (IOException e) { - e.printStackTrace(); - AL.warn(" [!] Error: " + e.getMessage() + " [!]"); - } - - } - - //Walks through files and finds ALL sub-folders in main working dir - private void findFoldersInWorkingDir(String searchPattern) { - - try { - final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); - - Files.walkFileTree(GD.WORKING_DIR.toPath(), new SimpleFileVisitor() { - - @NotNull - @Override - public FileVisitResult visitFile(Path path, - BasicFileAttributes attrs) throws IOException { - return FileVisitResult.CONTINUE; - } - - @NotNull - @Override - public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { - if (shouldSkipDirectory(dir, attrs)) { - return FileVisitResult.SKIP_SUBTREE; - } else if (!dir.toString().equals(GD.WORKING_DIR.toString())) { - // Adds folders to list - queryFiles.add(new File(dir.toString())); - return FileVisitResult.CONTINUE; - } else { - return FileVisitResult.CONTINUE; - } - } - - // Method to determine whether to skip the directory - private boolean shouldSkipDirectory(Path dir, BasicFileAttributes attrs) { - return !dir.equals(GD.WORKING_DIR) && attrs.isDirectory() && !matchesPattern(dir); - } - - // Method to check if directory name matches a pattern - private boolean matchesPattern(Path dir) { - return pathMatcher.matches(dir.getFileName()); - } - - - @NotNull - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - }); - - - } catch (IOException e) { - e.printStackTrace(); - AL.warn(" [!] Error: " + e.getMessage() + " [!]"); - } - - } - - //Walks through files (skips all Plugin directories) and finds one jar - private void findFileInPluginsDir(String searchPattern) { - - try { - final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); - - Files.walkFileTree(GD.PLUGINS_DIR.toPath(), new SimpleFileVisitor() { - - @NotNull - @Override - public FileVisitResult visitFile(@NotNull Path path, - BasicFileAttributes attrs) throws IOException { - - if (pathMatcher.matches(path.getFileName())) { - - queryFile = new File(path.toString()); - return FileVisitResult.TERMINATE; - } - return FileVisitResult.CONTINUE; - } - - @NotNull - @Override - public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { - - if (!dir.toString().equals(GD.PLUGINS_DIR.toString()) && attrs.isDirectory()) { - return FileVisitResult.SKIP_SUBTREE; - } else { - return FileVisitResult.CONTINUE; - } - - - } - - @NotNull - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - }); - - - } catch (IOException e) { - e.printStackTrace(); - AL.warn(" [!] Error: " + e.getMessage() + " [!]"); - } - - } - - //Walks through files (skips all Plugin directories) - private void findFilesInPluginsDir(String searchPattern) { - - try { - final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); - - Files.walkFileTree(GD.PLUGINS_DIR.toPath(), new SimpleFileVisitor() { - - @NotNull - @Override - public FileVisitResult visitFile(@NotNull Path path, - BasicFileAttributes attrs) throws IOException { - - if (pathMatcher.matches(path.getFileName())) { - - queryFile = new File(path.toString()); - queryFiles.add(queryFile); - } - return FileVisitResult.CONTINUE; - } - - @NotNull - @Override - public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { - - if (!dir.toString().equals(GD.PLUGINS_DIR.toString()) && attrs.isDirectory()) { - return FileVisitResult.SKIP_SUBTREE; - } else { - return FileVisitResult.CONTINUE; - } - - - } - - @NotNull - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - }); - - - } catch (IOException e) { - AL.warn(e); - } - - } } diff --git a/src/main/java/com/osiris/autoplug/client/managers/FileSearcher.java b/src/main/java/com/osiris/autoplug/client/managers/FileSearcher.java new file mode 100644 index 00000000..27d759db --- /dev/null +++ b/src/main/java/com/osiris/autoplug/client/managers/FileSearcher.java @@ -0,0 +1,266 @@ +package com.osiris.autoplug.client.managers; + +import com.osiris.autoplug.client.utils.GD; +import com.osiris.jlib.logger.AL; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nullable; +import java.io.File; +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; + +public class FileSearcher { + private static final List queryFiles = new ArrayList<>(); + @Nullable + private static File queryFile = null; + + public static void findFileInPluginsDir(String searchPattern) { + try { + final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); + + Files.walkFileTree(GD.PLUGINS_DIR.toPath(), new SimpleFileVisitor() { + + @NotNull + @Override + public FileVisitResult visitFile(@NotNull Path path, + BasicFileAttributes attrs) throws IOException { + + if (pathMatcher.matches(path.getFileName())) { + + queryFile = new File(path.toString()); + return FileVisitResult.TERMINATE; + } + return FileVisitResult.CONTINUE; + } + + @NotNull + @Override + public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { + + if (!dir.toString().equals(GD.PLUGINS_DIR.toString()) && attrs.isDirectory()) { + return FileVisitResult.SKIP_SUBTREE; + } else { + return FileVisitResult.CONTINUE; + } + + + } + + @NotNull + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + }); + + + } catch (IOException e) { + e.printStackTrace(); + AL.warn(" [!] Error: " + e.getMessage() + " [!]"); + } + } + + static void findFilesInPluginsDir(String searchPattern) { + + try { + final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); + + Files.walkFileTree(GD.PLUGINS_DIR.toPath(), new SimpleFileVisitor() { + + @NotNull + @Override + public FileVisitResult visitFile(@NotNull Path path, + BasicFileAttributes attrs) throws IOException { + + if (pathMatcher.matches(path.getFileName())) { + + queryFile = new File(path.toString()); + queryFiles.add(queryFile); + } + return FileVisitResult.CONTINUE; + } + + @NotNull + @Override + public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { + + if (!dir.toString().equals(GD.PLUGINS_DIR.toString()) && attrs.isDirectory()) { + return FileVisitResult.SKIP_SUBTREE; + } else { + return FileVisitResult.CONTINUE; + } + + + } + + @NotNull + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + }); + + + } catch (IOException e) { + AL.warn(e); + } + + } + + public static void findFilesInWorkingDir(String searchPattern) { + try { + final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); + + Files.walkFileTree(GD.WORKING_DIR.toPath(), new SimpleFileVisitor() { + + @NotNull + @Override + public FileVisitResult visitFile(@NotNull Path path, + BasicFileAttributes attrs) throws IOException { + + if (pathMatcher.matches(path.getFileName())) { + //Adds files to list to return multiple files + queryFiles.add(new File(path.toString())); + return FileVisitResult.CONTINUE; + } + return FileVisitResult.CONTINUE; + } + + @NotNull + @Override + public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { + + if (!dir.toString().equals(GD.WORKING_DIR.toString()) && attrs.isDirectory()) { + return FileVisitResult.SKIP_SUBTREE; + } else { + return FileVisitResult.CONTINUE; + } + } + + @NotNull + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + }); + + + } catch (IOException e) { + e.printStackTrace(); + AL.warn(" [!] Error: " + e.getMessage() + " [!]"); + } + } + + public static void findFoldersInWorkingDir(String searchPattern) { + try { + final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); + + Files.walkFileTree(GD.WORKING_DIR.toPath(), new SimpleFileVisitor() { + + @NotNull + @Override + public FileVisitResult visitFile(Path path, + BasicFileAttributes attrs) throws IOException { + return FileVisitResult.CONTINUE; + } + + @NotNull + @Override + public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { + // Skip subdirectories of non main working dirs and non matching dirs + if (shouldSkipDirectory(dir, attrs)) { + return FileVisitResult.SKIP_SUBTREE; + } else if (!dir.toString().equals(GD.WORKING_DIR.toString())) { + // Adds folders to list + queryFiles.add(new File(dir.toString())); + return FileVisitResult.CONTINUE; + } else { + return FileVisitResult.CONTINUE; + } + } + + // Method to determine whether to skip the directory + private boolean shouldSkipDirectory(Path dir, BasicFileAttributes attrs) { + return !dir.equals(GD.WORKING_DIR) && attrs.isDirectory() && !matchesPattern(dir); + } + + // Method to check if directory name matches a pattern + private boolean matchesPattern(Path dir) { + return pathMatcher.matches(dir.getFileName()); + } + + + @NotNull + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + }); + + + } catch (IOException e) { + e.printStackTrace(); + AL.warn(" [!] Error: " + e.getMessage() + " [!]"); + } + } + + public void findAutoPlugJarFileInDir(String searchPattern, File dirToSearch) { + try { + final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + searchPattern); + + Files.walkFileTree(dirToSearch.toPath(), new SimpleFileVisitor() { + + @NotNull + @Override + public FileVisitResult visitFile(@NotNull Path path, + BasicFileAttributes attrs) throws IOException { + if (pathMatcher.matches(path.getFileName()) + && FileManager.jarContainsAutoPlugProperties(path.toFile())) { + queryFile = new File(path.toString()); + return FileVisitResult.TERMINATE; + } + return FileVisitResult.CONTINUE; + } + + @NotNull + @Override + public FileVisitResult preVisitDirectory(@NotNull Path dir, @NotNull BasicFileAttributes attrs) throws IOException { + + if (!dir.toString().equals(dirToSearch.toString()) && attrs.isDirectory()) { + return FileVisitResult.SKIP_SUBTREE; + } else { + return FileVisitResult.CONTINUE; + } + } + + @NotNull + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + }); + + + } catch (IOException e) { + AL.warn(e); + } + } + + // Getter methods for queryFiles and queryFile + public List getQueryFiles() { + return queryFiles; + } + + @Nullable + public File getQueryFile() { + return queryFile; + } +} diff --git a/src/main/java/com/osiris/autoplug/client/network/online/connections/ConFileManager.java b/src/main/java/com/osiris/autoplug/client/network/online/connections/ConFileManager.java index b8adcd09..c67a20c4 100644 --- a/src/main/java/com/osiris/autoplug/client/network/online/connections/ConFileManager.java +++ b/src/main/java/com/osiris/autoplug/client/network/online/connections/ConFileManager.java @@ -64,7 +64,7 @@ public boolean open() throws Exception { } else if (requestType == 6) { doProtocolForCopyOrCutFiles(); } else if (requestType == 7) { - doProtocolForSendingRoots(); + FileSystemUtils.sendRoots(dos); } else { AL.warn("Unknown file operation / Unknown request type (" + requestType + ")."); } @@ -83,19 +83,6 @@ public boolean open() throws Exception { } } - private void doProtocolForSendingRoots() throws IOException { - File[] roots = File.listRoots(); - if (roots == null || roots.length == 0) { - dos.writeInt(0); - } else { - dos.writeInt(roots.length); - for (File f : - roots) { - dos.writeLine(f.getAbsolutePath()); // For example "C:\" or "D:\" etc. on Windows - } - } - } - private void doProtocolForCopyOrCutFiles() throws IOException { int filesCount = dis.readInt(); boolean isCopy = dis.readBoolean(); @@ -223,7 +210,7 @@ private void doProtocolForSendingFileDetails() throws IOException { filePath = dis.readLine(); // Wait until we receive the files path if (filePath.isEmpty()) requestedFile = GD.WORKING_DIR; else requestedFile = new File(filePath); - sendFileDetails(requestedFile); + FileSystemUtils.sendFileDetails(dos, requestedFile); if (requestedFile.isDirectory()) { File[] files = requestedFile.listFiles(); if (files == null) dos.writeInt(0); @@ -233,12 +220,12 @@ private void doProtocolForSendingFileDetails() throws IOException { for (File f : files) { // Send directories first and then files if (f.isDirectory()) - sendFileDetails(f); + FileSystemUtils.sendFileDetails(dos, f); } for (File f : files) { if (!f.isDirectory()) - sendFileDetails(f); + FileSystemUtils.sendFileDetails(dos, f); } } } else { // Is not a dir @@ -267,40 +254,4 @@ private void sendFileContent(File file) throws IOException { */ //System.out.println("Sent file!"); } - - private void sendFileDetails(File file) throws IOException { - dos.writeLine(file.getAbsolutePath()); - dos.writeBoolean(file.isDirectory()); - long length = file.length(); // In bytes - dos.writeLong(length); - if (length < 1000) // Smaller than 1kb - dos.writeLine(length + "B"); - else if (length < 1000000) // Smaller than 1mb - dos.writeLine(length / 1000 + "kB"); - else if (length < 1000000000) // Smaller than 1 gb - dos.writeLine(length / 1000000 + "MB"); - else // Bigger than 1 gb - dos.writeLine(length / 1000000000 + "GB"); - dos.writeLine(file.getName()); - dos.writeLong(file.lastModified()); - dos.writeBoolean(file.isHidden()); - } - - private void sendParentDirDetails(File file) throws IOException { - dos.writeLine(file.getAbsolutePath()); - dos.writeBoolean(file.isDirectory()); - long length = file.length(); // In bytes - dos.writeLong(length); - if (length < 1000) // Smaller than 1kb - dos.writeLine(length + "B"); - else if (length < 1000000) // Smaller than 1mb - dos.writeLine(length / 1000 + "kB"); - else if (length < 1000000000) // Smaller than 1 gb - dos.writeLine(length / 1000000 + "MB"); - else // Bigger than 1 gb - dos.writeLine(length / 1000000000 + "GB"); - dos.writeLine("..."); - dos.writeLong(file.lastModified()); - dos.writeBoolean(file.isHidden()); - } } diff --git a/src/main/java/com/osiris/autoplug/client/network/online/connections/FileSystemUtils.java b/src/main/java/com/osiris/autoplug/client/network/online/connections/FileSystemUtils.java new file mode 100644 index 00000000..109e438f --- /dev/null +++ b/src/main/java/com/osiris/autoplug/client/network/online/connections/FileSystemUtils.java @@ -0,0 +1,57 @@ +package com.osiris.autoplug.client.network.online.connections; + +import com.osiris.autoplug.client.utils.io.UFDataOut; + +import java.io.File; +import java.io.IOException; + +public class FileSystemUtils { + + public static void sendRoots(UFDataOut dos) throws IOException { + File[] roots = File.listRoots(); + if (roots == null || roots.length == 0) { + dos.writeInt(0); + } else { + dos.writeInt(roots.length); + for (File f : roots) { + dos.writeLine(f.getAbsolutePath()); // For example "C:\" or "D:\" etc. on Windows + } + } + } + + public static void sendFileDetails(UFDataOut dos, File file) throws IOException { + dos.writeLine(file.getAbsolutePath()); + dos.writeBoolean(file.isDirectory()); + long length = file.length(); // In bytes + dos.writeLong(length); + if (length < 1000) // Smaller than 1kb + dos.writeLine(length + "B"); + else if (length < 1000000) // Smaller than 1mb + dos.writeLine(length / 1000 + "kB"); + else if (length < 1000000000) // Smaller than 1 gb + dos.writeLine(length / 1000000 + "MB"); + else // Bigger than 1 gb + dos.writeLine(length / 1000000000 + "GB"); + dos.writeLine(file.getName()); + dos.writeLong(file.lastModified()); + dos.writeBoolean(file.isHidden()); + } + + public static void sendParentDirDetails(UFDataOut dos, File file) throws IOException { + dos.writeLine(file.getAbsolutePath()); + dos.writeBoolean(file.isDirectory()); + long length = file.length(); // In bytes + dos.writeLong(length); + if (length < 1000) // Smaller than 1kb + dos.writeLine(length + "B"); + else if (length < 1000000) // Smaller than 1mb + dos.writeLine(length / 1000 + "kB"); + else if (length < 1000000000) // Smaller than 1 gb + dos.writeLine(length / 1000000 + "MB"); + else // Bigger than 1 gb + dos.writeLine(length / 1000000000 + "GB"); + dos.writeLine("..."); + dos.writeLong(file.lastModified()); + dos.writeBoolean(file.isHidden()); + } +} \ No newline at end of file diff --git a/src/main/java/com/osiris/autoplug/client/tasks/updater/server/TaskServerUpdater.java b/src/main/java/com/osiris/autoplug/client/tasks/updater/server/TaskServerUpdater.java index 090d882e..b787f9a0 100644 --- a/src/main/java/com/osiris/autoplug/client/tasks/updater/server/TaskServerUpdater.java +++ b/src/main/java/com/osiris/autoplug/client/tasks/updater/server/TaskServerUpdater.java @@ -12,10 +12,6 @@ import com.osiris.autoplug.client.configs.GeneralConfig; import com.osiris.autoplug.client.configs.UpdaterConfig; import com.osiris.autoplug.client.managers.FileManager; -import com.osiris.autoplug.client.tasks.updater.TaskDownload; -import com.osiris.autoplug.client.tasks.updater.search.GithubSearch; -import com.osiris.autoplug.client.tasks.updater.search.JenkinsSearch; -import com.osiris.autoplug.client.tasks.updater.search.SearchResult; import com.osiris.autoplug.client.utils.GD; import com.osiris.autoplug.client.utils.SteamCMD; import com.osiris.autoplug.client.utils.UtilsLists; @@ -23,7 +19,6 @@ import com.osiris.betterthread.BThread; import com.osiris.betterthread.BThreadManager; import com.osiris.betterthread.BWarning; -import com.osiris.dyml.YamlSection; import com.osiris.dyml.exceptions.*; import com.osiris.jlib.logger.AL; import me.hsgamer.mcserverupdater.UpdateBuilder; @@ -76,7 +71,7 @@ public void runAtStart() throws Exception { } if (updaterConfig.server_github_repo_name.asString() != null || updaterConfig.server_jenkins_project_url.asString() != null) { - doAlternativeUpdatingLogic(); + updaterConfig.doAlternativeUpdatingLogic(this); } else { if (isSteamAppId) doSteamUpdaterLogic(); @@ -86,97 +81,6 @@ public void runAtStart() throws Exception { finish(); } - private void doAlternativeUpdatingLogic() - throws YamlWriterException, IOException, InterruptedException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException { - SearchResult sr = null; - if (updaterConfig.server_github_repo_name.asString() != null) { - sr = new GithubSearch().search(updaterConfig.server_github_repo_name.asString(), - updaterConfig.server_github_asset_name.asString(), - updaterConfig.server_github_version.asString()); - if (sr.resultCode == 0) { - setStatus("Your server is on the latest version!"); - setSuccess(true); - return; - } - if (sr.resultCode == 1) { - doInstallDependingOnProfile(updaterConfig.server_github_version, sr.latestVersion, sr.downloadUrl, sr.fileName); - } - } else { - sr = new JenkinsSearch().search(updaterConfig.server_jenkins_project_url.asString(), - updaterConfig.server_jenkins_artifact_name.asString(), - updaterConfig.server_jenkins_build_id.asInt()); - - if (sr.resultCode == 0) { - setStatus("Your server is on the latest version!"); - setSuccess(true); - return; - } - if (sr.resultCode == 1) { - doInstallDependingOnProfile(updaterConfig.server_jenkins_build_id, sr.latestVersion, sr.downloadUrl, sr.fileName); - } - } - } - - private void doInstallDependingOnProfile(YamlSection version, String latestVersion, String downloadUrl, String onlineFileName) throws IOException, InterruptedException, YamlWriterException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException { - if (profile.equals("NOTIFY")) { - setStatus("Update found (" + version.asString() + " -> " + latestVersion + ")!"); - } else if (profile.equals("MANUAL")) { - setStatus("Update found (" + version.asString() + " -> " + latestVersion + "), started download!"); - - // Download the file - File cache_dest = new File(downloadsDir.getAbsolutePath() + "/" + onlineFileName); - if (cache_dest.exists()) cache_dest.delete(); - cache_dest.createNewFile(); - TaskDownload download = new TaskDownload("ServerDownloader", getManager(), downloadUrl, cache_dest); - download.start(); - - while (true) { - Thread.sleep(500); // Wait until download is finished - if (download.isFinished()) { - if (download.isSuccess()) { - setStatus("Server update downloaded successfully."); - setSuccess(true); - } else { - setStatus("Server update failed!"); - setSuccess(false); - } - break; - } - } - } else { - setStatus("Update found (" + version.asString() + " -> " + latestVersion + "), started download!"); - - // Download the file - File cache_dest = new File(downloadsDir.getAbsolutePath() + "/" + onlineFileName); - if (cache_dest.exists()) cache_dest.delete(); - cache_dest.createNewFile(); - TaskDownload download = new TaskDownload("ServerDownloader", getManager(), downloadUrl, cache_dest); - download.start(); - - while (true) { - Thread.sleep(500); - if (download.isFinished()) { - if (download.isSuccess()) { - File final_dest = serverExe; - if (final_dest == null) - final_dest = new File(GD.WORKING_DIR + "/" + onlineFileName); - if (final_dest.exists()) final_dest.delete(); - final_dest.createNewFile(); - FileUtils.copyFile(cache_dest, final_dest); - setStatus("Server update was installed successfully (" + version.asString() + " -> " + latestVersion + ")!"); - version.setValues(latestVersion); - updaterConfig.save(); - setSuccess(true); - } else { - setStatus("Server update failed!"); - setSuccess(false); - } - break; - } - } - } - } - private void doMCServerUpdaterLogic() throws Exception { UpdateBuilder updateBuilder = UpdateBuilder .updateProject(serverSoftware) @@ -275,4 +179,4 @@ private void doSteamUpdaterLogic() throws Exception { setStatus("Installed updated if needed (SteamCMD)."); setSuccess(true); } -} +} \ No newline at end of file diff --git a/src/main/java/com/osiris/autoplug/client/ui/MainWindow.java b/src/main/java/com/osiris/autoplug/client/ui/MainWindow.java index b2d65b82..d096bceb 100644 --- a/src/main/java/com/osiris/autoplug/client/ui/MainWindow.java +++ b/src/main/java/com/osiris/autoplug/client/ui/MainWindow.java @@ -28,6 +28,9 @@ import java.io.InputStream; import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + public class MainWindow extends JFrame { /** * There should always be only one instance of {@link MainWindow}. @@ -61,18 +64,57 @@ public void initTheme() { initTheme(null); } + interface ThemeSetup { + boolean setup(); + } + + static class LightThemeSetup implements ThemeSetup { + @Override + public boolean setup() { + return FlatLightLaf.setup(); + } + } + + static class DarkThemeSetup implements ThemeSetup { + @Override + public boolean setup() { + return FlatDarkLaf.setup(); + } + } + + static class DarculaThemeSetup implements ThemeSetup { + @Override + public boolean setup() { + return FlatDarculaLaf.setup(); + } + } + + + private static final Map themeSetupMap = new HashMap<>(); + + static { + themeSetupMap.put("light", new LightThemeSetup()); + themeSetupMap.put("dark", new DarkThemeSetup()); + themeSetupMap.put("darcula", new DarculaThemeSetup()); + } + + private static ThemeSetup getThemeSetup(String theme) { + for (Map.Entry entry : themeSetupMap.entrySet()) { + if (entry.getKey().equalsIgnoreCase(theme)) { + return entry.getValue(); + } + } + + AL.warn("The selected theme '" + theme + "' is not a valid option! Using default."); + return new LightThemeSetup(); + } + public void initTheme(GeneralConfig generalConfig) { try { if (generalConfig == null) generalConfig = new GeneralConfig(); - if (generalConfig.autoplug_system_tray_theme.asString().equals("light")) { - if (!FlatLightLaf.setup()) throw new Exception("Returned false!"); - } else if (generalConfig.autoplug_system_tray_theme.asString().equals("dark")) { - if (!FlatDarkLaf.setup()) throw new Exception("Returned false!"); - } else if (generalConfig.autoplug_system_tray_theme.asString().equals("darcula")) { - if (!FlatDarculaLaf.setup()) throw new Exception("Returned false!"); - } else { - AL.warn("The selected theme '" + generalConfig.autoplug_system_tray_theme.asString() + "' is not a valid option! Using default."); - if (!FlatLightLaf.setup()) throw new Exception("Returned false!"); + ThemeSetup themeSetup = getThemeSetup(generalConfig.autoplug_system_tray_theme.asString()); + if (!themeSetup.setup()) { + throw new Exception("Returned false!"); } } catch (Exception e) { AL.warn("Failed to init GUI theme!", e);