SubServers.Bungee Beta 1

The first beta release of SubServers.Bungee
This commit is contained in:
ME1312 2016-12-15 16:04:39 -05:00
parent dd991b512e
commit 6fd13e81dc
53 changed files with 1861 additions and 559 deletions

8
.gitignore vendored
View File

@ -26,7 +26,11 @@ crashlytics.properties
crashlytics-build.properties
# Hide Unfinished Project Files
# (none)
/Artifacts/SubServers.Client.Bukkit.jar
/Artifacts/SubServers.Host.jar
/SubServers.Client/Bukkit/
/SubServers.Host/
# Hide Others
.DS_STORE
.DS_STORE
.alias

Binary file not shown.

View File

@ -0,0 +1,62 @@
package net.ME1312.SubServers.Proxy.Event;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.md_5.bungee.api.plugin.Event;
import java.util.UUID;
public class SubAddServerEvent extends Event {
private boolean cancelled = false;
private UUID player;
private Host host;
private Server server;
/**
* Server Add Event
*
* @param player Player Adding Server
* @param server Server Starting
*/
public SubAddServerEvent(UUID player, Host host, Server server) {
this.player = player;
this.host = host;
this.server = server;
}
/**
* Gets the Server to be Added
* @return The Server to be Added
*/
public Server getServer() { return server; }
/**
* Gets the Host of the Server
*
* @return The Host of the Server or null if isn't a SubServer
*/
public Host getHost() {
return host;
}
/**
* Gets the player that triggered the Event
* @return The Player that triggered this Event or null if Console
*/
public UUID getPlayer() { return player; }
/**
* Gets the Cancelled Status
* @return Cancelled Status
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Sets the Cancelled Status
*/
public void setCancelled(boolean value) {
cancelled = value;
}
}

View File

