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/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/console/Commands.java b/src/main/java/com/osiris/autoplug/client/console/Commands.java
index fdb23049..556b1aa2 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,19 @@
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.*;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.*;
+
+import com.osiris.dyml.exceptions.*;
+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 +46,8 @@
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.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 +362,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 +384,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 +447,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(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(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_update_check_name_for_mod_loader.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 +532,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..a7fc1831 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,13 +21,19 @@
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!
* 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;
@@ -50,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() + " [!] ");
@@ -67,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;
}
@@ -76,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;
@@ -90,7 +93,7 @@ public List serverWorldsFolders() {
public List serverFiles() {
String searchPattern = "*";
//Find the files
- findFilesInWorkingDir(searchPattern);
+ FileSearcher.findFilesInWorkingDir(searchPattern);
//Return the results
return queryFiles;
@@ -99,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();
}
/**
@@ -211,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;
@@ -302,200 +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 {
-
- //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())) {
- 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;
- }
-
-
- }
-
- @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/managers/SyncFilesManager.java b/src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java
index d1661991..e5b25d1e 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,26 +27,38 @@
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("\\"))
@@ -53,41 +66,49 @@ else if (value.contains("/") || value.contains("\\"))
// 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."); //TODO or ipv4/ipv6
}
+ return filesToSendTo;
+ }
- Consumer onFileChangeEvent = event -> {
+ 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(), "");
- 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/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);
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