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)
{
this.toString = new String(new char[]
{
COLOR_CHAR, code
});
{
COLOR_CHAR, code
});
}
@Override

View File

@ -127,9 +127,9 @@ public class PluginManager
{
plugin.onEnable();
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)
{
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);
URLClassLoader loader = new PluginClassloader(new URL[]
{
file.toURI().toURL()
});
{
file.toURI().toURL()
});
Class<?> main = loader.loadClass(desc.getMain());
Plugin plugin = (Plugin) main.getDeclaredConstructor().newInstance();
@ -169,9 +169,9 @@ public class PluginManager
plugins.put(desc.getName(), plugin);
plugin.onLoad();
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.
*/
private final Timer saveThread = new Timer("Reconnect Saver");
private final Timer saveThread = new Timer( "Reconnect Saver" );
/**
* Server socket listener.
*/
@ -98,15 +98,15 @@ public class BungeeCord extends ProxyServer
{
getPluginManager().registerCommand(new CommandReload());
getPluginManager().registerCommand(new CommandEnd());
getPluginManager().registerCommand(new CommandList());
getPluginManager().registerCommand(new CommandServer());
getPluginManager().registerCommand(new CommandIP());
getPluginManager().registerCommand(new CommandAlert());
getPluginManager().registerCommand(new CommandBungee());
getPluginManager().registerCommand( new CommandReload() );
getPluginManager().registerCommand( new CommandEnd() );
getPluginManager().registerCommand( new CommandList() );
getPluginManager().registerCommand( new CommandServer() );
getPluginManager().registerCommand( new CommandIP() );
getPluginManager().registerCommand( new CommandAlert() );
getPluginManager().registerCommand( new CommandBungee() );
registerChannel("BungeeCord");
registerChannel( "BungeeCord" );
}
public static BungeeCord getInstance()
@ -123,20 +123,20 @@ public class BungeeCord extends ProxyServer
public static void main(String[] args) throws IOException
{
BungeeCord bungee = new BungeeCord();
ProxyServer.setInstance(bungee);
$().info("Enabled BungeeCord version " + bungee.getVersion());
ProxyServer.setInstance( bungee );
$().info( "Enabled BungeeCord version " + bungee.getVersion() );
bungee.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (bungee.isRunning)
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
while ( bungee.isRunning )
{
String line = br.readLine();
if (line != null)
if ( line != null )
{
boolean handled = getInstance().getPluginManager().dispatchCommand(ConsoleCommandSender.getInstance(), line);
if (!handled)
boolean handled = getInstance().getPluginManager().dispatchCommand( ConsoleCommandSender.getInstance(), line );
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
{
File plugins = new File("plugins");
File plugins = new File( "plugins" );
plugins.mkdir();
pluginManager.loadPlugins(plugins);
pluginManager.loadPlugins( plugins );
config.load();
reconnectHandler = new YamlReconnectHandler();
isRunning = true;
pluginManager.enablePlugins();
for (ListenerInfo info : config.getListeners())
for ( ListenerInfo info : config.getListeners() )
{
$().info("Listening on " + info.getHost());
ListenThread listener = new ListenThread(info);
$().info( "Listening on " + info.getHost() );
ListenThread listener = new ListenThread( info );
listener.start();
listeners.add(listener);
listeners.add( listener );
}
saveThread.scheduleAtFixedRate(new TimerTask()
saveThread.scheduleAtFixedRate( new TimerTask()
{
@Override
public void run()
{
getReconnectHandler().save();
}
}, 0, TimeUnit.MINUTES.toMillis(5));
}, 0, TimeUnit.MINUTES.toMillis( 5 ) );
new Metrics().start();
}
@ -183,40 +183,40 @@ public class BungeeCord extends ProxyServer
public void stop()
{
this.isRunning = false;
$().info("Disabling plugins");
for (Plugin plugin : pluginManager.getPlugins())
$().info( "Disabling plugins" );
for ( Plugin plugin : pluginManager.getPlugins() )
{
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
{
listener.socket.close();
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();
$().info("Disconnecting " + connections.size() + " connections");
for (UserConnection user : connections.values())
$().info( "Disconnecting " + connections.size() + " connections" );
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();
saveThread.cancel();
$().info("Thank you and goodbye");
System.exit(0);
$().info( "Thank you and goodbye" );
System.exit( 0 );
}
/**
@ -228,9 +228,9 @@ public class BungeeCord extends ProxyServer
*/
public void setSocketOptions(Socket socket) throws IOException
{
socket.setSoTimeout(config.getTimeout());
socket.setTrafficClass(0x18);
socket.setTcpNoDelay(true);
socket.setSoTimeout( config.getTimeout() );
socket.setTrafficClass( 0x18 );
socket.setTcpNoDelay( true );
}
/**
@ -240,9 +240,9 @@ public class BungeeCord extends ProxyServer
*/
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
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
@ -274,14 +274,14 @@ public class BungeeCord extends ProxyServer
@Override
public ProxiedPlayer getPlayer(String name)
{
return connections.get(name);
return connections.get( name );
}
@Override
public Server getServer(String name)
{
Collection<ProxiedPlayer> users = getServers().get(name).getPlayers();
return (users != null && !users.isEmpty()) ? users.iterator().next().getServer() : null;
Collection<ProxiedPlayer> users = getServers().get( name ).getPlayers();
return ( users != null && !users.isEmpty() ) ? users.iterator().next().getServer() : null;
}
@Override
@ -293,40 +293,40 @@ public class BungeeCord extends ProxyServer
@Override
public ServerInfo getServerInfo(String name)
{
return getServers().get(name);
return getServers().get( name );
}
@Override
@Synchronized("pluginChannels")
public void registerChannel(String channel)
{
pluginChannels.add(channel);
pluginChannels.add( channel );
}
@Override
@Synchronized("pluginChannels")
public void unregisterChannel(String channel)
{
pluginChannels.remove(channel);
pluginChannels.remove( channel );
}
@Override
@Synchronized("pluginChannels")
public Collection<String> getChannels()
{
return Collections.unmodifiableCollection(pluginChannels);
return Collections.unmodifiableCollection( pluginChannels );
}
public PacketFAPluginMessage registerChannels()
{
StringBuilder sb = new StringBuilder();
for (String s : getChannels())
for ( String s : getChannels() )
{
sb.append(s);
sb.append('\00');
sb.append( s );
sb.append( '\00' );
}
byte[] payload = sb.substring(0, sb.length() - 1).getBytes();
return new PacketFAPluginMessage("REGISTER", payload);
byte[] payload = sb.substring( 0, sb.length() - 1 ).getBytes();
return new PacketFAPluginMessage( "REGISTER", payload );
}
@Override
@ -344,6 +344,6 @@ public class BungeeCord extends ProxyServer
@Override
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)
{
super(name, address);
super( name, address );
}
@Override
public void sendData(String channel, byte[] data)
{
Server server = ProxyServer.getInstance().getServer(getName());
if (server != null)
Server server = ProxyServer.getInstance().getServer( getName() );
if ( server != null )
{
server.sendData(channel, data);
server.sendData( channel, data );
} else
{
packetQueue.add(new PacketFAPluginMessage(channel, data));
packetQueue.add( new PacketFAPluginMessage( channel, data ) );
}
}
@ -51,24 +51,24 @@ public class BungeeServerInfo extends ServerInfo
try
{
Socket socket = new Socket();
socket.connect(getAddress());
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream()))
socket.connect( getAddress() );
try ( DataOutputStream out = new DataOutputStream( socket.getOutputStream() ) )
{
out.write(0xFE);
out.write(0x01);
out.write( 0xFE );
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]));
callback.done(ping, null);
ServerPing ping = new ServerPing( Byte.parseByte( split[1] ), split[2], split[3], Integer.parseInt( split[4] ), Integer.parseInt( split[5] ) );
callback.done( ping, null );
}
} catch (Throwable t)
} catch ( Throwable t )
{
callback.done(null, t);
callback.done( null, t );
}
}
}.start();

