Merge branch 'master' of github.com:jamezrin/PlayerBalancer

This commit is contained in:
Jaime Martínez Rincón 2020-07-12 20:16:13 +02:00
commit eea1bb42cd
No known key found for this signature in database
GPG Key ID: D7F007B5BBA8E142
27 changed files with 80 additions and 126 deletions

View File

@ -1,5 +1,5 @@
# PlayerBalancer
[Spigot Resource](https://www.spigotmc.org/resources/10788/)
[Spigot Resource](https://www.spigotmc.org/resources/playerbalancer.55011/)
### Build
* Clone this repository

View File

@ -6,7 +6,7 @@
<parent>
<groupId>com.jaimemartz</groupId>
<version>2.1.6.2-SNAPSHOT</version>
<version>2.2-SNAPSHOT</version>
<artifactId>playerbalancer-parent</artifactId>
</parent>

View File

@ -19,7 +19,7 @@ public class PlayerBalancerAddon extends JavaPlugin {
@Override
public void onDisable() {
//Nothing to do...
// Nothing to do...
}
public PluginMessageManager getManager() {

View File

@ -22,8 +22,8 @@ public class PlayerBalancerPlaceholderExpansion extends PlaceholderExpansion {
if (section == null)
return null;
//For the first call this placeholder will return 0
//For the next one, the result of the previous one
// For the first call this placeholder will return 0
// For the next one, the result of the previous one
plugin.getManager().getSectionPlayerCount(section, (count) -> {
sectionPlayerCounts.put(section, count);
});

View File

@ -27,7 +27,7 @@ public class PluginMessageManager implements PluginMessageListener {
plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, PB_CHANNEL, this);
plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, PB_CHANNEL);
//In case we need to use BungeeCord channels
// In case we need to use BungeeCord channels
plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, BC_CHANNEL, this);
plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, BC_CHANNEL);
}

View File

@ -6,7 +6,7 @@
<parent>
<groupId>com.jaimemartz</groupId>
<version>2.1.6.2-SNAPSHOT</version>
<version>2.2-SNAPSHOT</version>
<artifactId>playerbalancer-parent</artifactId>
</parent>
@ -66,12 +66,6 @@
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.imaginarycode.minecraft</groupId>
<artifactId>RedisBungee</artifactId>
<version>0.3.8-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-hocon</artifactId>

View File

@ -5,7 +5,6 @@ import com.jaimemartz.playerbalancer.commands.FallbackCommand;
import com.jaimemartz.playerbalancer.commands.MainCommand;
import com.jaimemartz.playerbalancer.commands.ManageCommand;
import com.jaimemartz.playerbalancer.connection.ServerAssignRegistry;
import com.jaimemartz.playerbalancer.helper.NetworkManager;
import com.jaimemartz.playerbalancer.helper.PasteHelper;
import com.jaimemartz.playerbalancer.helper.PlayerLocker;
import com.jaimemartz.playerbalancer.listeners.*;
@ -34,7 +33,6 @@ public class PlayerBalancer extends Plugin {
private StatusManager statusManager;
private SettingsHolder settings;
private SectionManager sectionManager;
private NetworkManager networkManager;
private ConfigurationLoader<CommentedConfigurationNode> loader;
private FallbackCommand fallbackCommand;
@ -78,7 +76,7 @@ public class PlayerBalancer extends Plugin {
public boolean checkUpToDate() {
try {
URLConnection con = new URL("https://api.spigotmc.org/legacy/update.php?resource=10788").openConnection();
URLConnection con = new URL("https:// api.spigotmc.org/legacy/update.php?resource=10788").openConnection();
String reply = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine();
return getDescription().getVersion().equals(reply);
} catch (IOException e) {
@ -89,7 +87,7 @@ public class PlayerBalancer extends Plugin {
@Override
public void onDisable() {
//Nothing else to do than normal stop
// Nothing else to do than normal stop
this.execStop();
}
@ -128,8 +126,6 @@ public class PlayerBalancer extends Plugin {
getProxy().getPluginManager().registerListener(this, reloadListener);
}
networkManager = new NetworkManager(this);
sectionManager = new SectionManager(this);
sectionManager.load();
@ -198,7 +194,7 @@ public class PlayerBalancer extends Plugin {
}
if (settings.getGeneralProps().isEnabled()) {
//Do not try to do anything if the plugin has not loaded correctly
// Do not try to do anything if the plugin has not loaded correctly
if (failed) return;
if (settings.getGeneralProps().isAutoReload()) {
@ -284,10 +280,6 @@ public class PlayerBalancer extends Plugin {
return statusManager;
}
public NetworkManager getNetworkManager() {
return networkManager;
}
public FallbackCommand getFallbackCommand() {
return fallbackCommand;
}

View File

@ -39,14 +39,10 @@ public abstract class ConnectionIntent {
.replace("{alias}", safeNull(section.getProps().getAlias()))
);
// Ensure a new copy of the section servers
List<ServerInfo> servers = new ArrayList<>(section.getServers());
//Prevents removing servers from the section
if (servers == section.getServers()) {
throw new IllegalStateException("The servers list parameter is the same reference, this cannot happen");
}
//Prevents connections to the same server
// Prevents connections to the same server
Server current = player.getServer();
if (current != null) {
servers.remove(current.getInfo());
@ -56,7 +52,7 @@ public abstract class ConnectionIntent {
ServerInfo target = this.fetchServer(player, section, section.getImplicitProvider(), servers);
if (target != null) {
this.connect(target, (response, throwable) -> {
if (response) { //only if the connect has been executed correctly
if (response) { // only if the connect has been executed correctly
MessageUtils.send(player, plugin.getSettings().getMessagesProps().getConnectedMessage(),
(str) -> str.replace("{server}", target.getName())
.replace("{section}", section.getName())

View File

@ -17,7 +17,7 @@ public class ProgressiveFillerProvider extends AbstractProvider {
for (ServerInfo server : servers) {
ServerStatus status = plugin.getStatusManager().getStatus(server);
int count = plugin.getNetworkManager().getPlayers(server);
int count = server.getPlayers().size();
if (count > max && count <= status.getMaximum()) {
max = count;

View File

@ -15,7 +15,7 @@ public class ProgressiveLowestProvider extends AbstractProvider {
ServerInfo target = null;
for (ServerInfo server : servers) {
int count = plugin.getNetworkManager().getPlayers(server);
int count = server.getPlayers().size();
if (count < min) {
min = count;

View File

@ -14,7 +14,7 @@ public class ProgressiveProvider extends AbstractProvider {
public ServerInfo requestTarget(PlayerBalancer plugin, ServerSection section, List<ServerInfo> servers, ProxiedPlayer player) {
for (ServerInfo server : servers) {
ServerStatus status = plugin.getStatusManager().getStatus(server);
if (plugin.getNetworkManager().getPlayers(server) < status.getMaximum()) {
if (server.getPlayers().size() < status.getMaximum()) {
return server;
}
}

View File

@ -18,7 +18,7 @@ public class RandomFillerProvider extends AbstractProvider {
int max = Integer.MIN_VALUE;
for (ServerInfo server : servers) {
int count = plugin.getNetworkManager().getPlayers(server);
int count = server.getPlayers().size();
if (count >= max) {
if (count > max) {

View File

@ -18,7 +18,7 @@ public class RandomLowestProvider extends AbstractProvider {
int min = Integer.MAX_VALUE;
for (ServerInfo server : servers) {
int count = plugin.getNetworkManager().getPlayers(server);
int count = server.getPlayers().size();
if (count <= min) {
if (count < min) {

View File

@ -1,25 +0,0 @@
package com.jaimemartz.playerbalancer.helper;
import com.imaginarycode.minecraft.redisbungee.RedisBungee;
import com.jaimemartz.playerbalancer.PlayerBalancer;
import net.md_5.bungee.api.config.ServerInfo;
public class NetworkManager {
private final PlayerBalancer plugin;
public NetworkManager(PlayerBalancer plugin) {
this.plugin = plugin;
}
public int getPlayers(ServerInfo server) {
if (plugin.getSettings().getGeneralProps().isRedisBungee()) {
try {
return RedisBungee.getApi().getPlayersOnServer(server.getName()).size();
} catch (Exception e) {
e.printStackTrace();
}
}
return server.getPlayers().size();
}
}

View File

@ -37,7 +37,7 @@ public enum PasteHelper {
try (FileInputStream stream = new FileInputStream(file)) {
try (InputStreamReader reader = new InputStreamReader(stream, "UTF-8")) {
String content = CharStreams.toString(reader);
HastebinPaste paste = new HastebinPaste("https://file.properties/paste/", content);
HastebinPaste paste = new HastebinPaste("https:// file.properties/paste/", content);
return paste.paste();
}
}
@ -62,7 +62,7 @@ public enum PasteHelper {
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
String content = CharStreams.toString(reader);
content = content.replaceAll("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}", "?.?.?.?");
HastebinPaste paste = new HastebinPaste("https://file.properties/paste/", content);
HastebinPaste paste = new HastebinPaste("https:// file.properties/paste/", content);
return paste.paste();
}
}
@ -86,7 +86,7 @@ public enum PasteHelper {
try (FileInputStream stream = new FileInputStream(file)) {
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
String content = CharStreams.toString(reader);
HastebinPaste paste = new HastebinPaste("https://file.properties/paste/", content);
HastebinPaste paste = new HastebinPaste("https:// file.properties/paste/", content);
return paste.paste();
}
}

View File

@ -31,7 +31,7 @@ public class PluginMessageListener implements Listener {
this.plugin = plugin;
GsonBuilder builder = new GsonBuilder();
//Only serialize the name of ServerInfo
// Only serialize the name of ServerInfo
builder.registerTypeAdapter(ServerInfo.class, (JsonSerializer<ServerInfo>) (server, type, context) ->
context.serialize(server.getName())
);

View File

@ -56,7 +56,7 @@ public class ServerConnectListener implements Listener {
ServerSection section = plugin.getSectionManager().getByServer(target);
if (section != null) {
//Checks only for servers (not the section server)
// Checks only for servers (not the section server)
if (!target.equals(section.getServer())) {
if (plugin.getSectionManager().isDummy(section)) {
return null;

View File

@ -37,7 +37,7 @@ public enum PingTactic {
try {
server.ping((ping, throwable) -> {
if (ping != null) {
//using deprecated method for bungee 1.8 compatibility
// Using deprecated method for bungee 1.8 compatibility
callback.done(new ServerStatus(
ping.getDescription(),
ping.getPlayers().getOnline(),

View File

@ -235,28 +235,31 @@ public class SectionManager {
}
public void registerServer(ServerInfo server, ServerSection section) {
//Checking for duplicated server on non dummy sections
if (servers.containsKey(server) && !isDummy(section)) {
ServerSection other = servers.get(server);
throw new IllegalArgumentException(String.format(
"The server \"%s\" is already in the section \"%s\"",
if (!isDummy(section)) {
// Checking for already we already added this server to other section
// This can only happen if another non dummy section registers this server
if (servers.containsKey(server)) {
ServerSection other = servers.get(server);
throw new IllegalArgumentException(String.format(
"The server \"%s\" is already in the section \"%s\"",
server.getName(),
other.getName()
));
}
plugin.getLogger().info(String.format("Registering server \"%s\" to section \"%s\"",
server.getName(),
other.getName()
section.getName()
));
servers.put(server, section);
}
plugin.getLogger().info(String.format("Registering server \"%s\" to section \"%s\"",
server.getName(),
section.getName()
));
servers.put(server, section);
}
public void calculateServers(ServerSection section) {
Set<ServerInfo> results = new HashSet<>();
//Searches for matches
// Searches for matches
section.getProps().getServerEntries().forEach(entry -> {
Pattern pattern = Pattern.compile(entry);
plugin.getProxy().getServers().forEach((name, server) -> {
@ -267,7 +270,7 @@ public class SectionManager {
});
});
//Checks if there are servers previously matched that are no longer valid
// Checks if there are servers previously matched that are no longer valid
section.getServers().forEach(server -> {
if (!results.contains(server)) {
servers.remove(server);
@ -278,7 +281,7 @@ public class SectionManager {
}
});
//Add matched servers to the section
// Add matched servers to the section
int addedServers = 0;
for (ServerInfo server : results) {
if (!section.getServers().contains(server)) {
@ -303,7 +306,7 @@ public class SectionManager {
public int calculatePosition(ServerSection section) {
ServerSection current = section;
//Calculate above principal
// Calculate above principal
int iterations = 0;
while (current != null) {
if (current == principal) {
@ -314,7 +317,7 @@ public class SectionManager {
iterations++;
}
//Calculate below principal
// Calculate below principal
if (principal != null) {
iterations = 0;
current = principal;

View File

@ -47,7 +47,7 @@ public class SectionServer extends BungeeServerInfo {
@Override
public boolean sendData(String channel, byte[] data, boolean queue) {
//Nothing to do
// Nothing to do
return true;
}

View File

@ -16,9 +16,6 @@ public class GeneralProps {
@Setting(value = "auto-reload")
private boolean autoReload;
@Setting(value = "redis-bungee")
private boolean redisBungee;
@Setting(value = "plugin-messaging")
private boolean pluginMessaging;

View File

@ -11,7 +11,7 @@ public class AdapterWrapper implements ConfigurationAdapter {
private final ConfigurationAdapter wrapped;
public AdapterWrapper(ConfigurationAdapter adapter) {
//Prevents memory leak
// Prevents memory leak
if (adapter instanceof AdapterWrapper) {
this.wrapped = ((AdapterWrapper) adapter).wrapped;
} else {

View File

@ -98,14 +98,14 @@ public class AlphanumComparator implements Comparator<String>
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)

View File

@ -20,35 +20,35 @@ public final class LevenshteinDistance {
int len0 = lhs.length() + 1;
int len1 = rhs.length() + 1;
// the array of distances
// the array of distances
int[] cost = new int[len0];
int[] newcost = new int[len0];
// initial cost of skipping prefix in String s0
// initial cost of skipping prefix in String s0
for (int i = 0; i < len0; i++) cost[i] = i;
// dynamically computing the array of distances
// dynamically computing the array of distances
// transformation cost for each letter in s1
// transformation cost for each letter in s1
for (int j = 1; j < len1; j++) {
// initial cost of skipping prefix in String s1
// initial cost of skipping prefix in String s1
newcost[0] = j;
// transformation cost for each letter in s0
// transformation cost for each letter in s0
for (int i = 1; i < len0; i++) {
// matching current letters in both strings
// matching current letters in both strings
int match = (lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1;
// computing cost for each transformation
// computing cost for each transformation
int cost_replace = cost[i - 1] + match;
int cost_insert = cost[i] + 1;
int cost_delete = newcost[i - 1] + 1;
// keep minimum cost
// keep minimum cost
newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace);
}
// swap cost/newcost arrays
// swap cost/newcost arrays
int[] swap = cost;
cost = newcost;
newcost = swap;

View File

@ -56,31 +56,31 @@ public final class ServerListPing {
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream())) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream handshake = new DataOutputStream(b);
handshake.writeByte(0x00); //packet id for handshake
writeVarInt(handshake, 4); //protocol version
writeVarInt(handshake, host.getHostString().length()); //host length
handshake.writeBytes(host.getHostString()); //host string
handshake.writeShort(host.getPort()); //port
writeVarInt(handshake, 1); //state (1 for handshake)
handshake.writeByte(0x00); // packet id for handshake
writeVarInt(handshake, 4); // protocol version
writeVarInt(handshake, host.getHostString().length()); // host length
handshake.writeBytes(host.getHostString()); // host string
handshake.writeShort(host.getPort()); // port
writeVarInt(handshake, 1); // state (1 for handshake)
writeVarInt(dataOutputStream, b.size()); //prepend size
dataOutputStream.write(b.toByteArray()); //write handshake packet
writeVarInt(dataOutputStream, b.size()); // prepend size
dataOutputStream.write(b.toByteArray()); // write handshake packet
dataOutputStream.writeByte(0x01); //size is only 1
dataOutputStream.writeByte(0x00); //packet id for ping
int size = readVarInt(dataInputStream); //size of packet
int id = readVarInt(dataInputStream); //packet id
dataOutputStream.writeByte(0x01); // size is only 1
dataOutputStream.writeByte(0x00); // packet id for ping
int size = readVarInt(dataInputStream); // size of packet
int id = readVarInt(dataInputStream); // packet id
if (id == -1) {
throw new IOException("Premature end of stream.");
}
if (id != 0x00) { //we want a status response
if (id != 0x00) { // we want a status response
throw new IOException("Invalid packetID");
}
int length = readVarInt(dataInputStream); //length of json string
int length = readVarInt(dataInputStream); // length of json string
if (length == -1) {
throw new IOException("Premature end of stream.");
}
@ -90,14 +90,14 @@ public final class ServerListPing {
}
byte[] in = new byte[length];
dataInputStream.readFully(in); //read json string
dataInputStream.readFully(in); // read json string
String json = new String(in);
long now = System.currentTimeMillis();
dataOutputStream.writeByte(0x09); //size of packet
dataOutputStream.writeByte(0x01); //0x01 for ping
dataOutputStream.writeLong(now); //time!?
dataOutputStream.writeByte(0x09); // size of packet
dataOutputStream.writeByte(0x01); // 0x01 for ping
dataOutputStream.writeLong(now); // time!?
readVarInt(dataInputStream);
id = readVarInt(dataInputStream);
@ -109,7 +109,7 @@ public final class ServerListPing {
throw new IOException("Invalid packetID");
}
long pingTime = dataInputStream.readLong(); //read response
long pingTime = dataInputStream.readLong(); // read response
StatusResponse response = gson.fromJson(json, StatusResponse.class);
response.time = (int) (now - pingTime);
return response;

View File

@ -11,9 +11,6 @@ general {
# When true, the plugin will reload when you execute /greload
auto-reload=true
# When true, the plugin will get player counts from RedisBungee
redis-bungee=false
# When true, this plugin will print less messages when loading
silent=false

View File

@ -6,7 +6,7 @@
<groupId>com.jaimemartz</groupId>
<artifactId>playerbalancer-parent</artifactId>
<version>2.1.6.2-SNAPSHOT</version>
<version>2.2-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>