Code style

This commit is contained in:
Nanit 2021-10-28 21:08:14 +03:00
parent 1c6da4ee0a
commit d170bcbee2
24 changed files with 120 additions and 120 deletions

View File

@ -4,6 +4,6 @@ public final class LimboConstants {
public static final String VELOCITY_INFO_CHANNEL = "velocity:player_info"; public static final String VELOCITY_INFO_CHANNEL = "velocity:player_info";
private LimboConstants(){} private LimboConstants() {}
} }

View File

@ -5,10 +5,10 @@ import ru.nanit.limbo.util.Logger;
public final class NanoLimbo { public final class NanoLimbo {
public static void main(String[] args){ public static void main(String[] args) {
try { try {
new LimboServer().start(); new LimboServer().start();
} catch (Exception e){ } catch (Exception e) {
Logger.error("Cannot start server: ", e); Logger.error("Cannot start server: ", e);
} }
} }

View File

@ -38,7 +38,7 @@ public final class LimboConfig {
private int bossGroupSize; private int bossGroupSize;
private int workerGroupSize; private int workerGroupSize;
public LimboConfig(Path root){ public LimboConfig(Path root) {
this.root = root; this.root = root;
} }

View File

@ -17,7 +17,7 @@ public class SocketAddressSerializer implements TypeSerializer<SocketAddress> {
int port = node.node("port").getInt(); int port = node.node("port").getInt();
SocketAddress address; SocketAddress address;
if (ip == null || ip.isEmpty()){ if (ip == null || ip.isEmpty()) {
address = new InetSocketAddress(port); address = new InetSocketAddress(port);
} else { } else {
address = new InetSocketAddress(ip, port); address = new InetSocketAddress(ip, port);

View File

@ -16,7 +16,7 @@ public class ClientChannelInitializer extends ChannelInitializer<Channel> {
private final LimboServer server; private final LimboServer server;
public ClientChannelInitializer(LimboServer server){ public ClientChannelInitializer(LimboServer server) {
this.server = server; this.server = server;
} }

View File

@ -53,7 +53,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
private int velocityLoginMessageId = -1; private int velocityLoginMessageId = -1;
public ClientConnection(Channel channel, LimboServer server){ public ClientConnection(Channel channel, LimboServer server) {
this.server = server; this.server = server;
this.channel = channel; this.channel = channel;
this.address = channel.remoteAddress(); this.address = channel.remoteAddress();
@ -64,7 +64,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
return gameProfile.getUuid(); return gameProfile.getUuid();
} }
public String getUsername(){ public String getUsername() {
return gameProfile.getUsername(); return gameProfile.getUsername();
} }
@ -74,7 +74,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
@Override @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (state.equals(State.PLAY)){ if (state.equals(State.PLAY)) {
server.getConnections().removeConnection(this); server.getConnections().removeConnection(this);
} }
super.channelInactive(ctx); super.channelInactive(ctx);
@ -82,7 +82,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (channel.isActive()){ if (channel.isActive()) {
Logger.error("Unhandled exception: ", cause); Logger.error("Unhandled exception: ", cause);
} }
} }
@ -92,17 +92,17 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
handlePacket(msg); handlePacket(msg);
} }
public void handlePacket(Object packet){ public void handlePacket(Object packet) {
if (packet instanceof PacketHandshake){ if (packet instanceof PacketHandshake) {
PacketHandshake handshake = (PacketHandshake) packet; PacketHandshake handshake = (PacketHandshake) packet;
clientVersion = handshake.getVersion(); clientVersion = handshake.getVersion();
updateState(State.getById(handshake.getNextState())); updateState(State.getById(handshake.getNextState()));
Logger.debug("Pinged from " + address); Logger.debug("Pinged from " + address);
if (server.getConfig().getInfoForwarding().isLegacy()){ if (server.getConfig().getInfoForwarding().isLegacy()) {
String[] split = handshake.getHost().split("\00"); String[] split = handshake.getHost().split("\00");
if (split.length == 3 || split.length == 4){ if (split.length == 3 || split.length == 4) {
setAddress(split[1]); setAddress(split[1]);
gameProfile.setUuid(UuidUtil.fromString(split[2])); gameProfile.setUuid(UuidUtil.fromString(split[2]));
} else { } else {
@ -112,28 +112,28 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
return; return;
} }
if (packet instanceof PacketStatusRequest){ if (packet instanceof PacketStatusRequest) {
sendPacket(new PacketStatusResponse(server)); sendPacket(new PacketStatusResponse(server));
return; return;
} }
if (packet instanceof PacketStatusPing){ if (packet instanceof PacketStatusPing) {
sendPacketAndClose(packet); sendPacketAndClose(packet);
return; return;
} }
if (packet instanceof PacketLoginStart){ if (packet instanceof PacketLoginStart) {
if (server.getConnections().getCount() >= server.getConfig().getMaxPlayers()){ if (server.getConnections().getCount() >= server.getConfig().getMaxPlayers()) {
disconnectLogin("Too many players connected"); disconnectLogin("Too many players connected");
return; return;
} }
if (!clientVersion.equals(Version.getCurrentSupported())){ if (!clientVersion.equals(Version.getCurrentSupported())) {
disconnectLogin("Incompatible client version"); disconnectLogin("Incompatible client version");
return; return;
} }
if (server.getConfig().getInfoForwarding().isModern()){ if (server.getConfig().getInfoForwarding().isModern()) {
velocityLoginMessageId = ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE); velocityLoginMessageId = ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE);
PacketLoginPluginRequest request = new PacketLoginPluginRequest(); PacketLoginPluginRequest request = new PacketLoginPluginRequest();
request.setMessageId(velocityLoginMessageId); request.setMessageId(velocityLoginMessageId);
@ -143,7 +143,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
return; return;
} }
if (!server.getConfig().getInfoForwarding().isModern()){ if (!server.getConfig().getInfoForwarding().isModern()) {
gameProfile.setUsername(((PacketLoginStart)packet).getUsername()); gameProfile.setUsername(((PacketLoginStart)packet).getUsername());
gameProfile.setUuid(UuidUtil.getOfflineModeUuid(getUsername())); gameProfile.setUuid(UuidUtil.getOfflineModeUuid(getUsername()));
} }
@ -152,13 +152,13 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
return; return;
} }
if (packet instanceof PacketLoginPluginResponse){ if (packet instanceof PacketLoginPluginResponse) {
PacketLoginPluginResponse response = (PacketLoginPluginResponse) packet; PacketLoginPluginResponse response = (PacketLoginPluginResponse) packet;
if (server.getConfig().getInfoForwarding().isModern() if (server.getConfig().getInfoForwarding().isModern()
&& response.getMessageId() == velocityLoginMessageId){ && response.getMessageId() == velocityLoginMessageId) {
if (!response.isSuccessful() || response.getData() == null){ if (!response.isSuccessful() || response.getData() == null) {
disconnectLogin("You need to connect with Velocity"); disconnectLogin("You need to connect with Velocity");
return; return;
} }
@ -178,8 +178,8 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
} }
} }
private void fireLoginSuccess(){ private void fireLoginSuccess() {
if (server.getConfig().getInfoForwarding().isModern() && velocityLoginMessageId == -1){ if (server.getConfig().getInfoForwarding().isModern() && velocityLoginMessageId == -1) {
disconnectLogin("You need to connect with Velocity"); disconnectLogin("You need to connect with Velocity");
return; return;
} }
@ -204,51 +204,51 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
sendKeepAlive(); sendKeepAlive();
} }
public void disconnectLogin(String reason){ public void disconnectLogin(String reason) {
if (isConnected() && state == State.LOGIN){ if (isConnected() && state == State.LOGIN) {
PacketDisconnect disconnect = new PacketDisconnect(); PacketDisconnect disconnect = new PacketDisconnect();
disconnect.setReason(reason); disconnect.setReason(reason);
sendPacketAndClose(disconnect); sendPacketAndClose(disconnect);
} }
} }
public void sendKeepAlive(){ public void sendKeepAlive() {
if (state.equals(State.PLAY)){ if (state.equals(State.PLAY)) {
PacketKeepAlive keepAlive = new PacketKeepAlive(); PacketKeepAlive keepAlive = new PacketKeepAlive();
keepAlive.setId(ThreadLocalRandom.current().nextLong()); keepAlive.setId(ThreadLocalRandom.current().nextLong());
sendPacket(keepAlive); sendPacket(keepAlive);
} }
} }
public void sendPacket(Object packet){ public void sendPacket(Object packet) {
if (isConnected()) if (isConnected())
channel.writeAndFlush(packet, channel.voidPromise()); channel.writeAndFlush(packet, channel.voidPromise());
} }
public void sendPacketAndClose(Object packet){ public void sendPacketAndClose(Object packet) {
if (isConnected()) if (isConnected())
channel.writeAndFlush(packet).addListener(ChannelFutureListener.CLOSE); channel.writeAndFlush(packet).addListener(ChannelFutureListener.CLOSE);
} }
public void writePacket(Object packet){ public void writePacket(Object packet) {
if (isConnected()) channel.write(packet, channel.voidPromise()); if (isConnected()) channel.write(packet, channel.voidPromise());
} }
public void flushPackets(){ public void flushPackets() {
if (isConnected()) channel.flush(); if (isConnected()) channel.flush();
} }
public boolean isConnected(){ public boolean isConnected() {
return channel.isActive(); return channel.isActive();
} }
private void updateState(State state){ private void updateState(State state) {
this.state = state; this.state = state;
channel.pipeline().get(PacketDecoder.class).updateState(state); channel.pipeline().get(PacketDecoder.class).updateState(state);
channel.pipeline().get(PacketEncoder.class).updateState(state); channel.pipeline().get(PacketEncoder.class).updateState(state);
} }
private void setAddress(String host){ private void setAddress(String host) {
this.address = new InetSocketAddress(host, ((InetSocketAddress)this.address).getPort()); this.address = new InetSocketAddress(host, ((InetSocketAddress)this.address).getPort());
} }
@ -272,7 +272,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
return true; return true;
} }
public static void preInitPackets(LimboServer server){ public static void preInitPackets(LimboServer server) {
final String username = server.getConfig().getPingData().getVersion(); final String username = server.getConfig().getPingData().getVersion();
final UUID uuid = UuidUtil.getOfflineModeUuid(username); final UUID uuid = UuidUtil.getOfflineModeUuid(username);
@ -325,7 +325,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
PACKET_PLAYER_INFO = PreEncodedPacket.of(info); PACKET_PLAYER_INFO = PreEncodedPacket.of(info);
PACKET_DECLARE_COMMANDS = PreEncodedPacket.of(declareCommands); PACKET_DECLARE_COMMANDS = PreEncodedPacket.of(declareCommands);
if (server.getConfig().isUseJoinMessage()){ if (server.getConfig().isUseJoinMessage()) {
PacketChatMessage joinMessage = new PacketChatMessage(); PacketChatMessage joinMessage = new PacketChatMessage();
joinMessage.setJsonData(server.getConfig().getJoinMessage()); joinMessage.setJsonData(server.getConfig().getJoinMessage());
joinMessage.setPosition(PacketChatMessage.Position.CHAT); joinMessage.setPosition(PacketChatMessage.Position.CHAT);
@ -333,7 +333,7 @@ public class ClientConnection extends ChannelInboundHandlerAdapter {
PACKET_JOIN_MESSAGE = PreEncodedPacket.of(joinMessage); PACKET_JOIN_MESSAGE = PreEncodedPacket.of(joinMessage);
} }
if (server.getConfig().isUseBossBar()){ if (server.getConfig().isUseBossBar()) {
PacketBossBar bossBar = new PacketBossBar(); PacketBossBar bossBar = new PacketBossBar();
bossBar.setBossBar(server.getConfig().getBossBar()); bossBar.setBossBar(server.getConfig().getBossBar());
bossBar.setUuid(UUID.randomUUID()); bossBar.setUuid(UUID.randomUUID());

View File

@ -13,7 +13,7 @@ public class PacketDecoder extends MessageToMessageDecoder<ByteBuf> {
private State.PacketRegistry mappings; private State.PacketRegistry mappings;
public PacketDecoder(){ public PacketDecoder() {
updateState(State.HANDSHAKING); updateState(State.HANDSHAKING);
} }
@ -25,10 +25,10 @@ public class PacketDecoder extends MessageToMessageDecoder<ByteBuf> {
int packetId = msg.readVarInt(); int packetId = msg.readVarInt();
Packet packet = mappings.getPacket(packetId); Packet packet = mappings.getPacket(packetId);
if (packet != null){ if (packet != null) {
try { try {
packet.decode(msg); packet.decode(msg);
} catch (Exception e){ } catch (Exception e) {
Logger.warning("Cannot decode packet 0x%s: %s", Integer.toHexString(packetId), e.getMessage()); Logger.warning("Cannot decode packet 0x%s: %s", Integer.toHexString(packetId), e.getMessage());
} }
@ -38,7 +38,7 @@ public class PacketDecoder extends MessageToMessageDecoder<ByteBuf> {
} }
} }
public void updateState(State state){ public void updateState(State state) {
this.mappings = state.serverBound; this.mappings = state.serverBound;
} }
} }

View File

@ -13,7 +13,7 @@ public class PacketEncoder extends MessageToByteEncoder<Packet> {
private State.PacketRegistry registry; private State.PacketRegistry registry;
public PacketEncoder(){ public PacketEncoder() {
updateState(State.HANDSHAKING); updateState(State.HANDSHAKING);
} }
@ -24,13 +24,13 @@ public class PacketEncoder extends MessageToByteEncoder<Packet> {
ByteMessage msg = new ByteMessage(out); ByteMessage msg = new ByteMessage(out);
int packetId; int packetId;
if (packet instanceof PreEncodedPacket){ if (packet instanceof PreEncodedPacket) {
packetId = registry.getPacketId(((PreEncodedPacket)packet).getWrappedPacket().getClass()); packetId = registry.getPacketId(((PreEncodedPacket)packet).getWrappedPacket().getClass());
} else { } else {
packetId = registry.getPacketId(packet.getClass()); packetId = registry.getPacketId(packet.getClass());
} }
if (packetId == -1){ if (packetId == -1) {
Logger.warning("Undefined packet class: %s", packet.getClass().getName()); Logger.warning("Undefined packet class: %s", packet.getClass().getName());
return; return;
} }
@ -39,12 +39,12 @@ public class PacketEncoder extends MessageToByteEncoder<Packet> {
try { try {
packet.encode(msg); packet.encode(msg);
} catch (Exception e){ } catch (Exception e) {
Logger.warning("Cannot encode packet 0x%s: %s", Integer.toHexString(packetId), e.getMessage()); Logger.warning("Cannot encode packet 0x%s: %s", Integer.toHexString(packetId), e.getMessage());
} }
} }
public void updateState(State state){ public void updateState(State state) {
this.registry = state.clientBound; this.registry = state.clientBound;
} }

View File

@ -23,11 +23,11 @@ public class ByteMessage extends ByteBuf {
private final ByteBuf buf; private final ByteBuf buf;
public ByteMessage(ByteBuf buf){ public ByteMessage(ByteBuf buf) {
this.buf = buf; this.buf = buf;
} }
public byte[] toByteArray(){ public byte[] toByteArray() {
byte[] bytes = new byte[buf.readableBytes()]; byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes); buf.readBytes(bytes);
return bytes; return bytes;
@ -50,7 +50,7 @@ public class ByteMessage extends ByteBuf {
throw new IllegalArgumentException("Cannot read VarInt"); throw new IllegalArgumentException("Cannot read VarInt");
} }
public void writeVarInt(int value){ public void writeVarInt(int value) {
while (true) { while (true) {
if ((value & 0xFFFFFF80) == 0) { if ((value & 0xFFFFFF80) == 0) {
buf.writeByte(value); buf.writeByte(value);
@ -78,7 +78,7 @@ public class ByteMessage extends ByteBuf {
buf.writeCharSequence(str, StandardCharsets.UTF_8); buf.writeCharSequence(str, StandardCharsets.UTF_8);
} }
public byte[] readBytesArray(){ public byte[] readBytesArray() {
int length = readVarInt(); int length = readVarInt();
byte[] array = new byte[length]; byte[] array = new byte[length];
buf.readBytes(array); buf.readBytes(array);
@ -146,7 +146,7 @@ public class ByteMessage extends ByteBuf {
writeVarInt(compoundTags.length); writeVarInt(compoundTags.length);
for (CompoundBinaryTag tag : compoundTags){ for (CompoundBinaryTag tag : compoundTags) {
BinaryTagIO.writeDataOutput(tag, stream); BinaryTagIO.writeDataOutput(tag, stream);
} }
} catch (IOException e) { } catch (IOException e) {
@ -1139,7 +1139,7 @@ public class ByteMessage extends ByteBuf {
return buf.release(decrement); return buf.release(decrement);
} }
public static ByteMessage create(){ public static ByteMessage create() {
return new ByteMessage(Unpooled.buffer()); return new ByteMessage(Unpooled.buffer());
} }
} }

View File

@ -26,7 +26,7 @@ public class PacketLoginPluginResponse implements PacketIn {
messageId = msg.readVarInt(); messageId = msg.readVarInt();
successful = msg.readBoolean(); successful = msg.readBoolean();
if (msg.readableBytes() > 0){ if (msg.readableBytes() > 0) {
int i = msg.readableBytes(); int i = msg.readableBytes();
data = new ByteMessage(msg.readBytes(i)); data = new ByteMessage(msg.readBytes(i));
} }

View File

@ -38,7 +38,7 @@ public class PacketChatMessage implements PacketOut {
private final int index; private final int index;
Position(int index){ Position(int index) {
this.index = index; this.index = index;
} }

View File

@ -22,14 +22,14 @@ public class PacketDeclareCommands implements PacketOut {
msg.writeByte(0); msg.writeByte(0);
msg.writeVarInt(commands.size()); msg.writeVarInt(commands.size());
for (int i = 1; i <= commands.size() * 2; i++){ for (int i = 1; i <= commands.size() * 2; i++) {
msg.writeVarInt(i++); msg.writeVarInt(i++);
} }
// Declare other commands // Declare other commands
int i = 1; int i = 1;
for (String cmd : commands){ for (String cmd : commands) {
msg.writeByte(1 | 0x04); msg.writeByte(1 | 0x04);
msg.writeVarInt(1); msg.writeVarInt(1);
msg.writeVarInt(i + 1); msg.writeVarInt(i + 1);

View File

@ -18,11 +18,11 @@ public class PacketPlayerInfo implements PacketOut {
this.gameMode = gameMode; this.gameMode = gameMode;
} }
public void setUsername(String username){ public void setUsername(String username) {
this.username = username; this.username = username;
} }
public void setUuid(UUID uuid){ public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }

View File

@ -10,9 +10,9 @@ public class PacketStatusResponse implements PacketOut {
private LimboServer server; private LimboServer server;
public PacketStatusResponse(){ } public PacketStatusResponse() { }
public PacketStatusResponse(LimboServer server){ public PacketStatusResponse(LimboServer server) {
this.server = server; this.server = server;
} }
@ -26,7 +26,7 @@ public class PacketStatusResponse implements PacketOut {
msg.writeString(json); msg.writeString(json);
} }
private String getResponseJson(String version, int protocol, int maxPlayers, int online, String description){ private String getResponseJson(String version, int protocol, int maxPlayers, int online, String description) {
return String.format(TEMPLATE, version, protocol, maxPlayers, online, description); return String.format(TEMPLATE, version, protocol, maxPlayers, online, description);
} }
} }

View File

@ -14,12 +14,12 @@ import java.util.function.Supplier;
public enum State { public enum State {
HANDSHAKING(0){ HANDSHAKING(0) {
{ {
serverBound.register(0x00, PacketHandshake::new); serverBound.register(0x00, PacketHandshake::new);
} }
}, },
STATUS(1){ STATUS(1) {
{ {
serverBound.register(0x01, PacketStatusPing::new); serverBound.register(0x01, PacketStatusPing::new);
serverBound.register(0x00, PacketStatusRequest::new); serverBound.register(0x00, PacketStatusRequest::new);
@ -27,7 +27,7 @@ public enum State {
clientBound.register(0x01, PacketStatusPing::new); clientBound.register(0x01, PacketStatusPing::new);
} }
}, },
LOGIN(2){ LOGIN(2) {
{ {
serverBound.register(0x00, PacketLoginStart::new); serverBound.register(0x00, PacketLoginStart::new);
serverBound.register(0x02, PacketLoginPluginResponse::new); serverBound.register(0x02, PacketLoginPluginResponse::new);
@ -36,7 +36,7 @@ public enum State {
clientBound.register(0x04, PacketLoginPluginRequest::new); clientBound.register(0x04, PacketLoginPluginRequest::new);
} }
}, },
PLAY(3){ PLAY(3) {
{ {
serverBound.register(0x10, PacketKeepAlive::new); serverBound.register(0x10, PacketKeepAlive::new);
clientBound.register(0x10, PacketDeclareCommands::new); clientBound.register(0x10, PacketDeclareCommands::new);
@ -53,7 +53,7 @@ public enum State {
private static final Map<Integer, State> STATE_BY_ID = new HashMap<>(); private static final Map<Integer, State> STATE_BY_ID = new HashMap<>();
static { static {
for (State registry : values()){ for (State registry : values()) {
STATE_BY_ID.put(registry.stateId, registry); STATE_BY_ID.put(registry.stateId, registry);
} }
} }
@ -62,11 +62,11 @@ public enum State {
public final PacketRegistry serverBound = new PacketRegistry(); public final PacketRegistry serverBound = new PacketRegistry();
public final PacketRegistry clientBound = new PacketRegistry(); public final PacketRegistry clientBound = new PacketRegistry();
State(int stateId){ State(int stateId) {
this.stateId = stateId; this.stateId = stateId;
} }
public static State getById(int stateId){ public static State getById(int stateId) {
return STATE_BY_ID.get(stateId); return STATE_BY_ID.get(stateId);
} }
@ -75,16 +75,16 @@ public enum State {
private final Map<Integer, Supplier<?>> packetsById = new HashMap<>(); private final Map<Integer, Supplier<?>> packetsById = new HashMap<>();
private final Map<Class<?>, Integer> packetIdByClass = new HashMap<>(); private final Map<Class<?>, Integer> packetIdByClass = new HashMap<>();
public Packet getPacket(int packetId){ public Packet getPacket(int packetId) {
Supplier<?> supplier = packetsById.get(packetId); Supplier<?> supplier = packetsById.get(packetId);
return supplier == null ? null : (Packet) supplier.get(); return supplier == null ? null : (Packet) supplier.get();
} }
public int getPacketId(Class<?> packetClass){ public int getPacketId(Class<?> packetClass) {
return packetIdByClass.getOrDefault(packetClass, -1); return packetIdByClass.getOrDefault(packetClass, -1);
} }
public void register(int packetId, Supplier<?> supplier){ public void register(int packetId, Supplier<?> supplier) {
packetsById.put(packetId, supplier); packetsById.put(packetId, supplier);
packetIdByClass.put(supplier.get().getClass(), packetId); packetIdByClass.put(supplier.get().getClass(), packetId);
} }

View File

@ -38,26 +38,26 @@ public enum Version {
static { static {
VERSION_MAP = new HashMap<>(); VERSION_MAP = new HashMap<>();
for (Version version : values()){ for (Version version : values()) {
VERSION_MAP.put(version.getProtocolNumber(), version); VERSION_MAP.put(version.getProtocolNumber(), version);
} }
} }
public static Version getCurrentSupported(){ public static Version getCurrentSupported() {
return V1_16_4; return V1_16_4;
} }
public static Version of(int protocolNumber){ public static Version of(int protocolNumber) {
return VERSION_MAP.getOrDefault(protocolNumber, UNDEFINED); return VERSION_MAP.getOrDefault(protocolNumber, UNDEFINED);
} }
private final int protocolNumber; private final int protocolNumber;
Version(int protocolNumber){ Version(int protocolNumber) {
this.protocolNumber = protocolNumber; this.protocolNumber = protocolNumber;
} }
public int getProtocolNumber(){ public int getProtocolNumber() {
return this.protocolNumber; return this.protocolNumber;
} }

View File

@ -13,24 +13,24 @@ public final class Connections {
private final Map<UUID, ClientConnection> connections; private final Map<UUID, ClientConnection> connections;
public Connections(){ public Connections() {
connections = new ConcurrentHashMap<>(); connections = new ConcurrentHashMap<>();
} }
public Collection<ClientConnection> getAllConnections(){ public Collection<ClientConnection> getAllConnections() {
return Collections.unmodifiableCollection(connections.values()); return Collections.unmodifiableCollection(connections.values());
} }
public int getCount(){ public int getCount() {
return connections.size(); return connections.size();
} }
public void addConnection(ClientConnection connection){ public void addConnection(ClientConnection connection) {
connections.put(connection.getUuid(), connection); connections.put(connection.getUuid(), connection);
Logger.info("Player %s connected (%s)", connection.getUsername(), connection.getAddress()); Logger.info("Player %s connected (%s)", connection.getUsername(), connection.getAddress());
} }
public void removeConnection(ClientConnection connection){ public void removeConnection(ClientConnection connection) {
connections.remove(connection.getUuid()); connections.remove(connection.getUuid());
Logger.info("Player %s disconnected", connection.getUsername()); Logger.info("Player %s disconnected", connection.getUsername());
} }

View File

@ -30,11 +30,11 @@ public final class LimboServer {
private EventLoopGroup bossGroup; private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup; private EventLoopGroup workerGroup;
public LimboConfig getConfig(){ public LimboConfig getConfig() {
return config; return config;
} }
public Connections getConnections(){ public Connections getConnections() {
return connections; return connections;
} }
@ -67,10 +67,10 @@ public final class LimboServer {
Logger.info("Server started on %s", config.getAddress()); Logger.info("Server started on %s", config.getAddress());
} }
private void startBootstrap(){ private void startBootstrap() {
Class<? extends ServerChannel> channelClass; Class<? extends ServerChannel> channelClass;
if (config.isUseEpoll() && Epoll.isAvailable()){ if (config.isUseEpoll() && Epoll.isAvailable()) {
bossGroup = new EpollEventLoopGroup(config.getBossGroupSize()); bossGroup = new EpollEventLoopGroup(config.getBossGroupSize());
workerGroup = new EpollEventLoopGroup(config.getWorkerGroupSize()); workerGroup = new EpollEventLoopGroup(config.getWorkerGroupSize());
channelClass = EpollServerSocketChannel.class; channelClass = EpollServerSocketChannel.class;
@ -91,20 +91,20 @@ public final class LimboServer {
.bind(); .bind();
} }
private void broadcastKeepAlive(){ private void broadcastKeepAlive() {
connections.getAllConnections().forEach(ClientConnection::sendKeepAlive); connections.getAllConnections().forEach(ClientConnection::sendKeepAlive);
} }
private void stop(){ private void stop() {
if (keepAliveTask != null){ if (keepAliveTask != null) {
keepAliveTask.cancel(true); keepAliveTask.cancel(true);
} }
if (bossGroup != null){ if (bossGroup != null) {
bossGroup.shutdownGracefully(); bossGroup.shutdownGracefully();
} }
if (workerGroup != null){ if (workerGroup != null) {
workerGroup.shutdownGracefully(); workerGroup.shutdownGracefully();
} }
} }

View File

@ -101,13 +101,13 @@ public class BossBar {
try { try {
bossBar.setColor(Color.valueOf(node.node("color").getString("").toUpperCase())); bossBar.setColor(Color.valueOf(node.node("color").getString("").toUpperCase()));
} catch (IllegalArgumentException e){ } catch (IllegalArgumentException e) {
throw new SerializationException("Invalid bossbar color"); throw new SerializationException("Invalid bossbar color");
} }
try { try {
bossBar.setDivision(Division.valueOf(node.node("division").getString("").toUpperCase())); bossBar.setDivision(Division.valueOf(node.node("division").getString("").toUpperCase()));
} catch (IllegalArgumentException e){ } catch (IllegalArgumentException e) {
throw new SerializationException("Invalid bossbar division"); throw new SerializationException("Invalid bossbar division");
} }

View File

@ -20,15 +20,15 @@ public class InfoForwarding {
return secretKey; return secretKey;
} }
public boolean isNone(){ public boolean isNone() {
return type == Type.NONE; return type == Type.NONE;
} }
public boolean isLegacy(){ public boolean isLegacy() {
return type == Type.LEGACY; return type == Type.LEGACY;
} }
public boolean isModern(){ public boolean isModern() {
return type == Type.MODERN; return type == Type.MODERN;
} }
@ -46,11 +46,11 @@ public class InfoForwarding {
try { try {
forwarding.type = Type.valueOf(node.node("type").getString("").toUpperCase()); forwarding.type = Type.valueOf(node.node("type").getString("").toUpperCase());
} catch (IllegalArgumentException e){ } catch (IllegalArgumentException e) {
throw new SerializationException("Undefined info forwarding type"); throw new SerializationException("Undefined info forwarding type");
} }
if (forwarding.type == Type.MODERN){ if (forwarding.type == Type.MODERN) {
forwarding.secretKey = node.node("secret").getString("").getBytes(StandardCharsets.UTF_8); forwarding.secretKey = node.node("secret").getString("").getBytes(StandardCharsets.UTF_8);
} }

View File

@ -5,9 +5,9 @@ public final class Colors {
private static final char CHAR_FROM = '\u0026'; private static final char CHAR_FROM = '\u0026';
private static final char CHAR_TO = '\u00A7'; private static final char CHAR_TO = '\u00A7';
private Colors(){} private Colors() {}
public static String of(String text){ public static String of(String text) {
return text.replace(CHAR_FROM, CHAR_TO); return text.replace(CHAR_FROM, CHAR_TO);
} }

View File

@ -8,48 +8,48 @@ public final class Logger {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("hh:mm:ss"); private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("hh:mm:ss");
private static int debugLevel = 3; private static int debugLevel = 3;
private Logger(){} private Logger() {}
public static void setLevel(int level){ public static void setLevel(int level) {
debugLevel = level; debugLevel = level;
} }
public static void info(Object msg, Object... args){ public static void info(Object msg, Object... args) {
print(Level.INFO, msg, null, args); print(Level.INFO, msg, null, args);
} }
public static void debug(Object msg, Object... args){ public static void debug(Object msg, Object... args) {
print(Level.DEBUG, msg, null, args); print(Level.DEBUG, msg, null, args);
} }
public static void warning(Object msg, Object... args){ public static void warning(Object msg, Object... args) {
print(Level.WARNING, msg, null, args); print(Level.WARNING, msg, null, args);
} }
public static void warning(Object msg, Throwable t, Object... args){ public static void warning(Object msg, Throwable t, Object... args) {
print(Level.WARNING, msg, t, args); print(Level.WARNING, msg, t, args);
} }
public static void error(Object msg, Object... args){ public static void error(Object msg, Object... args) {
print(Level.ERROR, msg, null, args); print(Level.ERROR, msg, null, args);
} }
public static void error(Object msg, Throwable t, Object... args){ public static void error(Object msg, Throwable t, Object... args) {
print(Level.ERROR, msg, t, args); print(Level.ERROR, msg, t, args);
} }
public static void print(Level level, Object msg, Throwable t, Object... args){ public static void print(Level level, Object msg, Throwable t, Object... args) {
if (debugLevel >= level.getIndex()){ if (debugLevel >= level.getIndex()) {
System.out.println(String.format("%s: %s", getPrefix(level), String.format(msg.toString(), args))); System.out.println(String.format("%s: %s", getPrefix(level), String.format(msg.toString(), args)));
if (t != null) t.printStackTrace(); if (t != null) t.printStackTrace();
} }
} }
private static String getPrefix(Level level){ private static String getPrefix(Level level) {
return String.format("[%s] [%s]", getTime(), level.getDisplay()); return String.format("[%s] [%s]", getTime(), level.getDisplay());
} }
private static String getTime(){ private static String getTime() {
return LocalTime.now().format(FORMATTER); return LocalTime.now().format(FORMATTER);
} }
@ -63,7 +63,7 @@ public final class Logger {
private final String display; private final String display;
private final int index; private final int index;
Level(String display, int index){ Level(String display, int index) {
this.display = display; this.display = display;
this.index = index; this.index = index;
} }

View File

@ -5,14 +5,14 @@ import java.util.UUID;
public final class UuidUtil { public final class UuidUtil {
private UuidUtil(){} private UuidUtil() {}
public static UUID getOfflineModeUuid(String username){ public static UUID getOfflineModeUuid(String username) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + username) return UUID.nameUUIDFromBytes(("OfflinePlayer:" + username)
.getBytes(StandardCharsets.UTF_8)); .getBytes(StandardCharsets.UTF_8));
} }
public static UUID fromString(String str){ public static UUID fromString(String str) {
if(str.contains("-")) return UUID.fromString(str); if(str.contains("-")) return UUID.fromString(str);
return UUID.fromString(str.replaceFirst("(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5")); return UUID.fromString(str.replaceFirst("(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5"));
} }

View File

@ -18,7 +18,7 @@ public final class DimensionRegistry {
private CompoundBinaryTag theEnd; private CompoundBinaryTag theEnd;
private CompoundBinaryTag nether; private CompoundBinaryTag nether;
public CompoundBinaryTag getCodec(){ public CompoundBinaryTag getCodec() {
return codec; return codec;
} }
@ -47,7 +47,7 @@ public final class DimensionRegistry {
nether = (CompoundBinaryTag) ((CompoundBinaryTag) dimensions.get(2)).get("element"); nether = (CompoundBinaryTag) ((CompoundBinaryTag) dimensions.get(2)).get("element");
theEnd = (CompoundBinaryTag) ((CompoundBinaryTag) dimensions.get(3)).get("element"); theEnd = (CompoundBinaryTag) ((CompoundBinaryTag) dimensions.get(3)).get("element");
switch (def.toLowerCase()){ switch (def.toLowerCase()) {
case "overworld": case "overworld":
defaultDimension = overWorld; defaultDimension = overWorld;
break; break;