Reformat to new code style, lots of spaces for easy reading.

This commit is contained in:
md_5 2013-02-09 17:55:48 +11:00
parent 69d618c648
commit 23582a635b
44 changed files with 699 additions and 701 deletions

View File

@ -113,9 +113,9 @@ public enum ChatColor
private ChatColor(char code) private ChatColor(char code)
{ {
this.toString = new String(new char[] this.toString = new String(new char[]
{ {
COLOR_CHAR, code COLOR_CHAR, code
}); });
} }
@Override @Override

View File

@ -127,9 +127,9 @@ public class PluginManager
{ {
plugin.onEnable(); plugin.onEnable();
ProxyServer.getInstance().getLogger().log(Level.INFO, "Enabled plugin {0} version {1} by {2}", new Object[] ProxyServer.getInstance().getLogger().log(Level.INFO, "Enabled plugin {0} version {1} by {2}", new Object[]
{ {
entry.getKey(), plugin.getDescription().getVersion(), plugin.getDescription().getAuthor() entry.getKey(), plugin.getDescription().getVersion(), plugin.getDescription().getAuthor()
}); });
} catch (Exception ex) } catch (Exception ex)
{ {
ProxyServer.getInstance().getLogger().log(Level.WARNING, "Exception encountered when loading plugin: " + entry.getKey(), ex); ProxyServer.getInstance().getLogger().log(Level.WARNING, "Exception encountered when loading plugin: " + entry.getKey(), ex);
@ -159,9 +159,9 @@ public class PluginManager
{ {
PluginDescription desc = yaml.loadAs(in, PluginDescription.class); PluginDescription desc = yaml.loadAs(in, PluginDescription.class);
URLClassLoader loader = new PluginClassloader(new URL[] URLClassLoader loader = new PluginClassloader(new URL[]
{ {
file.toURI().toURL() file.toURI().toURL()
}); });
Class<?> main = loader.loadClass(desc.getMain()); Class<?> main = loader.loadClass(desc.getMain());
Plugin plugin = (Plugin) main.getDeclaredConstructor().newInstance(); Plugin plugin = (Plugin) main.getDeclaredConstructor().newInstance();
@ -169,9 +169,9 @@ public class PluginManager
plugins.put(desc.getName(), plugin); plugins.put(desc.getName(), plugin);
plugin.onLoad(); plugin.onLoad();
ProxyServer.getInstance().getLogger().log(Level.INFO, "Loaded plugin {0} version {1} by {2}", new Object[] ProxyServer.getInstance().getLogger().log(Level.INFO, "Loaded plugin {0} version {1} by {2}", new Object[]
{ {
desc.getName(), desc.getVersion(), desc.getAuthor() desc.getName(), desc.getVersion(), desc.getAuthor()
}); });
} }
} }
} }

View File

@ -68,7 +68,7 @@ public class BungeeCord extends ProxyServer
/** /**
* locations.yml save thread. * locations.yml save thread.
*/ */
private final Timer saveThread = new Timer("Reconnect Saver"); private final Timer saveThread = new Timer( "Reconnect Saver" );
/** /**
* Server socket listener. * Server socket listener.
*/ */
@ -96,17 +96,17 @@ public class BungeeCord extends ProxyServer
private ConfigurationAdapter configurationAdapter = new YamlConfig(); private ConfigurationAdapter configurationAdapter = new YamlConfig();
private final Collection<String> pluginChannels = new HashSet<>(); private final Collection<String> pluginChannels = new HashSet<>();
{ {
getPluginManager().registerCommand(new CommandReload()); getPluginManager().registerCommand( new CommandReload() );
getPluginManager().registerCommand(new CommandEnd()); getPluginManager().registerCommand( new CommandEnd() );
getPluginManager().registerCommand(new CommandList()); getPluginManager().registerCommand( new CommandList() );
getPluginManager().registerCommand(new CommandServer()); getPluginManager().registerCommand( new CommandServer() );
getPluginManager().registerCommand(new CommandIP()); getPluginManager().registerCommand( new CommandIP() );
getPluginManager().registerCommand(new CommandAlert()); getPluginManager().registerCommand( new CommandAlert() );
getPluginManager().registerCommand(new CommandBungee()); getPluginManager().registerCommand( new CommandBungee() );
registerChannel("BungeeCord"); registerChannel( "BungeeCord" );
} }
public static BungeeCord getInstance() public static BungeeCord getInstance()
@ -123,20 +123,20 @@ public class BungeeCord extends ProxyServer
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException
{ {
BungeeCord bungee = new BungeeCord(); BungeeCord bungee = new BungeeCord();
ProxyServer.setInstance(bungee); ProxyServer.setInstance( bungee );
$().info("Enabled BungeeCord version " + bungee.getVersion()); $().info( "Enabled BungeeCord version " + bungee.getVersion() );
bungee.start(); bungee.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
while (bungee.isRunning) while ( bungee.isRunning )
{ {
String line = br.readLine(); String line = br.readLine();
if (line != null) if ( line != null )
{ {
boolean handled = getInstance().getPluginManager().dispatchCommand(ConsoleCommandSender.getInstance(), line); boolean handled = getInstance().getPluginManager().dispatchCommand( ConsoleCommandSender.getInstance(), line );
if (!handled) if ( !handled )
{ {
System.err.println("Command not found"); System.err.println( "Command not found" );
} }
} }
} }
@ -150,31 +150,31 @@ public class BungeeCord extends ProxyServer
*/ */
public void start() throws IOException public void start() throws IOException
{ {
File plugins = new File("plugins"); File plugins = new File( "plugins" );
plugins.mkdir(); plugins.mkdir();
pluginManager.loadPlugins(plugins); pluginManager.loadPlugins( plugins );
config.load(); config.load();
reconnectHandler = new YamlReconnectHandler(); reconnectHandler = new YamlReconnectHandler();
isRunning = true; isRunning = true;
pluginManager.enablePlugins(); pluginManager.enablePlugins();
for (ListenerInfo info : config.getListeners()) for ( ListenerInfo info : config.getListeners() )
{ {
$().info("Listening on " + info.getHost()); $().info( "Listening on " + info.getHost() );
ListenThread listener = new ListenThread(info); ListenThread listener = new ListenThread( info );
listener.start(); listener.start();
listeners.add(listener); listeners.add( listener );
} }
saveThread.scheduleAtFixedRate(new TimerTask() saveThread.scheduleAtFixedRate( new TimerTask()
{ {
@Override @Override
public void run() public void run()
{ {
getReconnectHandler().save(); getReconnectHandler().save();
} }
}, 0, TimeUnit.MINUTES.toMillis(5)); }, 0, TimeUnit.MINUTES.toMillis( 5 ) );
new Metrics().start(); new Metrics().start();
} }
@ -183,40 +183,40 @@ public class BungeeCord extends ProxyServer
public void stop() public void stop()
{ {
this.isRunning = false; this.isRunning = false;
$().info("Disabling plugins"); $().info( "Disabling plugins" );
for (Plugin plugin : pluginManager.getPlugins()) for ( Plugin plugin : pluginManager.getPlugins() )
{ {
plugin.onDisable(); plugin.onDisable();
} }
for (ListenThread listener : listeners) for ( ListenThread listener : listeners )
{ {
$().log(Level.INFO, "Closing listen thread {0}", listener.socket); $().log( Level.INFO, "Closing listen thread {0}", listener.socket );
try try
{ {
listener.socket.close(); listener.socket.close();
listener.join(); listener.join();
} catch (InterruptedException | IOException ex) } catch ( InterruptedException | IOException ex )
{ {
$().severe("Could not close listen thread"); $().severe( "Could not close listen thread" );
} }
} }
$().info("Closing pending connections"); $().info( "Closing pending connections" );
threadPool.shutdown(); threadPool.shutdown();
$().info("Disconnecting " + connections.size() + " connections"); $().info( "Disconnecting " + connections.size() + " connections" );
for (UserConnection user : connections.values()) for ( UserConnection user : connections.values() )
{ {
user.disconnect("Proxy restarting, brb."); user.disconnect( "Proxy restarting, brb." );
} }
$().info("Saving reconnect locations"); $().info( "Saving reconnect locations" );
reconnectHandler.save(); reconnectHandler.save();
saveThread.cancel(); saveThread.cancel();
$().info("Thank you and goodbye"); $().info( "Thank you and goodbye" );
System.exit(0); System.exit( 0 );
} }
/** /**
@ -228,9 +228,9 @@ public class BungeeCord extends ProxyServer
*/ */
public void setSocketOptions(Socket socket) throws IOException public void setSocketOptions(Socket socket) throws IOException
{ {
socket.setSoTimeout(config.getTimeout()); socket.setSoTimeout( config.getTimeout() );
socket.setTrafficClass(0x18); socket.setTrafficClass( 0x18 );
socket.setTcpNoDelay(true); socket.setTcpNoDelay( true );
} }
/** /**
@ -240,9 +240,9 @@ public class BungeeCord extends ProxyServer
*/ */
public void broadcast(DefinedPacket packet) public void broadcast(DefinedPacket packet)
{ {
for (UserConnection con : connections.values()) for ( UserConnection con : connections.values() )
{ {
con.packetQueue.add(packet); con.packetQueue.add( packet );
} }
} }
@ -255,7 +255,7 @@ public class BungeeCord extends ProxyServer
@Override @Override
public String getVersion() public String getVersion()
{ {
return (BungeeCord.class.getPackage().getImplementationVersion() == null) ? "unknown" : BungeeCord.class.getPackage().getImplementationVersion(); return ( BungeeCord.class.getPackage().getImplementationVersion() == null ) ? "unknown" : BungeeCord.class.getPackage().getImplementationVersion();
} }
@Override @Override
@ -274,14 +274,14 @@ public class BungeeCord extends ProxyServer
@Override @Override
public ProxiedPlayer getPlayer(String name) public ProxiedPlayer getPlayer(String name)
{ {
return connections.get(name); return connections.get( name );
} }
@Override @Override
public Server getServer(String name) public Server getServer(String name)
{ {
Collection<ProxiedPlayer> users = getServers().get(name).getPlayers(); Collection<ProxiedPlayer> users = getServers().get( name ).getPlayers();
return (users != null && !users.isEmpty()) ? users.iterator().next().getServer() : null; return ( users != null && !users.isEmpty() ) ? users.iterator().next().getServer() : null;
} }
@Override @Override
@ -293,40 +293,40 @@ public class BungeeCord extends ProxyServer
@Override @Override
public ServerInfo getServerInfo(String name) public ServerInfo getServerInfo(String name)
{ {
return getServers().get(name); return getServers().get( name );
} }
@Override @Override
@Synchronized("pluginChannels") @Synchronized("pluginChannels")
public void registerChannel(String channel) public void registerChannel(String channel)
{ {
pluginChannels.add(channel); pluginChannels.add( channel );
} }
@Override @Override
@Synchronized("pluginChannels") @Synchronized("pluginChannels")
public void unregisterChannel(String channel) public void unregisterChannel(String channel)
{ {
pluginChannels.remove(channel); pluginChannels.remove( channel );
} }
@Override @Override
@Synchronized("pluginChannels") @Synchronized("pluginChannels")
public Collection<String> getChannels() public Collection<String> getChannels()
{ {
return Collections.unmodifiableCollection(pluginChannels); return Collections.unmodifiableCollection( pluginChannels );
} }
public PacketFAPluginMessage registerChannels() public PacketFAPluginMessage registerChannels()
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String s : getChannels()) for ( String s : getChannels() )
{ {
sb.append(s); sb.append( s );
sb.append('\00'); sb.append( '\00' );
} }
byte[] payload = sb.substring(0, sb.length() - 1).getBytes(); byte[] payload = sb.substring( 0, sb.length() - 1 ).getBytes();
return new PacketFAPluginMessage("REGISTER", payload); return new PacketFAPluginMessage( "REGISTER", payload );
} }
@Override @Override
@ -344,6 +344,6 @@ public class BungeeCord extends ProxyServer
@Override @Override
public ServerInfo constructServerInfo(String name, InetSocketAddress address) public ServerInfo constructServerInfo(String name, InetSocketAddress address)
{ {
return new BungeeServerInfo(name, address); return new BungeeServerInfo( name, address );
} }
} }

View File

@ -24,19 +24,19 @@ public class BungeeServerInfo extends ServerInfo
public BungeeServerInfo(String name, InetSocketAddress address) public BungeeServerInfo(String name, InetSocketAddress address)
{ {
super(name, address); super( name, address );
} }
@Override @Override
public void sendData(String channel, byte[] data) public void sendData(String channel, byte[] data)
{ {
Server server = ProxyServer.getInstance().getServer(getName()); Server server = ProxyServer.getInstance().getServer( getName() );
if (server != null) if ( server != null )
{ {
server.sendData(channel, data); server.sendData( channel, data );
} else } else
{ {
packetQueue.add(new PacketFAPluginMessage(channel, data)); packetQueue.add( new PacketFAPluginMessage( channel, data ) );
} }
} }
@ -51,24 +51,24 @@ public class BungeeServerInfo extends ServerInfo
try try
{ {
Socket socket = new Socket(); Socket socket = new Socket();
socket.connect(getAddress()); socket.connect( getAddress() );
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) try ( DataOutputStream out = new DataOutputStream( socket.getOutputStream() ) )
{ {
out.write(0xFE); out.write( 0xFE );
out.write(0x01); out.write( 0x01 );
} }
try (PacketStream in = new PacketStream(socket.getInputStream())) try ( PacketStream in = new PacketStream( socket.getInputStream() ) )
{ {
PacketFFKick response = new PacketFFKick(in.readPacket()); PacketFFKick response = new PacketFFKick( in.readPacket() );
String[] split = response.message.split("\00"); String[] split = response.message.split( "\00" );
ServerPing ping = new ServerPing(Byte.parseByte(split[1]), split[2], split[3], Integer.parseInt(split[4]), Integer.parseInt(split[5])); ServerPing ping = new ServerPing( Byte.parseByte( split[1] ), split[2], split[3], Integer.parseInt( split[4] ), Integer.parseInt( split[5] ) );
callback.done(ping, null); callback.done( ping, null );
} }
} catch (Throwable t) } catch ( Throwable t )
{ {
callback.done(null, t); callback.done( null, t );
} }
} }
}.start(); }.start();