@ -1,7 +1,142 @@
package net.ME1312.SubServers.Proxy.Event;
/**
* Created by christian on 12/4/16.
*/
public class SubCreateEvent {
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubCreator;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.md_5.bungee.api.plugin.Event;
import java.util.UUID;
public class SubCreateEvent extends Event {
private boolean cancelled = false;
private UUID player;
private Host host;
private String name;
private SubCreator.ServerType type;
private Version version;
private int memory;
private int port;
/**
* Server Create Event
*
* @param player Player Creating
* @param host Potential Host
* @param name Server Name
* @param type Server Type
* @param version Server Version
* @param memory Server RAM Amount
* @param port Server Port Number
*/
public SubCreateEvent(UUID player, Host host, String name, SubCreator.ServerType type, Version version, int memory, int port) {
this.player = player;
this.host = host;
this.name = name;
this.type = type;
this.version = version;
this.memory = memory;
this.port = port;
}
/**
* Get the Host the SubServer will run on
*
* @return Potential Host
*/
public Host getHost() {
return host;
}
/**
* Get the name the SubServer will use
*
* @return SubServer Name
*/
public String getName() {
return name;
}
/**
* Get the type of Server to create
*
* @return Server Type
*/
public SubCreator.ServerType getType() {
return type;
}
/**
* Set the Type of Server to Create
*
* @param value Value
*/
public void setType(SubCreator.ServerType value) {
this.type = value;
}
/**
* Get the Version the Server will use
*
* @return Server Version
*/
public Version getVersion() {
return version;
}
/**
* Set the Version the Server will use
*
* @param value Value
*/
public void setVersion(Version value) {
this.version = value;
}
/**
* Get the Server RAM Amount (in MB)
*
* @return RAM Amount
*/
public int getMemory() {
return memory;
}
/**
* Set the Server RAM Amount (in MB)
*
* @param value Value
*/
public void setMemory(int value) {
this.memory = value;
}
/**
* Get the Port the Server will use
*
* @return Port Number
*/
public int getPort() {
return port;
}
/**
* Gets the player that triggered the Event
* @return The Player that triggered this Event or null if Console
*/
public UUID getPlayer() { return player; }
/**
* Gets the Cancelled Status
* @return Cancelled Status
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Sets the Cancelled Status
*/
public void setCancelled(boolean value) {
cancelled = value;
}
}

View File

@ -0,0 +1,51 @@
package net.ME1312.SubServers.Proxy.Event;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.md_5.bungee.api.plugin.Event;
import org.json.JSONObject;
public class SubDataRecieveGenericInfoEvent extends Event {
private String handle;
private Version version;
private JSONObject content;
/**
* SubData Generic Info Event
*
* @param handle Content Handle
* @param version Content Version
* @param content Content
*/
public SubDataRecieveGenericInfoEvent(String handle, Version version, JSONObject content) {
this.handle = handle;
this.version = version;
this.content = content;
}
/**
* Get Content Handle
*
* @return Content Handle
*/
public String getHandle() {
return handle;
}
/**
* Get Content Version
*
* @return Content Version
*/
public Version getVersion() {
return version;
}
/**
* Get Content
*
* @return Content
*/
public JSONObject getContent() {
return content;
}
}

View File

@ -12,12 +12,12 @@ public class SubSendCommandEvent extends Event {
private String command;
/**
* Server Start Event
* Server Command Event
*
* @param server Server Starting
* @param player Player Starting Server
* @param player Player Commanding Server
* @param server Server being Commanded
*/
public SubSendCommandEvent(SubServer server, UUID player, String command) {
public SubSendCommandEvent(UUID player, SubServer server, String command) {
this.player = player;
this.server = server;
this.command = command;
@ -30,8 +30,8 @@ public class SubSendCommandEvent extends Event {
public SubServer getServer() { return server; }
/**
* Gets the player that Triggered the Event
* @return The Player that triggered this Event or Null if Console
* Gets the player that triggered the Event
* @return The Player that triggered this Event or null if Console
*/
public UUID getPlayer() { return player; }
@ -50,7 +50,7 @@ public class SubSendCommandEvent extends Event {
* @param value Value
*/
public void setCommand(String value) {
command = value;
}
/**

View File

@ -13,10 +13,10 @@ public class SubStartEvent extends Event {
/**
* Server Start Event
*
* @param server Server Starting
* @param player Player Starting Server
* @param server Server Starting
*/
public SubStartEvent(SubServer server, UUID player) {
public SubStartEvent(UUID player, SubServer server) {
this.player = player;
this.server = server;
}
@ -28,8 +28,8 @@ public class SubStartEvent extends Event {
public SubServer getServer() { return server; }
/**
* Gets the player that Triggered the Event
* @return The Player that triggered this Event or Null if Console
* Gets the player that triggered the Event
* @return The Player that triggered this Event or null if Console
*/
public UUID getPlayer() { return player; }

View File

@ -14,11 +14,11 @@ public class SubStopEvent extends Event {
/**
* Server Stop Event
*
* @param server Server Stopping
* @param player Player Stopping Server
* @param server Server Stopping
* @param force If it was a Forced Shutdown
*/
public SubStopEvent(SubServer server, UUID player, boolean force) {
public SubStopEvent(UUID player, SubServer server, boolean force) {
this.player = player;
this.server = server;
this.force = force;
@ -31,8 +31,8 @@ public class SubStopEvent extends Event {
public SubServer getServer() { return server; }
/**
* Gets the player that Triggered the Event
* @return The Player that triggered this Event or Null if Console
* Gets the player that triggered the Event
* @return The Player that triggered this Event or null if Console
*/
public UUID getPlayer() { return player; }

View File

@ -1,10 +1,10 @@
package net.ME1312.SubServers.Proxy.Host;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Libraries.UniversalFile;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidHostException;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.NamedContainer;
import net.ME1312.SubServers.Proxy.SubPlugin;
import java.io.File;
import java.net.InetAddress;
import java.util.Map;
import java.util.UUID;
@ -20,11 +20,15 @@ public abstract class Host {
* This constructor is required to launch your host from the drivers list. Do not add or remove any arguments.
*
* @param plugin SubServers Internals
* @param enabled If your host is enabled
* @param address The address of your host
* @param directory The runtime directory of your host
* @param name The Name of your Host
* @param enabled If your host is Enabled
* @param address The address of your Host
* @param directory The runtime directory of your Host
* @param gitBash The Git Bash directory
*/
public Host(SubPlugin plugin, String name, Boolean enabled, InetAddress address, UniversalFile directory) {}
public Host(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, String gitBash) {
if (name.contains(" ")) throw new InvalidHostException("Host names cannot have spaces: " + name);
}
/**
* Is this Host Enabled?
@ -47,6 +51,20 @@ public abstract class Host {
*/
public abstract InetAddress getAddress();
/**
* Get the Directory of this Host
*
* @return Host Directory
*/
public abstract String getDirectory();
/**
* Get if the Host can be Edited
*
* @return Editable Status
*/
public abstract boolean isEditable();
/**
* Get the Name of this Host
*
@ -124,6 +142,13 @@ public abstract class Host {
*/
public abstract void command(UUID player, String command, String... servers);
/**
* Applies edits to the Host
*
* @param change Change(s) to be applied
*/
public abstract void edit(NamedContainer<String, ?>... change);
/**
* Gets the SubCreator Instance for this Host
*
@ -159,11 +184,12 @@ public abstract class Host {
* @param executable Executable
* @param stopcmd Command to Stop the Server
* @param restart Auto Restart Status
* @param restricted Players will need a permission to join if true
* @param temporary Temporary Status
* @return The SubServer
* @throws InvalidServerException
*/
public abstract SubServer addSubServer(UUID player, String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean temporary) throws InvalidServerException;
public abstract SubServer addSubServer(UUID player, String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean restricted, boolean temporary) throws InvalidServerException;
/**
* Adds a SubServer
@ -177,12 +203,13 @@ public abstract class Host {
* @param executable Executable
* @param stopcmd Command to Stop the Server
* @param restart Auto Restart Status
* @param restricted Players will need a permission to join if true
* @param temporary Temporary Status
* @return The SubServer
* @throws InvalidServerException
*/
public SubServer addSubServer(String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean temporary) throws InvalidServerException {
return addSubServer(null, name, enabled, port, motd, log, directory, executable, stopcmd, start, restart, temporary);
public SubServer addSubServer(String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean restricted, boolean temporary) throws InvalidServerException {
return addSubServer(null, name, enabled, port, motd, log, directory, executable, stopcmd, start, restart, restricted, temporary);
}
/**

View File

@ -1,14 +1,14 @@
package net.ME1312.SubServers.Proxy.Host.Internal;
import net.ME1312.SubServers.Proxy.Event.SubAddServerEvent;
import net.ME1312.SubServers.Proxy.Host.Executable;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubCreator;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Libraries.UniversalFile;
import net.ME1312.SubServers.Proxy.Library.NamedContainer;
import net.ME1312.SubServers.Proxy.SubPlugin;
import java.io.File;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
@ -22,16 +22,16 @@ public class InternalHost extends Host {
private boolean enabled;
private InetAddress address;
private InternalSubCreator creator;
UniversalFile directory;
private String directory;
SubPlugin plugin;
public InternalHost(SubPlugin plugin, String name, Boolean enabled, InetAddress address, UniversalFile directory) {
super(plugin, name, enabled, address, directory);
public InternalHost(SubPlugin plugin, String name, Boolean enabled, InetAddress address, String directory, String gitBash) {
super(plugin, name, enabled, address, directory, gitBash);
this.plugin = plugin;
this.name = name;
this.enabled = enabled;
this.address = address;
this.creator = new InternalSubCreator(this);
this.creator = new InternalSubCreator(this, gitBash);
this.directory = directory;
}
@ -50,6 +50,16 @@ public class InternalHost extends Host {
return address;
}
@Override
public String getDirectory() {
return directory;
}
@Override
public boolean isEditable() {
return true;
}
@Override
public String getName() {
return name;
@ -83,6 +93,15 @@ public class InternalHost extends Host {
}
}
@Override
public void edit(NamedContainer<String, ?>... changes) {
for (NamedContainer<String, ?> change : changes) {
switch (change.name().toLowerCase()) {
// TODO SubEditor
}
}
}
@Override
public SubCreator getCreator() {
return creator;
@ -99,11 +118,17 @@ public class InternalHost extends Host {
}
@Override
public SubServer addSubServer(UUID player, String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean temporary) throws InvalidServerException {
if (plugin.getServers().keySet().contains(name.toLowerCase())) throw new InvalidServerException("A Server already exists with this name!");
SubServer server = new InternalSubServer(this, name, enabled, port, motd, log, directory, executable, stopcmd, start, restart, temporary);
servers.put(name.toLowerCase(), server);
return server;
public SubServer addSubServer(UUID player, String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean restricted, boolean temporary) throws InvalidServerException {
if (plugin.api.getServers().keySet().contains(name.toLowerCase())) throw new InvalidServerException("A Server already exists with this name!");
SubServer server = new InternalSubServer(this, name, enabled, port, motd, log, directory, executable, stopcmd, start, restart, restricted, temporary);
SubAddServerEvent event = new SubAddServerEvent(player, this, server);
plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
servers.put(name.toLowerCase(), server);
return server;
} else {
return null;
}
}
@Override

View File

@ -1,27 +1,524 @@
package net.ME1312.SubServers.Proxy.Host.Internal;
import net.ME1312.SubServers.Proxy.Event.SubCreateEvent;
import net.ME1312.SubServers.Proxy.Host.Executable;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubCreator;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Library.Config.YAMLSection;
import net.ME1312.SubServers.Proxy.Library.Container;
import net.ME1312.SubServers.Proxy.Library.UniversalFile;
import net.ME1312.SubServers.Proxy.Library.Util;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.UUID;
public class InternalSubCreator extends SubCreator {
private Host host;
private InternalHost host;
private String gitBash;
private Thread thread = null;
public InternalSubCreator(Host host) {
this.host = host;
public InternalSubCreator(Host host, String gitBash) {
this.host = (InternalHost) host;
this.gitBash = gitBash;
}
private void GenerateEULA(File dir) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(new File(dir, "eula.txt"), "UTF-8");
writer.println("#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).");
writer.println("#" + new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy").format(Calendar.getInstance().getTime()));
writer.println("eula=true");
writer.close();
}
private void GenerateProperties(File dir, int port) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(new File(dir, "server.properties"), "UTF-8");
writer.println("#Minecraft server properties");
writer.println("#" + new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy").format(Calendar.getInstance().getTime()));
writer.println("generator-settings=");
writer.println("op-permission-level=4");
writer.println("allow-nether=true");
writer.println("resource-pack-hash=");
writer.println("level-name=world");
writer.println("enable-query=true");
writer.println("allow-flight=false");
writer.println("announce-player-achievements=false");
writer.println("server-port=" + port);
writer.println("max-world-size=29999984");
writer.println("level-type=DEFAULT");
writer.println("enable-rcon=false");
writer.println("level-seed=");
writer.println("force-gamemode=false");
writer.println("server-ip=" + host.getAddress().toString().substring(1));
writer.println("network-compression-threshold=-1");
writer.println("max-build-height=256");
writer.println("spawn-npcs=true");
writer.println("white-list=false");
writer.println("spawn-animals=true");
writer.println("snooper-enabled=true");
writer.println("online-mode=false");
writer.println("resource-pack=");
writer.println("pvp=true");
writer.println("difficulty=1");
writer.println("enable-command-block=true");
writer.println("gamemode=0");
writer.println("player-idle-timeout=0");
writer.println("max-players=20");
writer.println("max-tick-time=60000");
writer.println("spawn-monsters=true");
writer.println("generate-structures=true");
writer.println("view-distance=10");
writer.println("motd=A Generated SubServer");
writer.close();
}
private void GenerateSpigotYAML(File dir) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(new File(dir, "spigot.yml"), "UTF-8");
writer.println("# This is the main configuration file for Spigot.");
writer.println("# As you can see, there's tons to configure. Some options may impact gameplay, so use");
writer.println("# with caution, and make sure you know what each option does before configuring.");
writer.println("# For a reference for any variable inside this file, check out the Spigot wiki at");
writer.println("# http://www.spigotmc.org/wiki/spigot-configuration/");
writer.println("#");
writer.println("# If you need help with the configuration or have any questions related to Spigot,");
writer.println("# join us at the IRC or drop by our forums and leave a post.");
writer.println("#");
writer.println("# IRC: #spigot @ irc.spi.gt ( http://www.spigotmc.org/pages/irc/ )");
writer.println("# Forums: http://www.spigotmc.org/");
writer.println();
writer.println("config-version: 8");
writer.println("settings:");
writer.println(" debug: false");
writer.println(" save-user-cache-on-stop-only: false");
writer.println(" bungeecord: true");
writer.println(" late-bind: false");
writer.println(" sample-count: 12");
writer.println(" player-shuffle: 0");
writer.println(" filter-creative-items: true");
writer.println(" user-cache-size: 1000");
writer.println(" int-cache-limit: 1024");
writer.println(" moved-wrongly-threshold: 0.0625");
writer.println(" moved-too-quickly-threshold: 100.0");
writer.println(" timeout-time: 60");
writer.println(" restart-on-crash: false");
writer.println(" restart-script: ./start.sh");
writer.println(" netty-threads: 4");
writer.println(" attribute:");
writer.println(" maxHealth:");
writer.println(" max: 2048.0");
writer.println(" movementSpeed:");
writer.println(" max: 2048.0");
writer.println(" attackDamage:");
writer.println(" max: 2048.0");
writer.println("commands:");
writer.println(" tab-complete: 0");
writer.println(" log: true");
writer.println(" spam-exclusions:");
writer.println(" - /skill");
writer.println(" silent-commandblock-console: true");
writer.println(" replace-commands:");
writer.println(" - setblock");
writer.println(" - summon");
writer.println(" - testforblock");
writer.println(" - tellraw");
writer.println("messages:");
writer.println(" whitelist: You are not whitelisted on this server!");
writer.println(" unknown-command: Unknown command. Type \"/help\" for help.");
writer.println(" server-full: The server is full!");
writer.println(" outdated-client: Outdated client! Please use {0}");
writer.println(" outdated-server: Outdated server! I'm still on {0}");
writer.println(" restart: Server is restarting");
writer.println("stats:");
writer.println(" disable-saving: false");
writer.println(" forced-stats: {}");
writer.println("world-settings:");
writer.println(" default:");
writer.println(" verbose: true");
writer.println(" wither-spawn-sound-radius: 0");
writer.println(" view-distance: 10");
writer.println(" item-despawn-rate: 6000");
writer.println(" merge-radius:");
writer.println(" item: 2.5");
writer.println(" exp: 3.0");
writer.println(" arrow-despawn-rate: 1200");
writer.println(" enable-zombie-pigmen-portal-spawns: true");
writer.println(" zombie-aggressive-towards-villager: true");
writer.println(" hanging-tick-frequency: 100");
writer.println(" max-bulk-chunks: 10");
writer.println(" max-entity-collisions: 8");
writer.println(" random-light-updates: false");
writer.println(" save-structure-info: true");
writer.println(" mob-spawn-range: 4");
writer.println(" anti-xray:");
writer.println(" enabled: true");
writer.println(" engine-mode: 1");
writer.println(" hide-blocks:");
writer.println(" - 14");
writer.println(" - 15");
writer.println(" - 16");
writer.println(" - 21");
writer.println(" - 48");
writer.println(" - 49");
writer.println(" - 54");
writer.println(" - 56");
writer.println(" - 73");
writer.println(" - 74");
writer.println(" - 82");
writer.println(" - 129");
writer.println(" - 130");
writer.println(" replace-blocks:");
writer.println(" - 1");
writer.println(" - 5");
writer.println(" dragon-death-sound-radius: 0");
writer.println(" seed-village: 10387312");
writer.println(" seed-feature: 14357617");
writer.println(" hunger:");
writer.println(" walk-exhaustion: 0.2");
writer.println(" sprint-exhaustion: 0.8");
writer.println(" combat-exhaustion: 0.3");
writer.println(" regen-exhaustion: 3.0");
writer.println(" max-tnt-per-tick: 100");
writer.println(" max-tick-time:");
writer.println(" tile: 50");
writer.println(" entity: 50");
writer.println(" entity-activation-range:");
writer.println(" animals: 32");
writer.println(" monsters: 32");
writer.println(" misc: 16");
writer.println(" entity-tracking-range:");
writer.println(" players: 48");
writer.println(" animals: 48");
writer.println(" monsters: 48");
writer.println(" misc: 32");
writer.println(" other: 64");
writer.println(" ticks-per:");
writer.println(" hopper-transfer: 8");
writer.println(" hopper-check: 8");
writer.println(" hopper-amount: 1");
writer.println(" growth:");
writer.println(" cactus-modifier: 100");
writer.println(" cane-modifier: 100");
writer.println(" melon-modifier: 100");
writer.println(" mushroom-modifier: 100");
writer.println(" pumpkin-modifier: 100");
writer.println(" sapling-modifier: 100");
writer.println(" wheat-modifier: 100");
writer.println(" netherwart-modifier: 100");
writer.println(" nerf-spawner-mobs: false");
writer.println(" chunks-per-tick: 650");
writer.println(" clear-tick-list: false");
writer.println();
writer.close();
}
private void GenerateSpongeConf(File dir) throws FileNotFoundException, UnsupportedEncodingException {
new File(dir, "config" + File.separator + "sponge").mkdirs();
PrintWriter writer = new PrintWriter(new File(dir, "config" + File.separator + "sponge" + File.separator + "global.conf"), "UTF-8");
writer.println("# 1.0");
writer.println("#");
writer.println("# # If you need help with the configuration or have any questions related to Sponge,");
writer.println("# # join us at the IRC or drop by our forums and leave a post.");
writer.println("#");
writer.println("# # IRC: #sponge @ irc.esper.net ( http://webchat.esper.net/?channel=sponge )");
writer.println("# # Forums: https://forums.spongepowered.org/");
writer.println("#");
writer.println();
writer.println("sponge {");
writer.println(" block-tracking {");
writer.println(" # If enabled, adds player tracking support for block positions. Note: This should only be disabled if you do not care who caused a block to change.");
writer.println(" enabled=true");
writer.println(" }");
writer.println(" bungeecord {");
writer.println(" # If enabled, allows BungeeCord to forward IP address, UUID, and Game Profile to this server");
writer.println(" ip-forwarding=true");
writer.println(" }");
writer.println(" commands {}");
writer.println(" debug {");
writer.println(" # Dump chunks in the event of a deadlock");
writer.println(" dump-chunks-on-deadlock=false");
writer.println(" # Dump the heap in the event of a deadlock");
writer.println(" dump-heap-on-deadlock=false");
writer.println(" # Dump the server thread on deadlock warning");
writer.println(" dump-threads-on-warn=false");
writer.println(" # Enable Java's thread contention monitoring for thread dumps");
writer.println(" thread-contention-monitoring=false");
writer.println(" }");
writer.println(" entity {");
writer.println(" # Number of colliding entities in one spot before logging a warning. Set to 0 to disable");
writer.println(" collision-warn-size=200");
writer.println(" # Number of entities in one dimension before logging a warning. Set to 0 to disable");
writer.println(" count-warn-size=0");
writer.println(" # Number of ticks before a painting is respawned on clients when their art is changed");
writer.println(" entity-painting-respawn-delay=2");
writer.println(" # Number of ticks before the fake player entry of a human is removed from the tab list (range of 0 to 100 ticks).");
writer.println(" human-player-list-remove-delay=10");
writer.println(" # Controls the time in ticks for when an item despawns.");
writer.println(" item-despawn-rate=6000");
writer.println(" # Max size of an entity's bounding box before removing it. Set to 0 to disable");
writer.println(" max-bounding-box-size=1000");
writer.println(" # Square of the max speed of an entity before removing it. Set to 0 to disable");
writer.println(" max-speed=100");
writer.println(" }");
writer.println(" entity-activation-range {");
writer.println(" ambient-activation-range=32");
writer.println(" aquatic-activation-range=32");
writer.println(" creature-activation-range=32");
writer.println(" minecraft {");
writer.println(" creature {");
writer.println(" entityhorse=true");
writer.println(" pig=true");
writer.println(" sheep=true");
writer.println(" }");
writer.println(" enabled=true");
writer.println(" misc {");
writer.println(" item=true");
writer.println(" minecartchest=true");
writer.println(" }");
writer.println(" monster {");
writer.println(" guardian=true");
writer.println(" }");
writer.println(" }");
writer.println(" misc-activation-range=16");
writer.println(" monster-activation-range=32");
writer.println(" }");
writer.println(" general {");
writer.println(" # Forces Chunk Loading on provide requests (speedup for mods that don't check if a chunk is loaded)");
writer.println(" chunk-load-override=false");
writer.println(" # Disable warning messages to server admins");
writer.println(" disable-warnings=false");
writer.println(" }");
writer.println(" logging {");
writer.println(" # Log when blocks are broken");
writer.println(" block-break=false");
writer.println(" # Log when blocks are modified");
writer.println(" block-modify=false");
writer.println(" # Log when blocks are placed");
writer.println(" block-place=false");
writer.println(" # Log when blocks are populated in a chunk");
writer.println(" block-populate=false");
writer.println(" # Log when blocks are placed by players and tracked");
writer.println(" block-tracking=false");
writer.println(" # Log when chunks are loaded");
writer.println(" chunk-load=false");
writer.println(" # Log when chunks are unloaded");
writer.println(" chunk-unload=false");
writer.println(" # Whether to log entity collision/count checks");
writer.println(" entity-collision-checks=false");
writer.println(" # Log when living entities are destroyed");
writer.println(" entity-death=false");
writer.println(" # Log when living entities are despawned");
writer.println(" entity-despawn=false");
writer.println(" # Log when living entities are spawned");
writer.println(" entity-spawn=false");
writer.println(" # Whether to log entity removals due to speed");
writer.println(" entity-speed-removal=false");
writer.println(" # Add stack traces to dev logging");
writer.println(" log-stacktraces=false");
writer.println(" }");
writer.println(" modules {");
writer.println(" bungeecord=true");
writer.println(" entity-activation-range=true");
writer.println(" timings=true");
writer.println(" }");
writer.println(" # Configuration options related to the Sql service, including connection aliases etc");
writer.println(" sql {}");
writer.println(" timings {");
writer.println(" enabled=true");
writer.println(" hidden-config-entries=[");
writer.println(" \"sponge.sql\"");
writer.println(" ]");
writer.println(" history-interval=300");
writer.println(" history-length=3600");
writer.println(" server-name-privacy=false");
writer.println(" verbose=false");
writer.println(" }");
writer.println(" world {");
writer.println(" # Lava behaves like vanilla water when source block is removed");
writer.println(" flowing-lava-decay=false");
writer.println(" # Vanilla water source behavior - is infinite");
writer.println(" infinite-water-source=false");
writer.println(" }");
writer.println("}");
writer.println();
writer.close();
}
private void run(String name, ServerType type, Version version, int memory, int port) {
Executable exec = null;
UniversalFile dir = new UniversalFile(new File(host.getDirectory()), name);
dir.mkdirs();
if (type == ServerType.SPIGOT) {
exec = new Executable("java -Xmx" + memory + "M -Djline.terminal=jline.UnsupportedTerminal -Dcom.mojang.eula.agree=true -jar Spigot.jar");
try {
GenerateSpigotYAML(dir);
GenerateProperties(dir, port);
} catch (IOException e) {
e.printStackTrace();
}
} else if (type == ServerType.VANILLA) {
exec = new Executable("java -Xmx" + memory + "M -jar Vanilla.jar nogui");
try {
GenerateEULA(dir);
GenerateProperties(dir, port);
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (type == ServerType.SPONGE) {
try {
Document spongexml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(Util.readAll(new BufferedReader(new InputStreamReader(new URL("http://files.minecraftforge.net/maven/org/spongepowered/spongeforge/maven-metadata.xml").openStream(), Charset.forName("UTF-8")))))));
Document forgexml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(Util.readAll(new BufferedReader(new InputStreamReader(new URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml").openStream(), Charset.forName("UTF-8")))))));
NodeList spnodeList = spongexml.getElementsByTagName("version");
Version spversion = null;
for (int i = 0; i < spnodeList.getLength(); i++) {
Node node = spnodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getTextContent().startsWith(version.toString() + '-') && (spversion == null || new Version(node.getTextContent()).compareTo(spversion) >= 0)) {
spversion = new Version(node.getTextContent());
}
}
}
NodeList mcfnodeList = forgexml.getElementsByTagName("version");
Version mcfversion = null;
for (int i = 0; i < mcfnodeList.getLength(); i++) {
Node node = mcfnodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getTextContent().contains(spversion.toString().split("\\-")[1]) && (mcfversion == null || new Version(node.getTextContent()).compareTo(mcfversion) >= 0)) {
mcfversion = new Version(node.getTextContent());
}
}
}
exec = new Executable("java -Xmx" + memory + "M -jar Forge.jar");
version = new Version(mcfversion.toString() + "::" + spversion.toString());
GenerateEULA(dir);
GenerateProperties(dir, port);
GenerateSpongeConf(dir);
} catch (ParserConfigurationException | IOException | SAXException | NullPointerException e) {
e.printStackTrace();
}
}
try {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(new UniversalFile(host.plugin.dir, "SubServers:build.sh"));
output = new FileOutputStream(new File(dir, "build-subserver.sh"));
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
if (input != null)
input.close();
if (output != null)
output.close();
}
if (!(new File(dir, "build-subserver.sh").exists())) {
System.out.println("SubCreator > Problem Copying build-subserver.sh!");
} else {
File gitBash = new File(this.gitBash, "bin" + File.separatorChar + "bash.exe");
if (!(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)) {
Process process1 = Runtime.getRuntime().exec("chmod +x build-subserver.sh", null, dir);
try {
process1.waitFor();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (process1.exitValue() != 0) {
System.out.println("SubCreator > Problem Setting Executable Permissions for build-subserver.sh");
System.out.println("SubCreator > This may cause errors in the Build Process");
}
}
Process process2 = Runtime.getRuntime().exec((System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)?
"\"" + gitBash + "\" --login -i -c \"bash build-subserver.sh " + version.toString() + " " + type.toString().toLowerCase() + "\""
:("bash build-subserver.sh " + version.toString() + " " + type.toString().toLowerCase() + " " + System.getProperty("user.home")), null, dir);
InternalSubLogger read = new InternalSubLogger(process2.getInputStream(), host.getName() + "/Creator", new Container<Boolean>(host.plugin.config.get().getSection("Settings").getBoolean("Log-Creator")), new File(dir, "SubCreator-" + type.toString() + "-" + version.toString().replace("::", "@") + ".log"));
read.start();
try {
process2.waitFor();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (process2.exitValue() == 0) {
host.addSubServer(name, true, port, "&aThis is a SubServer", true, dir.getPath(), exec, "stop", true, false, false, false);
YAMLSection server = new YAMLSection();
server.set("Enabled", true);
server.set("Host", host.getName());
server.set("Port", port);
server.set("Motd", "&aThis is a SubServer");
server.set("Log", true);
server.set("Directory", dir.getPath());
server.set("Executable", exec.toString());
server.set("Stop-Command", "stop");
server.set("Run-On-Launch", false);
server.set("Auto-Restart", false);
server.set("Auto-Restart", false);
server.set("Restricted", false);
host.plugin.config.get().getSection("Servers").set(name, server);
host.plugin.config.save();
} else {
System.out.println("SubCreator > build-subserver.sh exited with an errors. Please try again.");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void create(UUID player, String name, int port, File directory, ServerType type, Version version, int memory) {
public void create(UUID player, String name, ServerType type, Version version, int memory, int port) {
if (!isBusy()) {
final SubCreateEvent event = new SubCreateEvent(player, host, name, type, version, memory, port);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
(thread = new Thread(() -> {
InternalSubCreator.this.run(name, event.getType(), event.getVersion(), event.getMemory(), port);
})).start();
}
}
}
@Override
public void waitFor() throws InterruptedException {
while (thread != null && thread.isAlive()) {
Thread.sleep(250);
}
}
@Override
@ -29,8 +526,13 @@ public class InternalSubCreator extends SubCreator {
return host;
}
@Override
public String getGitBashDirectory() {
return gitBash;
}
@Override
public boolean isBusy() {
return false;
return thread != null && thread.isAlive();
}
}

View File

@ -1,6 +1,7 @@
package net.ME1312.SubServers.Proxy.Host.Internal;
import net.ME1312.SubServers.Proxy.Libraries.Container;
import net.ME1312.SubServers.Proxy.Library.Container;
import net.md_5.bungee.api.ProxyServer;
import java.io.*;
import java.util.regex.Matcher;
@ -35,16 +36,29 @@ public class InternalSubLogger extends Thread {
while ((line = br.readLine()) != null) {
if (log.get() && !line.startsWith(">")) {
String msg = line;
/* REGEX Formatting
// REGEX Formatting
String type = "INFO";
Matcher matcher = Pattern.compile("^((?:\\s*\\[?[0-9]{2}:[0-9]{2}:[0-9]{2}]?)?\\s*(?:\\[|\\[.*\\/)?(INFO|WARN|WARNING|ERROR|ERR|SEVERE)\\]:?\\s*)").matcher(msg);
while (matcher.find()) {
type = matcher.group(2);
}
*/
msg = msg.replaceAll("^((?:\\s*\\[?[0-9]{2}:[0-9]{2}:[0-9]{2}]?)?\\s*(?:\\[|\\[.*\\/)?(INFO|WARN|WARNING|ERROR|ERR|SEVERE)\\]:?\\s*)", "");
System.out.println(name + " > " + msg);
switch (type) {
case "INFO":
ProxyServer.getInstance().getLogger().info(name + " > " + msg);
break;
case "WARNING":
case "WARN":
ProxyServer.getInstance().getLogger().warning(name + " > " + msg);
break;
case "SEVERE":
case "ERROR":
case "ERR":
ProxyServer.getInstance().getLogger().severe(name + " > " + msg);
break;
}
if (writer != null) {
writer.println(line);

View File

@ -5,17 +5,16 @@ import net.ME1312.SubServers.Proxy.Event.SubStartEvent;
import net.ME1312.SubServers.Proxy.Event.SubStopEvent;
import net.ME1312.SubServers.Proxy.Event.SubStoppedEvent;
import net.ME1312.SubServers.Proxy.Host.Executable;
import net.ME1312.SubServers.Proxy.Libraries.Container;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.Container;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Library.NamedContainer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class InternalSubServer extends SubServer {
@ -26,21 +25,22 @@ public class InternalSubServer extends SubServer {
private Executable executable;
private String stopcmd;
private Process process;
private List<String> queue;
private BufferedWriter command;
private boolean restart;
private boolean allowrestart;
private boolean temporary;
private InternalSubServer instance;
public InternalSubServer(Host host, String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean temporary) throws InvalidServerException {
super(host, name, port, motd);
public InternalSubServer(Host host, String name, boolean enabled, int port, String motd, boolean log, String directory, Executable executable, String stopcmd, boolean start, boolean restart, boolean restricted, boolean temporary) throws InvalidServerException {
super(host, name, port, motd, restricted);
this.host = (InternalHost) host;
this.enabled = enabled;
this.log = new Container<Boolean>(log);
this.directory = new File(((InternalHost) host).directory, directory);
this.directory = new File(host.getDirectory(), directory);
this.executable = executable;
this.stopcmd = stopcmd;
this.process = null;
this.queue = new ArrayList<String>();
this.command = null;
this.restart = restart;
this.temporary = temporary;
this.instance = this;
@ -49,82 +49,54 @@ public class InternalSubServer extends SubServer {
}
private void run() {
new Thread() {
public void run() {
final Container<Boolean> allowRestart = new Container<Boolean>(true);
new Thread(() -> {
allowrestart = true;
try {
process = Runtime.getRuntime().exec(executable.toString(), null, directory);
System.out.println("SubServers > Now starting " + instance.getName());
final InternalSubLogger read = new InternalSubLogger(process.getInputStream(), instance.getName(), log, null);
read.start();
command = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
try {
process = Runtime.getRuntime().exec(executable.toString(), null, directory);
System.out.println("SubServers > Now starting " + instance.getName());
final InternalSubLogger read = new InternalSubLogger(process.getInputStream(), instance.getName(), log, null);
read.start();
final BufferedWriter cmd = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
new Thread() {
@Override
public void run() {
try {
do {
if (!queue.isEmpty()) {
while (queue.size() > 0) {
try {
if (queue.get(0).equalsIgnoreCase(stopcmd)) allowRestart.set(false);
cmd.write(queue.get(0));
cmd.newLine();
cmd.flush();
queue.remove(0);
Thread.sleep(100);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Thread.sleep(500);
} while (read.isAlive());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
allowRestart.set(false);
}
} catch (IOException e) {
e.printStackTrace();
allowrestart = false;
}
SubStoppedEvent event = new SubStoppedEvent(instance);
host.plugin.getPluginManager().callEvent(event);
System.out.println("SubServers > " + instance.getName() + " has stopped");
process = null;
queue.clear();
SubStoppedEvent event = new SubStoppedEvent(instance);
host.plugin.getPluginManager().callEvent(event);
System.out.println("SubServers > " + instance.getName() + " has stopped");
process = null;
command = null;
if (temporary) {
if (temporary) {
try {
host.removeSubServer(instance.getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (restart && allowrestart) {
try {
host.removeSubServer(instance.getName());
Thread.sleep(2500);
start();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (restart && allowRestart.get()) {
try {
Thread.sleep(2500);
start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
}).start();
}
@Override
public void start(UUID player) {
if (enabled && !isRunning()) {
SubStartEvent event = new SubStartEvent(this, player);
SubStartEvent event = new SubStartEvent(player, this);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
run();
@ -135,10 +107,17 @@ public class InternalSubServer extends SubServer {
@Override
public void stop(UUID player) {
if (isRunning()) {
SubStopEvent event = new SubStopEvent(this, player, false);
SubStopEvent event = new SubStopEvent(player, this, false);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
queue.add(stopcmd);
try {
command.write(stopcmd);
command.newLine();
command.flush();
allowrestart = false;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@ -146,7 +125,7 @@ public class InternalSubServer extends SubServer {
@Override
public void terminate(UUID player) {
if (isRunning()) {
SubStopEvent event = new SubStopEvent(this, player, true);
SubStopEvent event = new SubStopEvent(player, this, true);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
process.destroyForcibly();
@ -157,10 +136,25 @@ public class InternalSubServer extends SubServer {
@Override
public void command(UUID player, String command) {
if (isRunning()) {
SubSendCommandEvent event = new SubSendCommandEvent(this, player, command);
SubSendCommandEvent event = new SubSendCommandEvent(player, this, command);
host.plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
queue.add(command);
try {
this.command.write(event.getCommand());
this.command.newLine();
this.command.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void edit(NamedContainer<String, ?>... changes) {
for (NamedContainer<String, ?> change : changes) {
switch (change.name().toLowerCase()) {
// TODO SubEditor
}
}
}
@ -192,6 +186,11 @@ public class InternalSubServer extends SubServer {
enabled = value;
}
@Override
public boolean isEditable() {
return host.isEditable() && !isRunning();
}
@Override
public boolean isLogging() {
return log.get();

View File

@ -1,6 +1,6 @@
package net.ME1312.SubServers.Proxy.Host;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.ClientHandler;
import net.md_5.bungee.BungeeServerInfo;

View File

@ -1,6 +1,6 @@
package net.ME1312.SubServers.Proxy.Host;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import java.io.File;
import java.util.UUID;
@ -13,19 +13,20 @@ import java.util.UUID;
public abstract class SubCreator {
public enum ServerType {
SPIGOT,
BUKKIT,
VANILLA,
SPONGE,
}
public abstract void create(UUID player, String name, int port, File directory, ServerType type, Version version, int memory);
public void create(String name, int port, File directory, ServerType type, Version version, int memory) {
create(null, name, port, directory, type, version, memory);
public abstract void create(UUID player, String name, ServerType type, Version version, int memory, int port);
public void create(String name, ServerType type, Version version, int memory, int port) {
create(null, name, type, version, memory, port);
}
public abstract void waitFor() throws InterruptedException;
public abstract Host getHost();
public abstract String getGitBashDirectory();
public abstract boolean isBusy();
}

View File

@ -1,6 +1,7 @@
package net.ME1312.SubServers.Proxy.Host;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.NamedContainer;
import java.net.InetSocketAddress;
import java.util.UUID;
@ -19,10 +20,11 @@ public abstract class SubServer extends Server {
* @param name Server Name
* @param port Port Number
* @param motd Server MOTD
* @param restricted Players will need a permission to join if true
* @throws InvalidServerException
*/
public SubServer(Host host, String name, int port, String motd) throws InvalidServerException {
super(name, InetSocketAddress.createUnresolved(host.getAddress().getHostAddress(), port), motd, false);
public SubServer(Host host, String name, int port, String motd, boolean restricted) throws InvalidServerException {
super(name, InetSocketAddress.createUnresolved(host.getAddress().getHostAddress(), port), motd, restricted);
}
/**
@ -84,6 +86,13 @@ public abstract class SubServer extends Server {
command(null, command);
}
/**
* Applies edits to the SubServer
*
* @param change Change(s) to be applied
*/
public abstract void edit(NamedContainer<String, ?>... change);
/**
* Waits for the Server to Stop
*
@ -119,6 +128,13 @@ public abstract class SubServer extends Server {
*/
public abstract void setEnabled(boolean value);
/**
* Get if the SubServer can be Edited
*
* @return Editable Status
*/
public abstract boolean isEditable();
/**
* If the Server is Logging
*

View File

@ -25,6 +25,7 @@ public final class Launch {
* @param args
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
System.out.println("");
System.out.println("*******************************************");

View File

@ -1,3 +0,0 @@
Version: '2.11.0a+'
Lang:
'Console-Only-Command': '&4Console Access Only.'

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Config;
package net.ME1312.SubServers.Proxy.Library.Config;
import org.json.JSONObject;
import org.yaml.snakeyaml.DumperOptions;

View File

@ -1,5 +1,6 @@
package net.ME1312.SubServers.Proxy.Libraries.Config;
package net.ME1312.SubServers.Proxy.Library.Config;
import net.ME1312.SubServers.Proxy.Library.Util;
import net.md_5.bungee.api.ChatColor;
import org.json.JSONObject;
import org.yaml.snakeyaml.Yaml;
@ -29,6 +30,10 @@ public class YAMLSection {
this.map = (Map<String, Object>) (this.yaml = new Yaml(YAMLConfig.getDumperOptions())).load(reader);
}
public YAMLSection(JSONObject json) {
this.map = (Map<String, Object>) (this.yaml = new Yaml(YAMLConfig.getDumperOptions())).load(json.toString(4));
}
public YAMLSection(String yaml) throws YAMLException {
this.map = (Map<String, Object>) (this.yaml = new Yaml(YAMLConfig.getDumperOptions())).load(yaml);
}
@ -341,18 +346,18 @@ public class YAMLSection {
}
public String getString(String label) {
return (map.get(label) != null)?unescapeJavaString((String) map.get(label)):null;
return (map.get(label) != null)?Util.unescapeJavaString((String) map.get(label)):null;
}
public String getString(String label, String def) {
return unescapeJavaString((String) ((map.get(label) != null) ? map.get(label) : def));
return Util.unescapeJavaString((String) ((map.get(label) != null) ? map.get(label) : def));
}
public List<String> getStringList(String label) {
if (map.get(label) != null) {
List<String> values = new ArrayList<String>();
for (String value : (List<String>) map.get(label)) {
values.add(unescapeJavaString(value));
values.add(Util.unescapeJavaString(value));
}
return values;
} else {
@ -366,25 +371,25 @@ public class YAMLSection {
} else {
List<String> values = new ArrayList<String>();
for (String value : def) {
values.add(unescapeJavaString(value));
values.add(Util.unescapeJavaString(value));
}
return values;
}
}
public String getColoredString(String label, char color) {
return (map.get(label) != null)? ChatColor.translateAlternateColorCodes(color, unescapeJavaString((String) map.get(label))):null;
return (map.get(label) != null)? ChatColor.translateAlternateColorCodes(color, Util.unescapeJavaString((String) map.get(label))):null;
}
public String getColoredString(String label, String def, char color) {
return ChatColor.translateAlternateColorCodes(color, unescapeJavaString((String) ((map.get(label) != null) ? map.get(label) : def)));
return ChatColor.translateAlternateColorCodes(color, Util.unescapeJavaString((String) ((map.get(label) != null) ? map.get(label) : def)));
}
public List<String> getColoredStringList(String label, char color) {
if (map.get(label) != null) {
List<String> values = new ArrayList<String>();
for (String value : (List<String>) map.get(label)) {
values.add(ChatColor.translateAlternateColorCodes(color, unescapeJavaString(value)));
values.add(ChatColor.translateAlternateColorCodes(color, Util.unescapeJavaString(value)));
}
return values;
} else {
@ -398,7 +403,7 @@ public class YAMLSection {
} else {
List<String> values = new ArrayList<String>();
for (String value : def) {
values.add(ChatColor.translateAlternateColorCodes(color, unescapeJavaString(value)));
values.add(ChatColor.translateAlternateColorCodes(color, Util.unescapeJavaString(value)));
}
return values;
}
@ -435,75 +440,4 @@ public class YAMLSection {
public boolean isString(String label) {
return (map.get(label) instanceof String);
}
static String unescapeJavaString(String str) {
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '\\') {
char nextChar = (i == str.length() - 1) ? '\\' : str
.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < str.length() - 1) && str.charAt(i + 1) >= '0'
&& str.charAt(i + 1) <= '7') {
code += str.charAt(i + 1);
i++;
if ((i < str.length() - 1) && str.charAt(i + 1) >= '0'
&& str.charAt(i + 1) <= '7') {
code += str.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= str.length() - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + str.charAt(i + 2) + str.charAt(i + 3)
+ str.charAt(i + 4) + str.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}

View File

@ -1,5 +1,6 @@
package net.ME1312.SubServers.Proxy.Libraries.Config;
package net.ME1312.SubServers.Proxy.Library.Config;
import net.ME1312.SubServers.Proxy.Library.Util;
import net.md_5.bungee.api.ChatColor;
import org.yaml.snakeyaml.Yaml;
@ -94,25 +95,25 @@ public class YAMLValue {
}
public String asString() {
return YAMLSection.unescapeJavaString((String) obj);
return Util.unescapeJavaString((String) obj);
}
public List<String> asStringList() {
List<String> values = new ArrayList<String>();
for (String value : (List<String>) obj) {
values.add(YAMLSection.unescapeJavaString(value));
values.add(Util.unescapeJavaString(value));
}
return values;
}
public String asColoredString(char color) {
return ChatColor.translateAlternateColorCodes(color, YAMLSection.unescapeJavaString((String) obj));
return ChatColor.translateAlternateColorCodes(color, Util.unescapeJavaString((String) obj));
}
public List<String> asColoredStringList(char color) {
List<String> values = new ArrayList<String>();
for (String value : (List<String>) obj) {
values.add(ChatColor.translateAlternateColorCodes(color, YAMLSection.unescapeJavaString(value)));
values.add(ChatColor.translateAlternateColorCodes(color, Util.unescapeJavaString(value)));
}
return values;
}

View File

@ -1,19 +1,19 @@
package net.ME1312.SubServers.Proxy.Libraries;
package net.ME1312.SubServers.Proxy.Library;
/**
* Container Class
*
* @author ME1312
*/
public class Container<T> {
private T obj;
public class Container<V> {
private V obj;
/**
* Creates a Container
*
* @param item Object to Store
*/
public Container(T item) {
public Container(V item) {
obj = item;
}
@ -22,7 +22,7 @@ public class Container<T> {
*
* @return The Object
*/
public T get() {
public V get() {
return obj;
}
@ -31,7 +31,7 @@ public class Container<T> {
*
* @param value Object to Store
*/
public void set(T value) {
public void set(V value) {
obj = value;
}
}

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Exception;
package net.ME1312.SubServers.Proxy.Library.Exception;
public class IllegalPacketException extends IllegalStateException {
public IllegalPacketException() {}

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Exception;
package net.ME1312.SubServers.Proxy.Library.Exception;
public class InvalidDriverException extends IllegalStateException {
public InvalidDriverException() {}

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Exception;
package net.ME1312.SubServers.Proxy.Library.Exception;
public class InvalidHostException extends IllegalStateException {
public InvalidHostException() {}

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Exception;
package net.ME1312.SubServers.Proxy.Library.Exception;
public class InvalidServerException extends IllegalStateException {
public InvalidServerException() {}

View File

@ -1,30 +1,29 @@
Settings:
Version: '2.11.0a+'
Git-Bash: 'C:\Program Files\Git'
Log-Creator: true
Enable-Graphic-Interface: true
Update-External-Files: true
SubData:
Address: '127.0.0.1:4391'
Password: 'password123'
Allowed-Connections: []
Hosts:
'~':
'~Built-In':
Enabled: true
Driver: 'BUILT-IN'
Address: '127.0.0.1'
Directory: './'
Git-Bash: 'C:\Program Files\Git'
Servers:
'Server_1':
Enabled: false
Host: '~'
Host: '~Built-In'
Port: 25566
Motd: '&aThis is a SubServer'
Log: true
Directory: '~/Server_1'
Directory: './Server_1'
Executable: 'java -Djline.terminal=jline.UnsupportedTerminal -jar Spigot.jar'
Stop-Command: 'stop'
Run-On-Launch: false
Auto-Restart: false
Auto-Restart: false
Restricted: false

View File

@ -0,0 +1,22 @@
Version: '2.11.0a+'
Lang:
'Interface.Generic.Back': '&cBack'
'Interface.Generic.Back-Arrow': '&e&l<--'
'Interface.Generic.Next-Arrow': '&e&l-->'
'Interface.Host-Menu.Title': 'Host Menu'
'Interface.Host-Menu.Host-Disabled': '&4Disabled'
'Interface.Host-Menu.Host-Server-Count': '&9$int$ Servers'
'Interface.Host-Menu.No-Hosts': '&4&oThere are No Hosts'
'Interface.Host-Menu.SubServer-Menu': '&a&lSubServer Menu'
'Interface.Host-Admin.Title': 'Host/$str$'
'Interface.Host-Creator.Title': 'Host/$str$/Create'
'Interface.Host-Editor.Title': 'Host/$str$/Edit'
'Interface.Host-SubServer.Title': 'Host/$str$/SubServers'
'Interface.SubServer-Menu.Title': 'SubServer Menu'
'Interface.SubServer-Menu.SubServer-Player-Count': '&e$int$ Players Online'
'Interface.SubServer-Menu.SubServer-Online': '&2Online'
'Interface.SubServer-Menu.SubServer-Temporary': '&9Temporary'
'Interface.SubServer-Menu.SubServer-Offline': '&6Offline'
'Interface.SubServer-Menu.SubServer-Disabled': '&4Disabled'
'Interface.SubServer-Menu.No-SubServers': '&4&oThere are No SubServers'
'Interface.SubServer-Menu.Host-Menu': '&b&lHost Menu'

View File

@ -0,0 +1,7 @@
package net.ME1312.SubServers.Proxy.Library;
import org.json.JSONObject;
public interface JSONCallback {
void run(JSONObject json);
}

View File

@ -0,0 +1,34 @@
package net.ME1312.SubServers.Proxy.Library;
public class NamedContainer<T, V> extends Container<V> {
private T name;
/**
* Creates a TaggedContainer
*
* @param name Tag to Bind
* @param item Object to Store
*/
public NamedContainer(T name, V item) {
super(item);
this.name = name;
}
/**
* Gets the name of the Container
*
* @return Container name
*/
public T name() {
return name;
}
/**
* Renames the Container
*
* @param name New Container Name
*/
public void rename(T name) {
this.name = name;
}
}

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries;
package net.ME1312.SubServers.Proxy.Library;
import java.io.File;

View File

@ -0,0 +1,111 @@
package net.ME1312.SubServers.Proxy.Library;
import java.io.*;
public final class Util {
public static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static void copyFromJar(ClassLoader loader, String resource, String destination) {
InputStream resStreamIn = loader.getResourceAsStream(resource);
File resDestFile = new File(destination);
try {
OutputStream resStreamOut = new FileOutputStream(resDestFile);
int readBytes;
byte[] buffer = new byte[4096];
while ((readBytes = resStreamIn.read(buffer)) > 0) {
resStreamOut.write(buffer, 0, readBytes);
}
resStreamOut.close();
resStreamIn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static boolean isException(Runnable runnable) {
try {
runnable.run();
return false;
} catch (Throwable e) {
return true;
}
}
public static String unescapeJavaString(String str) {
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '\\') {
char nextChar = (i == str.length() - 1) ? '\\' : str
.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < str.length() - 1) && str.charAt(i + 1) >= '0'
&& str.charAt(i + 1) <= '7') {
code += str.charAt(i + 1);
i++;
if ((i < str.length() - 1) && str.charAt(i + 1) >= '0'
&& str.charAt(i + 1) <= '7') {
code += str.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= str.length() - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + str.charAt(i + 2) + str.charAt(i + 3)
+ str.charAt(i + 4) + str.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Version;
package net.ME1312.SubServers.Proxy.Library.Version;
import java.io.Serializable;

View File

@ -1,4 +1,4 @@
package net.ME1312.SubServers.Proxy.Libraries.Version;
package net.ME1312.SubServers.Proxy.Library.Version;
public final class VersionTokenizer {
private final String _versionString;

View File

@ -1,6 +1,6 @@
package net.ME1312.SubServers.Proxy.Network;
import net.ME1312.SubServers.Proxy.Libraries.Exception.IllegalPacketException;
import net.ME1312.SubServers.Proxy.Library.Exception.IllegalPacketException;
import net.ME1312.SubServers.Proxy.Network.Packet.PacketAuthorization;
import net.ME1312.SubServers.Proxy.SubPlugin;
import org.json.JSONException;
@ -11,10 +11,9 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
@ -23,11 +22,11 @@ import java.util.TimerTask;
*
* @author ME1312
*/
public class Client {
public final class Client {
private Socket socket;
private SocketAddress address;
private InetSocketAddress address;
private ClientHandler handler;
private List<PacketOut> queue = new ArrayList<PacketOut>();
private PrintWriter writer;
private Timer authorized;
private SubPlugin plugin;
private Client instance;
@ -38,10 +37,11 @@ public class Client {
* @param plugin SubPlugin
* @param client Socket to Bind
*/
public Client(SubPlugin plugin, Socket client) {
public Client(SubPlugin plugin, Socket client) throws IOException {
this.plugin = plugin;
socket = client;
address = client.getRemoteSocketAddress();
writer = new PrintWriter(client.getOutputStream(), true);
address = new InetSocketAddress(client.getInetAddress(), client.getPort());
instance = this;
authorized = new Timer("auth" + client.getRemoteSocketAddress().toString());
authorized.schedule(new TimerTask() {
@ -61,73 +61,41 @@ public class Client {
* Network Loop
*/
protected void loop() {
new Thread() {
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String input;
while ((input = in.readLine()) != null) {
try {
JSONObject json = new JSONObject(input);
PacketIn packet = plugin.subdata.decodePacket(json);
if (authorized == null || packet instanceof PacketAuthorization) {
try {
packet.execute(instance, (json.keySet().contains("c")) ? json.getJSONObject("c") : null);
} catch (Exception e) {
new InvocationTargetException(e, "Exception while executing PacketIn").printStackTrace();
}
}
} catch (IllegalPacketException e) {
e.printStackTrace();
} catch (JSONException e) {
new IllegalPacketException("Unknown Packet Format: " + input).printStackTrace();
}
}
new Thread(() -> {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String input;
while ((input = in.readLine()) != null) {
try {
plugin.subdata.removeClient(instance);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
if (e.getMessage() == null || !e.getMessage().equals("Socket closed")) e.printStackTrace();
try {
plugin.subdata.removeClient(instance);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (!socket.isClosed()) {
while (queue.size() > 0) {
JSONObject json = new JSONObject(input);
PacketIn packet = SubDataServer.decodePacket(json);
if (authorized == null || packet instanceof PacketAuthorization) {
try {
out.println(plugin.subdata.encodePacket(queue.get(0)));
queue.remove(0);
} catch (IllegalPacketException e) {
e.printStackTrace();
packet.execute(instance, (json.keySet().contains("c")) ? json.getJSONObject("c") : null);
} catch (Exception e) {
new InvocationTargetException(e, "Exception while executing PacketIn").printStackTrace();
}
}
sleep(100);
}
try {
plugin.subdata.removeClient(instance);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
if (e.getMessage() == null || !e.getMessage().equals("Socket closed")) e.printStackTrace();
try {
plugin.subdata.removeClient(instance);
} catch (IOException e1) {
e1.printStackTrace();
} catch (IllegalPacketException e) {
e.printStackTrace();
} catch (JSONException e) {
new IllegalPacketException("Unknown Packet Format: " + input).printStackTrace();
}
}
try {
plugin.subdata.removeClient(instance);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
if (e.getMessage() == null || !e.getMessage().equals("Socket closed")) e.printStackTrace();
try {
plugin.subdata.removeClient(instance);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}.start();
}).start();
}
/**
@ -147,7 +115,11 @@ public class Client {
* @param packet Packet to send
*/
public void sendPacket(PacketOut packet) {
queue.add(packet);
try {
writer.println(SubDataServer.encodePacket(packet));
} catch (IllegalPacketException e) {
e.printStackTrace();
}
}
/**
@ -164,7 +136,7 @@ public class Client {
*
* @return Address
*/
public SocketAddress getAddress() {
public InetSocketAddress getAddress() {
return address;
}

View File

@ -1,6 +1,6 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
@ -23,7 +23,10 @@ public class PacketAuthorization implements PacketIn, PacketOut {
@Override
public JSONObject generate() {
return new JSONObject("{\"r\": " + response + ", \"" + message.replace("\"", "\\\"") + "\"}");
JSONObject json = new JSONObject();
json.put("r", response);
json.put("m", message);
return json;
}
@Override

View File

@ -0,0 +1,55 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Library.UniversalFile;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.LinkedList;
public class PacketDownloadBuildScript implements PacketIn, PacketOut {
private SubPlugin plugin;
private String id;
public PacketDownloadBuildScript(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketDownloadBuildScript(SubPlugin plugin, String id) {
this.plugin = plugin;
this.id = id;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
json.put("id", id);
try {
LinkedList<String> list = new LinkedList<String>();
BufferedReader script = new BufferedReader(new FileReader(new UniversalFile(plugin.dir, "SubServers:build.sh")));
String line;
while ((line = script.readLine()) != null) {
list.add(line);
}
script.close();
json.put("Script", list);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(new PacketDownloadBuildScript(plugin, (data != null && data.keySet().contains("id"))?data.getString("id"):null));
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -0,0 +1,80 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import org.json.JSONObject;
public class PacketDownloadHostInfo implements PacketIn, PacketOut {
private SubPlugin plugin;
private Host host;
private String id;
public PacketDownloadHostInfo(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketDownloadHostInfo(SubPlugin plugin, Host host, String id) {
this.plugin = plugin;
this.host = host;
this.id = id;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
json.put("id", id);
JSONObject info = new JSONObject();
if (host != null) {
json.put("valid", true);
info.put("name", host.getName());
info.put("enabled", host.isEnabled());
info.put("editable", host.isEditable());
info.put("address", host.getAddress().toString());
info.put("dir", host.getDirectory());
JSONObject cinfo = new JSONObject();
cinfo.put("busy", host.getCreator().isBusy());
cinfo.put("git-bash", host.getCreator().getGitBashDirectory());
info.put("creator", cinfo);
JSONObject servers = new JSONObject();
for (SubServer server : host.getSubServers().values()) {
JSONObject sinfo = new JSONObject();
sinfo.put("enabled", server.isEnabled());
sinfo.put("running", server.isRunning());
sinfo.put("temp", server.isTemporary());
JSONObject players = new JSONObject();
for (ProxiedPlayer player : server.getPlayers()) {
JSONObject pinfo = new JSONObject();
pinfo.put("name", player.getName());
pinfo.put("nick", player.getDisplayName());
players.put(player.getUniqueId().toString(), pinfo);
}
sinfo.put("players", players);
servers.put(server.getName(), sinfo);
}
info.put("servers", servers);
} else json.put("valid", false);
json.put("host", info);
return json;
}
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(new PacketDownloadHostInfo(plugin, plugin.api.getHost(data.getString("host")), (data.keySet().contains("id"))?data.getString("id"):null));
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -0,0 +1,39 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import org.json.JSONObject;
public class PacketDownloadLang implements PacketIn, PacketOut {
private SubPlugin plugin;
private String id;
public PacketDownloadLang(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketDownloadLang(SubPlugin plugin, String id) {
this.plugin = plugin;
this.id = id;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
json.put("id", id);
json.put("Lang", plugin.lang.get().getSection("Lang").toJSON());
return json;
}
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(new PacketDownloadLang(plugin, (data != null && data.keySet().contains("id"))?data.getString("id"):null));
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -0,0 +1,48 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import org.json.JSONObject;
public class PacketDownloadPlayerList implements PacketIn, PacketOut {
private SubPlugin plugin;
private String id;
public PacketDownloadPlayerList(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketDownloadPlayerList(SubPlugin plugin, String id) {
this.plugin = plugin;
this.id = id;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
json.put("id", id);
JSONObject players = new JSONObject();
for (ProxiedPlayer player : plugin.getPlayers()) {
JSONObject pinfo = new JSONObject();
pinfo.put("name", player.getName());
pinfo.put("nick", player.getDisplayName());
pinfo.put("server", player.getServer().getInfo().getName());
players.put(player.getUniqueId().toString(), pinfo);
}
json.put("players", players);
return json;
}
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(new PacketDownloadPlayerList(plugin, (data != null && data.keySet().contains("id"))?data.getString("id"):null));
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -2,34 +2,40 @@ package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import org.json.JSONArray;
import org.json.JSONObject;
public class PacketRequestServerInfo implements PacketIn, PacketOut {
public class PacketDownloadServerInfo implements PacketIn, PacketOut {
private SubPlugin plugin;
private Server server;
private String id;
public PacketRequestServerInfo(SubPlugin plugin, Server server) {
this.server = server;
}
public PacketRequestServerInfo(SubPlugin plugin) {
public PacketDownloadServerInfo(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketDownloadServerInfo(SubPlugin plugin, Server server, String id) {
this.plugin = plugin;
this.server = server;
this.id = id;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
JSONObject info = new JSONObject();
json.put("id", id);
json.put("type", (server == null)?"invalid":((server instanceof SubServer)?"subserver":"server"));
JSONObject info = new JSONObject();
if (server != null && server instanceof SubServer) {
info.put("host", ((SubServer) server).getHost().getName());
info.put("enabled", ((SubServer) server).isEnabled());
info.put("editable", ((SubServer) server).isEditable());
info.put("log", ((SubServer) server).isLogging());
info.put("dir", plugin.config.get().getSection("Servers").getSection(server.getName()).getString("Directory"));
info.put("exec", plugin.config.get().getSection("Servers").getSection(server.getName()).getString("Executable"));
@ -44,6 +50,15 @@ public class PacketRequestServerInfo implements PacketIn, PacketOut {
info.put("restricted", server.isRestricted());
info.put("motd", server.getMotd());
info.put("subdata", server.getSubDataClient() == null);
JSONObject players = new JSONObject();
for (ProxiedPlayer player : server.getPlayers()) {
JSONObject pinfo = new JSONObject();
pinfo.put("name", player.getName());
pinfo.put("nick", player.getDisplayName());
players.put(player.getUniqueId().toString(), pinfo);
}
info.put("players", players);
}
json.put("server", info);
@ -52,7 +67,7 @@ public class PacketRequestServerInfo implements PacketIn, PacketOut {
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(new PacketRequestServerInfo(plugin, plugin.api.getServer(data.getString("server"))));
client.sendPacket(new PacketDownloadServerInfo(plugin, plugin.api.getServer(data.getString("server")), (data.keySet().contains("id"))?data.getString("id"):null));
}
@Override

View File

@ -0,0 +1,95 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class PacketDownloadServerList implements PacketIn, PacketOut {
private SubPlugin plugin;
private String host;
private String id;
public PacketDownloadServerList(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketDownloadServerList(SubPlugin plugin, String host, String id) {
this.plugin = plugin;
this.host = host;
this.id = id;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
json.put("id", id);
if (host == null || host.equals("")) {
JSONObject exServers = new JSONObject();
for (Server server : plugin.exServers.values()) {
JSONObject info = new JSONObject();
JSONObject players = new JSONObject();
for (ProxiedPlayer player : server.getPlayers()) {
JSONObject pinfo = new JSONObject();
pinfo.put("name", player.getName());
pinfo.put("nick", player.getDisplayName());
players.put(player.getUniqueId().toString(), pinfo);
}
info.put("players", players);
exServers.put(server.getName(), info);
}
json.put("servers", exServers);
}
if (this.host == null || !this.host.equals("")) {
JSONObject hosts = new JSONObject();
for (Host host : plugin.api.getHosts().values()) {
if (this.host == null || this.host.equalsIgnoreCase(host.getName())) {
JSONObject hinfo = new JSONObject();
hinfo.put("enabled", host.isEnabled());
JSONObject servers = new JSONObject();
for (SubServer server : host.getSubServers().values()) {
JSONObject sinfo = new JSONObject();
sinfo.put("enabled", server.isEnabled());
sinfo.put("running", server.isRunning());
sinfo.put("temp", server.isTemporary());
JSONObject players = new JSONObject();
for (ProxiedPlayer player : server.getPlayers()) {
JSONObject pinfo = new JSONObject();
pinfo.put("name", player.getName());
pinfo.put("nick", player.getDisplayName());
players.put(player.getUniqueId().toString(), pinfo);
}
sinfo.put("players", players);
servers.put(server.getName(), sinfo);
}
hinfo.put("servers", servers);
hosts.put(host.getName(), hinfo);
}
}
json.put("hosts", hosts);
}
return json;
}
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(new PacketDownloadServerList(plugin, (data.keySet().contains("host"))?data.getString("host"):null, (data.keySet().contains("id"))?data.getString("id"):null));
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -0,0 +1,73 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Event.SubDataRecieveGenericInfoEvent;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.ClientHandler;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import org.json.JSONObject;
import java.net.InetSocketAddress;
public class PacketInfoPassthrough implements PacketIn, PacketOut {
private SubPlugin plugin;
private String h;
private Version v;
private JSONObject c;
public PacketInfoPassthrough(SubPlugin plugin) {
this.plugin = plugin;
}
public PacketInfoPassthrough(String handle, Version version, JSONObject content) {
this.h = handle;
this.v = version;
this.c = content;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
json.put("h", h);
json.put("v", v.toString());
json.put("c", c);
return json;
}
@Override
public void execute(Client client, JSONObject data) {
if (data.get("t") == null) {
plugin.getPluginManager().callEvent(new SubDataRecieveGenericInfoEvent(data.getString("h"), new Version(data.getString("v")), data.getJSONObject("c")));
} else {
try {
switch (data.getJSONObject("t").getString("type").toLowerCase()) {
case "address":
if (plugin.subdata.getClient(new InetSocketAddress(data.getJSONObject("t").getString("id").split(":")[0], Integer.parseInt(data.getJSONObject("t").getString("id").split(":")[1]))) != null)
plugin.subdata.getClient(new InetSocketAddress(data.getJSONObject("t").getString("id").split(":")[0], Integer.parseInt(data.getJSONObject("t").getString("id").split(":")[1])))
.sendPacket(new PacketInfoPassthrough(data.getString("h"), new Version(data.getString("v")), data.getJSONObject("c")));
break;
case "host":
if (plugin.hosts.keySet().contains(data.getJSONObject("t").getString("id").toLowerCase()) && plugin.hosts.get(data.getJSONObject("t").getString("id").toLowerCase()) instanceof ClientHandler)
((ClientHandler) plugin.hosts.get(data.getJSONObject("t").getString("id").toLowerCase())).getSubDataClient()
.sendPacket(new PacketInfoPassthrough(data.getString("h"), new Version(data.getString("v")), data.getJSONObject("c")));
break;
case "server":
case "subserver":
if (plugin.api.getServers().keySet().contains(data.getJSONObject("t").getString("id").toLowerCase()))
plugin.api.getServers().get(data.getJSONObject("t").getString("id").toLowerCase()).getSubDataClient()
.sendPacket(new PacketInfoPassthrough(data.getString("h"), new Version(data.getString("v")), data.getJSONObject("c")));
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -2,7 +2,7 @@ package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
@ -28,7 +28,10 @@ public class PacketLinkServer implements PacketIn, PacketOut {
@Override
public JSONObject generate() {
return new JSONObject("{\"r\": " + response + ", \"" + message.replace("\"", "\\\"") + "\"}");
JSONObject json = new JSONObject();
json.put("r", response);
json.put("m", message);
return json;
}
@Override
@ -37,9 +40,13 @@ public class PacketLinkServer implements PacketIn, PacketOut {
Map<String, Server> servers = plugin.api.getServers();
if (servers.keySet().contains(data.getString("name").toLowerCase())) {
Server server = servers.get(data.getString("name").toLowerCase());
server.linkSubDataClient(client);
System.out.println("SubData > " + client.getAddress().toString() + " has been defined as " + ((server instanceof SubServer)?"SubServer":"Server") + ": " + server.getName());
client.sendPacket(new PacketLinkServer(true, "Definition Successful"));
if (server.getSubDataClient() == null) {
server.linkSubDataClient(client);
System.out.println("SubData > " + client.getAddress().toString() + " has been defined as " + ((server instanceof SubServer) ? "SubServer" : "Server") + ": " + server.getName());
client.sendPacket(new PacketLinkServer(true, "Definition Successful"));
} else {
client.sendPacket(new PacketLinkServer(false, "Server already linked"));
}
} else {
client.sendPacket(new PacketLinkServer(false, "There is no server with that name"));
}

View File

@ -1,53 +0,0 @@
package net.ME1312.SubServers.Proxy.Network.Packet;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Network.PacketIn;
import net.ME1312.SubServers.Proxy.Network.PacketOut;
import net.ME1312.SubServers.Proxy.SubPlugin;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class PacketRequestServers implements PacketIn, PacketOut {
private SubPlugin plugin;
public PacketRequestServers(SubPlugin plugin) {
this.plugin = plugin;
}
@Override
public JSONObject generate() {
JSONObject json = new JSONObject();
List<String> exServers = new ArrayList<String>();
for (Server server : plugin.exServers.values()) {
exServers.add(server.getName());
}
json.put("servers", exServers);
TreeMap<String, List<String>> hosts = new TreeMap<String, List<String>>();
for (SubServer server : plugin.api.getSubServers().values()) {
List<String> servers = (hosts.keySet().contains(server.getHost().getName()))?hosts.get(server.getHost().getName()):new ArrayList<String>();
servers.add(server.getName());
hosts.put(server.getHost().getName(), servers);
}
json.put("hosts", hosts);
return json;
}
@Override
public void execute(Client client, JSONObject data) {
client.sendPacket(this);
}
@Override
public Version getVersion() {
return new Version("2.11.0a");
}
}

View File

@ -1,7 +1,6 @@
package net.ME1312.SubServers.Proxy.Network;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Client;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import org.json.JSONObject;
/**

View File

@ -1,6 +1,6 @@
package net.ME1312.SubServers.Proxy.Network;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import org.json.JSONObject;
/**

View File

@ -1,39 +1,34 @@
package net.ME1312.SubServers.Proxy.Network;
import net.ME1312.SubServers.Proxy.Libraries.Exception.IllegalPacketException;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Packet.PacketAuthorization;
import net.ME1312.SubServers.Proxy.Network.Packet.PacketLinkServer;
import net.ME1312.SubServers.Proxy.Network.Packet.PacketRequestServerInfo;
import net.ME1312.SubServers.Proxy.Network.Packet.PacketRequestServers;
import net.ME1312.SubServers.Proxy.Library.Exception.IllegalPacketException;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.Packet.*;
import net.ME1312.SubServers.Proxy.SubPlugin;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* NetworkManager Class
* SubDataServer Class
*
* @author ME1312
*/
public final class NetworkManager {
private HashMap<Class<? extends PacketOut>, String> pOut = new HashMap<Class<? extends PacketOut>, String>();
private HashMap<String, PacketIn> pIn = new HashMap<String, PacketIn>();
private HashMap<SocketAddress, Client> clients = new HashMap<SocketAddress, Client>();
private List<InetAddress> allowedAddresses = new ArrayList<InetAddress>();
public final class SubDataServer {
private static HashMap<Class<? extends PacketOut>, String> pOut = new HashMap<Class<? extends PacketOut>, String>();
private static HashMap<String, PacketIn> pIn = new HashMap<String, PacketIn>();
private static List<InetAddress> allowedAddresses = new ArrayList<InetAddress>();
private static boolean defaults = false;
private HashMap<InetSocketAddress, Client> clients = new HashMap<InetSocketAddress, Client>();
private ServerSocket server;
private SubPlugin plugin;
/**
* SubServers Network Manager
* SubData Server Instance
*
* @param plugin SubPlugin
* @param port Port
@ -41,15 +36,16 @@ public final class NetworkManager {
* @param address Bind Address
* @throws IOException
*/
public NetworkManager(SubPlugin plugin, int port, int backlog, InetAddress address) throws IOException {
public SubDataServer(SubPlugin plugin, int port, int backlog, InetAddress address) throws IOException {
server = new ServerSocket(port, backlog, address);
this.plugin = plugin;
allowConnection(address);
loadDefaults();
if (!defaults) loadDefaults();
}
private void loadDefaults() {
defaults = true;
for (String s : plugin.config.get().getSection("Settings").getSection("SubData").getStringList("Allowed-Connections")) {
try {
allowedAddresses.add(InetAddress.getByName(s));
@ -59,14 +55,24 @@ public final class NetworkManager {
}
registerPacket(new PacketAuthorization(plugin), "Authorization");
registerPacket(new PacketDownloadBuildScript(plugin), "DownloadBuildScript");
registerPacket(new PacketDownloadHostInfo(plugin), "DownloadHostInfo");
registerPacket(new PacketDownloadLang(plugin), "DownloadLang");
registerPacket(new PacketDownloadPlayerList(plugin), "DownloadPlayerList");
registerPacket(new PacketDownloadServerInfo(plugin), "DownloadServerInfo");
registerPacket(new PacketDownloadServerList(plugin), "DownloadServerList");
registerPacket(new PacketInfoPassthrough(plugin), "InfoPassthrough");
registerPacket(new PacketLinkServer(plugin), "LinkServer");
registerPacket(new PacketRequestServerInfo(plugin), "RequestServerInfo");
registerPacket(new PacketRequestServers(plugin), "RequestServers");
registerPacket(PacketAuthorization.class, "Authorization");
registerPacket(PacketDownloadBuildScript.class, "DownloadBuildScript");
registerPacket(PacketDownloadHostInfo.class, "DownloadHostInfo");
registerPacket(PacketDownloadLang.class, "DownloadLang");
registerPacket(PacketDownloadPlayerList.class, "DownloadPlayerList");
registerPacket(PacketDownloadServerInfo.class, "DownloadServerInfo");
registerPacket(PacketDownloadServerList.class, "DownloadServerList");
registerPacket(PacketInfoPassthrough.class, "InfoPassthrough");
registerPacket(PacketLinkServer.class, "LinkServer");
registerPacket(PacketRequestServerInfo.class, "RequestServerInfo");
registerPacket(PacketRequestServers.class, "RequestServers");
}
/**
@ -91,7 +97,7 @@ public final class NetworkManager {
clients.put(client.getAddress(), client);
return client;
} else {
System.out.println("SubData > " + socket.getRemoteSocketAddress().toString() + " attempted to connect, but isn't whitelisted");
System.out.println("SubData > " + socket.getInetAddress().toString() + ":" + socket.getPort() + " attempted to connect, but isn't whitelisted");
socket.close();
return null;
}
@ -104,7 +110,7 @@ public final class NetworkManager {
* @return Client
*/
public Client getClient(Socket socket) {
return clients.get(socket.getRemoteSocketAddress());
return clients.get(new InetSocketAddress(socket.getInetAddress(), socket.getPort()));
}
/**
@ -113,7 +119,7 @@ public final class NetworkManager {
* @param address Address to search
* @return Client
*/
public Client getClient(SocketAddress address) {
public Client getClient(InetSocketAddress address) {
return clients.get(address);
}
@ -138,7 +144,7 @@ public final class NetworkManager {
* @param address Address to Kick
* @throws IOException
*/
public void removeClient(SocketAddress address) throws IOException {
public void removeClient(InetSocketAddress address) throws IOException {
Client client = clients.get(address);
if (clients.keySet().contains(address)) {
clients.remove(address);
@ -148,23 +154,41 @@ public final class NetworkManager {
}
/**
* Register Packet to the Network
* Register PacketIn to the Network
*
* @param packet PacketIn to register
* @param handle Handle to Bind
*/
public void registerPacket(PacketIn packet, String handle) {
pIn.put(handle, packet);
public static void registerPacket(PacketIn packet, String handle) {
if (!pIn.keySet().contains(handle)) {
pIn.put(handle, packet);
} else {
throw new IllegalStateException("PacketIn Handle \"" + handle + "\" is already in use!");
}
}
/**
* Register Packet to the Network
* Register PacketOut to the Network
*
* @param packet PacketOut to register
* @param handle Handle to bind
*/
public void registerPacket(Class<? extends PacketOut> packet, String handle) {
pOut.put(packet, handle);
public static void registerPacket(Class<? extends PacketOut> packet, String handle) {
if (!pOut.values().contains(handle)) {
pOut.put(packet, handle);
} else {
throw new IllegalStateException("PacketOut Handle \"" + handle + "\" is already in use!");
}
}
/**
* Grab PacketIn Instance via handle
*
* @param handle Handle
* @return PacketIn
*/
public static PacketIn getPacket(String handle) {
return pIn.get(handle);
}
/**
@ -184,7 +208,7 @@ public final class NetworkManager {
*
* @param address Address to allow
*/
public void allowConnection(InetAddress address) {
public static void allowConnection(InetAddress address) {
if (!allowedAddresses.contains(address)) allowedAddresses.add(address);
}
@ -193,7 +217,7 @@ public final class NetworkManager {
*
* @param address Address to deny
*/
public void denyConnection(InetAddress address) {
public static void denyConnection(InetAddress address) {
allowedAddresses.remove(address);
}
@ -204,7 +228,7 @@ public final class NetworkManager {
* @return JSON Formatted Packet
* @throws IllegalPacketException
*/
protected JSONObject encodePacket(PacketOut packet) throws IllegalPacketException {
protected static JSONObject encodePacket(PacketOut packet) throws IllegalPacketException {
JSONObject json = new JSONObject();
if (!pOut.keySet().contains(packet.getClass())) throw new IllegalPacketException("Unknown PacketOut Channel: " + packet.getClass().getCanonicalName());
@ -225,7 +249,7 @@ public final class NetworkManager {
* @throws IllegalPacketException
* @throws InvocationTargetException
*/
protected PacketIn decodePacket(JSONObject json) throws IllegalPacketException, InvocationTargetException {
protected static PacketIn decodePacket(JSONObject json) throws IllegalPacketException, InvocationTargetException {
if (!json.keySet().contains("h") || !json.keySet().contains("v")) throw new IllegalPacketException("Unknown Packet Format: " + json.toString());
if (!pIn.keySet().contains(json.getString("h"))) throw new IllegalPacketException("Unknown PacketIn Channel: " + json.getString("h"));

View File

@ -1,14 +1,18 @@
package net.ME1312.SubServers.Proxy;
import net.ME1312.SubServers.Proxy.Event.SubAddServerEvent;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Libraries.UniversalFile;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Network.NetworkManager;
import net.ME1312.SubServers.Proxy.Library.UniversalFile;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.SubDataServer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
/**
* SubAPI Class
@ -49,7 +53,7 @@ public final class SubAPI {
*
* @return SubData Network Manager
*/
public NetworkManager getSubDataNetwork() {
public SubDataServer getSubDataNetwork() {
return plugin.subdata;
}
@ -97,6 +101,43 @@ public final class SubAPI {
return servers;
}
/**
* Adds a Server to the Network
*
* @param name Name of the Server
* @param ip IP of the Server
* @param port Port of the Server
* @param motd MOTD of the Server
* @param restricted Players will need a permission to join if true
* @return The Server
*/
public Server addServer(String name, InetAddress ip, int port, String motd, boolean restricted) {
return addServer(null, name, ip, port, motd, restricted);
}
/**
* Adds a Server to the Network
*
* @param player Player who added
* @param name Name of the Server
* @param ip IP of the Server
* @param port Port of the Server
* @param motd MOTD of the Server
* @param restricted Players will need a permission to join if true
* @return The Server
*/
public Server addServer(UUID player, String name, InetAddress ip, int port, String motd, boolean restricted) {
Server server = new Server(name, new InetSocketAddress(ip, port), motd, restricted);
SubAddServerEvent event = new SubAddServerEvent(player, null, server);
plugin.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
plugin.exServers.put(name.toLowerCase(), server);
return server;
} else {
return null;
}
}
/**
* Gets a Server
*

View File

@ -1,9 +1,14 @@
package net.ME1312.SubServers.Proxy;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Host.SubCreator;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Library.Util;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.command.ConsoleCommandSender;
@ -18,7 +23,7 @@ public final class SubCommand extends Command {
private SubPlugin plugin;
public SubCommand(SubPlugin plugin) {
super("subserver", "subservers.console_only", "sub", "subservers");
super("subserver", null, "sub", "subservers");
this.plugin = plugin;
}
@ -36,18 +41,20 @@ public final class SubCommand extends Command {
if (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("?")) {
sender.sendMessages(printHelp());
} else if (args[0].equalsIgnoreCase("version") || args[0].equalsIgnoreCase("ver")) {
sender.sendMessage("SubServers > SubServers.Proxy is running version " + plugin.version.toString());
sender.sendMessage("SubServers > SubServers.Bungee is running version " + plugin.version.toString() + ((plugin.bversion != null)?" BETA "+plugin.bversion.toString():""));
} else if (args[0].equalsIgnoreCase("list")) {
sender.sendMessages(
"SubServers > Host List:", plugin.hosts.keySet().toString(),
"SubServers > Server List:", plugin.getServers().keySet().toString());
"SubServers > Server List:", plugin.api.getServers().keySet().toString());
} else if (args[0].equalsIgnoreCase("start")) {
if (args.length > 1) {
Map<String, ServerInfo> servers = plugin.getServers();
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
sender.sendMessage("SubServers > That Server is not a SubServer");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).getHost().isEnabled()) {
sender.sendMessage("SubServers > That SubServer's Host is not enabled");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).isEnabled()) {
sender.sendMessage("SubServers > That SubServer is not enabled");
} else if (((SubServer) servers.get(args[1].toLowerCase())).isRunning()) {
@ -60,7 +67,7 @@ public final class SubCommand extends Command {
}
} else if (args[0].equalsIgnoreCase("stop")) {
if (args.length > 1) {
Map<String, ServerInfo> servers = plugin.getServers();
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
@ -75,7 +82,7 @@ public final class SubCommand extends Command {
}
} else if (args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("terminate")) {
if (args.length > 1) {
Map<String, ServerInfo> servers = plugin.getServers();
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
@ -90,7 +97,7 @@ public final class SubCommand extends Command {
}
} else if (args[0].equalsIgnoreCase("cmd") || args[0].equalsIgnoreCase("command")) {
if (args.length > 2) {
Map<String, ServerInfo> servers = plugin.getServers();
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
@ -112,13 +119,40 @@ public final class SubCommand extends Command {
sender.sendMessage("SubServers > Usage: /sub cmd <SubServer> <Command> [Args...]");
}
} else if (args[0].equalsIgnoreCase("create")) {
if (args.length > 5) {
if (plugin.api.getServers().keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is already a server with that name");
} else if (!plugin.hosts.keySet().contains(args[2].toLowerCase())) {
sender.sendMessage("SubServers > There is no host with that name");
} else if (plugin.hosts.get(args[2].toLowerCase()).getCreator().isBusy()) {
sender.sendMessage("SubServers > The SubCreator instance on that host is already running");
} else if (Util.isException(() -> SubCreator.ServerType.valueOf(args[3].toUpperCase()))) {
sender.sendMessage("SubServers > There is no server type with that name");
} 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) {
sender.sendMessage("SubServers > Invalid Port Number");
} else if (args.length > 6 && (Util.isException(() -> Integer.parseInt(args[6])) || Integer.parseInt(args[6]) < 256)) {
sender.sendMessage("SubServers > Invalid Ram Amount");
} else {
plugin.hosts.get(args[2].toLowerCase()).getCreator().create(args[1], SubCreator.ServerType.valueOf(args[3].toUpperCase()), new Version(args[4]), (args.length > 6)?Integer.parseInt(args[6]):1024, Integer.parseInt(args[5]));
}
} else {
sender.sendMessage("SubServers > Usage: /sub create <Name> <Host> <Type> <Version> <Port> [RAM]");
}
}
} else {
sender.sendMessages(printHelp());
}
} else {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.lang.get().getSection("Lang").getString("Console-Only-Command")));
String str = "";
int i = -1;
while ((i + 1) != args.length) {
i++;
str = str + " " + args[i];
}
System.out.println("/subserver" + str);
((ProxiedPlayer) sender).chat("/subserver" + str);
}
}

View File

@ -2,14 +2,15 @@ package net.ME1312.SubServers.Proxy;
import net.ME1312.SubServers.Proxy.Host.Executable;
import net.ME1312.SubServers.Proxy.Host.Server;
import net.ME1312.SubServers.Proxy.Libraries.Config.YAMLConfig;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidHostException;
import net.ME1312.SubServers.Proxy.Libraries.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Library.Config.YAMLConfig;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidHostException;
import net.ME1312.SubServers.Proxy.Library.Exception.InvalidServerException;
import net.ME1312.SubServers.Proxy.Host.Host;
import net.ME1312.SubServers.Proxy.Host.SubServer;
import net.ME1312.SubServers.Proxy.Libraries.UniversalFile;
import net.ME1312.SubServers.Proxy.Libraries.Version.Version;
import net.ME1312.SubServers.Proxy.Network.NetworkManager;
import net.ME1312.SubServers.Proxy.Library.UniversalFile;
import net.ME1312.SubServers.Proxy.Library.Util;
import net.ME1312.SubServers.Proxy.Library.Version.Version;
import net.ME1312.SubServers.Proxy.Network.SubDataServer;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.config.ServerInfo;
@ -29,11 +30,12 @@ public final class SubPlugin extends BungeeCord {
public final HashMap<String, Server> exServers = new HashMap<String, Server>();
public final HashMap<String, Host> hosts = new HashMap<String, Host>();
public final UniversalFile dir = new UniversalFile(new File("./"));
public final UniversalFile dir = new UniversalFile(new File(System.getProperty("user.dir")));
public YAMLConfig config;
public YAMLConfig lang;
public NetworkManager subdata;
public SubDataServer subdata = null;
public final Version version = new Version("2.11.0a");
protected Version bversion = new Version(1);
protected boolean running = false;
public final SubAPI api = new SubAPI(this);
@ -49,31 +51,31 @@ public final class SubPlugin extends BungeeCord {
*/
protected void enable() throws IOException {
if (running) throw new IllegalStateException("SubServers has already been loaded");
System.out.println("SubServers > Loading SubServers v" + version.toString() + " Libraries... ");
System.out.println("SubServers > Loading SubServers v" + version.toString() + " Library... ");
running = true;
UniversalFile dir = new UniversalFile(this.dir, "SubServers");
dir.mkdir();
if (!(new UniversalFile(dir, "config.yml").exists())) {
copyFromJar("net/ME1312/SubServers/Proxy/Libraries/Files/config.yml", new UniversalFile(dir, "config.yml").getPath());
Util.copyFromJar(SubPlugin.class.getClassLoader(), "net/ME1312/SubServers/Proxy/Library/Files/config.yml", new UniversalFile(dir, "config.yml").getPath());
System.out.println("SubServers > Created ~/SubServers/config.yml");
} else if ((new Version((new YAMLConfig(new UniversalFile(dir, "config.yml"))).get().getSection("Settings").getString("Version", "0")).compareTo(new Version("2.11.0a+"))) != 0) {
Files.move(new UniversalFile(dir, "config.yml").toPath(), new UniversalFile(dir, "config.old" + Math.round(Math.random() * 100000) + ".yml").toPath());
copyFromJar("net/ME1312/SubServers/Proxy/Libraries/Files/config.yml", new UniversalFile(dir, "config.yml").getPath());
Util.copyFromJar(SubPlugin.class.getClassLoader(), "net/ME1312/SubServers/Proxy/Library/Files/config.yml", new UniversalFile(dir, "config.yml").getPath());
System.out.println("SubServers > Updated ~/SubServers/config.yml");
}
if (!(new UniversalFile(dir, "lang.yml").exists())) {
copyFromJar("net/ME1312/SubServers/Proxy/Libraries/Files/lang.yml", new UniversalFile(dir, "lang.yml").getPath());
Util.copyFromJar(SubPlugin.class.getClassLoader(), "net/ME1312/SubServers/Proxy/Library/Files/lang.yml", new UniversalFile(dir, "lang.yml").getPath());
System.out.println("SubServers > Created ~/SubServers/lang.yml");
} else if ((new Version((new YAMLConfig(new UniversalFile(dir, "lang.yml"))).get().getString("Version", "0")).compareTo(new Version("2.11.0a+"))) != 0) {
Files.move(new UniversalFile(dir, "lang.yml").toPath(), new UniversalFile(dir, "lang.old" + Math.round(Math.random() * 100000) + ".yml").toPath());
copyFromJar("net/ME1312/SubServers/Proxy/Libraries/Files/lang.yml", new UniversalFile(dir, "lang.yml").getPath());
Util.copyFromJar(SubPlugin.class.getClassLoader(), "net/ME1312/SubServers/Proxy/Library/Files/lang.yml", new UniversalFile(dir, "lang.yml").getPath());
System.out.println("SubServers > Updated ~/SubServers/lang.yml");
}
if (!(new UniversalFile(dir, "build.sh").exists())) {
copyFromJar("net/ME1312/SubServers/Proxy/Libraries/Files/build.sh", new UniversalFile(dir, "build.sh").getPath());
Util.copyFromJar(SubPlugin.class.getClassLoader(), "net/ME1312/SubServers/Proxy/Library/Files/build.sh", new UniversalFile(dir, "build.sh").getPath());
System.out.println("SubServers > Created ~/SubServers/build.sh");
} else {
String Version = "null";
@ -85,14 +87,14 @@ public final class SubPlugin extends BungeeCord {
if (!Version.equalsIgnoreCase("2.11.0a+")) {
Files.move(new UniversalFile(dir, "build.sh").toPath(), new UniversalFile(dir, "build.old" + Math.round(Math.random() * 100000) + ".sh").toPath());
copyFromJar("net/ME1312/SubServers/Proxy/Libraries/Files/build.sh", new UniversalFile(dir, "build.sh").getPath());
Util.copyFromJar(SubPlugin.class.getClassLoader(), "net/ME1312/SubServers/Proxy/Library/Files/build.sh", new UniversalFile(dir, "build.sh").getPath());
System.out.println("SubServers > Updated ~/SubServers/build.sh");
}
}
hostDrivers.put("built-in", net.ME1312.SubServers.Proxy.Host.Internal.InternalHost.class);
System.out.println("SubServers > Loading BungeeCord Libraries...");
System.out.println("SubServers > Loading BungeeCord Library...");
}
/**
@ -103,8 +105,8 @@ public final class SubPlugin extends BungeeCord {
try {
config = new YAMLConfig(new UniversalFile(dir, "SubServers:config.yml"));
lang = new YAMLConfig(new UniversalFile(dir, "SubServers:lang.yml"));
subdata = new NetworkManager(this, Integer.parseInt(config.get().getSection("Settings").getSection("SubData").getString("Address", "127.0.0.1:4391").split(":")[1]), 10,
InetAddress.getByName(config.get().getSection("Settings").getSection("SubData").getString("Address", "127.0.0.1:4391").split(":")[0]));
subdata = new SubDataServer(this, Integer.parseInt(config.get().getSection("Settings").getSection("SubData").getRawString("Address", "127.0.0.1:4391").split(":")[1]), 10,
InetAddress.getByName(config.get().getSection("Settings").getSection("SubData").getRawString("Address", "127.0.0.1:4391").split(":")[0]));
System.out.println("SubServers > SubData Listening on " + subdata.getServer().getLocalSocketAddress().toString());
loop();
@ -113,12 +115,12 @@ public final class SubPlugin extends BungeeCord {
System.out.println("SubServers > Loading Hosts...");
for (String name : config.get().getSection("Hosts").getKeys()) {
try {
if (name.contains(" ")) throw new InvalidHostException("Host names cannot have spaces: " + name);
if (!hostDrivers.keySet().contains(config.get().getSection("Hosts").getSection(name).getString("Driver").toLowerCase())) throw new InvalidHostException("Invalid Driver for host: " + name);
Host host = hostDrivers.get(config.get().getSection("Hosts").getSection(name).getString("Driver").toLowerCase()).getConstructor(SubPlugin.class, String.class, Boolean.class, InetAddress.class, UniversalFile.class).newInstance(
this, name, (Boolean) config.get().getSection("Hosts").getSection(name).getBoolean("Enabled"), InetAddress.getByName(config.get().getSection("Hosts").getSection(name).getString("Address")), new UniversalFile(new File(config.get().getSection("Hosts").getSection(name).getString("Directory"))));
if (!hostDrivers.keySet().contains(config.get().getSection("Hosts").getSection(name).getRawString("Driver").toLowerCase())) throw new InvalidHostException("Invalid Driver for host: " + name);
Host host = hostDrivers.get(config.get().getSection("Hosts").getSection(name).getRawString("Driver").toLowerCase()).getConstructor(SubPlugin.class, String.class, Boolean.class, InetAddress.class, String.class, String.class).newInstance(
this, name, (Boolean) 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"));
this.hosts.put(name.toLowerCase(), host);
subdata.allowConnection(host.getAddress());
SubDataServer.allowConnection(host.getAddress());
hosts++;
} catch (Exception e) {
e.printStackTrace();
@ -130,11 +132,11 @@ public final class SubPlugin extends BungeeCord {
YAMLConfig bungee = new YAMLConfig(new UniversalFile(dir, "config.yml"));
for (String name : bungee.get().getSection("servers").getKeys()) {
try {
Server server = new Server(name, new InetSocketAddress(bungee.get().getSection("servers").getSection(name).getString("address").split(":")[0],
Integer.parseInt(bungee.get().getSection("servers").getSection(name).getString("address").split(":")[1])), bungee.get().getSection("servers").getSection(name).getString("motd"),
Server server = new Server(name, new InetSocketAddress(bungee.get().getSection("servers").getSection(name).getRawString("address").split(":")[0],
Integer.parseInt(bungee.get().getSection("servers").getSection(name).getRawString("address").split(":")[1])), bungee.get().getSection("servers").getSection(name).getColoredString("motd", '&'),
bungee.get().getSection("servers").getSection(name).getBoolean("restricted"));
exServers.put(name.toLowerCase(), server);
subdata.allowConnection(server.getAddress().getAddress());
SubDataServer.allowConnection(server.getAddress().getAddress());
servers++;
} catch (Exception e) {
e.printStackTrace();
@ -146,11 +148,14 @@ public final class SubPlugin extends BungeeCord {
for (String name : config.get().getSection("Servers").getKeys()) {
try {
if (!this.hosts.keySet().contains(config.get().getSection("Servers").getSection(name).getString("Host").toLowerCase())) throw new InvalidServerException("There is no host with this name:" + name);
if (exServers.keySet().contains(name.toLowerCase())) {
exServers.remove(name.toLowerCase());
servers--;
}
SubServer server = this.hosts.get(config.get().getSection("Servers").getSection(name).getString("Host").toLowerCase()).addSubServer(name, config.get().getSection("Servers").getSection(name).getBoolean("Enabled"),
config.get().getSection("Servers").getSection(name).getInt("Port"), config.get().getSection("Servers").getSection(name).getString("Motd"), config.get().getSection("Servers").getSection(name).getBoolean("Log"),
config.get().getSection("Servers").getSection(name).getString("Directory"), new Executable(config.get().getSection("Servers").getSection(name).getString("Executable")), config.get().getSection("Servers").getSection(name).getString("Stop-Command"),
config.get().getSection("Servers").getSection(name).getBoolean("Run-On-Launch"), config.get().getSection("Servers").getSection(name).getBoolean("Auto-Restart"), false);
config.get().getSection("Servers").getSection(name).getInt("Port"), config.get().getSection("Servers").getSection(name).getColoredString("Motd", '&'), config.get().getSection("Servers").getSection(name).getBoolean("Log"),
config.get().getSection("Servers").getSection(name).getRawString("Directory"), new Executable(config.get().getSection("Servers").getSection(name).getRawString("Executable")), config.get().getSection("Servers").getSection(name).getRawString("Stop-Command"),
config.get().getSection("Servers").getSection(name).getBoolean("Run-On-Launch"), config.get().getSection("Servers").getSection(name).getBoolean("Auto-Restart"), config.get().getSection("Servers").getSection(name).getBoolean("Restricted"), false);
subservers++;
} catch (Exception e) {
e.printStackTrace();
@ -167,35 +172,30 @@ public final class SubPlugin extends BungeeCord {
}
}
/**
* SubData Listener Loop
*/
public void loop() {
new Thread() {
public void run() {
while(running && subdata != null) {
try {
subdata.addClient(subdata.getServer().accept());
} catch (IOException e) {
if (e.getMessage() == null || !e.getMessage().equals("Socket closed")) e.printStackTrace();
}
private void loop() {
new Thread(() -> {
while (running && subdata != null) {
try {
subdata.addClient(subdata.getServer().accept());
} catch (IOException e) {
if (e.getMessage() == null || !e.getMessage().equals("Socket closed")) e.printStackTrace();
}
}
}.start();
}).start();
}
/**
* Override BungeeCord Servers
* Emulate BungeeCord's getServers()
*
* @see SubAPI#getServers()
* @return Server Map
*/
@Override
public Map<String, ServerInfo> getServers() {
TreeMap<String, ServerInfo> servers = new TreeMap<String, ServerInfo>();
servers.putAll(this.exServers);
HashMap<String, ServerInfo> servers = new HashMap<String, ServerInfo>();
for (ServerInfo server : exServers.values()) servers.put(server.getName(), server);
for (Host host : this.hosts.values()) {
servers.putAll(host.getSubServers());
for (ServerInfo server : host.getSubServers().values()) servers.put(server.getName(), server);
}
return servers;
}
@ -261,22 +261,4 @@ public final class SubPlugin extends BungeeCord {
disable();
super.stop(reason);
}
private void copyFromJar(String resource, String destination) {
InputStream resStreamIn = SubPlugin.class.getClassLoader().getResourceAsStream(resource);
File resDestFile = new File(destination);
try {
OutputStream resStreamOut = new FileOutputStream(resDestFile);
int readBytes;
byte[] buffer = new byte[4096];
while ((readBytes = resStreamIn.read(buffer)) > 0) {
resStreamOut.write(buffer, 0, readBytes);
}
resStreamOut.close();
resStreamIn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@ -1,54 +0,0 @@
name: 'SubServers'
main: 'net.ME1312.SubServers.Client.SubPlugin'
version: '2.11.0a'
authors: [ME1312]
website: 'http://www.example.com/'
commands:
subservers:
description: All SubServer Commands
usage: /SubServers [Server]
subserver:
description: All SubServer Commands
usage: /SubServer [Server]
sub:
description: All SubServer Commands
usage: /Sub [Server]
permissions:
subserver.*:
description: All Subserver Commands
default: op
children:
subserver.command:
description: Subservers GUI
default: op
subserver.command.*:
description: 'Subserver Commands/Actions'
default: op
children:
subserver.command.create:
description: Creates a SubServer
default: op
subserver.command.start.*:
description: Starts a Subserver
default: op
subserver.command.kill.*:
description: Terminates a Subserver
default: op
subserver.command.stop.*:
description: Stops a Subserver
default: op
subserver.command.send.*:
description: Sends Commands to a Subserver
default: op
subserver.command.edit.*:
description: Edits a SubServer
default: op
subserver.command.teleport.*:
description: Teleport to SubServers
default: op
subserver.command.teleport.others.*:
description: Teleport Others to SubServers
default: op
subserver.command.reload:
description: Reload Subservers Configs
default: op