Make the port argument optional

Not sure what port to use? Now SubServers can decide on a port number on it's own.
This commit is contained in:
ME1312 2018-10-08 17:07:44 -04:00
parent 3911b6e867
commit ba2a69a568
No known key found for this signature in database
GPG Key ID: FEFFE2F698E88FA8
24 changed files with 653 additions and 562 deletions

View File

@ -33,6 +33,7 @@ public class ExternalHost extends Host implements ClientHandler {
private InetAddress address;
private SubCreator creator;
private String directory;
protected NamedContainer<Integer, Integer> range;
protected NamedContainer<Boolean, Client> client;
private LinkedList<PacketOut> queue;
private boolean clean;
@ -48,8 +49,8 @@ public class ExternalHost extends Host implements ClientHandler {
* @param directory Directory
* @param gitBash Git Bash Location
*/
public ExternalHost(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, String gitBash) {
super(plugin, name, enabled, address, directory, gitBash);
public ExternalHost(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) {
super(plugin, name, enabled, address, directory, range, gitBash);
if (Util.isNull(plugin, name, enabled, address, directory, gitBash)) throw new NullPointerException();
this.plugin = plugin;
this.name = name;
@ -58,6 +59,7 @@ public class ExternalHost extends Host implements ClientHandler {
this.client = new NamedContainer<Boolean, Client>(false, null);
this.creator = new ExternalSubCreator(this, gitBash);
this.directory = directory;
this.range = range;
this.queue = new LinkedList<PacketOut>();
this.clean = false;
}

View File

@ -2,6 +2,7 @@ package net.ME1312.SubServers.Bungee.Host.External;
import net.ME1312.SubServers.Bungee.Event.SubCreateEvent;
import net.ME1312.SubServers.Bungee.Host.*;
import net.ME1312.SubServers.Bungee.Host.Internal.InternalSubCreator;
import net.ME1312.SubServers.Bungee.Library.*;
import net.ME1312.SubServers.Bungee.Library.Config.YAMLConfig;
import net.ME1312.SubServers.Bungee.Library.Config.YAMLSection;
@ -12,6 +13,7 @@ import net.ME1312.SubServers.Bungee.SubAPI;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.util.*;
/**
@ -22,7 +24,7 @@ public class ExternalSubCreator extends SubCreator {
private HashMap<String, ServerTemplate> templates = new HashMap<String, ServerTemplate>();
private ExternalHost host;
private String gitBash;
private TreeMap<String, ExternalSubLogger> thread;
private TreeMap<String, NamedContainer<Integer, ExternalSubLogger>> thread;
/**
* Creates an External SubCreator
@ -34,7 +36,7 @@ public class ExternalSubCreator extends SubCreator {
if (Util.isNull(host, gitBash)) throw new NullPointerException();
this.host = host;
this.gitBash = gitBash;
this.thread = new TreeMap<String, ExternalSubLogger>();
this.thread = new TreeMap<String, NamedContainer<Integer, ExternalSubLogger>>();
reload();
}
@ -58,12 +60,23 @@ public class ExternalSubCreator extends SubCreator {
}
@Override
public boolean create(UUID player, String name, ServerTemplate template, Version version, int port, Callback<SubServer> callback) {
if (Util.isNull(name, template, version, port)) throw new NullPointerException();
public boolean create(UUID player, String name, ServerTemplate template, Version version, Integer port, Callback<SubServer> callback) {
if (Util.isNull(name, template, version)) throw new NullPointerException();
if (host.isAvailable() && host.isEnabled() && template.isEnabled() && !SubAPI.getInstance().getSubServers().keySet().contains(name.toLowerCase()) && !SubCreator.isReserved(name)) {
StackTraceElement[] origin = new Exception().getStackTrace();
if (port == null) {
Container<Integer> i = new Container<Integer>(host.range.name() - 1);
port = Util.getNew(getAllReservedAddresses(), () -> {
i.set(i.get() + 1);
if (i.get() > host.range.get()) throw new IllegalStateException("There are no more ports available between " + host.range.name() + " and " + host.range.get());
return new InetSocketAddress(host.getAddress(), i.get());
}).getPort();
}
ExternalSubLogger logger = new ExternalSubLogger(this, name + File.separator + "Creator", new Container<Boolean>(host.plugin.config.get().getSection("Settings").getBoolean("Log-Creator")), null);
thread.put(name.toLowerCase(), logger);
thread.put(name.toLowerCase(), new NamedContainer<>(port, logger));
final int fport = port;
final SubCreateEvent event = new SubCreateEvent(player, host, name, template, version, port);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
@ -77,13 +90,13 @@ public class ExternalSubCreator extends SubCreator {
YAMLSection server = new YAMLSection();
YAMLSection config = new YAMLSection((Map<String, ?>) convert(data.getSection("c").get(), new NamedContainer<>("$player$", (player == null)?"":player.toString()), new NamedContainer<>("$name$", name),
new NamedContainer<>("$template$", template.getName()), new NamedContainer<>("$type$", template.getType().toString()), new NamedContainer<>("$version$", version.toString().replace(" ", "@")), new NamedContainer<>("$port$", Integer.toString(port))));
new NamedContainer<>("$template$", template.getName()), new NamedContainer<>("$type$", template.getType().toString()), new NamedContainer<>("$version$", version.toString().replace(" ", "@")), new NamedContainer<>("$port$", Integer.toString(fport))));
server.set("Enabled", true);
server.set("Display", "");
server.set("Host", host.getName());
server.set("Group", new ArrayList<String>());
server.set("Port", port);
server.set("Port", fport);
server.set("Motd", "Some SubServer");
server.set("Log", true);
server.set("Directory", "." + File.separatorChar + name);
@ -96,7 +109,7 @@ public class ExternalSubCreator extends SubCreator {
server.set("Hidden", false);
server.setAll(config);
SubServer subserver = host.addSubServer(player, name, server.getBoolean("Enabled"), port, server.getColoredString("Motd", '&'), server.getBoolean("Log"), server.getRawString("Directory"),
SubServer subserver = host.addSubServer(player, name, server.getBoolean("Enabled"), fport, server.getColoredString("Motd", '&'), server.getBoolean("Log"), server.getRawString("Directory"),
new Executable(server.getRawString("Executable")), server.getRawString("Stop-Command"), server.getBoolean("Hidden"), server.getBoolean("Restricted"));
if (server.getString("Display").length() > 0) subserver.setDisplayName(server.getString("Display"));
for (String group : server.getStringList("Group")) subserver.addGroup(group);
@ -157,7 +170,7 @@ public class ExternalSubCreator extends SubCreator {
@Override
public void terminate() {
HashMap<String, ExternalSubLogger> thread = new HashMap<String, ExternalSubLogger>();
HashMap<String, NamedContainer<Integer, ExternalSubLogger>> thread = new HashMap<String, NamedContainer<Integer, ExternalSubLogger>>();
thread.putAll(this.thread);
for (String i : thread.keySet()) {
terminate(i);
@ -174,7 +187,7 @@ public class ExternalSubCreator extends SubCreator {
@Override
public void waitFor() throws InterruptedException {
HashMap<String, ExternalSubLogger> thread = new HashMap<String, ExternalSubLogger>();
HashMap<String, NamedContainer<Integer, ExternalSubLogger>> thread = new HashMap<String, NamedContainer<Integer, ExternalSubLogger>>();
thread.putAll(this.thread);
for (String i : thread.keySet()) {
waitFor(i);
@ -199,13 +212,19 @@ public class ExternalSubCreator extends SubCreator {
}
@Override
public List<SubLogger> getLogger() {
return new LinkedList<SubLogger>(thread.values());
public List<SubLogger> getLoggers() {
List<SubLogger> loggers = new ArrayList<SubLogger>();
HashMap<String, NamedContainer<Integer, ExternalSubLogger>> temp = new HashMap<String, NamedContainer<Integer, ExternalSubLogger>>();
temp.putAll(thread);
for (String i : temp.keySet()) {
loggers.add(getLogger(i));
}
return loggers;
}
@Override
public SubLogger getLogger(String name) {
return this.thread.get(name.toLowerCase());
return this.thread.get(name.toLowerCase()).get();
}
@Override
@ -213,6 +232,13 @@ public class ExternalSubCreator extends SubCreator {
return new ArrayList<String>(thread.keySet());
}
@Override
public List<Integer> getReservedPorts() {
List<Integer> ports = new ArrayList<Integer>();
for (NamedContainer<Integer, ExternalSubLogger> task : thread.values()) ports.add(task.name());
return ports;
}
@Override
public Map<String, ServerTemplate> getTemplates() {
return new TreeMap<String, ServerTemplate>(templates);

View File

@ -6,6 +6,7 @@ import net.ME1312.SubServers.Bungee.Library.Config.YAMLValue;
import net.ME1312.SubServers.Bungee.Library.Exception.InvalidHostException;
import net.ME1312.SubServers.Bungee.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Bungee.Library.ExtraDataHandler;
import net.ME1312.SubServers.Bungee.Library.NamedContainer;
import net.ME1312.SubServers.Bungee.Library.Util;
import net.ME1312.SubServers.Bungee.Network.ClientHandler;
import net.ME1312.SubServers.Bungee.Network.SubDataServer;
@ -31,9 +32,10 @@ public abstract class Host implements ExtraDataHandler {
* @param enabled If your host is Enabled
* @param address The address of your Host
* @param directory The runtime directory of your Host
* @param range The range of ports to auto-select from
* @param gitBash The Git Bash directory
*/
public Host(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, String gitBash) {
public Host(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) {
if (name.contains(" ")) throw new InvalidHostException("Host names cannot have spaces: " + name);
signature = plugin.api.signAnonymousObject();
SubDataServer.allowConnection(address.getHostAddress());

View File

@ -9,6 +9,7 @@ import net.ME1312.SubServers.Bungee.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Bungee.Host.Host;
import net.ME1312.SubServers.Bungee.Host.SubCreator;
import net.ME1312.SubServers.Bungee.Host.SubServer;
import net.ME1312.SubServers.Bungee.Library.NamedContainer;
import net.ME1312.SubServers.Bungee.Library.UniversalFile;
import net.ME1312.SubServers.Bungee.Library.Util;
import net.ME1312.SubServers.Bungee.SubPlugin;
@ -29,6 +30,7 @@ public class InternalHost extends Host {
private InetAddress address;
private SubCreator creator;
private String directory;
protected NamedContainer<Integer, Integer> range;
protected SubPlugin plugin;
/**
@ -41,8 +43,8 @@ public class InternalHost extends Host {
* @param directory Directory
* @param gitBash Git Bash Location
*/
public InternalHost(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, String gitBash) {
super(plugin, name, enabled, address, directory, gitBash);
public InternalHost(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) {
super(plugin, name, enabled, address, directory, range, gitBash);
if (!DRM_ALLOW) throw new IllegalStateException("SubServers' hosting capabilities have been disabled by your provider");
if (Util.isNull(plugin, name, enabled, address, directory, gitBash)) throw new NullPointerException();
this.plugin = plugin;
@ -51,6 +53,7 @@ public class InternalHost extends Host {
this.address = address;
this.creator = new InternalSubCreator(this, gitBash);
this.directory = directory;
this.range = range;
}
@Override

View File

@ -18,6 +18,7 @@ import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
@ -31,50 +32,38 @@ public class InternalSubCreator extends SubCreator {
private HashMap<String, ServerTemplate> templates = new HashMap<String, ServerTemplate>();
private InternalHost host;
private String gitBash;
private TreeMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>> thread;
private TreeMap<String, CreatorTask> thread;
/**
* Creates an Internal SubCreator
*
* @param host Host
* @param gitBash Git Bash
*/
public InternalSubCreator(InternalHost host, String gitBash) {
if (Util.isNull(host, gitBash)) throw new NullPointerException();
this.host = host;
this.gitBash = (System.getenv("ProgramFiles(x86)") == null) ? Pattern.compile("%(ProgramFiles)\\(x86\\)%", Pattern.CASE_INSENSITIVE).matcher(gitBash).replaceAll("%$1%") : gitBash;
this.thread = new TreeMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>>();
reload();
private class CreatorTask extends Thread {
private final UUID player;
private final String name;
private final ServerTemplate template;
private final Version version;
private final int port;
private final InternalSubLogger log;
private final Callback<SubServer> callback;
private Process process;
private CreatorTask(UUID player, String name, ServerTemplate template, Version version, int port, Callback<SubServer> callback) {
this.player = player;
this.name = name;
this.template = template;
this.version = version;
this.port = port;
this.log = new InternalSubLogger(null, this, name + File.separator + "Creator", new Container<Boolean>(false), null);
this.callback = callback;
}
@Override
public void reload() {
templates.clear();
if (new UniversalFile(host.plugin.dir, "SubServers:Templates").exists())
for (File file : new UniversalFile(host.plugin.dir, "SubServers:Templates").listFiles()) {
try {
if (file.isDirectory()) {
YAMLSection config = (new UniversalFile(file, "template.yml").exists()) ? new YAMLConfig(new UniversalFile(file, "template.yml")).get().getSection("Template", new YAMLSection()) : new YAMLSection();
ServerTemplate template = new ServerTemplate(file.getName(), config.getBoolean("Enabled", true), config.getRawString("Icon", "::NULL::"), file, config.getSection("Build", new YAMLSection()), config.getSection("Settings", new YAMLSection()));
templates.put(file.getName().toLowerCase(), template);
if (config.getKeys().contains("Display")) template.setDisplayName(config.getString("Display"));
}
} catch (Exception e) {
System.out.println(host.getName() + File.separator + "Creator > Couldn't load template: " + file.getName());
e.printStackTrace();
}
}
}
private YAMLSection build(NamedContainer<InternalSubLogger, Process> thread, File dir, String name, ServerTemplate template, Version version, List<ServerTemplate> history) throws SubCreatorException {
private YAMLSection build(File dir, ServerTemplate template, List<ServerTemplate> history) throws SubCreatorException {
YAMLSection server = new YAMLSection();
Version version = this.version;
boolean error = false;
if (history.contains(template)) throw new IllegalStateException("Template Import loop detected");
history.add(template);
for (String other : template.getBuildOptions().getStringList("Import", new ArrayList<String>())) {
if (templates.keySet().contains(other.toLowerCase())) {
if (templates.get(other.toLowerCase()).isEnabled()) {
YAMLSection config = build(thread, dir, other, templates.get(other.toLowerCase()), version, history);
YAMLSection config = build(dir, templates.get(other.toLowerCase()), history);
if (config == null) {
throw new SubCreatorException();
} else {
@ -134,7 +123,7 @@ public class InternalSubCreator extends SubCreator {
}
if (template.getBuildOptions().contains("Shell-Location")) {
String gitBash = this.gitBash + ((this.gitBash.endsWith(File.separator)) ? "" : File.separator) + "bin" + File.separatorChar + "bash.exe";
String gitBash = InternalSubCreator.this.gitBash + ((InternalSubCreator.this.gitBash.endsWith(File.separator)) ? "" : File.separator) + "bin" + File.separatorChar + "bash.exe";
File cache;
if (template.getBuildOptions().getBoolean("Use-Cache", true)) {
cache = new UniversalFile(host.plugin.dir, "SubServers:Cache:Templates:" + template.getName());
@ -157,16 +146,16 @@ public class InternalSubCreator extends SubCreator {
try {
System.out.println(name + File.separator + "Creator > Launching " + template.getBuildOptions().getRawString("Shell-Location"));
thread.set(Runtime.getRuntime().exec((System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)?"cmd.exe /c \"\"" + gitBash + "\" --login -i -c \"bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace('\\', '/').replace(" ", "\\ ")) + "\"\"":("bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace(" ", "\\ "))), null, dir));
thread.name().log.set(host.plugin.config.get().getSection("Settings").getBoolean("Log-Creator"));
thread.name().file = new File(dir, "SubCreator-" + template.getName() + "-" + version.toString().replace(" ", "@") + ".log");
thread.name().process = thread.get();
thread.name().start();
process = Runtime.getRuntime().exec((System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)?"cmd.exe /c \"\"" + gitBash + "\" --login -i -c \"bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace('\\', '/').replace(" ", "\\ ")) + "\"\"":("bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace(" ", "\\ "))), null, dir);
log.log.set(host.plugin.config.get().getSection("Settings").getBoolean("Log-Creator"));
log.file = new File(dir, "SubCreator-" + template.getName() + "-" + version.toString().replace(" ", "@") + ".log");
log.process = process;
log.start();
thread.get().waitFor();
process.waitFor();
Thread.sleep(500);
if (thread.get().exitValue() != 0) error = true;
if (process.exitValue() != 0) error = true;
} catch (InterruptedException e) {
error = true;
} catch (Exception e) {
@ -188,14 +177,13 @@ public class InternalSubCreator extends SubCreator {
return server;
}
private SubServer run(UUID player, String name, ServerTemplate template, Version version, int port) {
NamedContainer<InternalSubLogger, Process> thread = this.thread.get(name.toLowerCase()).get();
public void run() {
UniversalFile dir = new UniversalFile(new File(host.getPath()), name);
dir.mkdirs();
YAMLSection server = new YAMLSection();
YAMLSection config;
try {
config = build(thread, dir, name, template, version, new LinkedList<>());
config = build(dir, template, new LinkedList<>());
generateProperties(dir, port);
generateClient(dir, template.getType(), name);
} catch (SubCreatorException e) {
@ -244,16 +232,15 @@ public class InternalSubCreator extends SubCreator {
if (template.getBuildOptions().getBoolean("Run-On-Finish", true))
subserver.start();
this.thread.remove(name.toLowerCase());
return subserver;
InternalSubCreator.this.thread.remove(name.toLowerCase());
callback.run(subserver);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println(name + File.separator + "Creator > Couldn't build the server jar. Check the SubCreator logs for more detail.");
}
this.thread.remove(name.toLowerCase());
return null;
InternalSubCreator.this.thread.remove(name.toLowerCase());
} private Object convert(Object value, NamedContainer<String, String>... replacements) {
if (value instanceof Map) {
List<String> list = new ArrayList<String>();
@ -277,21 +264,61 @@ public class InternalSubCreator extends SubCreator {
for (NamedContainer<String, String> replacement : replacements) string = string.replace(replacement.name(), replacement.get());
return string;
}
}
/**
* Creates an Internal SubCreator
*
* @param host Host
* @param gitBash Git Bash
*/
public InternalSubCreator(InternalHost host, String gitBash) {
if (Util.isNull(host, gitBash)) throw new NullPointerException();
this.host = host;
this.gitBash = (System.getenv("ProgramFiles(x86)") == null)?Pattern.compile("%(ProgramFiles)\\(x86\\)%", Pattern.CASE_INSENSITIVE).matcher(gitBash).replaceAll("%$1%"):gitBash;
this.thread = new TreeMap<String, CreatorTask>();
reload();
}
@Override
public boolean create(UUID player, String name, ServerTemplate template, Version version, int port, Callback<SubServer> callback) {
if (Util.isNull(name, template, version, port)) throw new NullPointerException();
public void reload() {
templates.clear();
if (new UniversalFile(host.plugin.dir, "SubServers:Templates").exists())
for (File file : new UniversalFile(host.plugin.dir, "SubServers:Templates").listFiles()) {
try {
if (file.isDirectory()) {
YAMLSection config = (new UniversalFile(file, "template.yml").exists()) ? new YAMLConfig(new UniversalFile(file, "template.yml")).get().getSection("Template", new YAMLSection()) : new YAMLSection();
ServerTemplate template = new ServerTemplate(file.getName(), config.getBoolean("Enabled", true), config.getRawString("Icon", "::NULL::"), file, config.getSection("Build", new YAMLSection()), config.getSection("Settings", new YAMLSection()));
templates.put(file.getName().toLowerCase(), template);
if (config.getKeys().contains("Display")) template.setDisplayName(config.getString("Display"));
}
} catch (Exception e) {
System.out.println(host.getName() + File.separator + "Creator > Couldn't load template: " + file.getName());
e.printStackTrace();
}
}
}
@SuppressWarnings("deprecation")
@Override
public boolean create(UUID player, String name, ServerTemplate template, Version version, Integer port, Callback<SubServer> callback) {
if (Util.isNull(name, template, version)) throw new NullPointerException();
if (host.isAvailable() && host.isEnabled() && template.isEnabled() && !SubAPI.getInstance().getSubServers().keySet().contains(name.toLowerCase()) && !SubCreator.isReserved(name)) {
StackTraceElement[] origin = new Exception().getStackTrace();
NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>> thread = new NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>(null, new NamedContainer<InternalSubLogger, Process>(new InternalSubLogger(null, this, name + File.separator + "Creator", new Container<Boolean>(false), null), null));
this.thread.put(name.toLowerCase(), thread);
if (port == null) {
Container<Integer> i = new Container<Integer>(host.range.name() - 1);
port = Util.getNew(getAllReservedAddresses(), () -> {
i.set(i.get() + 1);
if (i.get() > host.range.get()) throw new IllegalStateException("There are no more ports available between " + host.range.name() + " and " + host.range.get());
return new InetSocketAddress(host.getAddress(), i.get());
}).getPort();
}
final SubCreateEvent event = new SubCreateEvent(player, host, name, template, version, port);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
thread.rename(new Thread(() -> {
SubServer server = InternalSubCreator.this.run(player, name, event.getTemplate(), event.getVersion(), port);
CreatorTask task = new CreatorTask(player, name, template, version, port, server -> {
if (callback != null && server != null) try {
callback.run(server);
} catch (Throwable e) {
@ -299,8 +326,9 @@ public class InternalSubCreator extends SubCreator {
ew.setStackTrace(origin);
ew.printStackTrace();
}
}));
thread.name().start();
});
this.thread.put(name.toLowerCase(), task);
task.start();
return true;
} else {
this.thread.remove(name.toLowerCase());
@ -311,7 +339,7 @@ public class InternalSubCreator extends SubCreator {
@Override
public void terminate() {
HashMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>> temp = new HashMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>>();
HashMap<String, CreatorTask> temp = new HashMap<String, CreatorTask>();
temp.putAll(thread);
for (String i : temp.keySet()) {
terminate(i);
@ -320,17 +348,19 @@ public class InternalSubCreator extends SubCreator {
@Override
public void terminate(String name) {
if (this.thread.get(name.toLowerCase()).get().get() != null && this.thread.get(name.toLowerCase()).get().get().isAlive()) {
this.thread.get(name.toLowerCase()).get().get().destroyForcibly();
} else if (this.thread.get(name.toLowerCase()).name() != null && this.thread.get(name.toLowerCase()).name().isAlive()) {
this.thread.get(name.toLowerCase()).name().interrupt();
if (this.thread.keySet().contains(name.toLowerCase())) {
if (this.thread.get(name.toLowerCase()).process != null && this.thread.get(name.toLowerCase()).process.isAlive()) {
this.thread.get(name.toLowerCase()).process.destroyForcibly();
} else if (this.thread.get(name.toLowerCase()).isAlive()) {
this.thread.get(name.toLowerCase()).interrupt();
this.thread.remove(name.toLowerCase());
}
}
}
@Override
public void waitFor() throws InterruptedException {
HashMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>> temp = new HashMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>>();
HashMap<String, CreatorTask> temp = new HashMap<String, CreatorTask>();
temp.putAll(thread);
for (String i : temp.keySet()) {
waitFor(i);
@ -339,7 +369,7 @@ public class InternalSubCreator extends SubCreator {
@Override
public void waitFor(String name) throws InterruptedException {
while (this.thread.keySet().contains(name.toLowerCase()) && this.thread.get(name.toLowerCase()).name() != null && this.thread.get(name.toLowerCase()).name().isAlive()) {
while (this.thread.keySet().contains(name.toLowerCase()) && this.thread.get(name.toLowerCase()).isAlive()) {
Thread.sleep(250);
}
}
@ -355,9 +385,9 @@ public class InternalSubCreator extends SubCreator {
}
@Override
public List<SubLogger> getLogger() {
public List<SubLogger> getLoggers() {
List<SubLogger> loggers = new ArrayList<SubLogger>();
HashMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>> temp = new HashMap<String, NamedContainer<Thread, NamedContainer<InternalSubLogger, Process>>>();
HashMap<String, CreatorTask> temp = new HashMap<String, CreatorTask>();
temp.putAll(thread);
for (String i : temp.keySet()) {
loggers.add(getLogger(i));
@ -367,7 +397,7 @@ public class InternalSubCreator extends SubCreator {
@Override
public SubLogger getLogger(String name) {
return this.thread.get(name.toLowerCase()).get().name();
return this.thread.get(name.toLowerCase()).log;
}
@Override
@ -375,6 +405,13 @@ public class InternalSubCreator extends SubCreator {
return new ArrayList<String>(thread.keySet());
}
@Override
public List<Integer> getReservedPorts() {
List<Integer> ports = new ArrayList<Integer>();
for (CreatorTask task : thread.values()) ports.add(task.port);
return ports;
}
@Override
public Map<String, ServerTemplate> getTemplates() {
return new TreeMap<String, ServerTemplate>(templates);

View File

@ -8,6 +8,8 @@ import net.ME1312.SubServers.Bungee.Library.Version.Version;
import net.ME1312.SubServers.Bungee.SubAPI;
import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;
/**
@ -178,10 +180,10 @@ public abstract class SubCreator {
* @param name Server Name
* @param template Server Template
* @param version Server Version
* @param port Server Port Number
* @param port Server Port Number (null to auto-select)
* @return Success Status
*/
public abstract boolean create(UUID player, String name, ServerTemplate template, Version version, int port, Callback<SubServer> callback);
public abstract boolean create(UUID player, String name, ServerTemplate template, Version version, Integer port, Callback<SubServer> callback);
/**
* Create a SubServer
@ -190,10 +192,10 @@ public abstract class SubCreator {
* @param name Server Name
* @param template Server Template
* @param version Server Version
* @param port Server Port Number
* @param port Server Port Number (null to auto-select)
* @return Success Status
*/
public boolean create(UUID player, String name, ServerTemplate template, Version version, int port) {
public boolean create(UUID player, String name, ServerTemplate template, Version version, Integer port) {
return create(player, name, template, version, port, null);
}
@ -203,10 +205,10 @@ public abstract class SubCreator {
* @param name Server Name
* @param template Server Template
* @param version Server Version
* @param port Server Port Number
* @param port Server Port Number (null to auto-select)
* @return Success Status
*/
public boolean create(String name, ServerTemplate template, Version version, int port, Callback<SubServer> callback) {
public boolean create(String name, ServerTemplate template, Version version, Integer port, Callback<SubServer> callback) {
return create(null, name, template, version, port, callback);
}
@ -216,10 +218,10 @@ public abstract class SubCreator {
* @param name Server Name
* @param template Server Template
* @param version Server Version
* @param port Server Port Number
* @param port Server Port Number (null to auto-select)
* @return Success Status
*/
public boolean create(String name, ServerTemplate template, Version version, int port) {
public boolean create(String name, ServerTemplate template, Version version, Integer port) {
return create(null, name, template, version, port);
}
@ -269,7 +271,7 @@ public abstract class SubCreator {
*
* @return SubCreator Loggers
*/
public abstract List<SubLogger> getLogger();
public abstract List<SubLogger> getLoggers();
/**
* Gets the Logger for a SubCreator Instance
@ -287,6 +289,13 @@ public abstract class SubCreator {
*/
public abstract List<String> getReservedNames();
/**
* Get a list of currently reserved Server ports
*
* @return Reserved Ports
*/
public abstract List<Integer> getReservedPorts();
/**
* Check if a name has been reserved
*
@ -301,6 +310,20 @@ public abstract class SubCreator {
return reserved;
}
/**
* Check if an address has been reserved
*
* @param address Address to check
* @return Reserved Status
*/
public static boolean isReserved(InetSocketAddress address) {
boolean reserved = false;
for (InetSocketAddress list : getAllReservedAddresses()) {
if (list.equals(address)) reserved = true;
}
return reserved;
}
/**
* Get a list of all currently reserved Server names across all hosts
*
@ -312,6 +335,22 @@ public abstract class SubCreator {
return names;
}
/**
* Get a list of all currently reserved Server names across all hosts
*
* @return All Reserved Names
*/
public static List<InetSocketAddress> getAllReservedAddresses() {
List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>();
for (Server server : SubAPI.getInstance().getSubServers().values()) {
addresses.add(server.getAddress());
}
for (Host host : SubAPI.getInstance().getHosts().values())
for (int port : host.getCreator().getReservedPorts())
addresses.add(new InetSocketAddress(host.getAddress(), port));
return addresses;
}
/**
* Gets the Templates that can be used in this SubCreator instance
*

View File

@ -121,7 +121,7 @@ public abstract class SubServerContainer extends ServerContainer implements SubS
sinfo.set("running", isRunning());
sinfo.set("stop-cmd", getStopCommand());
sinfo.set("stop-action", getStopAction().toString());
sinfo.set("auto-run", SubAPI.getInstance().getInternals().config.get().getSection("Servers").getSection(getName()).getKeys().contains("Run-On-Launch") && SubAPI.getInstance().getInternals().config.get().getSection("Servers").getSection(getName()).getBoolean("Run-On-Launch"));
sinfo.set("auto-run", SubAPI.getInstance().getInternals().config.get().getSection("Servers").getSection(getName(), new YAMLSection()).getBoolean("Run-On-Launch", false));
List<String> incompatibleCurrent = new ArrayList<String>();
List<String> incompatible = new ArrayList<String>();
for (SubServer server : getCurrentIncompatibilities()) incompatibleCurrent.add(server.getName());

View File

@ -18,6 +18,7 @@ Hosts:
Display: 'Default'
Driver: 'BUILT-IN'
Address: '127.0.0.1'
Port-Range: '25500-25559'
Directory: './SubServers/Servers'
Git-Bash: '%ProgramFiles%\Git'

View File

@ -70,10 +70,10 @@ public class PacketCreateServer implements PacketIn, PacketOut {
client.sendPacket(new PacketCreateServer(8, "That Template is not enabled", (data.contains("id")) ? data.getRawString("id") : null));
} else if (new Version("1.8").compareTo(new Version(data.getSection("creator").getString("version"))) > 0) {
client.sendPacket(new PacketCreateServer(10, "SubCreator cannot create servers before Minecraft 1.8", (data.contains("id")) ? data.getRawString("id") : null));
} else if (data.getSection("creator").getInt("port") <= 0 || data.getSection("creator").getInt("port") > 65535) {
} else if (data.getSection("creator").contains("port") && (data.getSection("creator").getInt("port") <= 0 || data.getSection("creator").getInt("port") > 65535)) {
client.sendPacket(new PacketCreateServer(11, "Invalid Port Number", (data.contains("id")) ? data.getRawString("id") : null));
} else {
if (plugin.hosts.get(data.getSection("creator").getString("host").toLowerCase()).getCreator().create((data.contains("player"))?UUID.fromString(data.getRawString("player")):null, data.getSection("creator").getString("name"), plugin.hosts.get(data.getSection("creator").getString("host").toLowerCase()).getCreator().getTemplate(data.getSection("creator").getString("template")), new Version(data.getSection("creator").getString("version")), data.getSection("creator").getInt("port"))) {
if (plugin.hosts.get(data.getSection("creator").getString("host").toLowerCase()).getCreator().create((data.contains("player"))?UUID.fromString(data.getRawString("player")):null, data.getSection("creator").getString("name"), plugin.hosts.get(data.getSection("creator").getString("host").toLowerCase()).getCreator().getTemplate(data.getSection("creator").getString("template")), new Version(data.getSection("creator").getString("version")), (data.getSection("creator").contains("port"))?data.getSection("creator").getInt("port"):null)) {
if (data.contains("wait") && data.getBoolean("wait")) {
new Thread(() -> {
try {

View File

@ -137,6 +137,7 @@ public final class SubAPI {
* @param enabled Enabled Status
* @param address Address of the Host
* @param directory Directory of the Host
* @param range The range of ports to auto-select from
* @param gitBash Git Bash Directory
* @return The Host
* @throws NoSuchMethodException
@ -144,8 +145,8 @@ public final class SubAPI {
* @throws InvocationTargetException
* @throws InstantiationException
*/
public Host addHost(String driver, String name, boolean enabled, InetAddress address, String directory, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return addHost(null, driver, name, enabled, address, directory, gitBash);
public Host addHost(String driver, String name, boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return addHost(null, driver, name, enabled, address, directory, range, gitBash);
}
/**
@ -157,6 +158,7 @@ public final class SubAPI {
* @param enabled Enabled Status
* @param address Address of the Host
* @param directory Directory of the Host
* @param range The range of ports to auto-select from
* @param gitBash Git Bash Directory
* @return The Host
* @throws NoSuchMethodException
@ -164,10 +166,10 @@ public final class SubAPI {
* @throws InvocationTargetException
* @throws InstantiationException
*/
public Host addHost(UUID player, String driver, String name, boolean enabled, InetAddress address, String directory, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (Util.isNull(driver, name, enabled, address, directory, gitBash)) throw new NullPointerException();
public Host addHost(UUID player, String driver, String name, boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (Util.isNull(driver, name, enabled, address, directory, range, gitBash)) throw new NullPointerException();
if (!getHostDrivers().contains(driver.toUpperCase().replace('-', '_').replace(' ', '_'))) throw new InvalidHostException("Invalid Driver for host: " + name);
return addHost(player, plugin.hostDrivers.get(driver.toUpperCase().replace('-', '_').replace(' ', '_')), name, enabled, address, directory, gitBash);
return addHost(player, plugin.hostDrivers.get(driver.toUpperCase().replace('-', '_').replace(' ', '_')), name, enabled, address, directory, range, gitBash);
}
/**
@ -178,6 +180,7 @@ public final class SubAPI {
* @param enabled Enabled Status
* @param address Address of the Host
* @param directory Directory of the Host
* @param range The range of ports to auto-select from
* @param gitBash Git Bash Directory
* @return The Host
* @throws NoSuchMethodException
@ -185,8 +188,8 @@ public final class SubAPI {
* @throws InvocationTargetException
* @throws InstantiationException
*/
public Host addHost(Class<? extends Host> driver, String name, boolean enabled, InetAddress address, String directory, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return addHost(null, driver, name, enabled, address, directory, gitBash);
public Host addHost(Class<? extends Host> driver, String name, boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return addHost(null, driver, name, enabled, address, directory, range, gitBash);
}
/**
@ -198,6 +201,7 @@ public final class SubAPI {
* @param enabled Enabled Status
* @param address Address of the Host
* @param directory Directory of the Host
* @param range The range of ports to auto-select from
* @param gitBash Git Bash Directory
* @return The Host
* @throws NoSuchMethodException
@ -205,9 +209,9 @@ public final class SubAPI {
* @throws InvocationTargetException
* @throws InstantiationException
*/
public Host addHost(UUID player, Class<? extends Host> driver, String name, boolean enabled, InetAddress address, String directory, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (Util.isNull(driver, name, enabled, address, directory, gitBash)) throw new NullPointerException();
Host host = driver.getConstructor(SubPlugin.class, String.class, Boolean.class, InetAddress.class, String.class, String.class).newInstance(plugin, name, (Boolean) enabled, address, directory, gitBash);
public Host addHost(UUID player, Class<? extends Host> driver, String name, boolean enabled, InetAddress address, String directory, NamedContainer<Integer, Integer> range, String gitBash) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (Util.isNull(driver, name, enabled, address, directory, range, gitBash)) throw new NullPointerException();
Host host = driver.getConstructor(SubPlugin.class, String.class, Boolean.class, InetAddress.class, String.class, NamedContainer.class, String.class).newInstance(plugin, name, (Boolean) enabled, address, directory, range, gitBash);
return addHost(player, host)?host:null;
}

View File

@ -464,7 +464,7 @@ public final class SubCommand extends CommandX {
sender.sendMessage("SubServers > The BungeeCord library provided does not support console sudo.");
}
} else if (args[0].equalsIgnoreCase("create")) {
if (args.length > 5) {
if (args.length > 4) {
if (plugin.api.getSubServers().keySet().contains(args[1].toLowerCase()) || SubCreator.isReserved(args[1])) {
sender.sendMessage("SubServers > There is already a SubServer with that name");
} else if (!plugin.hosts.keySet().contains(args[2].toLowerCase())) {
@ -479,13 +479,13 @@ public final class SubCommand extends CommandX {
sender.sendMessage("SubServers > That Template is not enabled");
} else if (new Version("1.8").compareTo(new Version(args[4])) > 0) {
sender.sendMessage("SubServers > SubCreator cannot create servers before Minecraft 1.8");
} else if (Util.isException(() -> Integer.parseInt(args[5])) || Integer.parseInt(args[5]) <= 0 || Integer.parseInt(args[5]) > 65535) {
} else if (args.length > 5 && (Util.isException(() -> Integer.parseInt(args[5])) || Integer.parseInt(args[5]) <= 0 || Integer.parseInt(args[5]) > 65535)) {
sender.sendMessage("SubServers > Invalid Port Number");
} else {
plugin.hosts.get(args[2].toLowerCase()).getCreator().create(args[1], plugin.hosts.get(args[2].toLowerCase()).getCreator().getTemplate(args[3]), new Version(args[4]), Integer.parseInt(args[5]));
plugin.hosts.get(args[2].toLowerCase()).getCreator().create(args[1], plugin.hosts.get(args[2].toLowerCase()).getCreator().getTemplate(args[3]), new Version(args[4]), (args.length > 5)?Integer.parseInt(args[5]):null);
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <Name> <Host> <Template> <Version> <Port>");
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <Name> <Host> <Template> <Version> [Port]");
}
} else if (args[0].equalsIgnoreCase("del") || args[0].equalsIgnoreCase("delete")) {
if (args.length > 1) {
@ -532,7 +532,7 @@ public final class SubCommand extends CommandX {
" Terminate Server: /sub kill <SubServer>",
" Command Server: /sub cmd <SubServer> <Command> [Args...]",
" Sudo Server: /sub sudo <SubServer>",
" Create Server: /sub create <Name> <Host> <Template> <Version> <Port>",
" Create Server: /sub create <Name> <Host> <Template> <Version> [Port]",
" Remove Server: /sub delete <SubServer>",
"",
" To see BungeeCord supplied commands, please visit:",

View File

@ -211,7 +211,16 @@ public final class SubPlugin extends BungeeCord implements Listener {
if (getPluginManager().getPlugin("RedisBungee") != null) redis = Util.getDespiteException(() -> new Proxy((String) redis("getServerId")), null);
reload();
if (UPnP.isUPnPAvailable()) {
if (config.get().getSection("Settings").getSection("UPnP", new YAMLSection()).getBoolean("Forward-Proxy", true)) for (ListenerInfo listener : getConfig().getListeners()) {
UPnP.openPortTCP(listener.getHost().getPort());
}
} else {
getLogger().warning("UPnP is currently unavailable; Ports may not be automatically forwarded on this device");
}
super.startListeners();
if (!posted) {
post();
posted = true;
@ -307,11 +316,12 @@ public final class SubPlugin extends BungeeCord implements Listener {
!hostDrivers.get(config.get().getSection("Hosts").getSection(name).getRawString("Driver").toUpperCase().replace('-', '_').replace(' ', '_')).equals(host.getClass()) ||
!config.get().getSection("Hosts").getSection(name).getRawString("Address").equals(host.getAddress().getHostAddress()) ||
!config.get().getSection("Hosts").getSection(name).getRawString("Directory").equals(host.getPath()) ||
!config.get().getSection("Hosts").getSection(name).getRawString("Port-Range", "25500-25559").equals(prevconfig.getSection("Hosts", new YAMLSection()).getSection(name, new YAMLSection()).getRawString("Port-Range", "25500-25559")) ||
!config.get().getSection("Hosts").getSection(name).getRawString("Git-Bash").equals(host.getCreator().getBashDirectory())
) {
if (host != null) api.forceRemoveHost(name);
host = api.addHost(config.get().getSection("Hosts").getSection(name).getRawString("Driver").toLowerCase(), name, config.get().getSection("Hosts").getSection(name).getBoolean("Enabled"), InetAddress.getByName(config.get().getSection("Hosts").getSection(name).getRawString("Address")),
config.get().getSection("Hosts").getSection(name).getRawString("Directory"), config.get().getSection("Hosts").getSection(name).getRawString("Git-Bash"));
host = api.addHost(config.get().getSection("Hosts").getSection(name).getRawString("Driver").toLowerCase(), name, config.get().getSection("Hosts").getSection(name).getBoolean("Enabled"), InetAddress.getByName(config.get().getSection("Hosts").getSection(name).getRawString("Address")), config.get().getSection("Hosts").getSection(name).getRawString("Directory"),
new NamedContainer<>(Integer.parseInt(config.get().getSection("Hosts").getSection(name).getRawString("Port-Range", "25500-25559").split("-")[0]), Integer.parseInt(config.get().getSection("Hosts").getSection(name).getRawString("Port-Range", "25500-25559").split("-")[1])), config.get().getSection("Hosts").getSection(name).getRawString("Git-Bash"));
} else { // Host wasn't reset, so check for these changes
if (config.get().getSection("Hosts").getSection(name).getBoolean("Enabled") != host.isEnabled())
host.setEnabled(config.get().getSection("Hosts").getSection(name).getBoolean("Enabled"));
@ -515,13 +525,6 @@ public final class SubPlugin extends BungeeCord implements Listener {
for (Server server : api.getServers().values()) if (server.getSubData() != null) server.getSubData().sendPacket(new PacketOutReload(null));
}
if (UPnP.isUPnPAvailable()) {
if (config.get().getSection("Settings").getSection("UPnP", new YAMLSection()).getBoolean("Forward-Proxy", true)) for (ListenerInfo listener : getConfig().getListeners()) {
UPnP.openPortTCP(listener.getHost().getPort());
}
} else {
getLogger().warning("UPnP is currently unavailable; Ports may not be automatically forwarded on this device");
}
System.out.println("SubServers > " + ((plugins > 0)?plugins+" Plugin"+((plugins == 1)?"":"s")+", ":"") + ((proxies > 1)?proxies+" Proxies, ":"") + hosts + " Host"+((hosts == 1)?"":"s")+", " + servers + " Server"+((servers == 1)?"":"s")+", and " + subservers + " SubServer"+((subservers == 1)?"":"s")+" "+((status)?"re":"")+"loaded in " + new DecimalFormat("0.000").format((Calendar.getInstance().getTime().getTime() - begin) / 1000D) + "s");
}

View File

@ -364,16 +364,10 @@ public class DefaultUIRenderer extends UIRenderer {
inv.setItem(11, block);
inv.setItem(12, block);
if (options.getPort() <= 0) {
block = createItem("STAINED_GLASS_PANE", "RED_STAINED_GLASS_PANE", (short) 14);
blockMeta = block.getItemMeta();
blockMeta.setDisplayName(ChatColor.RED + plugin.api.getLang("SubServers", "Interface.Host-Creator.Edit-Port"));
} else {
block = createItem("STAINED_GLASS_PANE", "LIME_STAINED_GLASS_PANE", (short) 5);
blockMeta = block.getItemMeta();
blockMeta.setDisplayName(ChatColor.GREEN + plugin.api.getLang("SubServers", "Interface.Host-Creator.Edit-Port"));
blockMeta.setLore(Arrays.asList(ChatColor.GRAY.toString() + options.getPort()));
}
blockMeta.setLore(Arrays.asList(ChatColor.GRAY.toString() + ((options.getPort() == null)?"Auto Select":options.getPort())));
block.setItemMeta(blockMeta);
inv.setItem(14, block);
inv.setItem(15, block);
@ -424,7 +418,7 @@ public class DefaultUIRenderer extends UIRenderer {
inv.setItem(45, block);
inv.setItem(46, block);
if (options.getName() == null || options.getTemplate() == null || options.getVersion() == null || options.getPort() <= 0 && options.getMemory() < 256) {
if (options.getName() == null || options.getTemplate() == null || options.getVersion() == null) {
block = createItem("STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE", (short) 7);
blockMeta = block.getItemMeta();
blockMeta.setDisplayName(ChatColor.GRAY + ChatColor.stripColor(plugin.api.getLang("SubServers", "Interface.Host-Creator.Submit")));

View File

@ -422,8 +422,7 @@ public abstract class UIRenderer {
private String name = null;
private String template = null;
private Version version = null;
private int memory = 1024;
private int port = -1;
private Integer port = null;
/**
* Grabs a raw CreatorOptions instance
@ -506,42 +505,21 @@ public abstract class UIRenderer {
this.version = value;
}
/**
* Gets the RAM Amount for the Server
*
* @return Server RAM Amount (in MB)
*/
public int getMemory() {
return memory;
}
/**
* Sets the RAM AMount for the Server
*
* @param value Value (in MB)
*/
public void setMemory(int value) {
if (Util.isNull(value)) throw new NullPointerException();
final int memory = this.memory;
history.add(() -> this.memory = memory);
this.memory = value;
}
/**
* Gets the Port Number for the Server
*
* @return Server Port Number
* @return Server Port Number (null for auto-select)
*/
public int getPort() {
public Integer getPort() {
return port;
}
/**
* Sets the Port Number for the Server
*
* @param value Value
* @param value Value (null for auto-select)
*/
public void setPort(int value) {
public void setPort(Integer value) {
if (Util.isNull(value)) throw new NullPointerException();
final int port = this.port;
history.add(() -> this.port = port);

View File

@ -21,7 +21,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
private String host;
private String template;
private Version version;
private int port;
private Integer port;
private String id;
/**
@ -41,8 +41,8 @@ public class PacketCreateServer implements PacketIn, PacketOut {
* @param callback Callbacks
*/
@SafeVarargs
public PacketCreateServer(UUID player, String name, String host, String template, Version version, int port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, port, callback)) throw new NullPointerException();
public PacketCreateServer(UUID player, String name, String host, String template, Version version, Integer port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, callback)) throw new NullPointerException();
this.player = player;
this.name = name;
this.host = host;
@ -84,7 +84,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
creator.set("host", host);
creator.set("template", template);
creator.set("version", version.toString());
creator.set("port", port);
if (port != null) creator.set("port", port);
data.set("creator", creator);
return data;
}

View File

@ -443,12 +443,12 @@ public final class SubCommand implements CommandExecutor {
sender.sendMessage(plugin.api.getLang("SubServers", "Command.Generic.Usage").replace("$str$", label.toLowerCase() + " " + args[0].toLowerCase() + " <SubServer> <Command> [Args...]"));
}
} else if (args[0].equalsIgnoreCase("create")) {
if (args.length > 5) {
if (args.length > 4) {
if (sender.hasPermission("subservers.host.create.*") || sender.hasPermission("subservers.host.create." + args[2].toLowerCase())) {
if (Util.isException(() -> Integer.parseInt(args[5]))) {
if (args.length > 5 && Util.isException(() -> Integer.parseInt(args[5]))) {
sender.sendMessage(plugin.api.getLang("SubServers", "Command.Creator.Invalid-Port"));
} else {
plugin.subdata.sendPacket(new PacketCreateServer((sender instanceof Player)?((Player) sender).getUniqueId():null, args[1], args[2], args[3], new Version(args[4]), Integer.parseInt(args[5]), data -> {
plugin.subdata.sendPacket(new PacketCreateServer((sender instanceof Player)?((Player) sender).getUniqueId():null, args[1], args[2], args[3], new Version(args[4]), (args.length > 5)?Integer.parseInt(args[5]):null, data -> {
switch (data.getInt("r")) {
case 3:
case 4:
@ -480,7 +480,7 @@ public final class SubCommand implements CommandExecutor {
sender.sendMessage(plugin.api.getLang("SubServers", "Command.Creator"));
break;
default:
Bukkit.getLogger().warning("SubData > PacketCreateServer(" + ((sender instanceof Player)?((Player) sender).getUniqueId().toString():"null") + ", " + args[1] + ", " + args[2] + ", " + args[3] + ", " + args[4] + ", " + args[5] + ") responded with: " + data.getString("m"));
Bukkit.getLogger().warning("SubData > PacketCreateServer(" + ((sender instanceof Player)?((Player) sender).getUniqueId().toString():"null") + ", " + args[1] + ", " + args[2] + ", " + args[3] + ", " + args[4] + ", " + ((args.length > 5)?args[5]:"null") + ") responded with: " + data.getString("m"));
sender.sendMessage(plugin.api.getLang("SubServers", "Command.Creator"));
break;
}
@ -571,7 +571,7 @@ public final class SubCommand implements CommandExecutor {
plugin.api.getLang("SubServers", "Command.Help.SubServer.Stop").replace("$str$", label.toLowerCase() + " stop <SubServer>"),
plugin.api.getLang("SubServers", "Command.Help.SubServer.Terminate").replace("$str$", label.toLowerCase() + " kill <SubServer>"),
plugin.api.getLang("SubServers", "Command.Help.SubServer.Command").replace("$str$", label.toLowerCase() + " cmd <SubServer> <Command> [Args...]"),
plugin.api.getLang("SubServers", "Command.Help.Host.Create").replace("$str$", label.toLowerCase() + " create <Name> <Host> <Template> <Version> <Port>"),
plugin.api.getLang("SubServers", "Command.Help.Host.Create").replace("$str$", label.toLowerCase() + " create <Name> <Host> <Template> <Version> [Port]"),
};
}
}

View File

@ -377,8 +377,7 @@ public abstract class UIRenderer {
private String name = null;
private String template = null;
private Version version = null;
private int memory = 1024;
private int port = -1;
private Integer port = null;
/**
* Grabs a raw CreatorOptions instance
@ -461,42 +460,21 @@ public abstract class UIRenderer {
this.version = value;
}
/**
* Gets the RAM Amount for the Server
*
* @return Server RAM Amount (in MB)
*/
public int getMemory() {
return memory;
}
/**
* Sets the RAM AMount for the Server
*
* @param value Value (in MB)
*/
public void setMemory(int value) {
if (Util.isNull(value)) throw new NullPointerException();
final int memory = this.memory;
history.add(() -> this.memory = memory);
this.memory = value;
}
/**
* Gets the Port Number for the Server
*
* @return Server Port Number
* @return Server Port Number (null for auto-select)
*/
public int getPort() {
public Integer getPort() {
return port;
}
/**
* Sets the Port Number for the Server
*
* @param value Value
* @param value Value (null for auto-select)
*/
public void setPort(int value) {
public void setPort(Integer value) {
if (Util.isNull(value)) throw new NullPointerException();
final int port = this.port;
history.add(() -> this.port = port);

View File

@ -21,7 +21,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
private String host;
private String template;
private Version version;
private int port;
private Integer port;
private String id;
/**
@ -41,8 +41,8 @@ public class PacketCreateServer implements PacketIn, PacketOut {
* @param callback Callbacks
*/
@SafeVarargs
public PacketCreateServer(UUID player, String name, String host, String template, Version version, int port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, port, callback)) throw new NullPointerException();
public PacketCreateServer(UUID player, String name, String host, String template, Version version, Integer port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, callback)) throw new NullPointerException();
this.player = player;
this.name = name;
this.host = host;
@ -84,7 +84,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
creator.set("host", host);
creator.set("template", template);
creator.set("version", version.toString());
creator.set("port", port);
if (port != null) creator.set("port", port);
data.set("creator", creator);
return data;
}

View File

@ -794,13 +794,13 @@ public final class SubCommand implements CommandExecutor {
Optional<String> template = args.getOne(Text.of("Template"));
Optional<String> version = args.getOne(Text.of("Version"));
Optional<String> port = args.getOne(Text.of("Port"));
if (name.isPresent() && host.isPresent() && template.isPresent() && version.isPresent() && port.isPresent()) {
if (name.isPresent() && host.isPresent() && template.isPresent() && version.isPresent()) {
if (sender.hasPermission("subservers.host.create." + host.get().toLowerCase())) {
if (Util.isException(() -> Integer.parseInt(port.get()))) {
if (port.isPresent() && Util.isException(() -> Integer.parseInt(port.get()))) {
sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Invalid-Port")));
return CommandResult.builder().successCount(0).build();
} else {
plugin.subdata.sendPacket(new PacketCreateServer((sender instanceof Player)?((Player) sender).getUniqueId():null, name.get(), host.get(), template.get(), new Version(version.get()), Integer.parseInt(port.get()), data -> {
plugin.subdata.sendPacket(new PacketCreateServer((sender instanceof Player)?((Player) sender).getUniqueId():null, name.get(), host.get(), template.get(), new Version(version.get()), (port.isPresent())?Integer.parseInt(port.get()):null, data -> {
switch (data.getInt("r")) {
case 3:
case 4:
@ -832,7 +832,7 @@ public final class SubCommand implements CommandExecutor {
sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator")));
break;
default:
plugin.logger.warn("PacketCreateServer(" + ((sender instanceof Player)?((Player) sender).getUniqueId().toString():"null") + ", " + name.get() + ", " + host.get() + ", " + template.get() + ", " + version.get() + ", " + port.get() + ") responded with: " + data.getString("m"));
plugin.logger.warn("PacketCreateServer(" + ((sender instanceof Player)?((Player) sender).getUniqueId().toString():"null") + ", " + name.get() + ", " + host.get() + ", " + template.get() + ", " + version.get() + ", " + (port.orElse("null")) + ") responded with: " + data.getString("m"));
sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator")));
break;
}

View File

@ -31,7 +31,7 @@ import java.util.*;
*/
public class SubCreator {
private ExHost host;
private TreeMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>> thread;
private TreeMap<String, CreatorTask> thread;
public static class ServerTemplate extends net.ME1312.SubServers.Host.Network.API.SubCreator.ServerTemplate {
private String name;
@ -179,47 +179,57 @@ public class SubCreator {
}
}
/**
* Creates a SubCreator Instance
*
* @param host SubServers.Host
*/
public SubCreator(ExHost host) {
if (Util.isNull(host)) throw new NullPointerException();
this.host = host;
this.thread = new TreeMap<>();
private class CreatorTask extends Thread {
private final String name;
private final ServerTemplate template;
private final Version version;
private final int port;
private final UUID address;
private final String id;
private final SubLogger log;
private Process process;
private CreatorTask(String name, ServerTemplate template, Version version, int port, UUID address, String id) {
this.name = name;
this.template = template;
this.version = version;
this.port = port;
this.log = new SubLogger(null, this, name + File.separator + "Creator", address, new Container<Boolean>(true), null);
this.address = address;
this.id = id;
}
private YAMLSection build(NamedContainer<SubLogger, Process> thread, File dir, String name, ServerTemplate template, Version version, UUID address, List<ServerTemplate> history) throws SubCreatorException {
private YAMLSection build(File dir, ServerTemplate template, List<ServerTemplate> history) throws SubCreatorException {
YAMLSection server = new YAMLSection();
Version version = this.version;
boolean error = false;
if (history.contains(template)) throw new IllegalStateException("Template Import loop detected");
history.add(template);
for (String other : template.getBuildOptions().getStringList("Import", new ArrayList<String>())) {
if (host.templates.keySet().contains(other.toLowerCase())) {
if (host.templates.get(other.toLowerCase()).isEnabled()) {
YAMLSection config = build(thread, dir, other, host.templates.get(other.toLowerCase()), version, address, history);
YAMLSection config = build(dir, host.templates.get(other.toLowerCase()), history);
if (config == null) {
throw new SubCreatorException();
} else {
server.setAll(config);
}
} else {
thread.name().logger.warn.println("Skipping disabled template: " + other);
log.logger.warn.println("Skipping disabled template: " + other);
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Skipping disabled template: " + other));
}
} else {
thread.name().logger.warn.println("Skipping missing template: " + other);
log.logger.warn.println("Skipping missing template: " + other);
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Skipping missing template: " + other));
}
}
server.setAll(template.getConfigOptions());
try {
thread.name().logger.info.println("Loading Template: " + template.getDisplayName());
log.logger.info.println("Loading Template: " + template.getDisplayName());
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Loading Template: " + template.getDisplayName()));
Util.copyDirectory(template.getDirectory(), dir);
if (template.getType() == ServerType.FORGE || template.getType() == ServerType.SPONGE) {
thread.name().logger.info.println("Searching Versions...");
log.logger.info.println("Searching Versions...");
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Searching Versions..."));
Document spongexml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(Util.readAll(new BufferedReader(new InputStreamReader(new URL("https://repo.spongepowered.org/maven/org/spongepowered/sponge" + ((template.getType() == ServerType.FORGE)?"forge":"vanilla") + "/maven-metadata.xml").openStream(), Charset.forName("UTF-8")))))));
@ -235,7 +245,7 @@ public class SubCreator {
}
if (spversion == null)
throw new InvalidServerException("Cannot find Sponge version for Minecraft " + version.toString());
thread.name().logger.info.println("Found \"sponge" + ((template.getType() == ServerType.FORGE)?"forge":"vanilla") + "-" + spversion.toString() + '"');
log.logger.info.println("Found \"sponge" + ((template.getType() == ServerType.FORGE)?"forge":"vanilla") + "-" + spversion.toString() + '"');
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Found \"sponge" + ((template.getType() == ServerType.FORGE)?"forge":"vanilla") + "-" + spversion.toString() + '"'));
if (template.getType() == ServerType.FORGE) {
@ -253,14 +263,14 @@ public class SubCreator {
}
if (mcfversion == null)
throw new InvalidServerException("Cannot find Forge version for Sponge " + spversion.toString());
thread.name().logger.info.println("Found \"forge-" + mcfversion.toString() + '"');
log.logger.info.println("Found \"forge-" + mcfversion.toString() + '"');
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Found \"forge-" + mcfversion.toString() + '"'));
version = new Version(mcfversion.toString() + " " + spversion.toString());
} else version = new Version(spversion.toString());
}
} catch (Exception e) {
thread.name().logger.error.println(e);
log.logger.error.println(e);
}
if (template.getBuildOptions().contains("Shell-Location")) {
@ -277,33 +287,33 @@ public class SubCreator {
Process process = Runtime.getRuntime().exec("chmod " + template.getBuildOptions().getRawString("Permission") + ' ' + template.getBuildOptions().getRawString("Shell-Location"), null, dir);
Thread.sleep(500);
if (process.exitValue() != 0) {
thread.name().logger.info.println("Couldn't set " + template.getBuildOptions().getRawString("Permission") + " permissions to " + template.getBuildOptions().getRawString("Shell-Location"));
log.logger.info.println("Couldn't set " + template.getBuildOptions().getRawString("Permission") + " permissions to " + template.getBuildOptions().getRawString("Shell-Location"));
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Couldn't set " + template.getBuildOptions().getRawString("Permission") + " permissions to " + template.getBuildOptions().getRawString("Shell-Location")));
}
} catch (Exception e) {
thread.name().logger.info.println("Couldn't set " + template.getBuildOptions().getRawString("Permission") + " permissions to " + template.getBuildOptions().getRawString("Shell-Location"));
log.logger.info.println("Couldn't set " + template.getBuildOptions().getRawString("Permission") + " permissions to " + template.getBuildOptions().getRawString("Shell-Location"));
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Couldn't set " + template.getBuildOptions().getRawString("Permission") + " permissions to " + template.getBuildOptions().getRawString("Shell-Location")));
thread.name().logger.error.println(e);
log.logger.error.println(e);
}
}
try {
thread.name().logger.info.println("Launching " + template.getBuildOptions().getRawString("Shell-Location"));
log.logger.info.println("Launching " + template.getBuildOptions().getRawString("Shell-Location"));
host.subdata.sendPacket(new PacketOutExLogMessage(address, "Launching " + template.getBuildOptions().getRawString("Shell-Location")));
thread.set(Runtime.getRuntime().exec((System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)?"cmd.exe /c \"\"" + gitBash + "\" --login -i -c \"bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace('\\', '/').replace(" ", "\\ ")) + "\"\"":("bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace(" ", "\\ "))), null, dir));
thread.name().file = new File(dir, "SubCreator-" + template.getName() + "-" + version.toString().replace(" ", "@") + ".log");
thread.name().process = thread.get();
thread.name().start();
process = Runtime.getRuntime().exec((System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)?"cmd.exe /c \"\"" + gitBash + "\" --login -i -c \"bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace('\\', '/').replace(" ", "\\ ")) + "\"\"":("bash " + template.getBuildOptions().getRawString("Shell-Location") + ' ' + version.toString() + ' ' + ((cache == null)?':':cache.toString().replace(" ", "\\ "))), null, dir);
log.file = new File(dir, "SubCreator-" + template.getName() + "-" + version.toString().replace(" ", "@") + ".log");
log.process = process;
log.start();
thread.get().waitFor();
process.waitFor();
Thread.sleep(500);
if (thread.get().exitValue() != 0) error = true;
if (process.exitValue() != 0) error = true;
} catch (InterruptedException e) {
error = true;
} catch (Exception e) {
error = true;
thread.name().logger.error.println(e);
log.logger.error.println(e);
}
if (cache != null) {
@ -320,41 +330,52 @@ public class SubCreator {
return server;
}
private void run(String name, ServerTemplate template, Version version, int port, UUID address, String id) {
NamedContainer<SubLogger, Process> thread = this.thread.get(name.toLowerCase()).get();
public void run() {
UniversalFile dir = new UniversalFile(new File(host.host.getRawString("Directory")), name);
dir.mkdirs();
YAMLSection server;
try {
server = build(thread, dir, name, template, version, address, new LinkedList<>());
server = build(dir, template, new LinkedList<>());
generateProperties(dir, port);
generateClient(dir, template.getType(), name);
} catch (SubCreatorException e) {
server = null;
} catch (Exception e) {
server = null;
thread.name().logger.error.println(e);
log.logger.error.println(e);
}
if (server != null) {
host.subdata.sendPacket(new PacketExCreateServer(0, "Created Server Successfully", template.getConfigOptions(), id));
} else {
thread.name().logger.info.println("Couldn't build the server jar. Check the SubCreator logs for more detail.");
log.logger.info.println("Couldn't build the server jar. Check the SubCreator logs for more detail.");
host.subdata.sendPacket(new PacketExCreateServer(-1, "Couldn't build the server jar. Check the SubCreator logs for more detail.", template.getConfigOptions(), id));
}
this.thread.remove(name.toLowerCase());
SubCreator.this.thread.remove(name.toLowerCase());
}
}
/**
* Creates a SubCreator Instance
*
* @param host SubServers.Host
*/
public SubCreator(ExHost host) {
if (Util.isNull(host)) throw new NullPointerException();
this.host = host;
this.thread = new TreeMap<>();
}
public boolean create(String name, ServerTemplate template, Version version, int port, UUID address, String id) {
if (Util.isNull(name, template, version, port, address)) throw new NullPointerException();
NamedContainer<Thread, NamedContainer<SubLogger, Process>> run = new NamedContainer<Thread, NamedContainer<SubLogger, Process>>(new Thread(() -> SubCreator.this.run(name, template, version, port, address, id)), new NamedContainer<SubLogger, Process>(new SubLogger(null, this, name + File.separator + "Creator", address, new Container<Boolean>(true), null), null));
this.thread.put(name.toLowerCase(), run);
run.name().start();
CreatorTask task = new CreatorTask(name, template, version, port, address, id);
this.thread.put(name.toLowerCase(), task);
task.start();
return true;
}
public void terminate() {
HashMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>> temp = new HashMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>>();
HashMap<String, CreatorTask> temp = new HashMap<String, CreatorTask>();
temp.putAll(thread);
for (String i : temp.keySet()) {
terminate(i);
@ -362,16 +383,18 @@ public class SubCreator {
}
public void terminate(String name) {
if (this.thread.get(name).get().get() != null && this.thread.get(name).get().get().isAlive()) {
this.thread.get(name).get().get().destroyForcibly();
} else if (this.thread.get(name).name() != null && this.thread.get(name).name().isAlive()) {
this.thread.get(name).name().interrupt();
this.thread.remove(name);
if (this.thread.keySet().contains(name.toLowerCase())) {
if (this.thread.get(name.toLowerCase()).process != null && this.thread.get(name.toLowerCase()).process.isAlive()) {
this.thread.get(name.toLowerCase()).process.destroyForcibly();
} else if (this.thread.get(name.toLowerCase()).isAlive()) {
this.thread.get(name.toLowerCase()).interrupt();
this.thread.remove(name.toLowerCase());
}
}
}
public void waitFor() throws InterruptedException {
HashMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>> temp = new HashMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>>();
HashMap<String, CreatorTask> temp = new HashMap<String, CreatorTask>();
temp.putAll(thread);
for (String i : temp.keySet()) {
waitFor(i);
@ -379,14 +402,14 @@ public class SubCreator {
}
public void waitFor(String name) throws InterruptedException {
while (this.thread.get(name).name() != null && this.thread.get(name).name().isAlive()) {
while (this.thread.keySet().contains(name.toLowerCase()) && this.thread.get(name.toLowerCase()).isAlive()) {
Thread.sleep(250);
}
}
public List<SubLogger> getLogger() {
public List<SubLogger> getLoggers() {
List<SubLogger> loggers = new ArrayList<SubLogger>();
HashMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>> temp = new HashMap<String, NamedContainer<Thread, NamedContainer<SubLogger, Process>>>();
HashMap<String, CreatorTask> temp = new HashMap<String, CreatorTask>();
temp.putAll(thread);
for (String i : temp.keySet()) {
loggers.add(getLogger(i));
@ -395,7 +418,7 @@ public class SubCreator {
}
public SubLogger getLogger(String name) {
return this.thread.get(name).get().name();
return this.thread.get(name).log;
}
private void generateClient(File dir, ServerType type, String name) throws IOException {

View File

@ -20,7 +20,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
private String host;
private String template;
private Version version;
private int port;
private Integer port;
private String id;
/**
@ -40,8 +40,8 @@ public class PacketCreateServer implements PacketIn, PacketOut {
* @param callback Callbacks
*/
@SafeVarargs
public PacketCreateServer(UUID player, String name, String host, String template, Version version, int port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, port, callback)) throw new NullPointerException();
public PacketCreateServer(UUID player, String name, String host, String template, Version version, Integer port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, callback)) throw new NullPointerException();
this.player = player;
this.name = name;
this.host = host;
@ -62,7 +62,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
creator.set("host", host);
creator.set("template", template);
creator.set("version", version.toString());
creator.set("port", port);
if (port != null) creator.set("port", port);
data.set("creator", creator);
return data;
}

View File

@ -468,11 +468,11 @@ public class SubCommand {
new Command(host.info) {
@Override
public void command(String handle, String[] args) {
if (args.length > 4) {
if (Util.isException(() -> Integer.parseInt(args[4]))) {
if (args.length > 3) {
if (args.length > 4 && Util.isException(() -> Integer.parseInt(args[4]))) {
host.log.message.println("Invalid Port Number");
} else {
host.subdata.sendPacket(new PacketCreateServer(null, args[0], args[1], args[2], new Version(args[3]), Integer.parseInt(args[4]), data -> {
host.subdata.sendPacket(new PacketCreateServer(null, args[0], args[1], args[2], new Version(args[3]), (args.length > 4)?Integer.parseInt(args[4]):null, data -> {
switch (data.getInt("r")) {
case 3:
host.log.message.println("Server names cannot use spaces");
@ -505,7 +505,7 @@ public class SubCommand {
host.log.message.println("Launching SubCreator...");
break;
default:
host.log.warn.println("PacketCreateServer(null, " + args[0] + ", " + args[1] + ", " + args[2] + ", " + args[3] + ", " + args[4] + ") responded with: " + data.getRawString("m"));
host.log.warn.println("PacketCreateServer(null, " + args[0] + ", " + args[1] + ", " + args[2] + ", " + args[3] + ", " + ((args.length > 4)?args[4]:"null") + ") responded with: " + data.getRawString("m"));
host.log.message.println("Launching SubCreator...");
break;
}
@ -515,7 +515,7 @@ public class SubCommand {
host.log.message.println("Usage: /" + handle + " <Name> <Host> <Template> <Version> <Port>");
}
}
}.usage("<Name>", "<Host>", "<Template>", "<Version>", "<Port>").description("Creates a SubServer").help(
}.usage("<Name>", "<Host>", "<Template>", "<Version>", "[Port]").description("Creates a SubServer").help(
"This command is used to create and launch a SubServer on the specified host via the network.",
"Templates are downloaded from SubServers.Bungee to ~/Templates.",
"",
@ -531,11 +531,12 @@ public class SubCommand {
"The <Version> argument is required, and should be a version",
"string of the type of server that you want to create",
"",
"The <Port> argument is required, and should be the port number",
"that you want the server to listen on after it has been created.",
"When the <Port> argument is provided, it will set the port number",
"the server will listen on after it has been created.",
"",
"Examples:",
" /create ExampleServer ExampleHost Spigot 1.11 25565"
" /create ExampleServer ExampleHost Spigot 1.13.1",
" /create ExampleServer ExampleHost Spigot 1.13.1 25565"
).register("create");
}
}

View File

@ -20,7 +20,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
private String host;
private String template;
private Version version;
private int port;
private Integer port;
private String id;
/**
@ -40,8 +40,8 @@ public class PacketCreateServer implements PacketIn, PacketOut {
* @param callback Callbacks
*/
@SafeVarargs
public PacketCreateServer(UUID player, String name, String host, String template, Version version, int port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, port, callback)) throw new NullPointerException();
public PacketCreateServer(UUID player, String name, String host, String template, Version version, Integer port, Callback<YAMLSection>... callback) {
if (Util.isNull(name, host, template, version, callback)) throw new NullPointerException();
this.player = player;
this.name = name;
this.host = host;
@ -62,7 +62,7 @@ public class PacketCreateServer implements PacketIn, PacketOut {
creator.set("host", host);
creator.set("template", template);
creator.set("version", version.toString());
creator.set("port", port);
if (port != null) creator.set("port", port);
data.set("creator", creator);
return data;
}

View File

@ -428,11 +428,11 @@ public final class SubCommand extends CommandX {
sender.sendMessage("Usage: " + label + " <SubServer> <Command> [Args...]");
}
} else if (args[0].equalsIgnoreCase("create")) {
if (args.length > 5) {
if (Util.isException(() -> Integer.parseInt(args[5]))) {
if (args.length > 4) {
if (args.length > 5 && Util.isException(() -> Integer.parseInt(args[5]))) {
sender.sendMessage("Invalid Port Number");
} else {
plugin.subdata.sendPacket(new PacketCreateServer(null, args[1], args[2],args[3], new Version(args[4]), Integer.parseInt(args[5]), data -> {
plugin.subdata.sendPacket(new PacketCreateServer(null, args[1], args[2],args[3], new Version(args[4]), (args.length > 5)?Integer.parseInt(args[5]):null, data -> {
switch (data.getInt("r")) {
case 3:
case 4:
@ -464,7 +464,7 @@ public final class SubCommand extends CommandX {
sender.sendMessage("SubServers > Launching SubCreator...");
break;
default:
System.out.println("PacketCreateServer(null, " + args[1] + ", " + args[2] + ", " + args[3] + ", " + args[4] + ", " + args[5] + ") responded with: " + data.getRawString("m"));
System.out.println("PacketCreateServer(null, " + args[1] + ", " + args[2] + ", " + args[3] + ", " + args[4] + ", " + ((args.length > 5)?args[5]:"null") + ") responded with: " + data.getRawString("m"));
sender.sendMessage("SubServers > Launching SubCreator...");
break;
}