View File

@ -41,69 +41,69 @@ public class EncryptionUtil
static static
{ {
Security.addProvider(new BouncyCastleProvider()); Security.addProvider( new BouncyCastleProvider() );
} }
public static PacketFDEncryptionRequest encryptRequest() throws NoSuchAlgorithmException public static PacketFDEncryptionRequest encryptRequest() throws NoSuchAlgorithmException
{ {
if (keys == null) if ( keys == null )
{ {
keys = KeyPairGenerator.getInstance("RSA").generateKeyPair(); keys = KeyPairGenerator.getInstance( "RSA" ).generateKeyPair();
} }
String hash = Long.toString(random.nextLong(), 16); String hash = Long.toString( random.nextLong(), 16 );
byte[] pubKey = keys.getPublic().getEncoded(); byte[] pubKey = keys.getPublic().getEncoded();
byte[] verify = new byte[4]; byte[] verify = new byte[ 4 ];
random.nextBytes(verify); random.nextBytes( verify );
return new PacketFDEncryptionRequest(hash, pubKey, verify); return new PacketFDEncryptionRequest( hash, pubKey, verify );
} }
public static SecretKey getSecret(PacketFCEncryptionResponse resp, PacketFDEncryptionRequest request) throws BadPaddingException, IllegalBlockSizeException, IllegalStateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException public static SecretKey getSecret(PacketFCEncryptionResponse resp, PacketFDEncryptionRequest request) throws BadPaddingException, IllegalBlockSizeException, IllegalStateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException
{ {
Cipher cipher = Cipher.getInstance("RSA"); Cipher cipher = Cipher.getInstance( "RSA" );
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate()); cipher.init( Cipher.DECRYPT_MODE, keys.getPrivate() );
byte[] decrypted = cipher.doFinal(resp.verifyToken); byte[] decrypted = cipher.doFinal( resp.verifyToken );
if (!Arrays.equals(request.verifyToken, decrypted)) if ( !Arrays.equals( request.verifyToken, decrypted ) )
{ {
throw new IllegalStateException("Key pairs do not match!"); throw new IllegalStateException( "Key pairs do not match!" );
} }
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate()); cipher.init( Cipher.DECRYPT_MODE, keys.getPrivate() );
byte[] shared = resp.sharedSecret; byte[] shared = resp.sharedSecret;
byte[] secret = cipher.doFinal(shared); byte[] secret = cipher.doFinal( shared );
return new SecretKeySpec(secret, "AES"); return new SecretKeySpec( secret, "AES" );
} }
public static boolean isAuthenticated(String username, String connectionHash, SecretKey shared) throws NoSuchAlgorithmException, IOException public static boolean isAuthenticated(String username, String connectionHash, SecretKey shared) throws NoSuchAlgorithmException, IOException
{ {
String encName = URLEncoder.encode(username, "UTF-8"); String encName = URLEncoder.encode( username, "UTF-8" );
MessageDigest sha = MessageDigest.getInstance("SHA-1"); MessageDigest sha = MessageDigest.getInstance( "SHA-1" );
for (byte[] bit : new byte[][] for ( byte[] bit : new byte[][]
{
connectionHash.getBytes("ISO_8859_1"), shared.getEncoded(), keys.getPublic().getEncoded()
})
{ {
sha.update(bit); connectionHash.getBytes( "ISO_8859_1" ), shared.getEncoded(), keys.getPublic().getEncoded()
} )
{
sha.update( bit );
} }
String encodedHash = URLEncoder.encode(new BigInteger(sha.digest()).toString(16), "UTF-8"); String encodedHash = URLEncoder.encode( new BigInteger( sha.digest() ).toString( 16 ), "UTF-8" );
String authURL = "http://session.minecraft.net/game/checkserver.jsp?user=" + encName + "&serverId=" + encodedHash; String authURL = "http://session.minecraft.net/game/checkserver.jsp?user=" + encName + "&serverId=" + encodedHash;
String reply; String reply;
try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(authURL).openStream()))) try ( BufferedReader in = new BufferedReader( new InputStreamReader( new URL( authURL ).openStream() ) ) )
{ {
reply = in.readLine(); reply = in.readLine();
} }
return "YES".equals(reply); return "YES".equals( reply );
} }
public static BufferedBlockCipher getCipher(boolean forEncryption, Key shared) public static BufferedBlockCipher getCipher(boolean forEncryption, Key shared)
{ {
BufferedBlockCipher cip = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8)); BufferedBlockCipher cip = new BufferedBlockCipher( new CFBBlockCipher( new AESFastEngine(), 8 ) );
cip.init(forEncryption, new ParametersWithIV(new KeyParameter(shared.getEncoded()), shared.getEncoded())); cip.init( forEncryption, new ParametersWithIV( new KeyParameter( shared.getEncoded() ), shared.getEncoded() ) );
return cip; return cip;
} }
} }

View File