View File

@ -41,69 +41,69 @@ public class EncryptionUtil
static
{
Security.addProvider(new BouncyCastleProvider());
Security.addProvider( new BouncyCastleProvider() );
}
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[] verify = new byte[4];
random.nextBytes(verify);
return new PacketFDEncryptionRequest(hash, pubKey, verify);
byte[] verify = new byte[ 4 ];
random.nextBytes( verify );
return new PacketFDEncryptionRequest( hash, pubKey, verify );
}
public static SecretKey getSecret(PacketFCEncryptionResponse resp, PacketFDEncryptionRequest request) throws BadPaddingException, IllegalBlockSizeException, IllegalStateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException
{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
byte[] decrypted = cipher.doFinal(resp.verifyToken);
Cipher cipher = Cipher.getInstance( "RSA" );
cipher.init( Cipher.DECRYPT_MODE, keys.getPrivate() );
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[] 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
{
String encName = URLEncoder.encode(username, "UTF-8");
String encName = URLEncoder.encode( username, "UTF-8" );
MessageDigest sha = MessageDigest.getInstance("SHA-1");
for (byte[] bit : new byte[][]
{
connectionHash.getBytes("ISO_8859_1"), shared.getEncoded(), keys.getPublic().getEncoded()
})
MessageDigest sha = MessageDigest.getInstance( "SHA-1" );
for ( byte[] bit : new byte[][]
{
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 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();
}
return "YES".equals(reply);
return "YES".equals( reply );
}
public static BufferedBlockCipher getCipher(boolean forEncryption, Key shared)
{
BufferedBlockCipher cip = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
cip.init(forEncryption, new ParametersWithIV(new KeyParameter(shared.getEncoded()), shared.getEncoded()));
BufferedBlockCipher cip = new BufferedBlockCipher( new CFBBlockCipher( new AESFastEngine(), 8 ) );
cip.init( forEncryption, new ParametersWithIV( new KeyParameter( shared.getEncoded() ), shared.getEncoded() ) );
return cip;
}
}

View File

@ -6,7 +6,7 @@ package net.md_5.bungee;
public class EntityMap
{
public final static int[][] entityIds = new int[256][];
public final static int[][] entityIds = new int[ 256 ][];
static
{
@ -115,34 +115,34 @@ public class EntityMap
public static void rewrite(byte[] packet, int oldId, int newId)
{
int packetId = Util.getId(packet);
if (packetId == 0x1D)
int packetId = Util.getId( packet );
if ( packetId == 0x1D )
{ // 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);
if (readId == oldId)
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt(packet, pos, newId);
} else if (readId == newId)
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt(packet, pos, oldId);
setInt( packet, pos, oldId );
}
}
} else
{
int[] idArray = entityIds[packetId];
if (idArray != null)
if ( idArray != null )
{
for (int pos : idArray)
for ( int pos : idArray )
{
int readId = readInt(packet, pos);
if (readId == oldId)
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt(packet, pos, newId);
} else if (readId == newId)
setInt( packet, pos, 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)
{
buf[pos] = (byte) (i >> 24);
buf[pos + 1] = (byte) (i >> 16);
buf[pos + 2] = (byte) (i >> 8);
buf[pos] = (byte) ( i >> 24 );
buf[pos + 1] = (byte) ( i >> 16 );
buf[pos + 2] = (byte) ( i >> 8 );
buf[pos + 3] = (byte) i;
}
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)
{
if (socket.isClosed())
if ( socket.isClosed() )
{
return;
}
log("disconnected with " + reason);
log( "disconnected with " + reason );
try
{
stream.write(new PacketFFKick("[Proxy] " + reason));
} catch (IOException ex)
stream.write( new PacketFFKick( "[Proxy] " + reason ) );
} catch ( IOException ex )
{
} finally
{
@ -48,7 +48,7 @@ public class GenericConnection
{
socket.shutdownOutput();
socket.close();
} catch (IOException ioe)
} catch ( IOException ioe )
{
}
}
@ -56,6 +56,6 @@ public class GenericConnection
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.listener = info;
stream = new PacketStream(socket.getInputStream(), socket.getOutputStream());
stream = new PacketStream( socket.getInputStream(), socket.getOutputStream() );
}
private enum State
@ -55,69 +55,69 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
@Override
public void handle(PacketFEPing ping) throws Exception
{
socket.setSoTimeout(100);
socket.setSoTimeout( 100 );
boolean newPing = false;
try
{
socket.getInputStream().read();
newPing = true;
} catch (IOException ex)
} catch ( IOException ex )
{
}
ServerPing pingevent = new ServerPing(BungeeCord.PROTOCOL_VERSION, BungeeCord.GAME_VERSION,
listener.getMotd(), ProxyServer.getInstance().getPlayers().size(), listener.getMaxPlayers());
ServerPing pingevent = new ServerPing( BungeeCord.PROTOCOL_VERSION, BungeeCord.GAME_VERSION,
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.getGameVersion()
+ "\00" + pingevent.getMotd()
+ "\00" + pingevent.getCurrentPlayers()
+ "\00" + pingevent.getMaxPlayers()
: pingevent.getMotd() + ChatColor.COLOR_CHAR + pingevent.getCurrentPlayers() + ChatColor.COLOR_CHAR + pingevent.getMaxPlayers();
disconnect(response);
disconnect( response );
}
@Override
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;
request = EncryptionUtil.encryptRequest();
stream.write(request);
stream.write( request );
thisState = State.ENCRYPT;
}
@Override
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);
if (!EncryptionUtil.isAuthenticated(handshake.username, request.serverId, shared))
SecretKey shared = EncryptionUtil.getSecret( encryptResponse, request );
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
ProxiedPlayer old = ProxyServer.getInstance().getPlayer(handshake.username);
if (old != null)
ProxiedPlayer old = ProxyServer.getInstance().getPlayer( handshake.username );
if ( old != null )
{
old.disconnect("You are already connected to the server");
old.disconnect( "You are already connected to the server" );
}
// fire login event
LoginEvent event = new LoginEvent(this);
if (event.isCancelled())
LoginEvent event = new LoginEvent( this );
if ( event.isCancelled() )
{
disconnect(event.getCancelReason());
disconnect( event.getCancelReason() );
}
stream.write(new PacketFCEncryptionResponse());
stream = new PacketStream(new CipherInputStream(socket.getInputStream(),
EncryptionUtil.getCipher(false, shared)), new CipherOutputStream(socket.getOutputStream(), EncryptionUtil.getCipher(true, shared)));
stream.write( new PacketFCEncryptionResponse() );
stream = new PacketStream( new CipherInputStream( socket.getInputStream(),
EncryptionUtil.getCipher( false, shared ) ), new CipherOutputStream( socket.getOutputStream(), EncryptionUtil.getCipher( true, shared ) ) );
thisState = State.LOGIN;
}
@ -125,12 +125,12 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
@Override
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);
String server = ProxyServer.getInstance().getReconnectHandler().getServer(userCon);
ServerInfo s = BungeeCord.getInstance().config.getServers().get(server);
userCon.connect(s, true);
UserConnection userCon = new UserConnection( socket, this, stream, handshake );
String server = ProxyServer.getInstance().getReconnectHandler().getServer( userCon );
ServerInfo s = BungeeCord.getInstance().config.getServers().get( server );
userCon.connect( s, true );
thisState = State.FINISHED;
}
@ -140,15 +140,15 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
{
try
{
while (thisState != State.FINISHED)
while ( thisState != State.FINISHED )
{
byte[] buf = stream.readPacket();
DefinedPacket packet = DefinedPacket.packet(buf);
packet.handle(this);
DefinedPacket packet = DefinedPacket.packet( buf );
packet.handle( this );
}
} catch (Exception ex)
} catch ( Exception ex )
{
disconnect("[Proxy Error] " + Util.exception(ex));
disconnect( "[Proxy Error] " + Util.exception( ex ) );
ex.printStackTrace();
}
}
@ -159,8 +159,8 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
thisState = State.FINISHED;
try
{
stream.write(new PacketFFKick(reason));
} catch (IOException ioe)
stream.write( new PacketFFKick( reason ) );
} catch ( IOException ioe )
{
} finally
{
@ -168,7 +168,7 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
{
socket.shutdownOutput();
socket.close();
} catch (IOException ioe2)
} catch ( IOException ioe2 )
{
}
}
@ -177,19 +177,19 @@ public class InitialHandler extends PacketHandler implements Runnable, PendingCo
@Override
public String getName()
{
return (handshake == null) ? null : handshake.username;
return ( handshake == null ) ? null : handshake.username;
}
@Override
public byte getVersion()
{
return (handshake == null) ? -1 : handshake.procolVersion;
return ( handshake == null ) ? -1 : handshake.procolVersion;
}
@Override
public InetSocketAddress getVirtualHost()
{
return (handshake == null) ? null : new InetSocketAddress(handshake.host, handshake.port);
return ( handshake == null ) ? null : new InetSocketAddress( handshake.host, handshake.port );
}
@Override

