Adds comments and refactors several classes
All checks were successful
KnarCraft/Minecraft-Server-Launcher/master This commit looks good

Adds comments to Collection
Makes some variable and function names more descriptive
Adds some new methods for showing messsages and errors
Adds a lot of missing comments
Enhances some existing comments
This commit is contained in:
2020-02-13 21:10:18 +01:00
parent c59cbcefbb
commit 040740db84
11 changed files with 489 additions and 383 deletions

View File

@ -18,15 +18,32 @@ public class Collection {
private final Console serverConsole;
private final String name;
/**
* Creates a new collection with the given name
* @param name <p>The name identifying the server, server tab, collection and server console</p>
*/
Collection(String name) {
this.serverTab = new ServerTab(name);
this.server = new Server(name);
this.serverConsole = ServerConsoles.addTab(name);
this.serverConsole = ServerConsoles.addConsoleTab(name);
this.name = name;
}
/**
* Creates a new collection with the given parameters
* @param name <p>The name identifying the server, server tab, collection and server console</p>
* @param serverPath <p>The path of the server folder</p>
* @param enabled <p>Whether the server should be run when starting servers</p>
* @param typeName <p>The name of the server type the server uses</p>
* @param serverVersion <p>The version of the running server type.</p>
* @param maxRam <p>The maximum amount of RAM the server is allowed to use.</p>
* @param vanillaVersion <p>The currently selected vanilla version</p>
* @param snapshotVersion <p>The currently selected snapshot version</p>
* @param spongeVanillaVersion <p>The currently selected SpongeVanilla version</p>
* @param bungeeVersion <p>The currently selected Bungee version</p>
*/
Collection(String name,
String path,
String serverPath,
boolean enabled,
String typeName,
String serverVersion,
@ -39,7 +56,7 @@ public class Collection {
this.serverTab = new ServerTab(name);
this.server = new Server(
name,
path,
serverPath,
enabled,
typeName,
serverVersion,
@ -49,23 +66,39 @@ public class Collection {
spongeVanillaVersion,
bungeeVersion
);
this.serverConsole = ServerConsoles.addTab(name);
this.serverConsole = ServerConsoles.addConsoleTab(name);
this.name = name;
this.serverTab.setData(path, enabled, typeName, serverVersion, maxRam);
this.serverTab.setData(serverPath, enabled, typeName, serverVersion, maxRam);
}
/**
* Gets the name of the collection
* @return <p>Collection name</p>
*/
public String getName() {
return this.name;
}
/**
* Gets the server of the collection
* @return <p>Collection server</p>
*/
public Server getServer() {
return this.server;
}
/**
* Gets the server tab of the collection
* @return <p>Collection server tab</p>
*/
public ServerTab getServerTab() {
return this.serverTab;
}
/**
* Gets the server console of the collection
* @return <p>Collection server console</p>
*/
public Console getServerConsole() {
return this.serverConsole;
}

View File

@ -36,15 +36,15 @@ public class Profile {
private static final ArrayList<Profile> profiles = new ArrayList<>();
private static Profile current;
private static GUI gui;
private static final String profilesDir = Main.getAppDir() + File.separator + "files";
private static final String profilesFile = Main.getAppDir() + File.separator + "files" + File.separator + "Profiles.txt";
private static final String jarDir = Main.getAppDir() + File.separator + "files" + File.separator + "Jars" + File.separator;
private static final String profilesDir = Main.getApplicationWorkDirectory() + File.separator + "files";
private static final String profilesFile = Main.getApplicationWorkDirectory() + File.separator + "files" + File.separator + "Profiles.txt";
private static final String jarDirectory = Main.getApplicationWorkDirectory() + File.separator + "files" + File.separator + "Jars" + File.separator;
private final ArrayList<Collection> collections;
private final String name;
private boolean runInBackground;
private int delayStartup;
private boolean downloadJars;
private boolean downloadAllAvailableJARFiles;
private static String vanillaVersion;
private static String snapshotVersion;
private static String bungeeVersion;
@ -54,19 +54,19 @@ public class Profile {
this.name = name;
this.runInBackground = false;
this.delayStartup = 0;
this.downloadJars = false;
this.downloadAllAvailableJARFiles = false;
profiles.add(this);
if (current == null) {
current = this;
}
}
private Profile(String name, boolean runInBackground, int delayStartup, boolean downloadJars) {
private Profile(String name, boolean runInBackground, int delayStartup, boolean downloadAllAvailableJARFiles) {
this.collections = new ArrayList<>();
this.name = name;
this.runInBackground = runInBackground;
this.delayStartup = delayStartup;
this.downloadJars = downloadJars;
this.downloadAllAvailableJARFiles = downloadAllAvailableJARFiles;
profiles.add(this);
if (current == null) {
current = this;
@ -85,8 +85,8 @@ public class Profile {
return this.delayStartup;
}
public boolean getDownloadJars() {
return this.downloadJars;
public boolean getDownloadAllAvailableJARFiles() {
return this.downloadAllAvailableJARFiles;
}
public static Profile getCurrent() {
@ -139,8 +139,8 @@ public class Profile {
}
}
public void setDownloadJars(boolean value) {
this.downloadJars = value;
public void setDownloadAllAvailableJARFiles(boolean value) {
this.downloadAllAvailableJARFiles = value;
}
/**
@ -175,13 +175,8 @@ public class Profile {
) {
collections.add(new Collection(name));
} else {
JOptionPane.showMessageDialog(
null,
"A server name must my unique and not empty or \"All\"." +
"It can't contain any of the characters \"!\", \"?\" or \";\".",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("A server name must my unique and not empty or \"All\"." +
"It can't contain any of the characters \"!\", \"?\" or \";\".");
}
}
@ -195,22 +190,12 @@ public class Profile {
return;
}
if (name.equals("") && !name.matches("^[!?;]+$")) {
JOptionPane.showMessageDialog(
null,
"Profile name can't be blank.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Profile name can't be blank.");
return;
}
for (Profile profile : profiles) {
if (profile.name.equals(name)) {
JOptionPane.showMessageDialog(
null,
"There is already a profile with this name.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("There is already a profile with this name.");
return;
}
}
@ -227,6 +212,10 @@ public class Profile {
}
}
/**
* Removes a profile with the given name from the list of profiles, if such a profile exists
* @param name <p>The name of the profile to rempve</p>
*/
public static void removeProfile(String name) {
if (profiles.size() > 1) {
profiles.removeIf(profile -> profile.name.equals(name));
@ -234,7 +223,7 @@ public class Profile {
}
public void updateConsoles() {
JTabbedPane consolesTab = ServerConsoles.getTab();
JTabbedPane consolesTab = ServerConsoles.getTabbedPane();
consolesTab.removeAll();
for (Collection collection : collections) {
consolesTab.add(collection.getName(), collection.getServerConsole().getPanel());
@ -253,12 +242,7 @@ public class Profile {
try {
collection.getServer().sendCommand(command);
} catch (IOException e) {
JOptionPane.showMessageDialog(
null,
"Server " + collection.getName() + " caused an exception.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Server " + collection.getName() + " caused an exception.");
}
}
} else {
@ -268,19 +252,10 @@ public class Profile {
try {
target.sendCommand(command);
} catch (IOException e) {
JOptionPane.showMessageDialog(
null,
"Server " + target.getName() + " caused an exception.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Server " + target.getName() + " caused an exception.");
}
} else {
JOptionPane.showMessageDialog(
null,
"Server " + serverName + " is invalid.",
"Error", JOptionPane.ERROR_MESSAGE
);
showError("Server " + serverName + " is invalid.");
}
}
}
@ -299,33 +274,32 @@ public class Profile {
try {
server.setServerVersion(serverTab.getVersion());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(
null,
"Invalid server version for " + server.getName(),
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Invalid server version for " + server.getName());
}
server.toggle(serverTab.enabled());
}
if (!new File(profilesDir).exists() && !new File(profilesDir).mkdirs()) {
JOptionPane.showMessageDialog(
null,
"Unable to create the folder " + profilesDir,
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Unable to create the folder " + profilesDir);
throw new FileNotFoundException("Unable to create the profiles folder: " + profilesDir);
}
try (PrintWriter file = new PrintWriter(profilesFile)) {
int width;
int height;
if (gui == null) {
width = 440;
height = 170;
} else {
width = gui.getSize().width;
height = gui.getSize().height;
}
file.println(String.format(
"%s;%s;%s;%s;%d;%d",
current.name,
vanillaVersion,
snapshotVersion,
bungeeVersion,
gui.getSize().width,
gui.getSize().height
width,
height
));
file.close();
for (Profile profile : profiles) {
@ -334,7 +308,7 @@ public class Profile {
profile.name,
profile.runInBackground,
profile.delayStartup,
profile.downloadJars)
profile.downloadAllAvailableJARFiles)
);
for (Collection collection : profile.collections) {
Server server = collection.getServer();
@ -361,26 +335,16 @@ public class Profile {
fileAppend.println(saveString);
} catch (IOException e) {
if (gui != null) {
JOptionPane.showMessageDialog(
null,
"Unable to save to file. Try running the software as an administrator.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Unable to save to file. Try running the software as an administrator.");
} else {
System.out.println("Unable to save to file. Try running the software as an administrator.");
}
throw new FileNotFoundException("Unable to save to the profiles file.");
}
}
} catch (IOException | NullPointerException e) {
} catch (IOException e) {
if (gui != null) {
JOptionPane.showMessageDialog(
null,
"Unable to save to file. Try running the software as an administrator.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Unable to save to file. Try running the software as an administrator.");
}
throw new FileNotFoundException("Unable to create the profiles file");
}
@ -424,12 +388,8 @@ public class Profile {
current = getProfile(profileName);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
"Invalid Profile.txt file. Profiles could not be loaded. If this error persists, please manually delete the file.",
"Error",
JOptionPane.ERROR_MESSAGE
);
showError("Invalid Profile.txt file. Profiles could not be loaded. If this error persists, please " +
"manually delete the file.");
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
@ -438,21 +398,11 @@ public class Profile {
addProfile("Default");
}
} catch (FileNotFoundException | NoSuchElementException e) {
JOptionPane.showMessageDialog(
null,
"A profiles file was not found. Default profile was created.",
"Info",
JOptionPane.INFORMATION_MESSAGE
);
showMessage("A profiles file was not found. Default profile was created.");
try {
gui = new GUI();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null,
"Failed to load GUI messages. The GUI can't be shown.",
"Info",
JOptionPane.INFORMATION_MESSAGE
);
showMessage("Failed to load GUI messages. The GUI can't be shown.");
} catch (IOException ex) {
ex.printStackTrace();
}
@ -461,7 +411,7 @@ public class Profile {
gui.update();
gui.updateProfiles();
current.updateConsoles();
if (current.downloadJars) {
if (current.downloadAllAvailableJARFiles) {
Executors.newSingleThreadExecutor().execute(() -> {
try {
downloadJars();
@ -478,9 +428,8 @@ public class Profile {
/**
* Parses a profile, and creates a profile with the data.
*
* @param profileData The data of the new profile
* @return The new profile
* @param profileData <p>The data of the new profile</p>
* @return <p>The new profile</p>
*/
private static Profile parseProfile(String[] profileData) {
return new Profile(
@ -493,9 +442,8 @@ public class Profile {
/**
* Parses a server, and creates a new collection.
*
* @param profile The profile which to add the collection
* @param serverData The data to parse
* @param profile <p>The profile which to add the collection</p>
* @param serverData <p>The data to parse</p>
*/
private static void parseServer(Profile profile, String[] serverData) {
profile.collections.add(new Collection(
@ -518,13 +466,9 @@ public class Profile {
* @throws IOException On version file failure or folder creation failure
*/
public static void downloadJars() throws IOException {
if (!new File(jarDir).exists() && !new File(jarDir).mkdirs()) {
JOptionPane.showMessageDialog(
null,
"Could not create the Jars folder. Please run the program with admin permissions, or move it to a writable directory.",
"Error",
JOptionPane.ERROR_MESSAGE
);
if (!new File(jarDirectory).exists() && !new File(jarDirectory).mkdirs()) {
showError("Could not create the Jars folder. Please run the program with admin permissions, or move it to " +
"a writable directory.");
throw new FileNotFoundException("Unable to create jars folder");
}
try {
@ -538,81 +482,195 @@ public class Profile {
/**
* Prints something to the gui status field if the gui exists
* Otherwise it prints to the console
*
* @param str The string to show the user
* @param message <p>The string to show the user</p>
*/
private static void printToGui(String str) {
private static void printToGui(String message) {
if (gui != null) {
gui.setStatus(str);
gui.setStatus(message);
} else {
System.out.println(str);
System.out.println(message);
}
}
public static void showError(String title, String message) {
if (gui != null) {
JOptionPane.showMessageDialog(
null,
message,
title,
JOptionPane.ERROR_MESSAGE
);
} else {
System.out.println(message);
}
}
public static void showError(String message) {
if (gui != null) {
JOptionPane.showMessageDialog(
null,
message,
"Error",
JOptionPane.ERROR_MESSAGE
);
} else {
System.out.println(message);
}
}
public static void showMessage(String title, String message) {
if (gui != null) {
JOptionPane.showMessageDialog(
null,
message,
title,
JOptionPane.INFORMATION_MESSAGE
);
} else {
System.out.println(message);
}
}
public static void showMessage(String message) {
if (gui != null) {
JOptionPane.showMessageDialog(
null,
message,
"Info",
JOptionPane.INFORMATION_MESSAGE
);
} else {
System.out.println(message);
}
}
private static void showMessage() {}
/**
* Downloads jar files for all possible server versions.
*
* @throws IOException If a jar fails to download.
* Downloads jar files for all possible server versions
* @throws IOException <p>If a jar fails to download</p>
*/
private static void downloadAll() throws IOException {
for (ServerType type : ServerType.getServerTypes()) {
String url = Objects.requireNonNull(type).getDownloadURL(), name = type.getName(), newestVersion;
AdvancedServerType advType = type instanceof AdvancedServerType ? (AdvancedServerType) type : null;
String downloadURL = Objects.requireNonNull(type).getDownloadURL();
String typeName = type.getName();
AdvancedServerType advancedServerType = type instanceof AdvancedServerType ? (AdvancedServerType) type : null;
for (String version : type.getVersions()) {
boolean success;
printToGui("Downloading: " + name + version + ".jar");
File file = new File(jarDir + type.getName() + version + ".jar");
Path filePath = Paths.get(jarDir + type.getName() + version + ".jar");
printToGui("Downloading: " + typeName + version + ".jar");
File file = new File(jarDirectory + type.getName() + version + ".jar");
Path filePath = Paths.get(jarDirectory + type.getName() + version + ".jar");
switch (type.getName()) {
case "Vanilla":
case "Snapshot":
if (version.equals("Latest")) {
String versionText = readFile(Objects.requireNonNull(advType).getVersionURL());
JsonObject jsonObject = new JsonParser().parse(versionText).getAsJsonObject();
String latest = jsonObject.getAsJsonObject("latest").get("release").getAsString();
JsonElement ver = jsonObject.getAsJsonArray("versions").get(0);
String versionFile = ver.getAsJsonObject().get("url").getAsString();
versionText = readFile(versionFile);
jsonObject = new JsonParser().parse(versionText).getAsJsonObject();
String jarFile = jsonObject.getAsJsonObject("downloads").getAsJsonObject("server").get("url").getAsString();
setVersion(name, latest);
success = (file.isFile() && latest.equals(getVersion(name))) || downloadFile(jarFile, filePath);
} else {
success = file.isFile() || downloadFile(url + version + Objects.requireNonNull(advType).getDownloadURLPart() + version + ".jar", filePath);
}
success = downloadVanillaJar(advancedServerType, file, downloadURL, filePath, typeName, version);
break;
case "Spigot":
case "Craftbukkit":
case "MCPCplus":
success = file.isFile() || downloadFile(url + name + version + ".jar", filePath);
success = downloadSpigotJar(file, downloadURL, typeName, version, filePath);
break;
case "SpongeVanilla":
newestVersion = stringBetween(readFile(Objects.requireNonNull(advType).getVersionURL() + version), advType.getSrcStart(), advType.getSrcEnd());
success = file.isFile() || downloadFile(url + newestVersion + advType.getDownloadURLPart() + newestVersion + ".jar", filePath);
success = downloadSpongeVanillaJar(advancedServerType, file, downloadURL, filePath, version);
break;
case "Bungee":
newestVersion = stringBetween(readFile(Objects.requireNonNull(advType).getVersionURL()), advType.getSrcStart(), advType.getSrcEnd());
setVersion(name, newestVersion);
success = (file.isFile() && newestVersion.equals(getVersion(name))) || downloadFile(url, filePath);
success = downloadBungeeJar(advancedServerType, file, downloadURL, filePath, typeName);
break;
default:
success = true;
}
if (!success) {
printToGui("Error downloading: " + name + version + ".jar");
throw new FileNotFoundException("Error downloading: " + name + version + ".jar");
printToGui("Error downloading: " + typeName + version + ".jar");
throw new FileNotFoundException("Error downloading: " + typeName + version + ".jar");
}
}
}
}
/**
* Downloads a Spigot, Craftbukkit or MCPC+ .jar file
* @param file <p>The file the .jar file should be saved as</p>
* @param downloadURL <p>The base URL for downloading the .jar file</p>
* @param typeName <p>The name of the selected server type</p>
* @param version <p>The version of the .jar file to download</p>
* @param filePath <p>The path of the .jar file</p>
* @return <p>True if the file exists or the file was successfully downloaded</p>
*/
private static boolean downloadSpigotJar(File file, String downloadURL, String typeName, String version, Path filePath) {
return file.isFile() || downloadFile(downloadURL + typeName + version + ".jar", filePath);
}
/**
* Downloads a Vanilla/Snapshot .jar file according to the input
* @param advancedServerType <p>The advanced server type containing required information</p>
* @param file <p>The file the .jar file should be saved as</p>
* @param downloadURL <p>The base URL for downloading the .jar file</p>
* @param filePath <p>The path of the .jar file</p>
* @param typeName <p>The name of the selected server type</p>
* @param version <p>The version of the .jar file to download</p>
* @return <p>True if the file exists or the file was successfully downloaded</p>
* @throws IOException <p>If something goes horribly wrong</p>
*/
private static boolean downloadVanillaJar(AdvancedServerType advancedServerType, File file, String downloadURL,
Path filePath, String typeName, String version) throws IOException {
if (version.equals("Latest")) {
String versionText = readFile(Objects.requireNonNull(advancedServerType).getVersionURL());
JsonObject jsonObject = new JsonParser().parse(versionText).getAsJsonObject();
String latest = jsonObject.getAsJsonObject("latest").get("release").getAsString();
JsonElement ver = jsonObject.getAsJsonArray("versions").get(0);
String versionFile = ver.getAsJsonObject().get("url").getAsString();
versionText = readFile(versionFile);
jsonObject = new JsonParser().parse(versionText).getAsJsonObject();
String jarFile = jsonObject.getAsJsonObject("downloads").getAsJsonObject("server").get("url").getAsString();
setVersion(typeName, latest);
return (file.isFile() && latest.equals(getVersion(typeName))) || downloadFile(jarFile, filePath);
} else {
return file.isFile() || downloadFile(downloadURL + version +
Objects.requireNonNull(advancedServerType).getDownloadURLPart() + version + ".jar", filePath);
}
}
/**
* Downloads a SpongeVanilla .jar file according to the input
* @param advancedServerType <p>The advanced server type containing required information</p>
* @param file <p>The file the .jar file should be saved as</p>
* @param downloadURL <p>The base URL for downloading the .jar file</p>
* @param filePath <p>The path of the .jar file</p>
* @param version <p>The version of the .jar file to download</p>
* @return <p>True if the file exists or the file was successfully downloaded</p>
* @throws IOException <p>If something goes horribly wrong</p>
*/
private static boolean downloadSpongeVanillaJar(AdvancedServerType advancedServerType, File file,
String downloadURL, Path filePath,
String version) throws IOException {
String newestVersion = stringBetween(readFile(Objects.requireNonNull(advancedServerType).getVersionURL()
+ version), advancedServerType.getSrcStart(), advancedServerType.getSrcEnd());
return file.isFile() || downloadFile(downloadURL + newestVersion + advancedServerType.getDownloadURLPart()
+ newestVersion + ".jar", filePath);
}
/**
* Downloads a Bungee .jar file according to the input
* @param advancedServerType <p>The advanced server type containing required information</p>
* @param file <p>The file the .jar file should be saved as</p>
* @param downloadURL <p>The base URL for downloading the .jar file</p>
* @param filePath <p>The path of the .jar file</p>
* @param typeName <p>The name of the selected server type</p>
* @return <p>True if the file exists or the file was successfully downloaded</p>
* @throws IOException <p>If something goes horribly wrong</p>
*/
private static boolean downloadBungeeJar(AdvancedServerType advancedServerType, File file,
String downloadURL, Path filePath, String typeName) throws IOException {
String newestVersion = stringBetween(readFile(Objects.requireNonNull(advancedServerType).getVersionURL()),
advancedServerType.getSrcStart(), advancedServerType.getSrcEnd());
setVersion(typeName, newestVersion);
return (file.isFile() && newestVersion.equals(getVersion(typeName))) || downloadFile(downloadURL, filePath);
}
/**
* Returns the current version of a type
*
* @param type The version type
* @return The version string
* @param type <p>The version type</p>
* @return <p>The version string</p>
*/
private static String getVersion(String type) {
switch (type) {
@ -628,10 +686,9 @@ public class Profile {
}
/**
* Sets a server type's last downloaded version.
*
* @param type The version type
* @param version The version string
* Sets a server type's last downloaded version
* @param type <p>The version type</p>
* @param version <p>The version string</p>
*/
private static void setVersion(String type, String version) {
if (!type.equals("")) {