@ -6,7 +6,7 @@ package net.md_5.bungee;
public class EntityMap public class EntityMap
{ {
public final static int[][] entityIds = new int[256][]; public final static int[][] entityIds = new int[ 256 ][];
static static
{ {
@ -115,34 +115,34 @@ public class EntityMap
public static void rewrite(byte[] packet, int oldId, int newId) public static void rewrite(byte[] packet, int oldId, int newId)
{ {
int packetId = Util.getId(packet); int packetId = Util.getId( packet );
if (packetId == 0x1D) if ( packetId == 0x1D )
{ // bulk entity { // bulk entity
for (int pos = 2; pos < packet.length; pos += 4) for ( int pos = 2; pos < packet.length; pos += 4 )
{ {
int readId = readInt(packet, pos); int readId = readInt( packet, pos );
if (readId == oldId) if ( readId == oldId )
{ {
setInt(packet, pos, newId); setInt( packet, pos, newId );
} else if (readId == newId) } else if ( readId == newId )
{ {
setInt(packet, pos, oldId); setInt( packet, pos, oldId );
} }
} }
} else } else
{ {
int[] idArray = entityIds[packetId]; int[] idArray = entityIds[packetId];
if (idArray != null) if ( idArray != null )
{ {
for (int pos : idArray) for ( int pos : idArray )
{ {
int readId = readInt(packet, pos); int readId = readInt( packet, pos );
if (readId == oldId) if ( readId == oldId )
{ {
setInt(packet, pos, newId); setInt( packet, pos, newId );
} else if (readId == newId) } else if ( readId == newId )
{ {
setInt(packet, pos, oldId); setInt( packet, pos, oldId );
} }
} }
} }
@ -151,14 +151,14 @@ public class EntityMap
private static void setInt(byte[] buf, int pos, int i) private static void setInt(byte[] buf, int pos, int i)
{ {
buf[pos] = (byte) (i >> 24); buf[pos] = (byte) ( i >> 24 );
buf[pos + 1] = (byte) (i >> 16); buf[pos + 1] = (byte) ( i >> 16 );
buf[pos + 2] = (byte) (i >> 8); buf[pos + 2] = (byte) ( i >> 8 );
buf[pos + 3] = (byte) i; buf[pos + 3] = (byte) i;
} }
private static int readInt(byte[] buf, int pos) private static int readInt(byte[] buf, int pos)
{ {
return (((buf[pos] & 0xFF) << 24) | ((buf[pos + 1] & 0xFF) << 16) | ((buf[pos + 2] & 0xFF) << 8) | buf[pos + 3] & 0xFF); return ( ( ( buf[pos] & 0xFF ) << 24 ) | ( ( buf[pos + 1] & 0xFF ) << 16 ) | ( ( buf[pos + 2] & 0xFF ) << 8 ) | buf[pos + 3] & 0xFF );
} }
} }

View File

@ -32,15 +32,15 @@ public class GenericConnection
*/ */
public void disconnect(String reason) public void disconnect(String reason)
{ {
if (socket.isClosed()) if ( socket.isClosed() )
{ {
return; return;
} }
log("disconnected with " + reason); log( "disconnected with " + reason );
try try
{ {
stream.write(new PacketFFKick("[Proxy] " + reason)); stream.write( new PacketFFKick( "[Proxy] " + reason ) );
} catch (IOException ex) } catch ( IOException ex )
{ {
} finally } finally
{ {
@ -48,7 +48,7 @@ public class GenericConnection
{ {
socket.shutdownOutput(); socket.shutdownOutput();
socket.close(); socket.close();
} catch (IOException ioe) } catch ( IOException ioe )
{ {
} }
} }
@ -56,6 +56,6 @@ public class GenericConnection
public void log(String message) public void log(String message)
{ {
$().info(socket.getInetAddress() + ((name == null) ? " " : " [" + name + "] ") + message); $().info( socket.getInetAddress() + ( ( name == null ) ? " " : " [" + name + "] " ) + message );
} }
} }

View File

@ -43,7 +43,7 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
{ {
this.socket = socket; this.socket = socket;
this.listener = info; this.listener = info;
stream = new PacketStream(socket.getInputStream(), socket.getOutputStream()); stream = new PacketStream( socket.getInputStream(), socket.getOutputStream() );
} }
private enum State private enum State
@ -55,69 +55,69 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
@Override @Override
public void handle(PacketFEPing ping) throws Exception public void handle(PacketFEPing ping) throws Exception
{ {
socket.setSoTimeout(100); socket.setSoTimeout( 100 );
boolean newPing = false; boolean newPing = false;
try try
{ {
socket.getInputStream().read(); socket.getInputStream().read();
newPing = true; newPing = true;
} catch (IOException ex) } catch ( IOException ex )
{ {
} }
ServerPing pingevent = new ServerPing(BungeeCord.PROTOCOL_VERSION, BungeeCord.GAME_VERSION, ServerPing pingevent = new ServerPing( BungeeCord.PROTOCOL_VERSION, BungeeCord.GAME_VERSION,
listener.getMotd(), ProxyServer.getInstance().getPlayers().size(), listener.getMaxPlayers()); listener.getMotd(), ProxyServer.getInstance().getPlayers().size(), listener.getMaxPlayers() );
pingevent = ProxyServer.getInstance().getPluginManager().callEvent(new ProxyPingEvent(this, pingevent)).getResponse(); pingevent = ProxyServer.getInstance().getPluginManager().callEvent( new ProxyPingEvent( this, pingevent ) ).getResponse();
String response = (newPing) ? ChatColor.COLOR_CHAR + "1" String response = ( newPing ) ? ChatColor.COLOR_CHAR + "1"
+ "\00" + pingevent.getProtocolVersion() + "\00" + pingevent.getProtocolVersion()
+ "\00" + pingevent.getGameVersion() + "\00" + pingevent.getGameVersion()
+ "\00" + pingevent.getMotd() + "\00" + pingevent.getMotd()
+ "\00" + pingevent.getCurrentPlayers() + "\00" + pingevent.getCurrentPlayers()
+ "\00" + pingevent.getMaxPlayers() + "\00" + pingevent.getMaxPlayers()
: pingevent.getMotd() + ChatColor.COLOR_CHAR + pingevent.getCurrentPlayers() + ChatColor.COLOR_CHAR + pingevent.getMaxPlayers(); : pingevent.getMotd() + ChatColor.COLOR_CHAR + pingevent.getCurrentPlayers() + ChatColor.COLOR_CHAR + pingevent.getMaxPlayers();
disconnect(response); disconnect( response );
} }
@Override @Override
public void handle(Packet2Handshake handshake) throws Exception public void handle(Packet2Handshake handshake) throws Exception
{ {
Preconditions.checkState(thisState == State.HANDSHAKE, "Not expecting HANDSHAKE"); Preconditions.checkState( thisState == State.HANDSHAKE, "Not expecting HANDSHAKE" );
this.handshake = handshake; this.handshake = handshake;
request = EncryptionUtil.encryptRequest(); request = EncryptionUtil.encryptRequest();
stream.write(request); stream.write( request );
thisState = State.ENCRYPT; thisState = State.ENCRYPT;
} }
@Override @Override
public void handle(PacketFCEncryptionResponse encryptResponse) throws Exception public void handle(PacketFCEncryptionResponse encryptResponse) throws Exception
{ {
Preconditions.checkState(thisState == State.ENCRYPT, "Not expecting ENCRYPT"); Preconditions.checkState( thisState == State.ENCRYPT, "Not expecting ENCRYPT" );
SecretKey shared = EncryptionUtil.getSecret(encryptResponse, request); SecretKey shared = EncryptionUtil.getSecret( encryptResponse, request );
if (!EncryptionUtil.isAuthenticated(handshake.username, request.serverId, shared)) if ( !EncryptionUtil.isAuthenticated( handshake.username, request.serverId, shared ) )
{ {
throw new KickException("Not authenticated with minecraft.net"); throw new KickException( "Not authenticated with minecraft.net" );
} }
// Check for multiple connections // Check for multiple connections
ProxiedPlayer old = ProxyServer.getInstance().getPlayer(handshake.username); ProxiedPlayer old = ProxyServer.getInstance().getPlayer( handshake.username );
if (old != null) if ( old != null )
{ {
old.disconnect("You are already connected to the server"); old.disconnect( "You are already connected to the server" );
} }
// fire login event // fire login event
LoginEvent event = new LoginEvent(this); LoginEvent event = new LoginEvent( this );
if (event.isCancelled()) if ( event.isCancelled() )
{ {
disconnect(event.getCancelReason()); disconnect( event.getCancelReason() );
} }
stream.write(new PacketFCEncryptionResponse()); stream.write( new PacketFCEncryptionResponse() );
stream = new PacketStream(new CipherInputStream(socket.getInputStream(), stream = new PacketStream( new CipherInputStream( socket.getInputStream(),
EncryptionUtil.getCipher(false, shared)), new CipherOutputStream(socket.getOutputStream(), EncryptionUtil.getCipher(true, shared))); EncryptionUtil.getCipher( false, shared ) ), new CipherOutputStream( socket.getOutputStream(), EncryptionUtil.getCipher( true, shared ) ) );
thisState = State.LOGIN; thisState = State.LOGIN;
} }
@ -125,12 +125,12 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
@Override @Override
public void handle(PacketCDClientStatus clientStatus) throws Exception public void handle(PacketCDClientStatus clientStatus) throws Exception
{ {
Preconditions.checkState(thisState == State.LOGIN, "Not expecting LOGIN"); Preconditions.checkState( thisState == State.LOGIN, "Not expecting LOGIN" );
UserConnection userCon = new UserConnection(socket, this, stream, handshake); UserConnection userCon = new UserConnection( socket, this, stream, handshake );
String server = ProxyServer.getInstance().getReconnectHandler().getServer(userCon); String server = ProxyServer.getInstance().getReconnectHandler().getServer( userCon );
ServerInfo s = BungeeCord.getInstance().config.getServers().get(server); ServerInfo s = BungeeCord.getInstance().config.getServers().get( server );
userCon.connect(s, true); userCon.connect( s, true );
thisState = State.FINISHED; thisState = State.FINISHED;
} }
@ -140,15 +140,15 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
{ {
try try
{ {
while (thisState != State.FINISHED) while ( thisState != State.FINISHED )
{ {
byte[] buf = stream.readPacket(); byte[] buf = stream.readPacket();
DefinedPacket packet = DefinedPacket.packet(buf); DefinedPacket packet = DefinedPacket.packet( buf );
packet.handle(this); packet.handle( this );
} }
} catch (Exception ex) } catch ( Exception ex )
{ {
disconnect("[Proxy Error] " + Util.exception(ex)); disconnect( "[Proxy Error] " + Util.exception( ex ) );
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@ -159,8 +159,8 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
thisState = State.FINISHED; thisState = State.FINISHED;
try try
{ {
stream.write(new PacketFFKick(reason)); stream.write( new PacketFFKick( reason ) );
} catch (IOException ioe) } catch ( IOException ioe )
{ {
} finally } finally
{ {
@ -168,7 +168,7 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
{ {
socket.shutdownOutput(); socket.shutdownOutput();
socket.close(); socket.close();
} catch (IOException ioe2) } catch ( IOException ioe2 )
{ {
} }
} }
@ -177,19 +177,19 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
@Override @Override
public String getName() public String getName()
{ {
return (handshake == null) ? null : handshake.username; return ( handshake == null ) ? null : handshake.username;
} }
@Override @Override
public byte getVersion() public byte getVersion()
{ {
return (handshake == null) ? -1 : handshake.procolVersion; return ( handshake == null ) ? -1 : handshake.procolVersion;
} }
@Override @Override
public InetSocketAddress getVirtualHost() public InetSocketAddress getVirtualHost()
{ {
return (handshake == null) ? null : new InetSocketAddress(handshake.host, handshake.port); return ( handshake == null ) ? null : new InetSocketAddress( handshake.host, handshake.port );
} }
@Override @Override

View File

@ -9,6 +9,6 @@ public class KickException extends RuntimeException
public KickException(String message) public KickException(String message)
{ {
super(message); super( message );
} }
} }

View File

@ -18,27 +18,27 @@ public class ListenThread extends Thread
public ListenThread(ListenerInfo info) throws IOException public ListenThread(ListenerInfo info) throws IOException
{ {
super("Listen Thread - "+ info); super( "Listen Thread - " + info );
this.info = info; this.info = info;
socket = new ServerSocket(); socket = new ServerSocket();
socket.bind(info.getHost()); socket.bind( info.getHost() );
} }
@Override @Override
public void run() public void run()
{ {
while (BungeeCord.getInstance().isRunning) while ( BungeeCord.getInstance().isRunning )
{ {
try try
{ {
Socket client = socket.accept(); Socket client = socket.accept();
BungeeCord.getInstance().setSocketOptions(client); BungeeCord.getInstance().setSocketOptions( client );
$().info(client.getInetAddress() + " has connected"); $().info( client.getInetAddress() + " has connected" );
InitialHandler handler = new InitialHandler(client,info); InitialHandler handler = new InitialHandler( client, info );
BungeeCord.getInstance().threadPool.submit(handler); BungeeCord.getInstance().threadPool.submit( handler );
} catch (SocketException ex) } catch ( SocketException ex )
{ {
} catch (IOException ex) } catch ( IOException ex )
{ {
ex.printStackTrace(); // TODO ex.printStackTrace(); // TODO
} }

View File

@ -21,15 +21,15 @@ public class Logger extends java.util.logging.Logger
public Logger() public Logger()
{ {
super("RubberBand", null); super( "RubberBand", null );
try try
{ {
FileHandler handler = new FileHandler("proxy.log", 1 << 14, 1, true); FileHandler handler = new FileHandler( "proxy.log", 1 << 14, 1, true );
handler.setFormatter(formatter); handler.setFormatter( formatter );
addHandler(handler); addHandler( handler );
} catch (IOException ex) } catch ( IOException ex )
{ {
System.err.println("Could not register logger!"); System.err.println( "Could not register logger!" );
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@ -37,14 +37,14 @@ public class Logger extends java.util.logging.Logger
@Override @Override
public void log(LogRecord record) public void log(LogRecord record)
{ {
super.log(record); super.log( record );
String message = formatter.format(record); String message = formatter.format( record );
if (record.getLevel() == Level.SEVERE || record.getLevel() == Level.WARNING) if ( record.getLevel() == Level.SEVERE || record.getLevel() == Level.WARNING )
{ {
System.err.print(message); System.err.print( message );
} else } else
{ {
System.out.print(message); System.out.print( message );
} }
} }
@ -61,46 +61,46 @@ public class Logger extends java.util.logging.Logger
public static class ConsoleLogFormatter extends Formatter public static class ConsoleLogFormatter extends Formatter
{ {
private SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); private SimpleDateFormat formatter = new SimpleDateFormat( "HH:mm:ss" );
@Override @Override
public String format(LogRecord logrecord) public String format(LogRecord logrecord)
{ {
StringBuilder formatted = new StringBuilder(); StringBuilder formatted = new StringBuilder();
formatted.append(formatter.format(logrecord.getMillis())); formatted.append( formatter.format( logrecord.getMillis() ) );
Level level = logrecord.getLevel(); Level level = logrecord.getLevel();
if (level == Level.FINEST) if ( level == Level.FINEST )
{ {
formatted.append(" [FINEST] "); formatted.append( " [FINEST] " );
} else if (level == Level.FINER) } else if ( level == Level.FINER )
{ {
formatted.append(" [FINER] "); formatted.append( " [FINER] " );
} else if (level == Level.FINE) } else if ( level == Level.FINE )
{ {
formatted.append(" [FINE] "); formatted.append( " [FINE] " );
} else if (level == Level.INFO) } else if ( level == Level.INFO )
{ {
formatted.append(" [INFO] "); formatted.append( " [INFO] " );
} else if (level == Level.WARNING) } else if ( level == Level.WARNING )
{ {
formatted.append(" [WARNING] "); formatted.append( " [WARNING] " );
} else if (level == Level.SEVERE) } else if ( level == Level.SEVERE )
{ {
formatted.append(" [SEVERE] "); formatted.append( " [SEVERE] " );
} }
formatted.append(MessageFormat.format(logrecord.getMessage(), logrecord.getParameters())); formatted.append( MessageFormat.format( logrecord.getMessage(), logrecord.getParameters() ) );
formatted.append('\n'); formatted.append( '\n' );
Throwable throwable = logrecord.getThrown(); Throwable throwable = logrecord.getThrown();
if (throwable != null) if ( throwable != null )
{ {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer)); throwable.printStackTrace( new PrintWriter( writer ) );
formatted.append(writer); formatted.append( writer );
} }
return formatted.toString(); return formatted.toString();

View File

@ -33,34 +33,34 @@ public class Metrics extends Thread
public Metrics() public Metrics()
{ {
super("Metrics Gathering Thread"); super( "Metrics Gathering Thread" );
setDaemon(true); setDaemon( true );
} }
@Override @Override
public void run() public void run()
{ {
boolean firstPost = true; boolean firstPost = true;
while (true) while ( true )
{ {
try try
{ {
// We use the inverse of firstPost because if it is the first time we are posting, // We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE // it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING! // Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost); postPlugin( !firstPost );
// After the first post we set firstPost to false // After the first post we set firstPost to false
// Each post thereafter will be a ping // Each post thereafter will be a ping
firstPost = false; firstPost = false;
} catch (IOException ex) } catch ( IOException ex )
{ {
$().info("[Metrics] " + ex.getMessage()); $().info( "[Metrics] " + ex.getMessage() );
} }
try try
{ {
sleep(PING_INTERVAL * 1000 * 60); sleep( PING_INTERVAL * 1000 * 60 );
} catch (InterruptedException ex) } catch ( InterruptedException ex )
{ {
break; break;
} }
@ -74,41 +74,41 @@ public class Metrics extends Thread
{ {
// Construct the post data // Construct the post data
final StringBuilder data = new StringBuilder(); final StringBuilder data = new StringBuilder();
data.append(encode("guid")).append('=').append(encode(BungeeCord.getInstance().config.getUuid())); data.append( encode( "guid" ) ).append( '=' ).append( encode( BungeeCord.getInstance().config.getUuid() ) );
encodeDataPair(data, "version", ProxyServer.getInstance().getVersion()); encodeDataPair( data, "version", ProxyServer.getInstance().getVersion() );
encodeDataPair(data, "server", "0"); encodeDataPair( data, "server", "0" );
encodeDataPair(data, "players", Integer.toString(ProxyServer.getInstance().getPlayers().size())); encodeDataPair( data, "players", Integer.toString( ProxyServer.getInstance().getPlayers().size() ) );
encodeDataPair(data, "revision", String.valueOf(REVISION)); encodeDataPair( data, "revision", String.valueOf( REVISION ) );
// If we're pinging, append it // If we're pinging, append it
if (isPing) if ( isPing )
{ {
encodeDataPair(data, "ping", "true"); encodeDataPair( data, "ping", "true" );
} }
// Create the url // Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, encode("BungeeCord"))); URL url = new URL( BASE_URL + String.format( REPORT_URL, encode( "BungeeCord" ) ) );
// Connect to the website // Connect to the website
URLConnection connection; URLConnection connection;
connection = url.openConnection(); connection = url.openConnection();
connection.setDoOutput(true); connection.setDoOutput( true );
final BufferedReader reader; final BufferedReader reader;
final String response; final String response;
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) try ( OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() ) )
{ {
writer.write(data.toString()); writer.write( data.toString() );
writer.flush(); writer.flush();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
response = reader.readLine(); response = reader.readLine();
} }
reader.close(); reader.close();
if (response == null || response.startsWith("ERR")) if ( response == null || response.startsWith( "ERR" ) )
{ {
throw new IOException(response); //Throw the exception throw new IOException( response ); //Throw the exception
} }
} }
@ -128,7 +128,7 @@ public class Metrics extends Thread
*/ */
private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException
{ {
buffer.append('&').append(encode(key)).append('=').append(encode(value)); buffer.append( '&' ).append( encode( key ) ).append( '=' ).append( encode( value ) );
} }
/** /**
@ -139,6 +139,6 @@ public class Metrics extends Thread
*/ */
private static String encode(final String text) throws UnsupportedEncodingException private static String encode(final String text) throws UnsupportedEncodingException
{ {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode( text, "UTF-8" );
} }
} }

View File

@ -33,7 +33,7 @@ public class ServerConnection extends GenericConnection implements Server
public ServerConnection(Socket socket, ServerInfo info, PacketStream stream, Packet1Login loginPacket) public ServerConnection(Socket socket, ServerInfo info, PacketStream stream, Packet1Login loginPacket)
{ {
super(socket, stream); super( socket, stream );
this.info = info; this.info = info;
this.loginPacket = loginPacket; this.loginPacket = loginPacket;
} }
@ -43,48 +43,48 @@ public class ServerConnection extends GenericConnection implements Server
try try
{ {
Socket socket = new Socket(); Socket socket = new Socket();
socket.connect(info.getAddress(), BungeeCord.getInstance().config.getTimeout()); socket.connect( info.getAddress(), BungeeCord.getInstance().config.getTimeout() );
BungeeCord.getInstance().setSocketOptions(socket); BungeeCord.getInstance().setSocketOptions( socket );
PacketStream stream = new PacketStream(socket.getInputStream(), socket.getOutputStream()); PacketStream stream = new PacketStream( socket.getInputStream(), socket.getOutputStream() );
stream.write(handshake); stream.write( handshake );
stream.write(new PacketCDClientStatus((byte) 0)); stream.write( new PacketCDClientStatus( (byte) 0 ) );
stream.readPacket(); stream.readPacket();
byte[] loginResponse = stream.readPacket(); byte[] loginResponse = stream.readPacket();
if (Util.getId(loginResponse) == 0xFF) if ( Util.getId( loginResponse ) == 0xFF )
{ {
throw new KickException("[Kicked] " + new PacketFFKick(loginResponse).message); throw new KickException( "[Kicked] " + new PacketFFKick( loginResponse ).message );
} }
Packet1Login login = new Packet1Login(loginResponse); Packet1Login login = new Packet1Login( loginResponse );
ServerConnection server = new ServerConnection(socket, info, stream, login); ServerConnection server = new ServerConnection( socket, info, stream, login );
ServerConnectedEvent event = new ServerConnectedEvent(user, server); ServerConnectedEvent event = new ServerConnectedEvent( user, server );
ProxyServer.getInstance().getPluginManager().callEvent(event); ProxyServer.getInstance().getPluginManager().callEvent( event );
stream.write(BungeeCord.getInstance().registerChannels()); stream.write( BungeeCord.getInstance().registerChannels() );
Queue<DefinedPacket> packetQueue = ((BungeeServerInfo) info).getPacketQueue(); Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) info ).getPacketQueue();
while (!packetQueue.isEmpty()) while ( !packetQueue.isEmpty() )
{ {
stream.write(packetQueue.poll()); stream.write( packetQueue.poll() );
} }
return server; return server;
} catch (KickException ex) } catch ( KickException ex )
{ {
throw ex; throw ex;
} catch (Exception ex) } catch ( Exception ex )
{ {
ServerInfo def = ProxyServer.getInstance().getServers().get(user.getPendingConnection().getListener().getDefaultServer()); ServerInfo def = ProxyServer.getInstance().getServers().get( user.getPendingConnection().getListener().getDefaultServer() );
if (retry && !info.equals(def)) if ( retry && !info.equals( def ) )
{ {
user.sendMessage(ChatColor.RED + "Could not connect to target server, you have been moved to the default server"); user.sendMessage( ChatColor.RED + "Could not connect to target server, you have been moved to the default server" );
return connect(user, def, handshake, false); return connect( user, def, handshake, false );
} else } else
{ {
throw new RuntimeException("Could not connect to target server " + Util.exception(ex)); throw new RuntimeException( "Could not connect to target server " + Util.exception( ex ) );
} }
} }
} }
@ -92,13 +92,13 @@ public class ServerConnection extends GenericConnection implements Server
@Override @Override
public void sendData(String channel, byte[] data) public void sendData(String channel, byte[] data)
{ {
packetQueue.add(new PacketFAPluginMessage(channel, data)); packetQueue.add( new PacketFAPluginMessage( channel, data ) );
} }
@Override @Override
public void ping(final Callback<ServerPing> callback) public void ping(final Callback<ServerPing> callback)
{ {
getInfo().ping(callback); getInfo().ping( callback );
} }
@Override @Override

View File

@ -5,14 +5,12 @@ import java.io.ByteArrayOutputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
@ -56,25 +54,25 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public UserConnection(Socket socket, PendingConnection pendingConnection, PacketStream stream, Packet2Handshake handshake) public UserConnection(Socket socket, PendingConnection pendingConnection, PacketStream stream, Packet2Handshake handshake)
{ {
super(socket, stream); super( socket, stream );
this.handshake = handshake; this.handshake = handshake;
this.pendingConnection = pendingConnection; this.pendingConnection = pendingConnection;
name = handshake.username; name = handshake.username;
displayName = handshake.username; displayName = handshake.username;
Collection<String> g = ProxyServer.getInstance().getConfigurationAdapter().getGroups(name); Collection<String> g = ProxyServer.getInstance().getConfigurationAdapter().getGroups( name );
for (String s : g) for ( String s : g )
{ {
addGroups(s); addGroups( s );
} }
} }
@Override @Override
public void setDisplayName(String name) public void setDisplayName(String name)
{ {
ProxyServer.getInstance().getTabListHandler().onDisconnect(this); ProxyServer.getInstance().getTabListHandler().onDisconnect( this );
displayName = name; displayName = name;
ProxyServer.getInstance().getTabListHandler().onConnect(this); ProxyServer.getInstance().getTabListHandler().onConnect( this );
} }
@Override @Override
@ -85,36 +83,36 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public void connect(ServerInfo target, boolean force) public void connect(ServerInfo target, boolean force)
{ {
if (server == null) if ( server == null )
{ {
// First join // First join
BungeeCord.getInstance().connections.put(name, this); BungeeCord.getInstance().connections.put( name, this );
ProxyServer.getInstance().getTabListHandler().onConnect(this); ProxyServer.getInstance().getTabListHandler().onConnect( this );
} }
ServerConnectEvent event = new ServerConnectEvent(this, target); ServerConnectEvent event = new ServerConnectEvent( this, target );
BungeeCord.getInstance().getPluginManager().callEvent(event); BungeeCord.getInstance().getPluginManager().callEvent( event );
target = event.getTarget(); // Update in case the event changed target target = event.getTarget(); // Update in case the event changed target
ProxyServer.getInstance().getTabListHandler().onServerChange(this); ProxyServer.getInstance().getTabListHandler().onServerChange( this );
try try
{ {
reconnecting = true; reconnecting = true;
if (server != null) if ( server != null )
{ {
stream.write(new Packet9Respawn((byte) 1, (byte) 0, (byte) 0, (short) 256, "DEFAULT")); stream.write( new Packet9Respawn( (byte) 1, (byte) 0, (byte) 0, (short) 256, "DEFAULT" ) );
stream.write(new Packet9Respawn((byte) -1, (byte) 0, (byte) 0, (short) 256, "DEFAULT")); stream.write( new Packet9Respawn( (byte) -1, (byte) 0, (byte) 0, (short) 256, "DEFAULT" ) );
} }
ServerConnection newServer = ServerConnection.connect(this, target, handshake, true); ServerConnection newServer = ServerConnection.connect( this, target, handshake, true );
if (server == null) if ( server == null )
{ {
// Once again, first connection // Once again, first connection
clientEntityId = newServer.loginPacket.entityId; clientEntityId = newServer.loginPacket.entityId;
serverEntityId = newServer.loginPacket.entityId; serverEntityId = newServer.loginPacket.entityId;
stream.write(newServer.loginPacket); stream.write( newServer.loginPacket );
stream.write(BungeeCord.getInstance().registerChannels()); stream.write( BungeeCord.getInstance().registerChannels() );
upBridge = new UpstreamBridge(); upBridge = new UpstreamBridge();
upBridge.start(); upBridge.start();
@ -124,68 +122,68 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
{ {
downBridge.interrupt(); downBridge.interrupt();
downBridge.join(); downBridge.join();
} catch (InterruptedException ie) } catch ( InterruptedException ie )
{ {
} }
server.disconnect("Quitting"); server.disconnect( "Quitting" );
server.getInfo().removePlayer(this); server.getInfo().removePlayer( this );
Packet1Login login = newServer.loginPacket; Packet1Login login = newServer.loginPacket;
serverEntityId = login.entityId; serverEntityId = login.entityId;
stream.write(new Packet9Respawn(login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType)); stream.write( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) );
} }
// Reconnect process has finished, lets get the player moving again // Reconnect process has finished, lets get the player moving again
reconnecting = false; reconnecting = false;
// Add to new // Add to new
target.addPlayer(this); target.addPlayer( this );
// Start the bridges and move on // Start the bridges and move on
server = newServer; server = newServer;
downBridge = new DownstreamBridge(); downBridge = new DownstreamBridge();
downBridge.start(); downBridge.start();
} catch (KickException ex) } catch ( KickException ex )
{ {
destroySelf(ex.getMessage()); destroySelf( ex.getMessage() );
} catch (Exception ex) } catch ( Exception ex )
{ {
ex.printStackTrace(); // TODO: Remove ex.printStackTrace(); // TODO: Remove
destroySelf("Could not connect to server - " + ex.getClass().getSimpleName()); destroySelf( "Could not connect to server - " + ex.getClass().getSimpleName() );
} }
} }
private void destroySelf(String reason) private void destroySelf(String reason)
{ {
ProxyServer.getInstance().getPlayers().remove(this); ProxyServer.getInstance().getPlayers().remove( this );
disconnect(reason); disconnect( reason );
if (server != null) if ( server != null )
{ {
server.getInfo().removePlayer(this); server.getInfo().removePlayer( this );
server.disconnect("Quitting"); server.disconnect( "Quitting" );
ProxyServer.getInstance().getReconnectHandler().setServer(this); ProxyServer.getInstance().getReconnectHandler().setServer( this );
} }
} }
@Override @Override
public void disconnect(String reason) public void disconnect(String reason)
{ {
ProxyServer.getInstance().getTabListHandler().onDisconnect(this); ProxyServer.getInstance().getTabListHandler().onDisconnect( this );
super.disconnect(reason); super.disconnect( reason );
} }
@Override @Override
public void sendMessage(String message) public void sendMessage(String message)
{ {
packetQueue.add(new Packet3Chat(message)); packetQueue.add( new Packet3Chat( message ) );
} }
@Override @Override
public void sendData(String channel, byte[] data) public void sendData(String channel, byte[] data)
{ {
server.packetQueue.add(new PacketFAPluginMessage(channel, data)); server.packetQueue.add( new PacketFAPluginMessage( channel, data ) );
} }
@Override @Override
@ -198,19 +196,19 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
@Synchronized("permMutex") @Synchronized("permMutex")
public Collection<String> getGroups() public Collection<String> getGroups()
{ {
return Collections.unmodifiableCollection(groups); return Collections.unmodifiableCollection( groups );
} }
@Override @Override
@Synchronized("permMutex") @Synchronized("permMutex")
public void addGroups(String... groups) public void addGroups(String... groups)
{ {
for (String group : groups) for ( String group : groups )
{ {
this.groups.add(group); this.groups.add( group );
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group)) for ( String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions( group ) )
{ {
setPermission(permission, true); setPermission( permission, true );
} }
} }
} }
@ -219,12 +217,12 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
@Synchronized("permMutex") @Synchronized("permMutex")
public void removeGroups(String... groups) public void removeGroups(String... groups)
{ {
for (String group : groups) for ( String group : groups )
{ {
this.groups.remove(group); this.groups.remove( group );
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group)) for ( String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions( group ) )
{ {
setPermission(permission, false); setPermission( permission, false );
} }
} }
} }
@ -233,15 +231,15 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
@Synchronized("permMutex") @Synchronized("permMutex")
public boolean hasPermission(String permission) public boolean hasPermission(String permission)
{ {
Boolean val = permissions.get(permission); Boolean val = permissions.get( permission );
return (val == null) ? false : val; return ( val == null ) ? false : val;
} }
@Override @Override
@Synchronized("permMutex") @Synchronized("permMutex")
public void setPermission(String permission, boolean value) public void setPermission(String permission, boolean value)
{ {
permissions.put(permission, value); permissions.put( permission, value );
} }
private class UpstreamBridge extends Thread private class UpstreamBridge extends Thread
@ -249,82 +247,82 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public UpstreamBridge() public UpstreamBridge()
{ {
super("Upstream Bridge - " + name); super( "Upstream Bridge - " + name );
} }
@Override @Override
public void run() public void run()
{ {
while (!socket.isClosed()) while ( !socket.isClosed() )
{ {
try try
{ {
byte[] packet = stream.readPacket(); byte[] packet = stream.readPacket();
boolean sendPacket = true; boolean sendPacket = true;
int id = Util.getId(packet); int id = Util.getId( packet );
switch (id) switch ( id )
{ {
case 0x00: case 0x00:
if (trackingPingId == new Packet0KeepAlive(packet).id) if ( trackingPingId == new Packet0KeepAlive( packet ).id )
{ {
int newPing = (int) (System.currentTimeMillis() - pingTime); int newPing = (int) ( System.currentTimeMillis() - pingTime );
ProxyServer.getInstance().getTabListHandler().onPingChange(UserConnection.this, newPing); ProxyServer.getInstance().getTabListHandler().onPingChange( UserConnection.this, newPing );
ping = newPing; ping = newPing;
} }
break; break;
case 0x03: case 0x03:
Packet3Chat chat = new Packet3Chat(packet); Packet3Chat chat = new Packet3Chat( packet );
if (chat.message.startsWith("/")) if ( chat.message.startsWith( "/" ) )
{ {
sendPacket = !ProxyServer.getInstance().getPluginManager().dispatchCommand(UserConnection.this, chat.message.substring(1)); sendPacket = !ProxyServer.getInstance().getPluginManager().dispatchCommand( UserConnection.this, chat.message.substring( 1 ) );
} else } else
{ {
ChatEvent chatEvent = new ChatEvent(UserConnection.this, server, chat.message); ChatEvent chatEvent = new ChatEvent( UserConnection.this, server, chat.message );
ProxyServer.getInstance().getPluginManager().callEvent(chatEvent); ProxyServer.getInstance().getPluginManager().callEvent( chatEvent );
sendPacket = !chatEvent.isCancelled(); sendPacket = !chatEvent.isCancelled();
} }
break; break;
case 0xFA: case 0xFA:
// Call the onPluginMessage event // Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage(packet); PacketFAPluginMessage message = new PacketFAPluginMessage( packet );
// Might matter in the future // Might matter in the future
if (message.tag.equals("BungeeCord")) if ( message.tag.equals( "BungeeCord" ) )
{ {
continue; continue;
} }
PluginMessageEvent event = new PluginMessageEvent(UserConnection.this, server, message.tag, message.data); PluginMessageEvent event = new PluginMessageEvent( UserConnection.this, server, message.tag, message.data );
ProxyServer.getInstance().getPluginManager().callEvent(event); ProxyServer.getInstance().getPluginManager().callEvent( event );
if (event.isCancelled()) if ( event.isCancelled() )
{ {
continue; continue;
} }
break; break;
} }
while (!server.packetQueue.isEmpty()) while ( !server.packetQueue.isEmpty() )
{ {
DefinedPacket p = server.packetQueue.poll(); DefinedPacket p = server.packetQueue.poll();
if (p != null) if ( p != null )
{ {
server.stream.write(p); server.stream.write( p );
} }
} }
EntityMap.rewrite(packet, clientEntityId, serverEntityId); EntityMap.rewrite( packet, clientEntityId, serverEntityId );
if (sendPacket && !server.socket.isClosed()) if ( sendPacket && !server.socket.isClosed() )
{ {
server.stream.write(packet); server.stream.write( packet );
} }
} catch (IOException ex) } catch ( IOException ex )
{ {
destroySelf("Reached end of stream"); destroySelf( "Reached end of stream" );
} catch (Exception ex) } catch ( Exception ex )
{ {
destroySelf(Util.exception(ex)); destroySelf( Util.exception( ex ) );
} }
} }
} }
@ -335,7 +333,7 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public DownstreamBridge() public DownstreamBridge()
{ {
super("Downstream Bridge - " + name); super( "Downstream Bridge - " + name );
} }
@Override @Override
@ -344,180 +342,180 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
try try
{ {
outer: outer:
while (!reconnecting) while ( !reconnecting )
{ {
byte[] packet = server.stream.readPacket(); byte[] packet = server.stream.readPacket();
int id = Util.getId(packet); int id = Util.getId( packet );
switch (id) switch ( id )
{ {
case 0x00: case 0x00:
trackingPingId = new Packet0KeepAlive(packet).id; trackingPingId = new Packet0KeepAlive( packet ).id;
pingTime = System.currentTimeMillis(); pingTime = System.currentTimeMillis();
break; break;
case 0x03: case 0x03:
Packet3Chat chat = new Packet3Chat(packet); Packet3Chat chat = new Packet3Chat( packet );
ChatEvent chatEvent = new ChatEvent(server, UserConnection.this, chat.message); ChatEvent chatEvent = new ChatEvent( server, UserConnection.this, chat.message );
ProxyServer.getInstance().getPluginManager().callEvent(chatEvent); ProxyServer.getInstance().getPluginManager().callEvent( chatEvent );
if (chatEvent.isCancelled()) if ( chatEvent.isCancelled() )
{ {
continue; continue;
} }
break; break;
case 0xC9: case 0xC9:
PacketC9PlayerListItem playerList = new PacketC9PlayerListItem(packet); PacketC9PlayerListItem playerList = new PacketC9PlayerListItem( packet );
if (!ProxyServer.getInstance().getTabListHandler().onListUpdate(UserConnection.this, playerList.username, playerList.online, playerList.ping)) if ( !ProxyServer.getInstance().getTabListHandler().onListUpdate( UserConnection.this, playerList.username, playerList.online, playerList.ping ) )
{ {
continue; continue;
} }
break; break;
case 0xFA: case 0xFA:
// Call the onPluginMessage event // Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage(packet); PacketFAPluginMessage message = new PacketFAPluginMessage( packet );
DataInputStream in = new DataInputStream(new ByteArrayInputStream(message.data)); DataInputStream in = new DataInputStream( new ByteArrayInputStream( message.data ) );
PluginMessageEvent event = new PluginMessageEvent(server, UserConnection.this, message.tag, message.data); PluginMessageEvent event = new PluginMessageEvent( server, UserConnection.this, message.tag, message.data );
ProxyServer.getInstance().getPluginManager().callEvent(event); ProxyServer.getInstance().getPluginManager().callEvent( event );
if (event.isCancelled()) if ( event.isCancelled() )
{ {
continue; continue;
} }
if (message.tag.equals("BungeeCord")) if ( message.tag.equals( "BungeeCord" ) )
{ {
String subChannel = in.readUTF(); String subChannel = in.readUTF();
if (subChannel.equals("Forward")) if ( subChannel.equals( "Forward" ) )
{ {
String target = in.readUTF(); String target = in.readUTF();
String channel = in.readUTF(); String channel = in.readUTF();
short len = in.readShort(); short len = in.readShort();
byte[] data = new byte[len]; byte[] data = new byte[ len ];
in.readFully(data); in.readFully( data );
ByteArrayOutputStream b = new ByteArrayOutputStream(); ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b); DataOutputStream out = new DataOutputStream( b );
out.writeUTF(channel); out.writeUTF( channel );
out.writeShort(data.length); out.writeShort( data.length );
out.write(data); out.write( data );
if (target.equals("ALL")) if ( target.equals( "ALL" ) )
{ {
for (ServerInfo server : BungeeCord.getInstance().getServers().values()) for ( ServerInfo server : BungeeCord.getInstance().getServers().values() )
{ {
server.sendData("BungeeCord", b.toByteArray()); server.sendData( "BungeeCord", b.toByteArray() );
} }
} else } else
{ {
ServerInfo server = BungeeCord.getInstance().getServerInfo(target); ServerInfo server = BungeeCord.getInstance().getServerInfo( target );
if (server != null) if ( server != null )
{ {
server.sendData("BungeeCord", b.toByteArray()); server.sendData( "BungeeCord", b.toByteArray() );
} }
} }
} }
if (subChannel.equals("Connect")) if ( subChannel.equals( "Connect" ) )
{ {
ServerInfo server = ProxyServer.getInstance().getServerInfo(in.readUTF()); ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if (server != null) if ( server != null )
{ {
connect(server, true); connect( server, true );
break outer; break outer;
} }
} }
if (subChannel.equals("IP")) if ( subChannel.equals( "IP" ) )
{ {
ByteArrayOutputStream b = new ByteArrayOutputStream(); ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b); DataOutputStream out = new DataOutputStream( b );
out.writeUTF("IP"); out.writeUTF( "IP" );
out.writeUTF(getAddress().getHostString()); out.writeUTF( getAddress().getHostString() );
out.writeInt(getAddress().getPort()); out.writeInt( getAddress().getPort() );
getServer().sendData("BungeeCord", b.toByteArray()); getServer().sendData( "BungeeCord", b.toByteArray() );
} }
if (subChannel.equals("PlayerCount")) if ( subChannel.equals( "PlayerCount" ) )
{ {
ServerInfo server = ProxyServer.getInstance().getServerInfo(in.readUTF()); ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if (server != null) if ( server != null )
{ {
ByteArrayOutputStream b = new ByteArrayOutputStream(); ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b); DataOutputStream out = new DataOutputStream( b );
out.writeUTF("PlayerCount"); out.writeUTF( "PlayerCount" );
out.writeUTF(server.getName()); out.writeUTF( server.getName() );
out.writeInt(server.getPlayers().size()); out.writeInt( server.getPlayers().size() );
getServer().sendData("BungeeCord", b.toByteArray()); getServer().sendData( "BungeeCord", b.toByteArray() );
} }
} }
if (subChannel.equals("PlayerList")) if ( subChannel.equals( "PlayerList" ) )
{ {
ServerInfo server = ProxyServer.getInstance().getServerInfo(in.readUTF()); ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if (server != null) if ( server != null )
{ {
ByteArrayOutputStream b = new ByteArrayOutputStream(); ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b); DataOutputStream out = new DataOutputStream( b );
out.writeUTF("PlayerList"); out.writeUTF( "PlayerList" );
out.writeUTF(server.getName()); out.writeUTF( server.getName() );
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (ProxiedPlayer p : server.getPlayers()) for ( ProxiedPlayer p : server.getPlayers() )
{ {
sb.append(p.getName()); sb.append( p.getName() );
sb.append(","); sb.append( "," );
} }
out.writeUTF(sb.substring(0, sb.length() - 1)); out.writeUTF( sb.substring( 0, sb.length() - 1 ) );
getServer().sendData("BungeeCord", b.toByteArray()); getServer().sendData( "BungeeCord", b.toByteArray() );
} }
} }
if (subChannel.equals("GetServers")) if ( subChannel.equals( "GetServers" ) )
{ {
ByteArrayOutputStream b = new ByteArrayOutputStream(); ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b); DataOutputStream out = new DataOutputStream( b );
out.writeUTF("GetServers"); out.writeUTF( "GetServers" );
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String server : ProxyServer.getInstance().getServers().keySet()) for ( String server : ProxyServer.getInstance().getServers().keySet() )
{ {
sb.append(server); sb.append( server );
sb.append(","); sb.append( "," );
} }
out.writeUTF(sb.substring(0, sb.length() - 1)); out.writeUTF( sb.substring( 0, sb.length() - 1 ) );
getServer().sendData("BungeeCord", b.toByteArray()); getServer().sendData( "BungeeCord", b.toByteArray() );
} }
if (subChannel.equals("Message")) if ( subChannel.equals( "Message" ) )
{ {
ProxiedPlayer target = ProxyServer.getInstance().getPlayer(in.readUTF()); ProxiedPlayer target = ProxyServer.getInstance().getPlayer( in.readUTF() );
if (target != null) if ( target != null )
{ {
target.sendMessage(in.readUTF()); target.sendMessage( in.readUTF() );
} }
} }
continue; continue;
} }
} }
while (!packetQueue.isEmpty()) while ( !packetQueue.isEmpty() )
{ {
DefinedPacket p = packetQueue.poll(); DefinedPacket p = packetQueue.poll();
if (p != null) if ( p != null )
{ {
stream.write(p); stream.write( p );
} }
} }
EntityMap.rewrite(packet, serverEntityId, clientEntityId); EntityMap.rewrite( packet, serverEntityId, clientEntityId );
stream.write(packet); stream.write( packet );
if (nextServer != null) if ( nextServer != null )
{ {
connect(nextServer, true); connect( nextServer, true );
break outer; break outer;
} }
} }
} catch (Exception ex) } catch ( Exception ex )
{ {
destroySelf(Util.exception(ex)); destroySelf( Util.exception( ex ) );
} }
} }
} }