View File

@ -9,6 +9,6 @@ public class KickException extends RuntimeException
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
{
super("Listen Thread - "+ info);
super( "Listen Thread - " + info );
this.info = info;
socket = new ServerSocket();
socket.bind(info.getHost());
socket.bind( info.getHost() );
}
@Override
public void run()
{
while (BungeeCord.getInstance().isRunning)
while ( BungeeCord.getInstance().isRunning )
{
try
{
Socket client = socket.accept();
BungeeCord.getInstance().setSocketOptions(client);
$().info(client.getInetAddress() + " has connected");
InitialHandler handler = new InitialHandler(client,info);
BungeeCord.getInstance().threadPool.submit(handler);
} catch (SocketException ex)
BungeeCord.getInstance().setSocketOptions( client );
$().info( client.getInetAddress() + " has connected" );
InitialHandler handler = new InitialHandler( client, info );
BungeeCord.getInstance().threadPool.submit( handler );
} catch ( SocketException ex )
{
} catch (IOException ex)
} catch ( IOException ex )
{
ex.printStackTrace(); // TODO
}

View File

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

View File

@ -33,34 +33,34 @@ public class Metrics extends Thread
public Metrics()
{
super("Metrics Gathering Thread");
setDaemon(true);
super( "Metrics Gathering Thread" );
setDaemon( true );
}
@Override
public void run()
{
boolean firstPost = true;
while (true)
while ( true )
{
try
{
// 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
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
postPlugin( !firstPost );
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException ex)
} catch ( IOException ex )
{
$().info("[Metrics] " + ex.getMessage());
$().info( "[Metrics] " + ex.getMessage() );
}
try
{
sleep(PING_INTERVAL * 1000 * 60);
} catch (InterruptedException ex)
sleep( PING_INTERVAL * 1000 * 60 );
} catch ( InterruptedException ex )
{
break;
}
@ -74,41 +74,41 @@ public class Metrics extends Thread
{
// Construct the post data
final StringBuilder data = new StringBuilder();
data.append(encode("guid")).append('=').append(encode(BungeeCord.getInstance().config.getUuid()));
encodeDataPair(data, "version", ProxyServer.getInstance().getVersion());
encodeDataPair(data, "server", "0");
encodeDataPair(data, "players", Integer.toString(ProxyServer.getInstance().getPlayers().size()));
encodeDataPair(data, "revision", String.valueOf(REVISION));
data.append( encode( "guid" ) ).append( '=' ).append( encode( BungeeCord.getInstance().config.getUuid() ) );
encodeDataPair( data, "version", ProxyServer.getInstance().getVersion() );
encodeDataPair( data, "server", "0" );
encodeDataPair( data, "players", Integer.toString( ProxyServer.getInstance().getPlayers().size() ) );
encodeDataPair( data, "revision", String.valueOf( REVISION ) );
// If we're pinging, append it
if (isPing)
if ( isPing )
{
encodeDataPair(data, "ping", "true");
encodeDataPair( data, "ping", "true" );
}
// 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
URLConnection connection;
connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoOutput( true );
final BufferedReader reader;
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();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
response = reader.readLine();
}
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
{
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
{
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)
{
super(socket, stream);
super( socket, stream );
this.info = info;
this.loginPacket = loginPacket;
}
@ -43,48 +43,48 @@ public class ServerConnection extends GenericConnection implements Server
try
{
Socket socket = new Socket();
socket.connect(info.getAddress(), BungeeCord.getInstance().config.getTimeout());
BungeeCord.getInstance().setSocketOptions(socket);
socket.connect( info.getAddress(), BungeeCord.getInstance().config.getTimeout() );
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(new PacketCDClientStatus((byte) 0));
stream.write( handshake );
stream.write( new PacketCDClientStatus( (byte) 0 ) );
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);
ServerConnectedEvent event = new ServerConnectedEvent(user, server);
ProxyServer.getInstance().getPluginManager().callEvent(event);
ServerConnection server = new ServerConnection( socket, info, stream, login );
ServerConnectedEvent event = new ServerConnectedEvent( user, server );
ProxyServer.getInstance().getPluginManager().callEvent( event );
stream.write(BungeeCord.getInstance().registerChannels());
stream.write( BungeeCord.getInstance().registerChannels() );
Queue<DefinedPacket> packetQueue = ((BungeeServerInfo) info).getPacketQueue();
while (!packetQueue.isEmpty())
Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) info ).getPacketQueue();
while ( !packetQueue.isEmpty() )
{
stream.write(packetQueue.poll());
stream.write( packetQueue.poll() );
}
return server;
} catch (KickException ex)
} catch ( KickException ex )
{
throw ex;
} catch (Exception ex)
} catch ( Exception ex )
{
ServerInfo def = ProxyServer.getInstance().getServers().get(user.getPendingConnection().getListener().getDefaultServer());
if (retry && !info.equals(def))
ServerInfo def = ProxyServer.getInstance().getServers().get( user.getPendingConnection().getListener().getDefaultServer() );
if ( retry && !info.equals( def ) )
{
user.sendMessage(ChatColor.RED + "Could not connect to target server, you have been moved to the default server");
return connect(user, def, handshake, false);
user.sendMessage( ChatColor.RED + "Could not connect to target server, you have been moved to the default server" );
return connect( user, def, handshake, false );
} 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
public void sendData(String channel, byte[] data)
{
packetQueue.add(new PacketFAPluginMessage(channel, data));
packetQueue.add( new PacketFAPluginMessage( channel, data ) );
}
@Override
public void ping(final Callback<ServerPing> callback)
{
getInfo().ping(callback);
getInfo().ping( callback );
}
@Override

View File

@ -5,14 +5,12 @@ import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
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)
{
super(socket, stream);
super( socket, stream );
this.handshake = handshake;
this.pendingConnection = pendingConnection;
name = handshake.username;
displayName = handshake.username;
Collection<String> g = ProxyServer.getInstance().getConfigurationAdapter().getGroups(name);
for (String s : g)
Collection<String> g = ProxyServer.getInstance().getConfigurationAdapter().getGroups( name );
for ( String s : g )
{
addGroups(s);
addGroups( s );
}
}
@Override
public void setDisplayName(String name)
{
ProxyServer.getInstance().getTabListHandler().onDisconnect(this);
ProxyServer.getInstance().getTabListHandler().onDisconnect( this );
displayName = name;
ProxyServer.getInstance().getTabListHandler().onConnect(this);
ProxyServer.getInstance().getTabListHandler().onConnect( this );
}
@Override
@ -85,36 +83,36 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public void connect(ServerInfo target, boolean force)
{
if (server == null)
if ( server == null )
{
// First join
BungeeCord.getInstance().connections.put(name, this);
ProxyServer.getInstance().getTabListHandler().onConnect(this);
BungeeCord.getInstance().connections.put( name, this );
ProxyServer.getInstance().getTabListHandler().onConnect( this );
}
ServerConnectEvent event = new ServerConnectEvent(this, target);
BungeeCord.getInstance().getPluginManager().callEvent(event);
ServerConnectEvent event = new ServerConnectEvent( this, target );
BungeeCord.getInstance().getPluginManager().callEvent( event );
target = event.getTarget(); // Update in case the event changed target
ProxyServer.getInstance().getTabListHandler().onServerChange(this);
ProxyServer.getInstance().getTabListHandler().onServerChange( this );
try
{
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);
if (server == null)
ServerConnection newServer = ServerConnection.connect( this, target, handshake, true );
if ( server == null )
{
// Once again, first connection
clientEntityId = newServer.loginPacket.entityId;
serverEntityId = newServer.loginPacket.entityId;
stream.write(newServer.loginPacket);
stream.write(BungeeCord.getInstance().registerChannels());
stream.write( newServer.loginPacket );
stream.write( BungeeCord.getInstance().registerChannels() );
upBridge = new UpstreamBridge();
upBridge.start();
@ -124,68 +122,68 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
{
downBridge.interrupt();
downBridge.join();
} catch (InterruptedException ie)
} catch ( InterruptedException ie )
{
}
server.disconnect("Quitting");
server.getInfo().removePlayer(this);
server.disconnect( "Quitting" );
server.getInfo().removePlayer( this );
Packet1Login login = newServer.loginPacket;
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
reconnecting = false;
// Add to new
target.addPlayer(this);
target.addPlayer( this );
// Start the bridges and move on
server = newServer;
downBridge = new DownstreamBridge();
downBridge.start();
} catch (KickException ex)
} catch ( KickException ex )
{
destroySelf(ex.getMessage());
} catch (Exception ex)
destroySelf( ex.getMessage() );
} catch ( Exception ex )
{
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)
{
ProxyServer.getInstance().getPlayers().remove(this);
ProxyServer.getInstance().getPlayers().remove( this );
disconnect(reason);
if (server != null)
disconnect( reason );
if ( server != null )
{
server.getInfo().removePlayer(this);
server.disconnect("Quitting");
ProxyServer.getInstance().getReconnectHandler().setServer(this);
server.getInfo().removePlayer( this );
server.disconnect( "Quitting" );
ProxyServer.getInstance().getReconnectHandler().setServer( this );
}
}
@Override
public void disconnect(String reason)
{
ProxyServer.getInstance().getTabListHandler().onDisconnect(this);
super.disconnect(reason);
ProxyServer.getInstance().getTabListHandler().onDisconnect( this );
super.disconnect( reason );
}
@Override
public void sendMessage(String message)
{
packetQueue.add(new Packet3Chat(message));
packetQueue.add( new Packet3Chat( message ) );
}
@Override
public void sendData(String channel, byte[] data)
{
server.packetQueue.add(new PacketFAPluginMessage(channel, data));
server.packetQueue.add( new PacketFAPluginMessage( channel, data ) );
}
@Override
@ -198,19 +196,19 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
@Synchronized("permMutex")
public Collection<String> getGroups()
{
return Collections.unmodifiableCollection(groups);
return Collections.unmodifiableCollection( groups );
}
@Override
@Synchronized("permMutex")
public void addGroups(String... groups)
{
for (String group : groups)
for ( String group : groups )
{
this.groups.add(group);
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group))
this.groups.add( 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")
public void removeGroups(String... groups)
{
for (String group : groups)
for ( String group : groups )
{
this.groups.remove(group);
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group))
this.groups.remove( 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")
public boolean hasPermission(String permission)
{
Boolean val = permissions.get(permission);
return (val == null) ? false : val;
Boolean val = permissions.get( permission );
return ( val == null ) ? false : val;
}
@Override
@Synchronized("permMutex")
public void setPermission(String permission, boolean value)
{
permissions.put(permission, value);
permissions.put( permission, value );
}
private class UpstreamBridge extends Thread
@ -249,82 +247,82 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public UpstreamBridge()
{
super("Upstream Bridge - " + name);
super( "Upstream Bridge - " + name );
}
@Override
public void run()
{
while (!socket.isClosed())
while ( !socket.isClosed() )
{
try
{
byte[] packet = stream.readPacket();
boolean sendPacket = true;
int id = Util.getId(packet);
int id = Util.getId( packet );
switch (id)
switch ( id )
{
case 0x00:
if (trackingPingId == new Packet0KeepAlive(packet).id)
if ( trackingPingId == new Packet0KeepAlive( packet ).id )
{
int newPing = (int) (System.currentTimeMillis() - pingTime);
ProxyServer.getInstance().getTabListHandler().onPingChange(UserConnection.this, newPing);
int newPing = (int) ( System.currentTimeMillis() - pingTime );
ProxyServer.getInstance().getTabListHandler().onPingChange( UserConnection.this, newPing );
ping = newPing;
}
break;
case 0x03:
Packet3Chat chat = new Packet3Chat(packet);
if (chat.message.startsWith("/"))
Packet3Chat chat = new Packet3Chat( packet );
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
{
ChatEvent chatEvent = new ChatEvent(UserConnection.this, server, chat.message);
ProxyServer.getInstance().getPluginManager().callEvent(chatEvent);
ChatEvent chatEvent = new ChatEvent( UserConnection.this, server, chat.message );
ProxyServer.getInstance().getPluginManager().callEvent( chatEvent );
sendPacket = !chatEvent.isCancelled();
}
break;
case 0xFA:
// Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage(packet);
PacketFAPluginMessage message = new PacketFAPluginMessage( packet );
// Might matter in the future
if (message.tag.equals("BungeeCord"))
if ( message.tag.equals( "BungeeCord" ) )
{
continue;
}
PluginMessageEvent event = new PluginMessageEvent(UserConnection.this, server, message.tag, message.data);
ProxyServer.getInstance().getPluginManager().callEvent(event);
PluginMessageEvent event = new PluginMessageEvent( UserConnection.this, server, message.tag, message.data );
ProxyServer.getInstance().getPluginManager().callEvent( event );
if (event.isCancelled())
if ( event.isCancelled() )
{
continue;
}
break;
}
while (!server.packetQueue.isEmpty())
while ( !server.packetQueue.isEmpty() )
{
DefinedPacket p = server.packetQueue.poll();
if (p != null)
if ( p != null )
{
server.stream.write(p);
server.stream.write( p );
}
}
EntityMap.rewrite(packet, clientEntityId, serverEntityId);
if (sendPacket && !server.socket.isClosed())
EntityMap.rewrite( packet, clientEntityId, serverEntityId );
if ( sendPacket && !server.socket.isClosed() )
{
server.stream.write(packet);
server.stream.write( packet );
}
} catch (IOException ex)
} catch ( IOException ex )
{
destroySelf("Reached end of stream");
} catch (Exception ex)
destroySelf( "Reached end of stream" );
} catch ( Exception ex )
{
destroySelf(Util.exception(ex));
destroySelf( Util.exception( ex ) );
}
}
}
@ -335,7 +333,7 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
public DownstreamBridge()
{
super("Downstream Bridge - " + name);
super( "Downstream Bridge - " + name );
}
@Override
@ -344,180 +342,180 @@ public class UserConnection extends GenericConnection implements ProxiedPlayer
try
{
outer:
while (!reconnecting)
while ( !reconnecting )
{
byte[] packet = server.stream.readPacket();
int id = Util.getId(packet);
int id = Util.getId( packet );
switch (id)
switch ( id )
{
case 0x00:
trackingPingId = new Packet0KeepAlive(packet).id;
trackingPingId = new Packet0KeepAlive( packet ).id;
pingTime = System.currentTimeMillis();
break;
case 0x03:
Packet3Chat chat = new Packet3Chat(packet);
ChatEvent chatEvent = new ChatEvent(server, UserConnection.this, chat.message);
ProxyServer.getInstance().getPluginManager().callEvent(chatEvent);
Packet3Chat chat = new Packet3Chat( packet );
ChatEvent chatEvent = new ChatEvent( server, UserConnection.this, chat.message );
ProxyServer.getInstance().getPluginManager().callEvent( chatEvent );
if (chatEvent.isCancelled())
if ( chatEvent.isCancelled() )
{
continue;
}
break;
case 0xC9:
PacketC9PlayerListItem playerList = new PacketC9PlayerListItem(packet);
if (!ProxyServer.getInstance().getTabListHandler().onListUpdate(UserConnection.this, playerList.username, playerList.online, playerList.ping))
PacketC9PlayerListItem playerList = new PacketC9PlayerListItem( packet );
if ( !ProxyServer.getInstance().getTabListHandler().onListUpdate( UserConnection.this, playerList.username, playerList.online, playerList.ping ) )
{
continue;
}
break;
case 0xFA:
// Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage(packet);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(message.data));
PluginMessageEvent event = new PluginMessageEvent(server, UserConnection.this, message.tag, message.data);
ProxyServer.getInstance().getPluginManager().callEvent(event);
PacketFAPluginMessage message = new PacketFAPluginMessage( packet );
DataInputStream in = new DataInputStream( new ByteArrayInputStream( message.data ) );
PluginMessageEvent event = new PluginMessageEvent( server, UserConnection.this, message.tag, message.data );
ProxyServer.getInstance().getPluginManager().callEvent( event );
if (event.isCancelled())
if ( event.isCancelled() )
{
continue;
}
if (message.tag.equals("BungeeCord"))
if ( message.tag.equals( "BungeeCord" ) )
{
String subChannel = in.readUTF();
if (subChannel.equals("Forward"))
if ( subChannel.equals( "Forward" ) )
{
String target = in.readUTF();
String channel = in.readUTF();
short len = in.readShort();
byte[] data = new byte[len];
in.readFully(data);
byte[] data = new byte[ len ];
in.readFully( data );
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
out.writeUTF(channel);
out.writeShort(data.length);
out.write(data);
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( channel );
out.writeShort( data.length );
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
{
ServerInfo server = BungeeCord.getInstance().getServerInfo(target);
if (server != null)
ServerInfo server = BungeeCord.getInstance().getServerInfo( target );
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());
if (server != null)
ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if ( server != null )
{
connect(server, true);
connect( server, true );
break outer;
}
}
if (subChannel.equals("IP"))
if ( subChannel.equals( "IP" ) )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
out.writeUTF("IP");
out.writeUTF(getAddress().getHostString());
out.writeInt(getAddress().getPort());
getServer().sendData("BungeeCord", b.toByteArray());
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "IP" );
out.writeUTF( getAddress().getHostString() );
out.writeInt( getAddress().getPort() );
getServer().sendData( "BungeeCord", b.toByteArray() );
}
if (subChannel.equals("PlayerCount"))
if ( subChannel.equals( "PlayerCount" ) )
{
ServerInfo server = ProxyServer.getInstance().getServerInfo(in.readUTF());
if (server != null)
ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if ( server != null )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
out.writeUTF("PlayerCount");
out.writeUTF(server.getName());
out.writeInt(server.getPlayers().size());
getServer().sendData("BungeeCord", b.toByteArray());
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "PlayerCount" );
out.writeUTF( server.getName() );
out.writeInt( server.getPlayers().size() );
getServer().sendData( "BungeeCord", b.toByteArray() );
}
}
if (subChannel.equals("PlayerList"))
if ( subChannel.equals( "PlayerList" ) )
{
ServerInfo server = ProxyServer.getInstance().getServerInfo(in.readUTF());
if (server != null)
ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if ( server != null )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
out.writeUTF("PlayerList");
out.writeUTF(server.getName());
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "PlayerList" );
out.writeUTF( server.getName() );
StringBuilder sb = new StringBuilder();
for (ProxiedPlayer p : server.getPlayers())
for ( ProxiedPlayer p : server.getPlayers() )
{
sb.append(p.getName());
sb.append(",");
sb.append( p.getName() );
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();
DataOutputStream out = new DataOutputStream(b);
out.writeUTF("GetServers");
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "GetServers" );
StringBuilder sb = new StringBuilder();
for (String server : ProxyServer.getInstance().getServers().keySet())
for ( String server : ProxyServer.getInstance().getServers().keySet() )
{
sb.append(server);
sb.append(",");
sb.append( server );
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());
if (target != null)
ProxiedPlayer target = ProxyServer.getInstance().getPlayer( in.readUTF() );
if ( target != null )
{
target.sendMessage(in.readUTF());
target.sendMessage( in.readUTF() );
}
}
continue;
}
}
while (!packetQueue.isEmpty())
while ( !packetQueue.isEmpty() )
{
DefinedPacket p = packetQueue.poll();
if (p != null)
if ( p != null )
{
stream.write(p);
stream.write( p );
}
}
EntityMap.rewrite(packet, serverEntityId, clientEntityId);
stream.write(packet);
EntityMap.rewrite( packet, serverEntityId, clientEntityId );
stream.write( packet );
if (nextServer != null)
if ( nextServer != null )
{
connect(nextServer, true);
connect( nextServer, true );
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)
{
String[] split = hostline.split(":");
String[] split = hostline.split( ":" );
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)
{
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();
}
@ -68,7 +68,7 @@ public class Util
*/
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 File file = new File("locations.yml");
private final File file = new File( "locations.yml" );
/*========================================================================*/
private Map<String, String> data;
@ -28,21 +28,21 @@ public class YamlReconnectHandler implements ReconnectHandler
try
{
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<>();
} else
{
data = new ConcurrentHashMap<>(data);
data = new ConcurrentHashMap<>( data );
}
}
@ -50,19 +50,19 @@ public class YamlReconnectHandler implements ReconnectHandler
public String getServer(ProxiedPlayer player)
{
ListenerInfo listener = player.getPendingConnection().getListener();
if (listener.isForceDefault())
if ( listener.isForceDefault() )
{
return listener.getDefaultServer();
}
String forced = listener.getForcedHosts().get(player.getPendingConnection().getVirtualHost().getHostName());
String server = (forced == null) ? data.get(key(player)) : forced;
return (server != null) ? server : listener.getDefaultServer();
String forced = listener.getForcedHosts().get( player.getPendingConnection().getVirtualHost().getHostName() );
String server = ( forced == null ) ? data.get( key( player ) ) : forced;
return ( server != null ) ? server : listener.getDefaultServer();
}
@Override
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)
@ -74,12 +74,12 @@ public class YamlReconnectHandler implements ReconnectHandler
@Override
public void save()
{
try (FileWriter wr = new FileWriter(file))
try ( FileWriter wr = new FileWriter( file ) )
{
yaml.dump(data, wr);
} catch (IOException ex)
yaml.dump( data, wr );
} 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()
{
super("alert", "bungeecord.command.alert");
super( "alert", "bungeecord.command.alert" );
}
@Override
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
{
StringBuilder builder = new StringBuilder();
if (args[0].startsWith("&h"))
if ( args[0].startsWith( "&h" ) )
{
// Remove &h
args[0] = args[0].substring(2, args[0].length());
args[0] = args[0].substring( 2, args[0].length() );
} else
{
builder.append(ChatColor.DARK_PURPLE);
builder.append("[Alert] ");
builder.append( ChatColor.DARK_PURPLE );
builder.append( "[Alert] " );
}
for (String s : args)
for ( String s : args )
{
builder.append(ChatColor.translateAlternateColorCodes('&', s));
builder.append(" ");
builder.append( ChatColor.translateAlternateColorCodes( '&', s ) );
builder.append( " " );
}
String message = builder.substring(0, builder.length() - 1);
for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers())
String message = builder.substring( 0, builder.length() - 1 );
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()
{
super("bungee");
super( "bungee" );
}
@Override
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()
{
super("end", "bungeecord.command.end");
super( "end", "bungeecord.command.end" );
}
@Override