View File

@ -18,13 +18,13 @@ public class Util
*/ */
public static InetSocketAddress getAddr(String hostline) public static InetSocketAddress getAddr(String hostline)
{ {
String[] split = hostline.split(":"); String[] split = hostline.split( ":" );
int port = DEFAULT_PORT; int port = DEFAULT_PORT;
if (split.length > 1) if ( split.length > 1 )
{ {
port = Integer.parseInt(split[1]); port = Integer.parseInt( split[1] );
} }
return new InetSocketAddress(split[0], port); return new InetSocketAddress( split[0], port );
} }
/** /**
@ -49,13 +49,13 @@ public class Util
public static String normalize(String s) public static String normalize(String s)
{ {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) for ( char c : s.toCharArray() )
{ {
if (Character.isUpperCase(c)) if ( Character.isUpperCase( c ) )
{ {
result.append("_"); result.append( "_" );
} }
result.append(Character.toLowerCase(c)); result.append( Character.toLowerCase( c ) );
} }
return result.toString(); return result.toString();
} }
@ -68,7 +68,7 @@ public class Util
*/ */
public static String hex(int i) public static String hex(int i)
{ {
return String.format("0x%02X", i); return String.format( "0x%02X", i );
} }
/** /**

View File

@ -18,7 +18,7 @@ public class YamlReconnectHandler implements ReconnectHandler
{ {
private final Yaml yaml = new Yaml(); private final Yaml yaml = new Yaml();
private final File file = new File("locations.yml"); private final File file = new File( "locations.yml" );
/*========================================================================*/ /*========================================================================*/
private Map<String, String> data; private Map<String, String> data;
@ -28,21 +28,21 @@ public class YamlReconnectHandler implements ReconnectHandler
try try
{ {
file.createNewFile(); file.createNewFile();
try (FileReader rd = new FileReader(file)) try ( FileReader rd = new FileReader( file ) )
{ {
data = yaml.loadAs(rd, Map.class); data = yaml.loadAs( rd, Map.class );
} }
} catch (IOException ex) } catch ( IOException ex )
{ {
ProxyServer.getInstance().getLogger().log(Level.WARNING, "Could not load reconnect locations", ex); ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load reconnect locations", ex );
} }
if (data == null) if ( data == null )
{ {
data = new ConcurrentHashMap<>(); data = new ConcurrentHashMap<>();
} else } else
{ {
data = new ConcurrentHashMap<>(data); data = new ConcurrentHashMap<>( data );
} }
} }
@ -50,19 +50,19 @@ public class YamlReconnectHandler implements ReconnectHandler
public String getServer(ProxiedPlayer player) public String getServer(ProxiedPlayer player)
{ {
ListenerInfo listener = player.getPendingConnection().getListener(); ListenerInfo listener = player.getPendingConnection().getListener();
if (listener.isForceDefault()) if ( listener.isForceDefault() )
{ {
return listener.getDefaultServer(); return listener.getDefaultServer();
} }
String forced = listener.getForcedHosts().get(player.getPendingConnection().getVirtualHost().getHostName()); String forced = listener.getForcedHosts().get( player.getPendingConnection().getVirtualHost().getHostName() );
String server = (forced == null) ? data.get(key(player)) : forced; String server = ( forced == null ) ? data.get( key( player ) ) : forced;
return (server != null) ? server : listener.getDefaultServer(); return ( server != null ) ? server : listener.getDefaultServer();
} }
@Override @Override
public void setServer(ProxiedPlayer player) public void setServer(ProxiedPlayer player)
{ {
data.put(key(player), player.getServer().getInfo().getName()); data.put( key( player ), player.getServer().getInfo().getName() );
} }
private String key(ProxiedPlayer player) private String key(ProxiedPlayer player)
@ -74,12 +74,12 @@ public class YamlReconnectHandler implements ReconnectHandler
@Override @Override
public void save() public void save()
{ {
try (FileWriter wr = new FileWriter(file)) try ( FileWriter wr = new FileWriter( file ) )
{ {
yaml.dump(data, wr); yaml.dump( data, wr );
} catch (IOException ex) } catch ( IOException ex )
{ {
ProxyServer.getInstance().getLogger().log(Level.WARNING, "Could not save reconnect locations", ex); ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not save reconnect locations", ex );
} }
} }
} }