View File

@ -11,24 +11,24 @@ public class CommandIP extends Command
public CommandIP()
{
super("ip", "bungeecord.command.ip");
super( "ip", "bungeecord.command.ip" );
}
@Override
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;
}
ProxiedPlayer user = ProxyServer.getInstance().getPlayer(args[0]);
if (user == null)
ProxiedPlayer user = ProxyServer.getInstance().getPlayer( args[0] );
if ( user == null )
{
sender.sendMessage(ChatColor.RED + "That user is not online");
sender.sendMessage( ChatColor.RED + "That user is not online" );
} 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()
{
super("glist", "bungeecord.command.list");
super( "glist", "bungeecord.command.list" );
}
@Override
@ -24,20 +24,20 @@ public class CommandList extends Command
StringBuilder users = new StringBuilder();
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;
}
for (ProxiedPlayer player : connections)
for ( ProxiedPlayer player : connections )
{
users.append(player.getDisplayName());
users.append(", ");
users.append(ChatColor.RESET);
users.append( player.getDisplayName() );
users.append( ", " );
users.append( ChatColor.RESET );
}
users.setLength(users.length() - 2);
sender.sendMessage(ChatColor.BLUE + "Currently online across all servers (" + connections.size() + "): " + ChatColor.RESET + users);
users.setLength( users.length() - 2 );
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()
{
super("greload", "bungeecord.command.reload");
super( "greload", "bungeecord.command.reload" );
}
@Override
public void execute(CommandSender sender, String[] args)
{
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()
{
super("server", "bungeecord.command.server");
super( "server", "bungeecord.command.server" );
}
@Override
public void execute(CommandSender sender, String[] args)
{
if (!(sender instanceof ProxiedPlayer))
if ( !( sender instanceof ProxiedPlayer ) )
{
return;
}
ProxiedPlayer player = (ProxiedPlayer) sender;
Map<String, ServerInfo> servers = BungeeCord.getInstance().config.getServers();
if (args.length == 0)
if ( args.length == 0 )
{
StringBuilder serverList = new StringBuilder();
for (String server : servers.keySet())
for ( String server : servers.keySet() )
{
serverList.append(server);
serverList.append(", ");
serverList.append( server );
serverList.append( ", " );
}
serverList.setLength(serverList.length() - 2);
player.sendMessage(ChatColor.GOLD + "You may connect to the following servers at this time: " + serverList.toString());
serverList.setLength( serverList.length() - 2 );
player.sendMessage( ChatColor.GOLD + "You may connect to the following servers at this time: " + serverList.toString() );
} else
{
ServerInfo server = servers.get(args[0]);
if (server == null)
ServerInfo server = servers.get( args[0] );
if ( server == null )
{
player.sendMessage(ChatColor.RED + "The specified server does not exist");
} else if (server.equals(player.getServer().getInfo()))
player.sendMessage( ChatColor.RED + "The specified server does not exist" );
} 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
{
player.connect(server);
player.connect( server );
}
}
}