View File

@ -11,38 +11,38 @@ public class CommandAlert extends Command
public CommandAlert() public CommandAlert()
{ {
super("alert", "bungeecord.command.alert"); super( "alert", "bungeecord.command.alert" );
} }
@Override @Override
public void execute(CommandSender sender, String[] args) public void execute(CommandSender sender, String[] args)
{ {
if (args.length == 0) if ( args.length == 0 )
{ {
sender.sendMessage(ChatColor.RED + "You must supply a message."); sender.sendMessage( ChatColor.RED + "You must supply a message." );
} else } else
{ {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
if (args[0].startsWith("&h")) if ( args[0].startsWith( "&h" ) )
{ {
// Remove &h // Remove &h
args[0] = args[0].substring(2, args[0].length()); args[0] = args[0].substring( 2, args[0].length() );
} else } else
{ {
builder.append(ChatColor.DARK_PURPLE); builder.append( ChatColor.DARK_PURPLE );
builder.append("[Alert] "); builder.append( "[Alert] " );
} }
for (String s : args) for ( String s : args )
{ {
builder.append(ChatColor.translateAlternateColorCodes('&', s)); builder.append( ChatColor.translateAlternateColorCodes( '&', s ) );
builder.append(" "); builder.append( " " );
} }
String message = builder.substring(0, builder.length() - 1); String message = builder.substring( 0, builder.length() - 1 );
for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) for ( ProxiedPlayer player : ProxyServer.getInstance().getPlayers() )
{ {
player.sendMessage(message); player.sendMessage( message );
} }
} }
} }

View File

@ -10,12 +10,12 @@ public class CommandBungee extends Command
public CommandBungee() public CommandBungee()
{ {
super("bungee"); super( "bungee" );
} }
@Override @Override
public void execute(CommandSender sender, String[] args) public void execute(CommandSender sender, String[] args)
{ {
sender.sendMessage(ChatColor.BLUE + "This server is running BungeeCord version " + ProxyServer.getInstance().getVersion() + " by md_5"); sender.sendMessage( ChatColor.BLUE + "This server is running BungeeCord version " + ProxyServer.getInstance().getVersion() + " by md_5" );
} }
} }

View File

@ -12,7 +12,7 @@ public class CommandEnd extends Command
public CommandEnd() public CommandEnd()
{ {
super("end", "bungeecord.command.end"); super( "end", "bungeecord.command.end" );
} }
@Override @Override

View File

@ -11,24 +11,24 @@ public class CommandIP extends Command
public CommandIP() public CommandIP()
{ {
super("ip", "bungeecord.command.ip"); super( "ip", "bungeecord.command.ip" );
} }
@Override @Override
public void execute(CommandSender sender, String[] args) public void execute(CommandSender sender, String[] args)
{ {
if (args.length < 1) if ( args.length < 1 )
{ {
sender.sendMessage(ChatColor.RED + "Please follow this command by a user name"); sender.sendMessage( ChatColor.RED + "Please follow this command by a user name" );
return; return;
} }
ProxiedPlayer user = ProxyServer.getInstance().getPlayer(args[0]); ProxiedPlayer user = ProxyServer.getInstance().getPlayer( args[0] );
if (user == null) if ( user == null )
{ {
sender.sendMessage(ChatColor.RED + "That user is not online"); sender.sendMessage( ChatColor.RED + "That user is not online" );
} else } else
{ {
sender.sendMessage(ChatColor.BLUE + "IP of " + args[0] + " is " + user.getAddress()); sender.sendMessage( ChatColor.BLUE + "IP of " + args[0] + " is " + user.getAddress() );
} }
} }
} }

View File

@ -15,7 +15,7 @@ public class CommandList extends Command
public CommandList() public CommandList()
{ {
super("glist", "bungeecord.command.list"); super( "glist", "bungeecord.command.list" );
} }
@Override @Override
@ -24,20 +24,20 @@ public class CommandList extends Command
StringBuilder users = new StringBuilder(); StringBuilder users = new StringBuilder();
Collection<ProxiedPlayer> connections = ProxyServer.getInstance().getPlayers(); Collection<ProxiedPlayer> connections = ProxyServer.getInstance().getPlayers();
if (connections.isEmpty()) if ( connections.isEmpty() )
{ {
sender.sendMessage(ChatColor.BLUE + "Currently no players online."); sender.sendMessage( ChatColor.BLUE + "Currently no players online." );
return; return;
} }
for (ProxiedPlayer player : connections) for ( ProxiedPlayer player : connections )
{ {
users.append(player.getDisplayName()); users.append( player.getDisplayName() );
users.append(", "); users.append( ", " );
users.append(ChatColor.RESET); users.append( ChatColor.RESET );
} }
users.setLength(users.length() - 2); users.setLength( users.length() - 2 );
sender.sendMessage(ChatColor.BLUE + "Currently online across all servers (" + connections.size() + "): " + ChatColor.RESET + users); sender.sendMessage( ChatColor.BLUE + "Currently online across all servers (" + connections.size() + "): " + ChatColor.RESET + users );
} }
} }

View File

@ -10,13 +10,13 @@ public class CommandReload extends Command
public CommandReload() public CommandReload()
{ {
super("greload", "bungeecord.command.reload"); super( "greload", "bungeecord.command.reload" );
} }
@Override @Override
public void execute(CommandSender sender, String[] args) public void execute(CommandSender sender, String[] args)
{ {
BungeeCord.getInstance().config.load(); BungeeCord.getInstance().config.load();
sender.sendMessage(ChatColor.GREEN + "Reloaded config, please restart if you have any issues"); sender.sendMessage( ChatColor.GREEN + "Reloaded config, please restart if you have any issues" );
} }
} }

View File

@ -16,40 +16,40 @@ public class CommandServer extends Command
public CommandServer() public CommandServer()
{ {
super("server", "bungeecord.command.server"); super( "server", "bungeecord.command.server" );
} }
@Override @Override
public void execute(CommandSender sender, String[] args) public void execute(CommandSender sender, String[] args)
{ {
if (!(sender instanceof ProxiedPlayer)) if ( !( sender instanceof ProxiedPlayer ) )
{ {
return; return;
} }
ProxiedPlayer player = (ProxiedPlayer) sender; ProxiedPlayer player = (ProxiedPlayer) sender;
Map<String, ServerInfo> servers = BungeeCord.getInstance().config.getServers(); Map<String, ServerInfo> servers = BungeeCord.getInstance().config.getServers();
if (args.length == 0) if ( args.length == 0 )
{ {
StringBuilder serverList = new StringBuilder(); StringBuilder serverList = new StringBuilder();
for (String server : servers.keySet()) for ( String server : servers.keySet() )
{ {
serverList.append(server); serverList.append( server );
serverList.append(", "); serverList.append( ", " );
} }
serverList.setLength(serverList.length() - 2); serverList.setLength( serverList.length() - 2 );
player.sendMessage(ChatColor.GOLD + "You may connect to the following servers at this time: " + serverList.toString()); player.sendMessage( ChatColor.GOLD + "You may connect to the following servers at this time: " + serverList.toString() );
} else } else
{ {
ServerInfo server = servers.get(args[0]); ServerInfo server = servers.get( args[0] );
if (server == null) if ( server == null )
{ {
player.sendMessage(ChatColor.RED + "The specified server does not exist"); player.sendMessage( ChatColor.RED + "The specified server does not exist" );
} else if (server.equals(player.getServer().getInfo())) } else if ( server.equals( player.getServer().getInfo() ) )
{ {
player.sendMessage(ChatColor.RED + "You are already on this server."); player.sendMessage( ChatColor.RED + "You are already on this server." );
} else } else
{ {
player.connect(server); player.connect( server );
} }
} }
} }

View File

@ -22,7 +22,7 @@ public class ConsoleCommandSender implements CommandSender
@Override @Override
public void sendMessage(String message) public void sendMessage(String message)
{ {
System.out.println(ChatColor.stripColor(message)); System.out.println( ChatColor.stripColor( message ) );
} }
@Override @Override
@ -40,13 +40,13 @@ public class ConsoleCommandSender implements CommandSender
@Override @Override
public void addGroups(String... groups) public void addGroups(String... groups)
{ {
throw new UnsupportedOperationException("Console may not have groups"); throw new UnsupportedOperationException( "Console may not have groups" );
} }
@Override @Override
public void removeGroups(String... groups) public void removeGroups(String... groups)
{ {
throw new UnsupportedOperationException("Console may not have groups"); throw new UnsupportedOperationException( "Console may not have groups" );
} }
@Override @Override
@ -58,6 +58,6 @@ public class ConsoleCommandSender implements CommandSender
@Override @Override
public void setPermission(String permission, boolean value) public void setPermission(String permission, boolean value)
{ {
throw new UnsupportedOperationException("Console has all permissions"); throw new UnsupportedOperationException( "Console has all permissions" );
} }
} }

View File

@ -49,36 +49,36 @@ public class Configuration
{ {
ConfigurationAdapter adapter = ProxyServer.getInstance().getConfigurationAdapter(); ConfigurationAdapter adapter = ProxyServer.getInstance().getConfigurationAdapter();
timeout = adapter.getInt("timeout", timeout); timeout = adapter.getInt( "timeout", timeout );
uuid = adapter.getString("stats", uuid); uuid = adapter.getString( "stats", uuid );
DefaultTabList tab = DefaultTabList.valueOf(adapter.getString("tab_list", "GLOBAL_PING")); DefaultTabList tab = DefaultTabList.valueOf( adapter.getString( "tab_list", "GLOBAL_PING" ) );
if (tab == null) if ( tab == null )
{ {
tab = DefaultTabList.GLOBAL_PING; tab = DefaultTabList.GLOBAL_PING;
} }
switch (tab) switch ( tab )
{ {
case GLOBAL: case GLOBAL:
ProxyServer.getInstance().setTabListHandler(new GlobalTabList()); ProxyServer.getInstance().setTabListHandler( new GlobalTabList() );
break; break;
case GLOBAL_PING: case GLOBAL_PING:
ProxyServer.getInstance().setTabListHandler(new GlobalPingTabList()); ProxyServer.getInstance().setTabListHandler( new GlobalPingTabList() );
break; break;
case SERVER: case SERVER:
ProxyServer.getInstance().setTabListHandler(new ServerUniqueTabList()); ProxyServer.getInstance().setTabListHandler( new ServerUniqueTabList() );
break; break;
} }
listeners = adapter.getListeners(); listeners = adapter.getListeners();
Preconditions.checkArgument(listeners != null && !listeners.isEmpty(), "No listeners defined."); Preconditions.checkArgument( listeners != null && !listeners.isEmpty(), "No listeners defined." );
servers = adapter.getServers(); servers = adapter.getServers();
Preconditions.checkArgument(servers != null && !servers.isEmpty(), "No servers defined"); Preconditions.checkArgument( servers != null && !servers.isEmpty(), "No servers defined" );
for (ListenerInfo listener : listeners) for ( ListenerInfo listener : listeners )
{ {
Preconditions.checkArgument(servers.containsKey(listener.getDefaultServer())); Preconditions.checkArgument( servers.containsKey( listener.getDefaultServer() ) );
} }
} }
} }

View File