View File

@ -22,7 +22,7 @@ public class ConsoleCommandSender implements CommandSender
@Override
public void sendMessage(String message)
{
System.out.println(ChatColor.stripColor(message));
System.out.println( ChatColor.stripColor( message ) );
}
@Override
@ -40,13 +40,13 @@ public class ConsoleCommandSender implements CommandSender
@Override
public void addGroups(String... groups)
{
throw new UnsupportedOperationException("Console may not have groups");
throw new UnsupportedOperationException( "Console may not have groups" );
}
@Override
public void removeGroups(String... groups)
{
throw new UnsupportedOperationException("Console may not have groups");
throw new UnsupportedOperationException( "Console may not have groups" );
}
@Override
@ -58,6 +58,6 @@ public class ConsoleCommandSender implements CommandSender
@Override
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();
timeout = adapter.getInt("timeout", timeout);
uuid = adapter.getString("stats", uuid);
timeout = adapter.getInt( "timeout", timeout );
uuid = adapter.getString( "stats", uuid );
DefaultTabList tab = DefaultTabList.valueOf(adapter.getString("tab_list", "GLOBAL_PING"));
if (tab == null)
DefaultTabList tab = DefaultTabList.valueOf( adapter.getString( "tab_list", "GLOBAL_PING" ) );
if ( tab == null )
{
tab = DefaultTabList.GLOBAL_PING;
}
switch (tab)
switch ( tab )
{
case GLOBAL:
ProxyServer.getInstance().setTabListHandler(new GlobalTabList());
ProxyServer.getInstance().setTabListHandler( new GlobalTabList() );
break;
case GLOBAL_PING:
ProxyServer.getInstance().setTabListHandler(new GlobalPingTabList());
ProxyServer.getInstance().setTabListHandler( new GlobalPingTabList() );
break;
case SERVER:
ProxyServer.getInstance().setTabListHandler(new ServerUniqueTabList());
ProxyServer.getInstance().setTabListHandler( new ServerUniqueTabList() );
break;
}
listeners = adapter.getListeners();
Preconditions.checkArgument(listeners != null && !listeners.isEmpty(), "No listeners defined.");
Preconditions.checkArgument( listeners != null && !listeners.isEmpty(), "No listeners defined." );
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 Yaml yaml;
private Map config;
private final File file = new File("config.yml");
private final File file = new File( "config.yml" );
public void load()
{
@ -36,79 +36,79 @@ public class YamlConfig implements ConfigurationAdapter
{
file.createNewFile();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(options);
options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK );
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();
}
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>());
if (permissions.isEmpty())
Map<String, Object> permissions = get( "permissions", new HashMap<String, Object>() );
if ( permissions.isEmpty() )
{
permissions.put("default", Arrays.asList(new String[]
{
"bungeecord.command.server", "bungeecord.command.list"
}));
permissions.put("admin", Arrays.asList(new String[]
{
"bungeecord.command.alert", "bungeecord.command.end", "bungeecord.command.ip", "bungeecord.command.reload"
}));
permissions.put( "default", Arrays.asList( new String[]
{
"bungeecord.command.server", "bungeecord.command.list"
} ) );
permissions.put( "admin", Arrays.asList( new String[]
{
"bungeecord.command.alert", "bungeecord.command.end", "bungeecord.command.ip", "bungeecord.command.reload"
} ) );
}
Map<String, Object> groups = get("groups", new HashMap<String, Object>());
if (groups.isEmpty())
Map<String, Object> groups = get( "groups", new HashMap<String, Object>() );
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)
{
if (!loaded)
if ( !loaded )
{
load();
}
return get(path, def, config);
return get( path, def, config );
}
@SuppressWarnings("unchecked")
private <T> T get(String path, T def, Map submap)
{
if (!loaded)
if ( !loaded )
{
load();
}
int index = path.indexOf('.');
if (index == -1)
int index = path.indexOf( '.' );
if ( index == -1 )
{
Object val = submap.get(path);
if (val == null && def != null)
Object val = submap.get( path );
if ( val == null && def != null )
{
val = def;
submap.put(path, def);
submap.put( path, def );
save();
}
return (T) val;
} else
{
String first = path.substring(0, index);
String second = path.substring(index + 1, path.length());
Map sub = (Map) submap.get(first);
return (sub != null) ? get(second, def, sub) : def;
String first = path.substring( 0, index );
String second = path.substring( index + 1, path.length() );
Map sub = (Map) submap.get( first );
return ( sub != null ) ? get( second, def, sub ) : def;
}
}
@ -116,43 +116,43 @@ public class YamlConfig implements ConfigurationAdapter
{
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
public int getInt(String path, int def)
{
return get(path, def);
return get( path, def );
}
@Override
public String getString(String path, String def)
{
return get(path, def);
return get( path, def );
}
@Override
@SuppressWarnings("unchecked")
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<>();
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();
String name = entry.getKey();
String addr = get("address", "localhost:25565", val);
InetSocketAddress address = Util.getAddr(addr);
ServerInfo info = ProxyServer.getInstance().constructServerInfo(name, address);
ret.put(name, info);
String addr = get( "address", "localhost:25565", val );
InetSocketAddress address = Util.getAddr( addr );
ServerInfo info = ProxyServer.getInstance().constructServerInfo( name, address );
ret.put( name, info );
}
return ret;
@ -162,28 +162,28 @@ public class YamlConfig implements ConfigurationAdapter
@SuppressWarnings("unchecked")
public Collection<ListenerInfo> getListeners()
{
Collection<Map<String, Object>> base = get("listeners", (Collection) Arrays.asList(new Map[]
{
new HashMap()
}));
Collection<Map<String, Object>> base = get( "listeners", (Collection) Arrays.asList( new Map[]
{
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<>();
for (Map<String, Object> val : base)
for ( Map<String, Object> val : base )
{
String motd = get("motd", "Another Bungee server", val);
motd = ChatColor.translateAlternateColorCodes('&', motd);
String motd = get( "motd", "Another Bungee server", val );
motd = ChatColor.translateAlternateColorCodes( '&', motd );
int maxPlayers = get("max_players", 1, val);
String defaultServer = get("default_server", "lobby", val);
boolean forceDefault = get("force_default_server", false, val);
String host = get("host", "0.0.0.0:25577", val);
InetSocketAddress address = Util.getAddr(host);
Map<String, String> forced = get("forced_hosts", forcedDef, val);
ListenerInfo info = new ListenerInfo(address, motd, maxPlayers, defaultServer, forceDefault, forced);
ret.add(info);
int maxPlayers = get( "max_players", 1, val );
String defaultServer = get( "default_server", "lobby", val );
boolean forceDefault = get( "force_default_server", false, val );
String host = get( "host", "0.0.0.0:25577", val );
InetSocketAddress address = Util.getAddr( host );
Map<String, String> forced = get( "forced_hosts", forcedDef, val );
ListenerInfo info = new ListenerInfo( address, motd, maxPlayers, defaultServer, forceDefault, forced );
ret.add( info );
}
return ret;
@ -193,9 +193,9 @@ public class YamlConfig implements ConfigurationAdapter
@SuppressWarnings("unchecked")
public Collection<String> getGroups(String player)
{
Collection<String> groups = get("groups." + player, null);
Collection<String> ret = (groups == null) ? new HashSet<String>() : new HashSet<>(groups);
ret.add("default");
Collection<String> groups = get( "groups." + player, null );
Collection<String> ret = ( groups == null ) ? new HashSet<String>() : new HashSet<>( groups );
ret.add( "default" );
return ret;
}
@ -203,6 +203,6 @@ public class YamlConfig implements ConfigurationAdapter
@SuppressWarnings("unchecked")
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)
{
in = ByteStreams.newDataInput(buf);
if (readUnsignedByte() != id)
in = ByteStreams.newDataInput( buf );
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;
packet = buf;
@ -53,7 +53,7 @@ public abstract class DefinedPacket implements DataInput, DataOutput
{
out = ByteStreams.newDataOutput();
this.id = id;
writeByte(id);
writeByte( id );
}
/**
@ -70,33 +70,33 @@ public abstract class DefinedPacket implements DataInput, DataOutput
@Override
public void writeUTF(String s)
{
writeShort(s.length());
writeChars(s);
writeShort( s.length() );
writeChars( s );
}
@Override
public String readUTF()
{
short len = readShort();
char[] chars = new char[len];
for (int i = 0; i < len; i++)
char[] chars = new char[ len ];
for ( int i = 0; i < len; i++ )
{
chars[i] = this.readChar();
}
return new String(chars);
return new String( chars );
}
public void writeArray(byte[] b)
{
writeShort(b.length);
write(b);
writeShort( b.length );
write( b );
}
public byte[] readArray()
{
short len = readShort();
byte[] ret = new byte[len];
readFully(ret);
byte[] ret = new byte[ len ];
readFully( ret );
return ret;
}
@ -111,25 +111,25 @@ public abstract class DefinedPacket implements DataInput, DataOutput
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)
{
int id = Util.getId(buf);
int id = Util.getId( buf );
Class<? extends DefinedPacket> clazz = classes[id];
DefinedPacket ret = null;
if (clazz != null)
if ( clazz != null )
{
try
{
Constructor<? extends DefinedPacket> constructor = clazz.getDeclaredConstructor(byte[].class);
if (constructor != null)
Constructor<? extends DefinedPacket> constructor = clazz.getDeclaredConstructor( byte[].class );
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)
{
super(0x00, buffer);
super( 0x00, buffer );
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)
{
super(0x01);
writeInt(entityId);
writeUTF(levelType);
writeByte(gameMode);
writeByte(dimension);
writeByte(difficulty);
writeByte(unused);
writeByte(maxPlayers);
super( 0x01 );
writeInt( entityId );
writeUTF( levelType );
writeByte( gameMode );
writeByte( dimension );
writeByte( difficulty );
writeByte( unused );
writeByte( maxPlayers );
}
public Packet1Login(byte[] buf)
{
super(0x01, buf);
super( 0x01, buf );
this.entityId = readInt();
this.levelType = readUTF();
this.gameMode = readByte();
@ -43,6 +43,6 @@ public class Packet1Login extends DefinedPacket
@Override
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)
{
super(0x02);
writeByte(protocolVersion);
writeUTF(username);
writeUTF(host);
writeInt(port);
super( 0x02 );
writeByte( protocolVersion );
writeUTF( username );
writeUTF( host );
writeInt( port );
}
public Packet2Handshake(byte[] buf)
{
super(0x02, buf);
super( 0x02, buf );
this.procolVersion = readByte();
this.username = readUTF();
this.host = readUTF();
@ -34,6 +34,6 @@ public class Packet2Handshake extends DefinedPacket
@Override
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)
{
super(0x03);
writeUTF(message);
super( 0x03 );
writeUTF( message );
}
public Packet3Chat(byte[] buf)
{
super(0x03, buf);
super( 0x03, buf );
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)
{
super(0x09);
writeInt(dimension);
writeByte(difficulty);
writeByte(gameMode);
writeShort(worldHeight);
writeUTF(levelType);
super( 0x09 );
writeInt( dimension );
writeByte( difficulty );
writeByte( gameMode );
writeShort( worldHeight );
writeUTF( levelType );
}
public Packet9Respawn(byte[] buf)
{
super(0x09, buf);
super( 0x09, buf );
this.dimension = readInt();
this.difficulty = readByte();
this.gameMode = readByte();

View File

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

View File

@ -15,18 +15,18 @@ public class PacketCDClientStatus extends DefinedPacket
*/
public PacketCDClientStatus(byte payload)
{
super(0xCD);
writeByte(payload);
super( 0xCD );
writeByte( payload );
}
public PacketCDClientStatus(byte[] buf)
{
super(0xCD, buf);
super( 0xCD, buf );
}
@Override
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)
{
super(0xFA);
writeUTF(tag);
writeArray(data);
super( 0xFA );
writeUTF( tag );
writeArray( data );
this.tag = tag;
this.data = data;
}
public PacketFAPluginMessage(byte[] buf)
{
super(0xFA, buf);
super( 0xFA, buf );
this.tag = readUTF();
this.data = readArray();
}
@ -30,6 +30,6 @@ public class PacketFAPluginMessage extends DefinedPacket
@Override
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()
{
super(0xFC);
writeArray(new byte[0]);
writeArray(new byte[0]);
super( 0xFC );
writeArray( new byte[ 0 ] );
writeArray( new byte[ 0 ] );
}
public PacketFCEncryptionResponse(byte[] sharedSecret, byte[] verifyToken)
{
super(0xFC);
writeArray(sharedSecret);
writeArray(verifyToken);
super( 0xFC );
writeArray( sharedSecret );
writeArray( verifyToken );
}
public PacketFCEncryptionResponse(byte[] buf)
{
super(0xFC, buf);
super( 0xFC, buf );
this.sharedSecret = readArray();
this.verifyToken = readArray();
}
@ -35,6 +35,6 @@ public class PacketFCEncryptionResponse extends DefinedPacket
@Override
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)
{
super(0xFD);
writeUTF(serverId);
writeArray(publicKey);
writeArray(verifyToken);
super( 0xFD );
writeUTF( serverId );
writeArray( publicKey );
writeArray( verifyToken );
this.serverId = serverId;
this.publicKey = publicKey;
this.verifyToken = verifyToken;
@ -25,7 +25,7 @@ public class PacketFDEncryptionRequest extends DefinedPacket
public PacketFDEncryptionRequest(byte[] buf)
{
super(0xFD, buf);
super( 0xFD, buf );
serverId = readUTF();
publicKey = readArray();
verifyToken = readArray();
@ -34,6 +34,6 @@ public class PacketFDEncryptionRequest extends DefinedPacket
@Override
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)
{
super(0xFE, buffer);
super( 0xFE, buffer );
}
@Override
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)
{
super(0xFF);
writeUTF(message);
super( 0xFF );
writeUTF( message );
}
public PacketFFKick(byte[] buf)
{
super(0xFF, buf);
super( 0xFF, buf );
this.message = readUTF();
}
}

View File

@ -5,7 +5,7 @@ public abstract class PacketHandler
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

View File

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

View File

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

View File

@ -20,28 +20,28 @@ public class GlobalTabList implements TabListHandler
public void onConnect(ProxiedPlayer 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
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()));
sentPings.put(player, PRESENT);
BungeeCord.getInstance().broadcast( new PacketC9PlayerListItem( player.getDisplayName(), true, player.getPing() ) );
sentPings.put( player, PRESENT );
}
}
@Override
public void onDisconnect(ProxiedPlayer player)
{
BungeeCord.getInstance().broadcast(new PacketC9PlayerListItem(player.getDisplayName(), false, 9999));
sentPings.remove(player);
BungeeCord.getInstance().broadcast( new PacketC9PlayerListItem( player.getDisplayName(), false, 9999 ) );
sentPings.remove( player );
}
@Override

View File

@ -27,20 +27,20 @@ public class ServerUniqueTabList implements TabListHandler
@Override
public void onDisconnect(ProxiedPlayer player)
{
sentUsernames.remove(player);
sentUsernames.remove( player );
}
@Override
public void onServerChange(ProxiedPlayer player)
{
Set<String> usernames = sentUsernames.get(player);
if (usernames != null)
Set<String> usernames = sentUsernames.get( player );
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();
}
@ -50,21 +50,21 @@ public class ServerUniqueTabList implements TabListHandler
@Override
public boolean onListUpdate(ProxiedPlayer player, String name, boolean online, int ping)
{
Set<String> usernames = sentUsernames.get(player);
if (usernames == null)
Set<String> usernames = sentUsernames.get( player );
if ( usernames == null )
{
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
{
usernames.remove(name);
usernames.remove( name );
}
}