@ -28,7 +28,7 @@ public class YamlConfig implements ConfigurationAdapter
private boolean loaded; private boolean loaded;
private Yaml yaml; private Yaml yaml;
private Map config; private Map config;
private final File file = new File("config.yml"); private final File file = new File( "config.yml" );
public void load() public void load()
{ {
@ -36,79 +36,79 @@ public class YamlConfig implements ConfigurationAdapter
{ {
file.createNewFile(); file.createNewFile();
DumperOptions options = new DumperOptions(); DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK );
yaml = new Yaml(options); yaml = new Yaml( options );
try (InputStream is = new FileInputStream(file)) try ( InputStream is = new FileInputStream( file ) )
{ {
config = (Map) yaml.load(is); config = (Map) yaml.load( is );
} }
if (config == null) if ( config == null )
{ {
config = new HashMap(); config = new HashMap();
} }
loaded = true; loaded = true;
} catch (IOException ex) } catch ( IOException ex )
{ {
throw new RuntimeException("Could not load configuration!", ex); throw new RuntimeException( "Could not load configuration!", ex );
} }
Map<String, Object> permissions = get("permissions", new HashMap<String, Object>()); Map<String, Object> permissions = get( "permissions", new HashMap<String, Object>() );
if (permissions.isEmpty()) if ( permissions.isEmpty() )
{ {
permissions.put("default", Arrays.asList(new String[] permissions.put( "default", Arrays.asList( new String[]
{ {
"bungeecord.command.server", "bungeecord.command.list" "bungeecord.command.server", "bungeecord.command.list"
})); } ) );
permissions.put("admin", Arrays.asList(new String[] permissions.put( "admin", Arrays.asList( new String[]
{ {
"bungeecord.command.alert", "bungeecord.command.end", "bungeecord.command.ip", "bungeecord.command.reload" "bungeecord.command.alert", "bungeecord.command.end", "bungeecord.command.ip", "bungeecord.command.reload"
})); } ) );
} }
Map<String, Object> groups = get("groups", new HashMap<String, Object>()); Map<String, Object> groups = get( "groups", new HashMap<String, Object>() );
if (groups.isEmpty()) if ( groups.isEmpty() )
{ {
groups.put("md_5", Collections.singletonList("admin")); groups.put( "md_5", Collections.singletonList( "admin" ) );
} }
} }
private <T> T get(String path, T def) private <T> T get(String path, T def)
{ {
if (!loaded) if ( !loaded )
{ {
load(); load();
} }
return get(path, def, config); return get( path, def, config );
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T get(String path, T def, Map submap) private <T> T get(String path, T def, Map submap)
{ {
if (!loaded) if ( !loaded )
{ {
load(); load();
} }
int index = path.indexOf('.'); int index = path.indexOf( '.' );
if (index == -1) if ( index == -1 )
{ {
Object val = submap.get(path); Object val = submap.get( path );
if (val == null && def != null) if ( val == null && def != null )
{ {
val = def; val = def;
submap.put(path, def); submap.put( path, def );
save(); save();
} }
return (T) val; return (T) val;
} else } else
{ {
String first = path.substring(0, index); String first = path.substring( 0, index );
String second = path.substring(index + 1, path.length()); String second = path.substring( index + 1, path.length() );
Map sub = (Map) submap.get(first); Map sub = (Map) submap.get( first );
return (sub != null) ? get(second, def, sub) : def; return ( sub != null ) ? get( second, def, sub ) : def;
} }
} }
@ -116,43 +116,43 @@ public class YamlConfig implements ConfigurationAdapter
{ {
try try
{ {
try (FileWriter wr = new FileWriter(file)) try ( FileWriter wr = new FileWriter( file ) )
{ {
yaml.dump(config, wr); yaml.dump( config, wr );
} }
} catch (IOException ex) } catch ( IOException ex )
{ {
ProxyServer.getInstance().getLogger().log(Level.WARNING, "Could not save config", ex); ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not save config", ex );
} }
} }
@Override @Override
public int getInt(String path, int def) public int getInt(String path, int def)
{ {
return get(path, def); return get( path, def );
} }
@Override @Override
public String getString(String path, String def) public String getString(String path, String def)
{ {
return get(path, def); return get( path, def );
} }
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Map<String, ServerInfo> getServers() public Map<String, ServerInfo> getServers()
{ {
Map<String, Map<String, Object>> base = get("servers", (Map) Collections.singletonMap("lobby", new HashMap<>())); Map<String, Map<String, Object>> base = get( "servers", (Map) Collections.singletonMap( "lobby", new HashMap<>() ) );
Map<String, ServerInfo> ret = new HashMap<>(); Map<String, ServerInfo> ret = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> entry : base.entrySet()) for ( Map.Entry<String, Map<String, Object>> entry : base.entrySet() )
{ {
Map<String, Object> val = entry.getValue(); Map<String, Object> val = entry.getValue();
String name = entry.getKey(); String name = entry.getKey();
String addr = get("address", "localhost:25565", val); String addr = get( "address", "localhost:25565", val );
InetSocketAddress address = Util.getAddr(addr); InetSocketAddress address = Util.getAddr( addr );
ServerInfo info = ProxyServer.getInstance().constructServerInfo(name, address); ServerInfo info = ProxyServer.getInstance().constructServerInfo( name, address );
ret.put(name, info); ret.put( name, info );
} }
return ret; return ret;
@ -162,28 +162,28 @@ public class YamlConfig implements ConfigurationAdapter
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Collection<ListenerInfo> getListeners() public Collection<ListenerInfo> getListeners()
{ {
Collection<Map<String, Object>> base = get("listeners", (Collection) Arrays.asList(new Map[] Collection<Map<String, Object>> base = get( "listeners", (Collection) Arrays.asList( new Map[]
{ {
new HashMap() new HashMap()
})); } ) );
Map<String, String> forcedDef = new HashMap<>(); Map<String, String> forcedDef = new HashMap<>();
forcedDef.put("pvp.md-5.net", "pvp"); forcedDef.put( "pvp.md-5.net", "pvp" );
Collection<ListenerInfo> ret = new HashSet<>(); Collection<ListenerInfo> ret = new HashSet<>();
for (Map<String, Object> val : base) for ( Map<String, Object> val : base )
{ {
String motd = get("motd", "Another Bungee server", val); String motd = get( "motd", "Another Bungee server", val );
motd = ChatColor.translateAlternateColorCodes('&', motd); motd = ChatColor.translateAlternateColorCodes( '&', motd );
int maxPlayers = get("max_players", 1, val); int maxPlayers = get( "max_players", 1, val );
String defaultServer = get("default_server", "lobby", val); String defaultServer = get( "default_server", "lobby", val );
boolean forceDefault = get("force_default_server", false, val); boolean forceDefault = get( "force_default_server", false, val );
String host = get("host", "0.0.0.0:25577", val); String host = get( "host", "0.0.0.0:25577", val );
InetSocketAddress address = Util.getAddr(host); InetSocketAddress address = Util.getAddr( host );
Map<String, String> forced = get("forced_hosts", forcedDef, val); Map<String, String> forced = get( "forced_hosts", forcedDef, val );
ListenerInfo info = new ListenerInfo(address, motd, maxPlayers, defaultServer, forceDefault, forced); ListenerInfo info = new ListenerInfo( address, motd, maxPlayers, defaultServer, forceDefault, forced );
ret.add(info); ret.add( info );
} }
return ret; return ret;
@ -193,9 +193,9 @@ public class YamlConfig implements ConfigurationAdapter
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Collection<String> getGroups(String player) public Collection<String> getGroups(String player)
{ {
Collection<String> groups = get("groups." + player, null); Collection<String> groups = get( "groups." + player, null );
Collection<String> ret = (groups == null) ? new HashSet<String>() : new HashSet<>(groups); Collection<String> ret = ( groups == null ) ? new HashSet<String>() : new HashSet<>( groups );
ret.add("default"); ret.add( "default" );
return ret; return ret;
} }
@ -203,6 +203,6 @@ public class YamlConfig implements ConfigurationAdapter
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Collection<String> getPermissions(String group) public Collection<String> getPermissions(String group)
{ {
return get("permissions." + group, Collections.EMPTY_LIST); return get( "permissions." + group, Collections.EMPTY_LIST );
} }
} }

View File

@ -40,10 +40,10 @@ public abstract class DefinedPacket implements DataInput, DataOutput
public DefinedPacket(int id, byte[] buf) public DefinedPacket(int id, byte[] buf)
{ {
in = ByteStreams.newDataInput(buf); in = ByteStreams.newDataInput( buf );
if (readUnsignedByte() != id) if ( readUnsignedByte() != id )
{ {
throw new IllegalArgumentException("Wasn't expecting packet id " + Util.hex(id)); throw new IllegalArgumentException( "Wasn't expecting packet id " + Util.hex( id ) );
} }
this.id = id; this.id = id;
packet = buf; packet = buf;
@ -53,7 +53,7 @@ public abstract class DefinedPacket implements DataInput, DataOutput
{ {
out = ByteStreams.newDataOutput(); out = ByteStreams.newDataOutput();
this.id = id; this.id = id;
writeByte(id); writeByte( id );
} }
/** /**
@ -70,33 +70,33 @@ public abstract class DefinedPacket implements DataInput, DataOutput
@Override @Override
public void writeUTF(String s) public void writeUTF(String s)
{ {
writeShort(s.length()); writeShort( s.length() );
writeChars(s); writeChars( s );
} }
@Override @Override
public String readUTF() public String readUTF()
{ {
short len = readShort(); short len = readShort();
char[] chars = new char[len]; char[] chars = new char[ len ];
for (int i = 0; i < len; i++) for ( int i = 0; i < len; i++ )
{ {
chars[i] = this.readChar(); chars[i] = this.readChar();
} }
return new String(chars); return new String( chars );
} }
public void writeArray(byte[] b) public void writeArray(byte[] b)
{ {
writeShort(b.length); writeShort( b.length );
write(b); write( b );
} }
public byte[] readArray() public byte[] readArray()
{ {
short len = readShort(); short len = readShort();
byte[] ret = new byte[len]; byte[] ret = new byte[ len ];
readFully(ret); readFully( ret );
return ret; return ret;
} }
@ -111,25 +111,25 @@ public abstract class DefinedPacket implements DataInput, DataOutput
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
private static Class<? extends DefinedPacket>[] classes = new Class[256]; private static Class<? extends DefinedPacket>[] classes = new Class[ 256 ];
public static DefinedPacket packet(byte[] buf) public static DefinedPacket packet(byte[] buf)
{ {
int id = Util.getId(buf); int id = Util.getId( buf );
Class<? extends DefinedPacket> clazz = classes[id]; Class<? extends DefinedPacket> clazz = classes[id];
DefinedPacket ret = null; DefinedPacket ret = null;
if (clazz != null) if ( clazz != null )
{ {
try try
{ {
Constructor<? extends DefinedPacket> constructor = clazz.getDeclaredConstructor(byte[].class); Constructor<? extends DefinedPacket> constructor = clazz.getDeclaredConstructor( byte[].class );
if (constructor != null) if ( constructor != null )
{ {
ret = constructor.newInstance(buf); ret = constructor.newInstance( buf );
} }
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException ex) } catch ( IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException ex )
{ {
} }
} }

View File

@ -12,7 +12,7 @@ public class Packet0KeepAlive extends DefinedPacket
public Packet0KeepAlive(byte[] buffer) public Packet0KeepAlive(byte[] buffer)
{ {
super(0x00, buffer); super( 0x00, buffer );
id = readInt(); id = readInt();
} }
} }

View File

@ -18,19 +18,19 @@ public class Packet1Login extends DefinedPacket
public Packet1Login(int entityId, String levelType, byte gameMode, byte dimension, byte difficulty, byte unused, byte maxPlayers) public Packet1Login(int entityId, String levelType, byte gameMode, byte dimension, byte difficulty, byte unused, byte maxPlayers)
{ {
super(0x01); super( 0x01 );
writeInt(entityId); writeInt( entityId );
writeUTF(levelType); writeUTF( levelType );
writeByte(gameMode); writeByte( gameMode );
writeByte(dimension); writeByte( dimension );
writeByte(difficulty); writeByte( difficulty );
writeByte(unused); writeByte( unused );
writeByte(maxPlayers); writeByte( maxPlayers );
} }
public Packet1Login(byte[] buf) public Packet1Login(byte[] buf)
{ {
super(0x01, buf); super( 0x01, buf );
this.entityId = readInt(); this.entityId = readInt();
this.levelType = readUTF(); this.levelType = readUTF();
this.gameMode = readByte(); this.gameMode = readByte();
@ -43,6 +43,6 @@ public class Packet1Login extends DefinedPacket
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -15,16 +15,16 @@ public class Packet2Handshake extends DefinedPacket
public Packet2Handshake(byte protocolVersion, String username, String host, int port) public Packet2Handshake(byte protocolVersion, String username, String host, int port)
{ {
super(0x02); super( 0x02 );
writeByte(protocolVersion); writeByte( protocolVersion );
writeUTF(username); writeUTF( username );
writeUTF(host); writeUTF( host );
writeInt(port); writeInt( port );
} }
public Packet2Handshake(byte[] buf) public Packet2Handshake(byte[] buf)
{ {
super(0x02, buf); super( 0x02, buf );
this.procolVersion = readByte(); this.procolVersion = readByte();
this.username = readUTF(); this.username = readUTF();
this.host = readUTF(); this.host = readUTF();
@ -34,6 +34,6 @@ public class Packet2Handshake extends DefinedPacket
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -12,13 +12,13 @@ public class Packet3Chat extends DefinedPacket
public Packet3Chat(String message) public Packet3Chat(String message)
{ {
super(0x03); super( 0x03 );
writeUTF(message); writeUTF( message );
} }
public Packet3Chat(byte[] buf) public Packet3Chat(byte[] buf)
{ {
super(0x03, buf); super( 0x03, buf );
this.message = readUTF(); this.message = readUTF();
} }
} }

View File

@ -16,17 +16,17 @@ public class Packet9Respawn extends DefinedPacket
public Packet9Respawn(int dimension, byte difficulty, byte gameMode, short worldHeight, String levelType) public Packet9Respawn(int dimension, byte difficulty, byte gameMode, short worldHeight, String levelType)
{ {
super(0x09); super( 0x09 );
writeInt(dimension); writeInt( dimension );
writeByte(difficulty); writeByte( difficulty );
writeByte(gameMode); writeByte( gameMode );
writeShort(worldHeight); writeShort( worldHeight );
writeUTF(levelType); writeUTF( levelType );
} }
public Packet9Respawn(byte[] buf) public Packet9Respawn(byte[] buf)
{ {
super(0x09, buf); super( 0x09, buf );
this.dimension = readInt(); this.dimension = readInt();
this.difficulty = readByte(); this.difficulty = readByte();
this.gameMode = readByte(); this.gameMode = readByte();

View File

@ -14,7 +14,7 @@ public class PacketC9PlayerListItem extends DefinedPacket
public PacketC9PlayerListItem(byte[] packet) public PacketC9PlayerListItem(byte[] packet)
{ {
super(0xC9, packet); super( 0xC9, packet );
username = readUTF(); username = readUTF();
online = readBoolean(); online = readBoolean();
ping = readShort(); ping = readShort();
@ -22,9 +22,9 @@ public class PacketC9PlayerListItem extends DefinedPacket
public PacketC9PlayerListItem(String username, boolean online, int ping) public PacketC9PlayerListItem(String username, boolean online, int ping)
{ {
super(0xC9); super( 0xC9 );
writeUTF(username); writeUTF( username );
writeBoolean(online); writeBoolean( online );
writeShort(ping); writeShort( ping );
} }
} }

View File

@ -15,18 +15,18 @@ public class PacketCDClientStatus extends DefinedPacket
*/ */
public PacketCDClientStatus(byte payload) public PacketCDClientStatus(byte payload)
{ {
super(0xCD); super( 0xCD );
writeByte(payload); writeByte( payload );
} }
public PacketCDClientStatus(byte[] buf) public PacketCDClientStatus(byte[] buf)
{ {
super(0xCD, buf); super( 0xCD, buf );
} }
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -13,16 +13,16 @@ public class PacketFAPluginMessage extends DefinedPacket
public PacketFAPluginMessage(String tag, byte[] data) public PacketFAPluginMessage(String tag, byte[] data)
{ {
super(0xFA); super( 0xFA );
writeUTF(tag); writeUTF( tag );
writeArray(data); writeArray( data );
this.tag = tag; this.tag = tag;
this.data = data; this.data = data;
} }
public PacketFAPluginMessage(byte[] buf) public PacketFAPluginMessage(byte[] buf)
{ {
super(0xFA, buf); super( 0xFA, buf );
this.tag = readUTF(); this.tag = readUTF();
this.data = readArray(); this.data = readArray();
} }
@ -30,6 +30,6 @@ public class PacketFAPluginMessage extends DefinedPacket
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -13,21 +13,21 @@ public class PacketFCEncryptionResponse extends DefinedPacket
public PacketFCEncryptionResponse() public PacketFCEncryptionResponse()
{ {
super(0xFC); super( 0xFC );
writeArray(new byte[0]); writeArray( new byte[ 0 ] );
writeArray(new byte[0]); writeArray( new byte[ 0 ] );
} }
public PacketFCEncryptionResponse(byte[] sharedSecret, byte[] verifyToken) public PacketFCEncryptionResponse(byte[] sharedSecret, byte[] verifyToken)
{ {
super(0xFC); super( 0xFC );
writeArray(sharedSecret); writeArray( sharedSecret );
writeArray(verifyToken); writeArray( verifyToken );
} }
public PacketFCEncryptionResponse(byte[] buf) public PacketFCEncryptionResponse(byte[] buf)
{ {
super(0xFC, buf); super( 0xFC, buf );
this.sharedSecret = readArray(); this.sharedSecret = readArray();
this.verifyToken = readArray(); this.verifyToken = readArray();
} }
@ -35,6 +35,6 @@ public class PacketFCEncryptionResponse extends DefinedPacket
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -14,10 +14,10 @@ public class PacketFDEncryptionRequest extends DefinedPacket
public PacketFDEncryptionRequest(String serverId, byte[] publicKey, byte[] verifyToken) public PacketFDEncryptionRequest(String serverId, byte[] publicKey, byte[] verifyToken)
{ {
super(0xFD); super( 0xFD );
writeUTF(serverId); writeUTF( serverId );
writeArray(publicKey); writeArray( publicKey );
writeArray(verifyToken); writeArray( verifyToken );
this.serverId = serverId; this.serverId = serverId;
this.publicKey = publicKey; this.publicKey = publicKey;
this.verifyToken = verifyToken; this.verifyToken = verifyToken;
@ -25,7 +25,7 @@ public class PacketFDEncryptionRequest extends DefinedPacket
public PacketFDEncryptionRequest(byte[] buf) public PacketFDEncryptionRequest(byte[] buf)
{ {
super(0xFD, buf); super( 0xFD, buf );
serverId = readUTF(); serverId = readUTF();
publicKey = readArray(); publicKey = readArray();
verifyToken = readArray(); verifyToken = readArray();
@ -34,6 +34,6 @@ public class PacketFDEncryptionRequest extends DefinedPacket
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -10,12 +10,12 @@ public class PacketFEPing extends DefinedPacket
public PacketFEPing(byte[] buffer) public PacketFEPing(byte[] buffer)
{ {
super(0xFE, buffer); super( 0xFE, buffer );
} }
@Override @Override
public void handle(PacketHandler handler) throws Exception public void handle(PacketHandler handler) throws Exception
{ {
handler.handle(this); handler.handle( this );
} }
} }

View File

@ -12,13 +12,13 @@ public class PacketFFKick extends DefinedPacket
public PacketFFKick(String message) public PacketFFKick(String message)
{ {
super(0xFF); super( 0xFF );
writeUTF(message); writeUTF( message );
} }
public PacketFFKick(byte[] buf) public PacketFFKick(byte[] buf)
{ {
super(0xFF, buf); super( 0xFF, buf );
this.message = readUTF(); this.message = readUTF();
} }
} }

View File

@ -5,7 +5,7 @@ public abstract class PacketHandler
public void handle(DefinedPacket packet) throws Exception public void handle(DefinedPacket packet) throws Exception
{ {
throw new UnsupportedOperationException("No handler defined for packet " + packet.getClass()); throw new UnsupportedOperationException( "No handler defined for packet " + packet.getClass() );
} }
public void handle(Packet1Login login) throws Exception public void handle(Packet1Login login) throws Exception

View File

@ -21,28 +21,28 @@ public class PacketStream implements AutoCloseable
@Getter @Getter
private OutputStream out; private OutputStream out;
private final TrackingInputStream tracker; private final TrackingInputStream tracker;
private final byte[] buffer = new byte[1 << 18]; private final byte[] buffer = new byte[ 1 << 18 ];
public PacketStream(InputStream in) public PacketStream(InputStream in)
{ {
this(in, null); this( in, null );
} }
public PacketStream(InputStream in, OutputStream out) public PacketStream(InputStream in, OutputStream out)
{ {
tracker = new TrackingInputStream(in); tracker = new TrackingInputStream( in );
dataInput = new DataInputStream(tracker); dataInput = new DataInputStream( tracker );
this.out = out; this.out = out;
} }
public void write(byte[] b) throws IOException public void write(byte[] b) throws IOException
{ {
out.write(b); out.write( b );
} }
public void write(DefinedPacket packet) throws IOException public void write(DefinedPacket packet) throws IOException
{ {
out.write(packet.getPacket()); out.write( packet.getPacket() );
} }
/** /**
@ -54,7 +54,7 @@ public class PacketStream implements AutoCloseable
public byte[] readPacket() throws IOException public byte[] readPacket() throws IOException
{ {
tracker.out.reset(); tracker.out.reset();
DataInputPacketReader.readPacket(dataInput, buffer); DataInputPacketReader.readPacket( dataInput, buffer );
return tracker.out.toByteArray(); return tracker.out.toByteArray();
} }
@ -75,22 +75,22 @@ public class PacketStream implements AutoCloseable
public TrackingInputStream(InputStream in) public TrackingInputStream(InputStream in)
{ {
super(in); super( in );
} }
@Override @Override
public int read() throws IOException public int read() throws IOException
{ {
int ret = in.read(); int ret = in.read();
out.write(ret); out.write( ret );
return ret; return ret;
} }
@Override @Override
public int read(byte[] b, int off, int len) throws IOException public int read(byte[] b, int off, int len) throws IOException
{ {
int ret = in.read(b, off, len); int ret = in.read( b, off, len );
out.write(b, off, ret); out.write( b, off, ret );
return ret; return ret;
} }
} }

View File

@ -15,18 +15,18 @@ public class GlobalPingTabList extends GlobalTabList
@Override @Override
public void onDisconnect(ProxiedPlayer player) public void onDisconnect(ProxiedPlayer player)
{ {
lastPings.remove(player); lastPings.remove( player );
super.onDisconnect(player); super.onDisconnect( player );
} }
@Override @Override
public void onPingChange(ProxiedPlayer player, int ping) public void onPingChange(ProxiedPlayer player, int ping)
{ {
Integer lastPing = lastPings.get(player); Integer lastPing = lastPings.get( player );
if (lastPing == null || (ping - PING_THRESHOLD > lastPing && ping + PING_THRESHOLD < lastPing)) if ( lastPing == null || ( ping - PING_THRESHOLD > lastPing && ping + PING_THRESHOLD < lastPing ) )
{ {
BungeeCord.getInstance().broadcast(new PacketC9PlayerListItem(player.getDisplayName(), true, ping)); BungeeCord.getInstance().broadcast( new PacketC9PlayerListItem( player.getDisplayName(), true, ping ) );
lastPings.put(player, ping); lastPings.put( player, ping );
} }
} }
} }

View File

@ -20,28 +20,28 @@ public class GlobalTabList implements TabListHandler
public void onConnect(ProxiedPlayer player) public void onConnect(ProxiedPlayer player)
{ {
UserConnection con = (UserConnection) player; UserConnection con = (UserConnection) player;
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) for ( ProxiedPlayer p : ProxyServer.getInstance().getPlayers() )
{ {
con.packetQueue.add(new PacketC9PlayerListItem(p.getDisplayName(), true, p.getPing())); con.packetQueue.add( new PacketC9PlayerListItem( p.getDisplayName(), true, p.getPing() ) );
} }
BungeeCord.getInstance().broadcast(new PacketC9PlayerListItem(player.getDisplayName(), true, player.getPing())); BungeeCord.getInstance().broadcast( new PacketC9PlayerListItem( player.getDisplayName(), true, player.getPing() ) );
} }
@Override @Override
public void onPingChange(ProxiedPlayer player, int ping) public void onPingChange(ProxiedPlayer player, int ping)
{ {
if (!sentPings.containsKey(player)) if ( !sentPings.containsKey( player ) )
{ {
BungeeCord.getInstance().broadcast(new PacketC9PlayerListItem(player.getDisplayName(), true, player.getPing())); BungeeCord.getInstance().broadcast( new PacketC9PlayerListItem( player.getDisplayName(), true, player.getPing() ) );
sentPings.put(player, PRESENT); sentPings.put( player, PRESENT );
} }
} }
@Override @Override
public void onDisconnect(ProxiedPlayer player) public void onDisconnect(ProxiedPlayer player)
{ {
BungeeCord.getInstance().broadcast(new PacketC9PlayerListItem(player.getDisplayName(), false, 9999)); BungeeCord.getInstance().broadcast( new PacketC9PlayerListItem( player.getDisplayName(), false, 9999 ) );
sentPings.remove(player); sentPings.remove( player );
} }
@Override @Override

View File

@ -27,20 +27,20 @@ public class ServerUniqueTabList implements TabListHandler
@Override @Override
public void onDisconnect(ProxiedPlayer player) public void onDisconnect(ProxiedPlayer player)
{ {
sentUsernames.remove(player); sentUsernames.remove( player );
} }
@Override @Override
public void onServerChange(ProxiedPlayer player) public void onServerChange(ProxiedPlayer player)
{ {
Set<String> usernames = sentUsernames.get(player); Set<String> usernames = sentUsernames.get( player );
if (usernames != null) if ( usernames != null )
{ {
synchronized (usernames) synchronized ( usernames )
{ {
for (String username : usernames) for ( String username : usernames )
{ {
((UserConnection) player).packetQueue.add(new PacketC9PlayerListItem(username, false, 9999)); ( (UserConnection) player ).packetQueue.add( new PacketC9PlayerListItem( username, false, 9999 ) );
} }
usernames.clear(); usernames.clear();
} }
@ -50,21 +50,21 @@ public class ServerUniqueTabList implements TabListHandler
@Override @Override
public boolean onListUpdate(ProxiedPlayer player, String name, boolean online, int ping) public boolean onListUpdate(ProxiedPlayer player, String name, boolean online, int ping)
{ {
Set<String> usernames = sentUsernames.get(player); Set<String> usernames = sentUsernames.get( player );
if (usernames == null) if ( usernames == null )
{ {
usernames = new HashSet<>(); usernames = new HashSet<>();
sentUsernames.put(player, usernames); sentUsernames.put( player, usernames );
} }
synchronized (usernames) synchronized ( usernames )
{ {
if (online) if ( online )
{ {
usernames.add(name); usernames.add( name );
} else } else
{ {
usernames.remove(name); usernames.remove( name );
} }
} }