3
0
Mirror von https://github.com/PaperMC/Velocity.git synchronisiert 2024-11-17 05:20:14 +01:00

[Breaking] Many renamings in the API

The get prefix has been dropped from getters where it is unambiguous what is being referred to. Other getters have also received renames to clarify their purpose.

The main exception is the ProxyConfig API, but it's one of my personal sore spots in the API, so it'll be replaced instead.
Dieser Commit ist enthalten in:
Andrew Steinborn 2021-04-17 04:58:16 -04:00
Ursprung 2254e3b617
Commit 47c354e6ee
133 geänderte Dateien mit 951 neuen und 965 gelöschten Zeilen

Datei anzeigen

@ -21,7 +21,7 @@ public interface CommandMeta {
* *
* @return the command aliases * @return the command aliases
*/ */
Collection<String> getAliases(); Collection<String> aliases();
/** /**
* Returns a collection containing command nodes that provide additional * Returns a collection containing command nodes that provide additional
@ -30,7 +30,7 @@ public interface CommandMeta {
* *
* @return the hinting command nodes * @return the hinting command nodes
*/ */
Collection<CommandNode<CommandSource>> getHints(); Collection<CommandNode<CommandSource>> hints();
/** /**
* Provides a fluent interface to create {@link CommandMeta}s. * Provides a fluent interface to create {@link CommandMeta}s.

Datei anzeigen

@ -18,12 +18,5 @@ public interface RawCommand extends InvocableCommand<RawCommand.Invocation> {
* Contains the invocation data for a raw command. * Contains the invocation data for a raw command.
*/ */
interface Invocation extends CommandInvocation<String> { interface Invocation extends CommandInvocation<String> {
/**
* Returns the used alias to execute the command.
*
* @return the used command alias
*/
String alias();
} }
} }

Datei anzeigen

@ -22,12 +22,5 @@ public interface SimpleCommand extends InvocableCommand<SimpleCommand.Invocation
* Contains the invocation data for a simple command. * Contains the invocation data for a simple command.
*/ */
interface Invocation extends CommandInvocation<String @NonNull []> { interface Invocation extends CommandInvocation<String @NonNull []> {
/**
* Returns the used alias to execute the command.
*
* @return the used command alias
*/
String alias();
} }
} }

Datei anzeigen

@ -23,7 +23,7 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
* *
* @return the result of this event * @return the result of this event
*/ */
R getResult(); R result();
/** /**
* Sets the result of this event. The result must be non-null. * Sets the result of this event. The result must be non-null.
@ -99,7 +99,7 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
return status; return status;
} }
public Optional<Component> getReason() { public Optional<Component> reason() {
return Optional.ofNullable(reason); return Optional.ofNullable(reason);
} }

Datei anzeigen

@ -27,11 +27,12 @@ public @interface Subscribe {
short order() default PostOrder.NORMAL; short order() default PostOrder.NORMAL;
/** /**
* Whether the handler is required to be called asynchronously. * Whether the handler must be called asynchronously.
* *
* <p>If this method returns {@code true}, the method is guaranteed to be executed * <p>If this method returns {@code true}, the method is guaranteed to be executed
* asynchronously from the current thread. Otherwise, the handler may be executed on the * asynchronously. Otherwise, the handler may be executed on the current thread or
* current thread or asynchronously.</p> * asynchronously. <strong>This still means you must consider thread-safety in your
* event listeners</strong> as the "current thread" can and will be different each time.</p>
* *
* <p>If any method handler targeting an event type is marked with {@code true}, then every * <p>If any method handler targeting an event type is marked with {@code true}, then every
* handler targeting that event type will be executed asynchronously.</p> * handler targeting that event type will be executed asynchronously.</p>

Datei anzeigen

@ -20,13 +20,13 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/ */
public interface CommandExecuteEvent extends ResultedEvent<CommandResult> { public interface CommandExecuteEvent extends ResultedEvent<CommandResult> {
CommandSource getCommandSource(); CommandSource source();
/** /**
* Gets the original command being executed without the first slash. * Gets the original command being executed without the first slash.
* @return the original command being executed * @return the original command being executed
*/ */
String getCommand(); String rawCommand();
final class CommandResult implements ResultedEvent.Result { final class CommandResult implements ResultedEvent.Result {
@ -44,7 +44,7 @@ public interface CommandExecuteEvent extends ResultedEvent<CommandResult> {
this.command = command; this.command = command;
} }
public Optional<String> getCommand() { public Optional<String> modifiedCommand() {
return Optional.ofNullable(command); return Optional.ofNullable(command);
} }

Datei anzeigen

@ -31,7 +31,7 @@ public final class CommandExecuteEventImpl implements CommandExecuteEvent {
} }
@Override @Override
public CommandSource getCommandSource() { public CommandSource source() {
return commandSource; return commandSource;
} }
@ -40,12 +40,12 @@ public final class CommandExecuteEventImpl implements CommandExecuteEvent {
* @return the original command being executed * @return the original command being executed
*/ */
@Override @Override
public String getCommand() { public String rawCommand() {
return command; return command;
} }
@Override @Override
public CommandResult getResult() { public CommandResult result() {
return result; return result;
} }

Datei anzeigen

@ -16,7 +16,7 @@ import com.velocitypowered.api.proxy.connection.Player;
*/ */
public interface PlayerAvailableCommandsEvent { public interface PlayerAvailableCommandsEvent {
Player getPlayer(); Player player();
RootCommandNode<?> getRootNode(); RootCommandNode<?> rootNode();
} }

Datei anzeigen

@ -35,12 +35,12 @@ public class PlayerAvailableCommandsEventImpl implements PlayerAvailableCommands
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public RootCommandNode<?> getRootNode() { public RootCommandNode<?> rootNode() {
return rootNode; return rootNode;
} }
} }

Datei anzeigen

@ -7,9 +7,12 @@
package com.velocitypowered.api.event.connection; package com.velocitypowered.api.event.connection;
import com.velocitypowered.api.proxy.connection.InboundConnection;
/** /**
* This event is fired when a handshake is established between a client and the proxy. * This event is fired when a handshake is established between a client and the proxy.
*/ */
public interface ConnectionHandshakeEvent { public interface ConnectionHandshakeEvent {
InboundConnection connection();
} }

Datei anzeigen

@ -21,7 +21,8 @@ public final class ConnectionHandshakeEventImpl implements ConnectionHandshakeEv
this.connection = Preconditions.checkNotNull(connection, "connection"); this.connection = Preconditions.checkNotNull(connection, "connection");
} }
public InboundConnection getConnection() { @Override
public InboundConnection connection() {
return connection; return connection;
} }

Datei anzeigen

@ -7,9 +7,7 @@
package com.velocitypowered.api.event.connection; package com.velocitypowered.api.event.connection;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.velocitypowered.api.event.ResultedEvent; import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.proxy.connection.Player; import com.velocitypowered.api.proxy.connection.Player;
import com.velocitypowered.api.proxy.connection.ServerConnection; import com.velocitypowered.api.proxy.connection.ServerConnection;
@ -17,86 +15,29 @@ import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.messages.ChannelMessageSink; import com.velocitypowered.api.proxy.messages.ChannelMessageSink;
import com.velocitypowered.api.proxy.messages.ChannelMessageSource; import com.velocitypowered.api.proxy.messages.ChannelMessageSource;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.util.Arrays;
/** /**
* This event is fired when a plugin message is sent to the proxy, either from a client ({@link * This event is fired when a plugin message is sent to the proxy, either from a client ({@link
* Player}) or a server ({@link ServerConnection}). * Player}) or a server ({@link ServerConnection}).
*/ */
public final class PluginMessageEvent implements ResultedEvent<PluginMessageEvent.ForwardResult> { public interface PluginMessageEvent extends ResultedEvent<PluginMessageEvent.ForwardResult> {
private final ChannelMessageSource source; ChannelMessageSource getSource();
private final ChannelMessageSink target;
private final ChannelIdentifier identifier;
private final byte[] data;
private ForwardResult result;
/** ChannelMessageSink getTarget();
* Creates a new instance.
*
* @param source the source of the plugin message
* @param target the destination of the plugin message
* @param identifier the channel for this plugin message
* @param data the payload of the plugin message
*/
public PluginMessageEvent(ChannelMessageSource source, ChannelMessageSink target,
ChannelIdentifier identifier, byte[] data) {
this.source = Preconditions.checkNotNull(source, "source");
this.target = Preconditions.checkNotNull(target, "target");
this.identifier = Preconditions.checkNotNull(identifier, "identifier");
this.data = Preconditions.checkNotNull(data, "data");
this.result = ForwardResult.forward();
}
@Override ChannelIdentifier getIdentifier();
public ForwardResult getResult() {
return result;
}
@Override byte[] getData();
public void setResult(ForwardResult result) {
this.result = Preconditions.checkNotNull(result, "result");
}
public ChannelMessageSource getSource() { ByteArrayInputStream dataAsInputStream();
return source;
}
public ChannelMessageSink getTarget() { ByteArrayDataInput dataAsDataStream();
return target;
}
public ChannelIdentifier getIdentifier() {
return identifier;
}
public byte[] getData() {
return Arrays.copyOf(data, data.length);
}
public ByteArrayInputStream dataAsInputStream() {
return new ByteArrayInputStream(data);
}
public ByteArrayDataInput dataAsDataStream() {
return ByteStreams.newDataInput(data);
}
@Override
public String toString() {
return "PluginMessageEvent{"
+ "source=" + source
+ ", target=" + target
+ ", identifier=" + identifier
+ ", data=" + Arrays.toString(data)
+ ", result=" + result
+ '}';
}
/** /**
* A result determining whether or not to forward this message on. * A result determining whether or not to forward this message on.
*/ */
public static final class ForwardResult implements ResultedEvent.Result { public static final class ForwardResult implements Result {
private static final ForwardResult ALLOWED = new ForwardResult(true); private static final ForwardResult ALLOWED = new ForwardResult(true);
private static final ForwardResult DENIED = new ForwardResult(false); private static final ForwardResult DENIED = new ForwardResult(false);

Datei anzeigen

@ -0,0 +1,101 @@
/*
* Copyright (C) 2018 Velocity Contributors
*
* The Velocity API is licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in the api top-level directory.
*/
package com.velocitypowered.api.event.connection;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.velocitypowered.api.proxy.connection.Player;
import com.velocitypowered.api.proxy.connection.ServerConnection;
import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.messages.ChannelMessageSink;
import com.velocitypowered.api.proxy.messages.ChannelMessageSource;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
/**
* This event is fired when a plugin message is sent to the proxy, either from a client ({@link
* Player}) or a server ({@link ServerConnection}).
*/
public final class PluginMessageEventImpl implements PluginMessageEvent {
private final ChannelMessageSource source;
private final ChannelMessageSink target;
private final ChannelIdentifier identifier;
private final byte[] data;
private ForwardResult result;
/**
* Creates a new instance.
*
* @param source the source of the plugin message
* @param target the destination of the plugin message
* @param identifier the channel for this plugin message
* @param data the payload of the plugin message
*/
public PluginMessageEventImpl(ChannelMessageSource source, ChannelMessageSink target,
ChannelIdentifier identifier, byte[] data) {
this.source = Preconditions.checkNotNull(source, "source");
this.target = Preconditions.checkNotNull(target, "target");
this.identifier = Preconditions.checkNotNull(identifier, "identifier");
this.data = Preconditions.checkNotNull(data, "data");
this.result = ForwardResult.forward();
}
@Override
public ForwardResult result() {
return result;
}
@Override
public void setResult(ForwardResult result) {
this.result = Preconditions.checkNotNull(result, "result");
}
@Override
public ChannelMessageSource getSource() {
return source;
}
@Override
public ChannelMessageSink getTarget() {
return target;
}
@Override
public ChannelIdentifier getIdentifier() {
return identifier;
}
@Override
public byte[] getData() {
return Arrays.copyOf(data, data.length);
}
@Override
public ByteArrayInputStream dataAsInputStream() {
return new ByteArrayInputStream(data);
}
@Override
public ByteArrayDataInput dataAsDataStream() {
return ByteStreams.newDataInput(data);
}
@Override
public String toString() {
return "PluginMessageEvent{"
+ "source=" + source
+ ", target=" + target
+ ", identifier=" + identifier
+ ", data=" + Arrays.toString(data)
+ ", result=" + result
+ '}';
}
}

Datei anzeigen

@ -15,9 +15,9 @@ import com.velocitypowered.api.proxy.server.ServerPing;
*/ */
public interface ProxyPingEvent { public interface ProxyPingEvent {
InboundConnection getConnection(); InboundConnection connection();
ServerPing getPing(); ServerPing ping();
void setPing(ServerPing ping); void setPing(ServerPing ping);
} }

Datei anzeigen

@ -25,12 +25,12 @@ public final class ProxyPingEventImpl implements ProxyPingEvent {
} }
@Override @Override
public InboundConnection getConnection() { public InboundConnection connection() {
return connection; return connection;
} }
@Override @Override
public ServerPing getPing() { public ServerPing ping() {
return ping; return ping;
} }

Datei anzeigen

@ -20,21 +20,21 @@ public interface ProxyQueryEvent {
* *
* @return query type * @return query type
*/ */
QueryType getQueryType(); QueryType type();
/** /**
* Get the address of the client that sent this query. * Get the address of the client that sent this query.
* *
* @return querier address * @return querier address
*/ */
InetAddress getQuerierAddress(); InetAddress queryingAddress();
/** /**
* Returns the current query response. * Returns the current query response.
* *
* @return the current query response * @return the current query response
*/ */
QueryResponse getResponse(); QueryResponse response();
/** /**
* Sets a new query response. * Sets a new query response.

Datei anzeigen

@ -39,7 +39,7 @@ public final class ProxyQueryEventImpl implements ProxyQueryEvent {
* @return query type * @return query type
*/ */
@Override @Override
public QueryType getQueryType() { public QueryType type() {
return queryType; return queryType;
} }
@ -49,7 +49,7 @@ public final class ProxyQueryEventImpl implements ProxyQueryEvent {
* @return querier address * @return querier address
*/ */
@Override @Override
public InetAddress getQuerierAddress() { public InetAddress queryingAddress() {
return querierAddress; return querierAddress;
} }
@ -59,7 +59,7 @@ public final class ProxyQueryEventImpl implements ProxyQueryEvent {
* @return the current query response * @return the current query response
*/ */
@Override @Override
public QueryResponse getResponse() { public QueryResponse response() {
return response; return response;
} }

Datei anzeigen

@ -15,7 +15,7 @@ import java.net.SocketAddress;
*/ */
public interface ListenerBoundEvent { public interface ListenerBoundEvent {
SocketAddress getAddress(); SocketAddress address();
ListenerType getListenerType(); ListenerType type();
} }

Datei anzeigen

@ -25,12 +25,12 @@ public final class ListenerBoundEventImpl implements ListenerBoundEvent {
} }
@Override @Override
public SocketAddress getAddress() { public SocketAddress address() {
return address; return address;
} }
@Override @Override
public ListenerType getListenerType() { public ListenerType type() {
return listenerType; return listenerType;
} }

Datei anzeigen

@ -15,7 +15,7 @@ import java.net.SocketAddress;
*/ */
public interface ListenerClosedEvent { public interface ListenerClosedEvent {
SocketAddress getAddress(); SocketAddress address();
ListenerType getListenerType(); ListenerType type();
} }

Datei anzeigen

@ -25,12 +25,12 @@ public final class ListenerClosedEventImpl implements ListenerClosedEvent {
} }
@Override @Override
public SocketAddress getAddress() { public SocketAddress address() {
return address; return address;
} }
@Override @Override
public ListenerType getListenerType() { public ListenerType type() {
return listenerType; return listenerType;
} }

Datei anzeigen

@ -19,7 +19,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/ */
public interface PermissionsSetupEvent { public interface PermissionsSetupEvent {
PermissionSubject getSubject(); PermissionSubject subject();
/** /**
* Uses the provider function to obtain a {@link PermissionFunction} for the subject. * Uses the provider function to obtain a {@link PermissionFunction} for the subject.
@ -29,7 +29,7 @@ public interface PermissionsSetupEvent {
*/ */
PermissionFunction createFunction(PermissionSubject subject); PermissionFunction createFunction(PermissionSubject subject);
PermissionProvider getProvider(); PermissionProvider provider();
/** /**
* Sets the {@link PermissionFunction} that should be used for the subject. * Sets the {@link PermissionFunction} that should be used for the subject.

Datei anzeigen

@ -30,7 +30,7 @@ public final class PermissionsSetupEventImpl implements PermissionsSetupEvent {
} }
@Override @Override
public PermissionSubject getSubject() { public PermissionSubject subject() {
return this.subject; return this.subject;
} }
@ -46,7 +46,7 @@ public final class PermissionsSetupEventImpl implements PermissionsSetupEvent {
} }
@Override @Override
public PermissionProvider getProvider() { public PermissionProvider provider() {
return this.provider; return this.provider;
} }

Datei anzeigen

@ -9,11 +9,15 @@ package com.velocitypowered.api.event.player;
import com.velocitypowered.api.proxy.connection.Player; import com.velocitypowered.api.proxy.connection.Player;
/**
* This event is fired when a player disconnects from the proxy. Operations on the provided player,
* aside from basic data retrieval operations, may behave in undefined ways.
*/
public interface DisconnectEvent { public interface DisconnectEvent {
Player getPlayer(); Player player();
LoginStatus getLoginStatus(); LoginStatus loginStatus();
public enum LoginStatus { public enum LoginStatus {

Datei anzeigen

@ -25,12 +25,12 @@ public final class DisconnectEventImpl implements DisconnectEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public LoginStatus getLoginStatus() { public LoginStatus loginStatus() {
return loginStatus; return loginStatus;
} }

Datei anzeigen

@ -17,11 +17,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/ */
public interface GameProfileRequestEvent { public interface GameProfileRequestEvent {
InboundConnection getConnection(); InboundConnection connection();
String getUsername(); String username();
GameProfile getOriginalProfile(); GameProfile initialProfile();
boolean isOnlineMode(); boolean isOnlineMode();
@ -32,7 +32,7 @@ public interface GameProfileRequestEvent {
* *
* @return the user's {@link GameProfile} * @return the user's {@link GameProfile}
*/ */
GameProfile getGameProfile(); GameProfile gameProfile();
/** /**
* Sets the game profile to use for this connection. * Sets the game profile to use for this connection.

Datei anzeigen

@ -39,17 +39,17 @@ public final class GameProfileRequestEventImpl implements GameProfileRequestEven
} }
@Override @Override
public InboundConnection getConnection() { public InboundConnection connection() {
return connection; return connection;
} }
@Override @Override
public String getUsername() { public String username() {
return username; return username;
} }
@Override @Override
public GameProfile getOriginalProfile() { public GameProfile initialProfile() {
return originalProfile; return originalProfile;
} }
@ -66,7 +66,7 @@ public final class GameProfileRequestEventImpl implements GameProfileRequestEven
* @return the user's {@link GameProfile} * @return the user's {@link GameProfile}
*/ */
@Override @Override
public GameProfile getGameProfile() { public GameProfile gameProfile() {
return gameProfile == null ? originalProfile : gameProfile; return gameProfile == null ? originalProfile : gameProfile;
} }

Datei anzeigen

@ -24,16 +24,16 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public interface KickedFromServerEvent extends public interface KickedFromServerEvent extends
ResultedEvent<KickedFromServerEvent.ServerKickResult> { ResultedEvent<KickedFromServerEvent.ServerKickResult> {
Player getPlayer(); Player player();
RegisteredServer getServer(); RegisteredServer server();
/** /**
* Gets the reason the server kicked the player from the server. * Gets the reason the server kicked the player from the server.
* *
* @return the server kicked the player from the server * @return the server kicked the player from the server
*/ */
Optional<Component> getServerKickReason(); Optional<Component> serverKickReason();
/** /**
* Returns whether or not the player got kicked while connecting to another server. * Returns whether or not the player got kicked while connecting to another server.
@ -54,10 +54,10 @@ public interface KickedFromServerEvent extends
*/ */
final class DisconnectPlayer implements ServerKickResult { final class DisconnectPlayer implements ServerKickResult {
private final Component component; private final Component message;
private DisconnectPlayer(Component component) { private DisconnectPlayer(Component message) {
this.component = Preconditions.checkNotNull(component, "component"); this.message = Preconditions.checkNotNull(message, "message");
} }
@Override @Override
@ -65,8 +65,8 @@ public interface KickedFromServerEvent extends
return true; return true;
} }
public Component getReason() { public Component message() {
return component; return message;
} }
/** /**
@ -104,7 +104,7 @@ public interface KickedFromServerEvent extends
return server; return server;
} }
public Component getMessage() { public Component message() {
return message; return message;
} }
@ -142,7 +142,7 @@ public interface KickedFromServerEvent extends
return false; return false;
} }
public Component getMessage() { public Component message() {
return message; return message;
} }

Datei anzeigen

@ -48,7 +48,7 @@ public final class KickedFromServerEventImpl implements KickedFromServerEvent {
} }
@Override @Override
public ServerKickResult getResult() { public ServerKickResult result() {
return result; return result;
} }
@ -58,12 +58,12 @@ public final class KickedFromServerEventImpl implements KickedFromServerEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public RegisteredServer getServer() { public RegisteredServer server() {
return server; return server;
} }
@ -72,7 +72,7 @@ public final class KickedFromServerEventImpl implements KickedFromServerEvent {
* @return the server kicked the player from the server * @return the server kicked the player from the server
*/ */
@Override @Override
public Optional<Component> getServerKickReason() { public Optional<Component> serverKickReason() {
return Optional.ofNullable(originalReason); return Optional.ofNullable(originalReason);
} }

Datei anzeigen

@ -16,11 +16,6 @@ import com.velocitypowered.api.proxy.connection.Player;
*/ */
public interface LoginEvent extends ResultedEvent<ResultedEvent.ComponentResult> { public interface LoginEvent extends ResultedEvent<ResultedEvent.ComponentResult> {
Player getPlayer(); Player player();
@Override
ComponentResult getResult();
@Override
void setResult(ComponentResult result);
} }

Datei anzeigen

@ -25,12 +25,12 @@ public final class LoginEventImpl implements LoginEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public ComponentResult getResult() { public ComponentResult result() {
return result; return result;
} }

Datei anzeigen

@ -17,7 +17,7 @@ import java.util.List;
*/ */
public interface PlayerChannelRegisterEvent { public interface PlayerChannelRegisterEvent {
Player getPlayer(); Player player();
List<ChannelIdentifier> getChannels(); List<ChannelIdentifier> channels();
} }

Datei anzeigen

@ -27,12 +27,12 @@ public final class PlayerChannelRegisterEventImpl implements PlayerChannelRegist
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public List<ChannelIdentifier> getChannels() { public List<ChannelIdentifier> channels() {
return channels; return channels;
} }

Datei anzeigen

@ -16,15 +16,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public interface PlayerChatEvent extends ResultedEvent<PlayerChatEvent.ChatResult> { public interface PlayerChatEvent extends ResultedEvent<PlayerChatEvent.ChatResult> {
Player getPlayer(); Player player();
String getMessage(); String sentMessage();
@Override
ChatResult getResult();
@Override
void setResult(ChatResult result);
/** /**
* Represents the result of the {@link PlayerChatEvent}. * Represents the result of the {@link PlayerChatEvent}.
@ -42,7 +36,7 @@ public interface PlayerChatEvent extends ResultedEvent<PlayerChatEvent.ChatResul
this.message = message; this.message = message;
} }
public Optional<String> getMessage() { public Optional<String> modifiedMessage() {
return Optional.ofNullable(message); return Optional.ofNullable(message);
} }
@ -80,7 +74,7 @@ public interface PlayerChatEvent extends ResultedEvent<PlayerChatEvent.ChatResul
* @param message the message to use instead * @param message the message to use instead
* @return a result with a new message * @return a result with a new message
*/ */
public static ChatResult message(@NonNull String message) { public static ChatResult replaceMessage(@NonNull String message) {
Preconditions.checkNotNull(message, "message"); Preconditions.checkNotNull(message, "message");
return new ChatResult(true, message); return new ChatResult(true, message);
} }

Datei anzeigen

@ -31,17 +31,17 @@ public final class PlayerChatEventImpl implements PlayerChatEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public String getMessage() { public String sentMessage() {
return message; return message;
} }
@Override @Override
public ChatResult getResult() { public ChatResult result() {
return result; return result;
} }

Datei anzeigen

@ -17,9 +17,9 @@ import java.util.Optional;
*/ */
public interface PlayerChooseInitialServerEvent { public interface PlayerChooseInitialServerEvent {
Player getPlayer(); Player player();
Optional<RegisteredServer> getInitialServer(); Optional<RegisteredServer> initialServer();
/** /**
* Sets the new initial server. * Sets the new initial server.

Datei anzeigen

@ -33,12 +33,12 @@ public class PlayerChooseInitialServerEventImpl implements PlayerChooseInitialSe
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public Optional<RegisteredServer> getInitialServer() { public Optional<RegisteredServer> initialServer() {
return Optional.ofNullable(initialServer); return Optional.ofNullable(initialServer);
} }

Datei anzeigen

@ -8,11 +8,11 @@
package com.velocitypowered.api.event.player; package com.velocitypowered.api.event.player;
import com.velocitypowered.api.proxy.connection.Player; import com.velocitypowered.api.proxy.connection.Player;
import com.velocitypowered.api.proxy.player.PlayerSettings; import com.velocitypowered.api.proxy.player.ClientSettings;
public interface PlayerSettingsChangedEvent { public interface PlayerClientSettingsChangedEvent {
Player getPlayer(); Player player();
PlayerSettings getPlayerSettings(); ClientSettings settings();
} }

Datei anzeigen

@ -10,33 +10,34 @@ package com.velocitypowered.api.event.player;
import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.velocitypowered.api.proxy.connection.Player; import com.velocitypowered.api.proxy.connection.Player;
import com.velocitypowered.api.proxy.player.PlayerSettings; import com.velocitypowered.api.proxy.player.ClientSettings;
public final class PlayerSettingsChangedEventImpl implements PlayerSettingsChangedEvent { public final class PlayerClientSettingsChangedEventImpl implements
PlayerClientSettingsChangedEvent {
private final Player player; private final Player player;
private final PlayerSettings playerSettings; private final ClientSettings clientSettings;
public PlayerSettingsChangedEventImpl(Player player, PlayerSettings playerSettings) { public PlayerClientSettingsChangedEventImpl(Player player, ClientSettings clientSettings) {
this.player = Preconditions.checkNotNull(player, "player"); this.player = Preconditions.checkNotNull(player, "player");
this.playerSettings = Preconditions.checkNotNull(playerSettings, "playerSettings"); this.clientSettings = Preconditions.checkNotNull(clientSettings, "playerSettings");
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public PlayerSettings getPlayerSettings() { public ClientSettings settings() {
return playerSettings; return clientSettings;
} }
@Override @Override
public String toString() { public String toString() {
return MoreObjects.toStringHelper(this) return MoreObjects.toStringHelper(this)
.add("player", player) .add("player", player)
.add("playerSettings", playerSettings) .add("playerSettings", clientSettings)
.toString(); .toString();
} }
} }

Datei anzeigen

@ -16,7 +16,7 @@ import com.velocitypowered.api.util.ModInfo;
*/ */
public interface PlayerModInfoEvent { public interface PlayerModInfoEvent {
Player getPlayer(); Player player();
ModInfo getModInfo(); ModInfo modInfo();
} }

Datei anzeigen

@ -23,12 +23,12 @@ public final class PlayerModInfoEventImpl implements PlayerModInfoEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public ModInfo getModInfo() { public ModInfo modInfo() {
return modInfo; return modInfo;
} }

Datei anzeigen

@ -20,14 +20,14 @@ public interface PlayerResourcePackStatusEvent {
* *
* @return the player * @return the player
*/ */
Player getPlayer(); Player player();
/** /**
* Returns the new status for the resource pack. * Returns the new status for the resource pack.
* *
* @return the new status * @return the new status
*/ */
Status getStatus(); Status status();
/** /**
* Represents the possible statuses for the resource pack. * Represents the possible statuses for the resource pack.

Datei anzeigen

@ -30,7 +30,7 @@ public class PlayerResourcePackStatusEventImpl implements PlayerResourcePackStat
* @return the player * @return the player
*/ */
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@ -40,7 +40,7 @@ public class PlayerResourcePackStatusEventImpl implements PlayerResourcePackStat
* @return the new status * @return the new status
*/ */
@Override @Override
public Status getStatus() { public Status status() {
return status; return status;
} }

Datei anzeigen

@ -15,5 +15,5 @@ import com.velocitypowered.api.proxy.connection.Player;
*/ */
public interface PostLoginEvent { public interface PostLoginEvent {
Player getPlayer(); Player player();
} }

Datei anzeigen

@ -23,7 +23,7 @@ public final class PostLoginEventImpl implements PostLoginEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }

Datei anzeigen

@ -22,15 +22,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/ */
public interface PreLoginEvent extends ResultedEvent<PreLoginEvent.PreLoginComponentResult> { public interface PreLoginEvent extends ResultedEvent<PreLoginEvent.PreLoginComponentResult> {
InboundConnection getConnection(); InboundConnection connection();
String getUsername(); String username();
@Override
PreLoginComponentResult getResult();
@Override
void setResult(@NonNull PreLoginComponentResult result);
/** /**
* Represents an "allowed/allowed with forced online\offline mode/denied" result with a reason * Represents an "allowed/allowed with forced online\offline mode/denied" result with a reason
@ -59,7 +53,7 @@ public interface PreLoginEvent extends ResultedEvent<PreLoginEvent.PreLoginCompo
return result != Result.DISALLOWED; return result != Result.DISALLOWED;
} }
public Optional<Component> getReason() { public Optional<Component> denialReason() {
return Optional.ofNullable(reason); return Optional.ofNullable(reason);
} }

Datei anzeigen

@ -34,17 +34,17 @@ public final class PreLoginEventImpl implements PreLoginEvent {
} }
@Override @Override
public InboundConnection getConnection() { public InboundConnection connection() {
return connection; return connection;
} }
@Override @Override
public String getUsername() { public String username() {
return username; return username;
} }
@Override @Override
public PreLoginComponentResult getResult() { public PreLoginComponentResult result() {
return result; return result;
} }

Datei anzeigen

@ -17,9 +17,9 @@ import java.util.Optional;
*/ */
public interface ServerConnectedEvent { public interface ServerConnectedEvent {
Player getPlayer(); Player player();
RegisteredServer getServer(); RegisteredServer target();
Optional<RegisteredServer> getPreviousServer(); Optional<RegisteredServer> previousServer();
} }

Datei anzeigen

@ -37,17 +37,17 @@ public final class ServerConnectedEventImpl implements ServerConnectedEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public RegisteredServer getServer() { public RegisteredServer target() {
return server; return server;
} }
@Override @Override
public Optional<RegisteredServer> getPreviousServer() { public Optional<RegisteredServer> previousServer() {
return Optional.ofNullable(previousServer); return Optional.ofNullable(previousServer);
} }

Datei anzeigen

@ -13,11 +13,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
* Fired after the player has connected to a server. The server the player is now connected to is * Fired after the player has connected to a server. The server the player is now connected to is
* available in {@link Player#getCurrentServer()}. * available in {@link Player#connectedServer()}.
*/ */
public interface ServerPostConnectEvent { public interface ServerPostConnectEvent {
Player getPlayer(); Player player();
@Nullable RegisteredServer getPreviousServer(); @Nullable RegisteredServer previousServer();
} }

Datei anzeigen

@ -14,7 +14,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
* Fired after the player has connected to a server. The server the player is now connected to is * Fired after the player has connected to a server. The server the player is now connected to is
* available in {@link Player#getCurrentServer()}. * available in {@link Player#connectedServer()}.
*/ */
public class ServerPostConnectEventImpl implements ServerPostConnectEvent { public class ServerPostConnectEventImpl implements ServerPostConnectEvent {
@ -28,12 +28,12 @@ public class ServerPostConnectEventImpl implements ServerPostConnectEvent {
} }
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public @Nullable RegisteredServer getPreviousServer() { public @Nullable RegisteredServer previousServer() {
return previousServer; return previousServer;
} }

Datei anzeigen

@ -26,22 +26,16 @@ public interface ServerPreConnectEvent extends ResultedEvent<ServerPreConnectEve
* *
* @return the player connecting to the server * @return the player connecting to the server
*/ */
Player getPlayer(); Player player();
@Override
ServerResult getResult();
@Override
void setResult(ServerResult result);
/** /**
* Returns the server that the player originally tried to connect to. To get the server the player * Returns the server that the player originally tried to connect to. To get the server the player
* will connect to, see the {@link ServerResult} of this event. To get the server the player is * will connect to, see the {@link ServerResult} of this event. To get the server the player is
* currently on when this event is fired, use {@link Player#getCurrentServer()}. * currently on when this event is fired, use {@link Player#connectedServer()}.
* *
* @return the server that the player originally tried to connect to * @return the server that the player originally tried to connect to
*/ */
RegisteredServer getOriginalServer(); RegisteredServer originalTarget();
/** /**
* Represents the result of the {@link ServerPreConnectEvent}. * Represents the result of the {@link ServerPreConnectEvent}.
@ -50,25 +44,25 @@ public interface ServerPreConnectEvent extends ResultedEvent<ServerPreConnectEve
private static final ServerResult DENIED = new ServerResult(null); private static final ServerResult DENIED = new ServerResult(null);
private final @Nullable RegisteredServer server; private final @Nullable RegisteredServer target;
private ServerResult(@Nullable RegisteredServer server) { private ServerResult(@Nullable RegisteredServer target) {
this.server = server; this.target = target;
} }
@Override @Override
public boolean isAllowed() { public boolean isAllowed() {
return server != null; return target != null;
} }
public Optional<RegisteredServer> getServer() { public Optional<RegisteredServer> target() {
return Optional.ofNullable(server); return Optional.ofNullable(target);
} }
@Override @Override
public String toString() { public String toString() {
if (server != null) { if (target != null) {
return "allowed: connect to " + server.getServerInfo().getName(); return "allowed: connect to " + target.serverInfo().name();
} }
return "denied"; return "denied";
} }
@ -87,12 +81,12 @@ public interface ServerPreConnectEvent extends ResultedEvent<ServerPreConnectEve
/** /**
* Allows the player to connect to the specified server. * Allows the player to connect to the specified server.
* *
* @param server the new server to connect to * @param target the new server to connect to
* @return a result to allow the player to connect to the specified server * @return a result to allow the player to connect to the specified server
*/ */
public static ServerResult allowed(RegisteredServer server) { public static ServerResult allowed(RegisteredServer target) {
Preconditions.checkNotNull(server, "server"); Preconditions.checkNotNull(target, "server");
return new ServerResult(server); return new ServerResult(target);
} }
} }
} }

Datei anzeigen

@ -36,12 +36,12 @@ public final class ServerPreConnectEventImpl implements ServerPreConnectEvent {
* @return the player connecting to the server * @return the player connecting to the server
*/ */
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public ServerResult getResult() { public ServerResult result() {
return result; return result;
} }
@ -53,11 +53,11 @@ public final class ServerPreConnectEventImpl implements ServerPreConnectEvent {
/** /**
* Returns the server that the player originally tried to connect to. To get the server the * Returns the server that the player originally tried to connect to. To get the server the
* player will connect to, see the {@link ServerResult} of this event. To get the server the * player will connect to, see the {@link ServerResult} of this event. To get the server the
* player is currently on when this event is fired, use {@link Player#getCurrentServer()}. * player is currently on when this event is fired, use {@link Player#connectedServer()}.
* @return the server that the player originally tried to connect to * @return the server that the player originally tried to connect to
*/ */
@Override @Override
public RegisteredServer getOriginalServer() { public RegisteredServer originalTarget() {
return originalServer; return originalServer;
} }

Datei anzeigen

@ -21,19 +21,19 @@ public interface TabCompleteEvent {
* *
* @return the requesting player * @return the requesting player
*/ */
Player getPlayer(); Player player();
/** /**
* Returns the message being partially completed. * Returns the message being partially completed.
* *
* @return the partial message * @return the partial message
*/ */
String getPartialMessage(); String partialMessage();
/** /**
* Returns all the suggestions provided to the user, as a mutable list. * Returns all the suggestions provided to the user, as a mutable list.
* *
* @return the suggestions * @return the suggestions
*/ */
List<String> getSuggestions(); List<String> suggestions();
} }

Datei anzeigen

@ -39,7 +39,7 @@ public class TabCompleteEventImpl implements TabCompleteEvent {
* @return the requesting player * @return the requesting player
*/ */
@Override @Override
public Player getPlayer() { public Player player() {
return player; return player;
} }
@ -48,7 +48,7 @@ public class TabCompleteEventImpl implements TabCompleteEvent {
* @return the partial message * @return the partial message
*/ */
@Override @Override
public String getPartialMessage() { public String partialMessage() {
return partialMessage; return partialMessage;
} }
@ -57,7 +57,7 @@ public class TabCompleteEventImpl implements TabCompleteEvent {
* @return the suggestions * @return the suggestions
*/ */
@Override @Override
public List<String> getSuggestions() { public List<String> suggestions() {
return suggestions; return suggestions;
} }

Datei anzeigen

@ -75,8 +75,8 @@ public enum ProtocolVersion implements Ordered<ProtocolVersion> {
* The user-friendly representation of the lowest and highest supported versions. * The user-friendly representation of the lowest and highest supported versions.
*/ */
public static final String SUPPORTED_VERSION_STRING = String public static final String SUPPORTED_VERSION_STRING = String
.format("%s-%s", MINIMUM_VERSION.getVersionIntroducedIn(), .format("%s-%s", MINIMUM_VERSION.versionIntroducedIn(),
MAXIMUM_VERSION.getMostRecentSupportedVersion()); MAXIMUM_VERSION.mostRecentSupportedVersion());
/** /**
* A map linking the protocol version number to its {@link ProtocolVersion} representation. * A map linking the protocol version number to its {@link ProtocolVersion} representation.
@ -135,29 +135,17 @@ public enum ProtocolVersion implements Ordered<ProtocolVersion> {
* *
* @return the protocol version * @return the protocol version
*/ */
public int getProtocol() { public int protocol() {
return protocol == -1 ? snapshotProtocol : protocol; return protocol == -1 ? snapshotProtocol : protocol;
} }
/**
* Returns the user-friendly name for this protocol.
*
* @return the protocol name
* @deprecated A protocol may be shared by multiple versions. Use @link{#getVersionIntroducedIn()}
* or @link{#getVersionsSupportedBy()} to get more accurate version names.
*/
@Deprecated
public String getName() {
return getVersionIntroducedIn();
}
/** /**
* Returns the user-friendly name of the version * Returns the user-friendly name of the version
* this protocol was introduced in. * this protocol was introduced in.
* *
* @return the version name * @return the version name
*/ */
public String getVersionIntroducedIn() { public String versionIntroducedIn() {
return names[0]; return names[0];
} }
@ -167,7 +155,7 @@ public enum ProtocolVersion implements Ordered<ProtocolVersion> {
* *
* @return the version name * @return the version name
*/ */
public String getMostRecentSupportedVersion() { public String mostRecentSupportedVersion() {
return names[names.length - 1]; return names[names.length - 1];
} }
@ -176,7 +164,7 @@ public enum ProtocolVersion implements Ordered<ProtocolVersion> {
* *
* @return the version names * @return the version names
*/ */
public List<String> getVersionsSupportedBy() { public List<String> supportedVersions() {
return ImmutableList.copyOf(names); return ImmutableList.copyOf(names);
} }
@ -186,7 +174,7 @@ public enum ProtocolVersion implements Ordered<ProtocolVersion> {
* @param protocol the protocol as an int * @param protocol the protocol as an int
* @return the protocol version * @return the protocol version
*/ */
public static ProtocolVersion getProtocolVersion(int protocol) { public static ProtocolVersion byMinecraftProtocolVersion(int protocol) {
return ID_TO_PROTOCOL_CONSTANT.getOrDefault(protocol, UNKNOWN); return ID_TO_PROTOCOL_CONSTANT.getOrDefault(protocol, UNKNOWN);
} }
@ -232,6 +220,6 @@ public enum ProtocolVersion implements Ordered<ProtocolVersion> {
@Override @Override
public String toString() { public String toString() {
return getVersionIntroducedIn(); return versionIntroducedIn();
} }
} }

Datei anzeigen

@ -29,10 +29,10 @@ public interface PermissionFunction {
PermissionFunction ALWAYS_UNDEFINED = p -> Tristate.UNDEFINED; PermissionFunction ALWAYS_UNDEFINED = p -> Tristate.UNDEFINED;
/** /**
* Gets the subjects setting for a particular permission. * Evaluates whether or not the player has a permission.
* *
* @param permission the permission * @param permission the permission
* @return the value the permission is set to * @return the value the permission is set to
*/ */
Tristate getPermissionValue(String permission); Tristate evaluatePermission(String permission);
} }

Datei anzeigen

@ -19,7 +19,7 @@ public interface PermissionSubject {
* @return whether or not the subject has the permission * @return whether or not the subject has the permission
*/ */
default boolean hasPermission(String permission) { default boolean hasPermission(String permission) {
return getPermissionValue(permission).asBoolean(); return evaluatePermission(permission).asBoolean();
} }
/** /**
@ -28,5 +28,5 @@ public interface PermissionSubject {
* @param permission the permission * @param permission the permission
* @return the value the permission is set to * @return the value the permission is set to
*/ */
Tristate getPermissionValue(String permission); Tristate evaluatePermission(String permission);
} }

Datei anzeigen

@ -19,14 +19,14 @@ public interface PluginContainer {
* *
* @return the plugin's description * @return the plugin's description
*/ */
PluginDescription getDescription(); PluginDescription description();
/** /**
* Returns the created plugin if it is available. * Returns the created plugin if it is available.
* *
* @return the instance if available * @return the instance if available
*/ */
default Optional<?> getInstance() { default Optional<?> instance() {
return Optional.empty(); return Optional.empty();
} }
} }

Datei anzeigen

@ -34,7 +34,7 @@ public interface PluginDescription {
* @return the plugin ID * @return the plugin ID
* @see Plugin#id() * @see Plugin#id()
*/ */
String getId(); String id();
/** /**
* Gets the name of the {@link Plugin} within this container. * Gets the name of the {@link Plugin} within this container.
@ -42,7 +42,7 @@ public interface PluginDescription {
* @return an {@link Optional} with the plugin name, may be empty * @return an {@link Optional} with the plugin name, may be empty
* @see Plugin#name() * @see Plugin#name()
*/ */
default Optional<String> getName() { default Optional<String> name() {
return Optional.empty(); return Optional.empty();
} }
@ -52,7 +52,7 @@ public interface PluginDescription {
* @return an {@link Optional} with the plugin version, may be empty * @return an {@link Optional} with the plugin version, may be empty
* @see Plugin#version() * @see Plugin#version()
*/ */
default Optional<String> getVersion() { default Optional<String> version() {
return Optional.empty(); return Optional.empty();
} }
@ -62,7 +62,7 @@ public interface PluginDescription {
* @return an {@link Optional} with the plugin description, may be empty * @return an {@link Optional} with the plugin description, may be empty
* @see Plugin#description() * @see Plugin#description()
*/ */
default Optional<String> getDescription() { default Optional<String> description() {
return Optional.empty(); return Optional.empty();
} }
@ -72,7 +72,7 @@ public interface PluginDescription {
* @return an {@link Optional} with the plugin url, may be empty * @return an {@link Optional} with the plugin url, may be empty
* @see Plugin#url() * @see Plugin#url()
*/ */
default Optional<String> getUrl() { default Optional<String> url() {
return Optional.empty(); return Optional.empty();
} }
@ -82,7 +82,7 @@ public interface PluginDescription {
* @return the plugin authors, may be empty * @return the plugin authors, may be empty
* @see Plugin#authors() * @see Plugin#authors()
*/ */
default List<String> getAuthors() { default List<String> authors() {
return ImmutableList.of(); return ImmutableList.of();
} }
@ -92,7 +92,7 @@ public interface PluginDescription {
* @return the plugin dependencies, can be empty * @return the plugin dependencies, can be empty
* @see Plugin#dependencies() * @see Plugin#dependencies()
*/ */
default Collection<PluginDependency> getDependencies() { default Collection<PluginDependency> dependencies() {
return ImmutableSet.of(); return ImmutableSet.of();
} }
@ -101,11 +101,11 @@ public interface PluginDescription {
} }
/** /**
* Returns the source the plugin was loaded from. * Returns the file path the plugin was loaded from.
* *
* @return the source the plugin was loaded from or {@link Optional#empty()} if unknown * @return the path the plugin was loaded from or {@link Optional#empty()} if unknown
*/ */
default Optional<Path> getSource() { default Optional<Path> file() {
return Optional.empty(); return Optional.empty();
} }
} }

Datei anzeigen

@ -24,6 +24,7 @@ import java.util.Collection;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
/** /**
* Provides an interface to a Minecraft server proxy. * Provides an interface to a Minecraft server proxy.
@ -35,7 +36,7 @@ public interface ProxyServer extends Audience {
* *
* @param reason message to kick online players with * @param reason message to kick online players with
*/ */
void shutdown(net.kyori.adventure.text.Component reason); void shutdown(Component reason);
/** /**
* Shuts down the proxy, kicking players with the default reason. * Shuts down the proxy, kicking players with the default reason.
@ -65,14 +66,14 @@ public interface ProxyServer extends Audience {
* *
* @return the players online on this proxy * @return the players online on this proxy
*/ */
Collection<Player> getAllPlayers(); Collection<Player> connectedPlayers();
/** /**
* Returns the number of players currently connected to this proxy. * Returns the number of players currently connected to this proxy.
* *
* @return the players on this proxy * @return the players on this proxy
*/ */
int getPlayerCount(); int countConnectedPlayers();
/** /**
* Retrieves a registered {@link RegisteredServer} instance by its name. The search is * Retrieves a registered {@link RegisteredServer} instance by its name. The search is
@ -81,14 +82,14 @@ public interface ProxyServer extends Audience {
* @param name the name of the server * @param name the name of the server
* @return the registered server, which may be empty * @return the registered server, which may be empty
*/ */
Optional<RegisteredServer> getServer(String name); Optional<RegisteredServer> server(String name);
/** /**
* Retrieves all {@link RegisteredServer}s registered with this proxy. * Retrieves all {@link RegisteredServer}s registered with this proxy.
* *
* @return the servers registered with this proxy * @return the servers registered with this proxy
*/ */
Collection<RegisteredServer> getAllServers(); Collection<RegisteredServer> registeredServers();
/** /**
* Matches all {@link Player}s whose names start with the provided partial name. * Matches all {@link Player}s whose names start with the provided partial name.
@ -129,62 +130,54 @@ public interface ProxyServer extends Audience {
* *
* @return the console command invoker * @return the console command invoker
*/ */
ConsoleCommandSource getConsoleCommandSource(); ConsoleCommandSource consoleCommandSource();
/** /**
* Gets the {@link PluginManager} instance. * Gets the {@link PluginManager} instance.
* *
* @return the plugin manager instance * @return the plugin manager instance
*/ */
PluginManager getPluginManager(); PluginManager pluginManager();
/** /**
* Gets the {@link EventManager} instance. * Gets the {@link EventManager} instance.
* *
* @return the event manager instance * @return the event manager instance
*/ */
EventManager getEventManager(); EventManager eventManager();
/** /**
* Gets the {@link CommandManager} instance. * Gets the {@link CommandManager} instance.
* *
* @return the command manager * @return the command manager
*/ */
CommandManager getCommandManager(); CommandManager commandManager();
/** /**
* Gets the {@link Scheduler} instance. * Gets the {@link Scheduler} instance.
* *
* @return the scheduler instance * @return the scheduler instance
*/ */
Scheduler getScheduler(); Scheduler scheduler();
/** /**
* Gets the {@link ChannelRegistrar} instance. * Gets the {@link ChannelRegistrar} instance.
* *
* @return the channel registrar * @return the channel registrar
*/ */
ChannelRegistrar getChannelRegistrar(); ChannelRegistrar channelRegistrar();
/**
* Gets the address that this proxy is bound to. This does not necessarily indicate the external
* IP address of the proxy.
*
* @return the address the proxy is bound to
*/
SocketAddress getBoundAddress();
/** /**
* Gets the {@link ProxyConfig} instance. * Gets the {@link ProxyConfig} instance.
* *
* @return the proxy config * @return the proxy config
*/ */
ProxyConfig getConfiguration(); ProxyConfig configuration();
/** /**
* Returns the version of the proxy. * Returns the version of the proxy.
* *
* @return the proxy version * @return the proxy version
*/ */
ProxyVersion getVersion(); ProxyVersion version();
} }

Datei anzeigen

@ -80,7 +80,7 @@ public interface ProxyConfig {
/** /**
* Get a Map of all servers registered in <code>velocity.toml</code>. This method does * Get a Map of all servers registered in <code>velocity.toml</code>. This method does
* <strong>not</strong> return all the servers currently in memory, although in most cases it * <strong>not</strong> return all the servers currently in memory, although in most cases it
* does. For a view of all registered servers, see {@link ProxyServer#getAllServers()}. * does. For a view of all registered servers, see {@link ProxyServer#registeredServers()}.
* *
* @return registered servers map * @return registered servers map
*/ */

Datei anzeigen

@ -22,14 +22,14 @@ public interface InboundConnection {
* *
* @return the player's remote address * @return the player's remote address
*/ */
SocketAddress getRemoteAddress(); SocketAddress remoteAddress();
/** /**
* Returns the hostname that the user entered into the client, if applicable. * Returns the hostname that the user entered into the client, if applicable.
* *
* @return the hostname from the client * @return the hostname from the client
*/ */
Optional<InetSocketAddress> getVirtualHost(); Optional<InetSocketAddress> connectedHost();
/** /**
* Determine whether or not the player remains online. * Determine whether or not the player remains online.
@ -43,5 +43,5 @@ public interface InboundConnection {
* *
* @return the protocol version the connection uses * @return the protocol version the connection uses
*/ */
ProtocolVersion getProtocolVersion(); ProtocolVersion protocolVersion();
} }

Datei anzeigen

@ -11,8 +11,8 @@ import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.player.PlayerResourcePackStatusEventImpl; import com.velocitypowered.api.event.player.PlayerResourcePackStatusEventImpl;
import com.velocitypowered.api.proxy.messages.ChannelMessageSink; import com.velocitypowered.api.proxy.messages.ChannelMessageSink;
import com.velocitypowered.api.proxy.messages.ChannelMessageSource; import com.velocitypowered.api.proxy.messages.ChannelMessageSource;
import com.velocitypowered.api.proxy.player.ClientSettings;
import com.velocitypowered.api.proxy.player.ConnectionRequestBuilder; import com.velocitypowered.api.proxy.player.ConnectionRequestBuilder;
import com.velocitypowered.api.proxy.player.PlayerSettings;
import com.velocitypowered.api.proxy.player.TabList; import com.velocitypowered.api.proxy.player.TabList;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.util.GameProfile; import com.velocitypowered.api.util.GameProfile;
@ -34,49 +34,49 @@ public interface Player extends CommandSource, Identified, InboundConnection,
* *
* @return the username * @return the username
*/ */
String getUsername(); String username();
/** /**
* Returns the player's UUID. * Returns the player's UUID.
* *
* @return the UUID * @return the UUID
*/ */
UUID getUniqueId(); UUID id();
/** /**
* Returns the server that the player is currently connected to. * Returns the server that the player is currently connected to.
* *
* @return an {@link Optional} the server that the player is connected to, which may be empty * @return an {@link Optional} the server that the player is connected to, which may be empty
*/ */
Optional<ServerConnection> getCurrentServer(); Optional<ServerConnection> connectedServer();
/** /**
* Returns the player's client settings. * Returns the player's client settings.
* *
* @return the settings * @return the settings
*/ */
PlayerSettings getPlayerSettings(); ClientSettings clientSettings();
/** /**
* Returns the player's mod info if they have a modded client. * Returns the player's mod info if they have a modded client.
* *
* @return an {@link Optional} the mod info. which may be empty * @return an {@link Optional} the mod info. which may be empty
*/ */
Optional<ModInfo> getModInfo(); Optional<ModInfo> modInfo();
/** /**
* Returns the current player's ping. * Returns the current player's ping.
* *
* @return the player's ping or -1 if ping information is currently unknown * @return the player's ping or -1 if ping information is currently unknown
*/ */
long getPing(); long ping();
/** /**
* Returns the player's connection status. * Returns the player's connection status.
* *
* @return true if the player is authenticated with Mojang servers * @return true if the player is authenticated with Mojang servers
*/ */
boolean isOnlineMode(); boolean onlineMode();
/** /**
* Creates a new connection request so that the player can connect to another server. * Creates a new connection request so that the player can connect to another server.
@ -96,14 +96,14 @@ public interface Player extends CommandSource, Identified, InboundConnection,
/** /**
* Returns the player's game profile. * Returns the player's game profile.
*/ */
GameProfile getGameProfile(); GameProfile gameProfile();
/** /**
* Returns the player's tab list. * Returns the player's tab list.
* *
* @return this player's tab list * @return this player's tab list
*/ */
TabList getTabList(); TabList tabList();
/** /**
* Disconnects the player with the specified reason. Once this method is called, further calls to * Disconnects the player with the specified reason. Once this method is called, further calls to

Datei anzeigen

@ -22,19 +22,19 @@ public interface ServerConnection extends ChannelMessageSource, ChannelMessageSi
* *
* @return the server this connection is connected to * @return the server this connection is connected to
*/ */
RegisteredServer getServer(); RegisteredServer target();
/** /**
* Returns the server info for this connection. * Returns the server info for this connection.
* *
* @return the server info for this connection * @return the server info for this connection
*/ */
ServerInfo getServerInfo(); ServerInfo serverInfo();
/** /**
* Returns the player that this connection is associated with. * Returns the player that this connection is associated with.
* *
* @return the player for this connection * @return the player for this connection
*/ */
Player getPlayer(); Player player();
} }

Datei anzeigen

@ -17,5 +17,5 @@ public interface ChannelIdentifier {
* *
* @return the textual representation of the identifier * @return the textual representation of the identifier
*/ */
String getId(); String id();
} }

Datei anzeigen

@ -7,6 +7,8 @@
package com.velocitypowered.api.proxy.messages; package com.velocitypowered.api.proxy.messages;
import com.velocitypowered.api.event.connection.PluginMessageEventImpl;
/** /**
* Represents an interface to register and unregister {@link ChannelIdentifier}s for the proxy to * Represents an interface to register and unregister {@link ChannelIdentifier}s for the proxy to
* listen on. * listen on.
@ -15,7 +17,7 @@ public interface ChannelRegistrar {
/** /**
* Registers the specified message identifiers to listen on so you can intercept plugin messages * Registers the specified message identifiers to listen on so you can intercept plugin messages
* on the channel using {@link com.velocitypowered.api.event.connection.PluginMessageEvent}. * on the channel using {@link PluginMessageEventImpl}.
* *
* @param identifiers the channel identifiers to register * @param identifiers the channel identifiers to register
*/ */

Datei anzeigen

@ -58,7 +58,7 @@ public final class LegacyChannelIdentifier implements ChannelIdentifier {
} }
@Override @Override
public String getId() { public String id() {
return this.getName(); return this.getName();
} }
} }

Datei anzeigen

@ -108,7 +108,7 @@ public final class MinecraftChannelIdentifier implements ChannelIdentifier {
} }
@Override @Override
public String getId() { public String id() {
return namespace + ":" + name; return namespace + ":" + name;
} }
} }

Datei anzeigen

@ -12,7 +12,7 @@ import java.util.Locale;
/** /**
* Represents the client settings for the player. * Represents the client settings for the player.
*/ */
public interface PlayerSettings { public interface ClientSettings {
/** /**
* Returns the locale of the Minecraft client. * Returns the locale of the Minecraft client.

Datei anzeigen

@ -24,7 +24,7 @@ public interface ConnectionRequestBuilder {
* *
* @return the server this request will connect to * @return the server this request will connect to
*/ */
RegisteredServer getServer(); RegisteredServer target();
/** /**
* Initiates the connection to the remote server and emits a result on the {@link * Initiates the connection to the remote server and emits a result on the {@link
@ -61,7 +61,7 @@ public interface ConnectionRequestBuilder {
* @return whether or not the request succeeded * @return whether or not the request succeeded
*/ */
default boolean isSuccessful() { default boolean isSuccessful() {
return getStatus() == Status.SUCCESS; return status() == Status.SUCCESS;
} }
/** /**
@ -69,21 +69,21 @@ public interface ConnectionRequestBuilder {
* *
* @return the status for this result * @return the status for this result
*/ */
Status getStatus(); Status status();
/** /**
* Returns an (optional) textual reason for the failure to connect to the server. * Returns an (optional) textual reason for the failure to connect to the server.
* *
* @return the reason why the user could not connect to the server * @return the reason why the user could not connect to the server
*/ */
Optional<Component> getReason(); Optional<Component> failureReason();
/** /**
* Returns the server we actually tried to connect to. * Returns the server we actually tried to connect to.
* *
* @return the server we actually tried to connect to * @return the server we actually tried to connect to
*/ */
RegisteredServer getAttemptedConnection(); RegisteredServer finalTarget();
} }
/** /**

Datei anzeigen

@ -63,7 +63,7 @@ public interface TabList {
* *
* @return immutable {@link Collection} of tab list entries * @return immutable {@link Collection} of tab list entries
*/ */
Collection<TabListEntry> getEntries(); Collection<TabListEntry> entries();
/** /**
* Builds a tab list entry. * Builds a tab list entry.

Datei anzeigen

@ -22,7 +22,7 @@ public interface TabListEntry {
* *
* @return parent {@link TabList} * @return parent {@link TabList}
*/ */
TabList getTabList(); TabList parent();
/** /**
* Returns the {@link GameProfile} of the entry, which uniquely identifies the entry with the * Returns the {@link GameProfile} of the entry, which uniquely identifies the entry with the
@ -31,7 +31,7 @@ public interface TabListEntry {
* *
* @return {@link GameProfile} of the entry * @return {@link GameProfile} of the entry
*/ */
GameProfile getProfile(); GameProfile gameProfile();
/** /**
* Returns {@link Optional} text {@link Component}, which if present is the text * Returns {@link Optional} text {@link Component}, which if present is the text
@ -41,7 +41,7 @@ public interface TabListEntry {
* @return {@link Optional} text {@link Component} of name displayed in the tab * @return {@link Optional} text {@link Component} of name displayed in the tab
* list * list
*/ */
Optional<Component> getDisplayName(); Optional<Component> displayName();
/** /**
* Sets the text {@link Component} to be displayed for {@code this} {@link TabListEntry}. If * Sets the text {@link Component} to be displayed for {@code this} {@link TabListEntry}. If
@ -68,16 +68,16 @@ public interface TabListEntry {
* *
* @return latency set for {@code this} entry * @return latency set for {@code this} entry
*/ */
int getLatency(); int ping();
/** /**
* Sets the latency for {@code this} entry to the specified value. * Sets the latency for {@code this} entry to the specified value.
* *
* @param latency to changed to * @param latency to changed to
* @return {@code this}, for chaining * @return {@code this}, for chaining
* @see #getLatency() * @see #ping()
*/ */
TabListEntry setLatency(int latency); TabListEntry setPing(int latency);
/** /**
* Gets the game mode {@code this} entry has been set to. * Gets the game mode {@code this} entry has been set to.
@ -92,14 +92,14 @@ public interface TabListEntry {
* *
* @return the game mode * @return the game mode
*/ */
int getGameMode(); int gameMode();
/** /**
* Sets the game mode for {@code this} entry to the specified value. * Sets the game mode for {@code this} entry to the specified value.
* *
* @param gameMode to change to * @param gameMode to change to
* @return {@code this}, for chaining * @return {@code this}, for chaining
* @see #getGameMode() * @see #gameMode()
*/ */
TabListEntry setGameMode(int gameMode); TabListEntry setGameMode(int gameMode);
@ -145,7 +145,7 @@ public interface TabListEntry {
* *
* @param profile to set * @param profile to set
* @return {@code this}, for chaining * @return {@code this}, for chaining
* @see TabListEntry#getProfile() * @see TabListEntry#gameProfile()
*/ */
public Builder profile(GameProfile profile) { public Builder profile(GameProfile profile) {
this.profile = profile; this.profile = profile;
@ -157,7 +157,7 @@ public interface TabListEntry {
* *
* @param displayName to set * @param displayName to set
* @return {@code this}, for chaining * @return {@code this}, for chaining
* @see TabListEntry#getDisplayName() * @see TabListEntry#displayName()
*/ */
public Builder displayName(@Nullable Component displayName) { public Builder displayName(@Nullable Component displayName) {
this.displayName = displayName; this.displayName = displayName;
@ -169,7 +169,7 @@ public interface TabListEntry {
* *
* @param latency to set * @param latency to set
* @return {@code this}, for chaining * @return {@code this}, for chaining
* @see TabListEntry#getLatency() * @see TabListEntry#ping()
*/ */
public Builder latency(int latency) { public Builder latency(int latency) {
this.latency = latency; this.latency = latency;
@ -181,7 +181,7 @@ public interface TabListEntry {
* *
* @param gameMode to set * @param gameMode to set
* @return {@code this}, for chaining * @return {@code this}, for chaining
* @see TabListEntry#getGameMode() * @see TabListEntry#gameMode()
*/ */
public Builder gameMode(int gameMode) { public Builder gameMode(int gameMode) {
this.gameMode = gameMode; this.gameMode = gameMode;

Datei anzeigen

@ -30,7 +30,7 @@ public final class QueryResponse {
private final String hostname; private final String hostname;
private final String gameVersion; private final String gameVersion;
private final String map; private final String map;
private final int currentPlayers; private final int onlinePlayers;
private final int maxPlayers; private final int maxPlayers;
private final String proxyHost; private final String proxyHost;
private final int proxyPort; private final int proxyPort;
@ -39,13 +39,13 @@ public final class QueryResponse {
private final ImmutableCollection<PluginInformation> plugins; private final ImmutableCollection<PluginInformation> plugins;
@VisibleForTesting @VisibleForTesting
QueryResponse(String hostname, String gameVersion, String map, int currentPlayers, QueryResponse(String hostname, String gameVersion, String map, int onlinePlayers,
int maxPlayers, String proxyHost, int proxyPort, ImmutableCollection<String> players, int maxPlayers, String proxyHost, int proxyPort, ImmutableCollection<String> players,
String proxyVersion, ImmutableCollection<PluginInformation> plugins) { String proxyVersion, ImmutableCollection<PluginInformation> plugins) {
this.hostname = hostname; this.hostname = hostname;
this.gameVersion = gameVersion; this.gameVersion = gameVersion;
this.map = map; this.map = map;
this.currentPlayers = currentPlayers; this.onlinePlayers = onlinePlayers;
this.maxPlayers = maxPlayers; this.maxPlayers = maxPlayers;
this.proxyHost = proxyHost; this.proxyHost = proxyHost;
this.proxyPort = proxyPort; this.proxyPort = proxyPort;
@ -60,7 +60,7 @@ public final class QueryResponse {
* *
* @return hostname * @return hostname
*/ */
public String getHostname() { public String hostname() {
return hostname; return hostname;
} }
@ -70,7 +70,7 @@ public final class QueryResponse {
* *
* @return game version * @return game version
*/ */
public String getGameVersion() { public String gameVersion() {
return gameVersion; return gameVersion;
} }
@ -80,7 +80,7 @@ public final class QueryResponse {
* *
* @return map name * @return map name
*/ */
public String getMap() { public String mapName() {
return map; return map;
} }
@ -89,8 +89,8 @@ public final class QueryResponse {
* *
* @return online player count * @return online player count
*/ */
public int getCurrentPlayers() { public int onlinePlayers() {
return currentPlayers; return onlinePlayers;
} }
/** /**
@ -98,7 +98,7 @@ public final class QueryResponse {
* *
* @return max player count * @return max player count
*/ */
public int getMaxPlayers() { public int maxPlayers() {
return maxPlayers; return maxPlayers;
} }
@ -107,7 +107,7 @@ public final class QueryResponse {
* *
* @return proxy hostname * @return proxy hostname
*/ */
public String getProxyHost() { public String proxyHost() {
return proxyHost; return proxyHost;
} }
@ -116,7 +116,7 @@ public final class QueryResponse {
* *
* @return proxy port * @return proxy port
*/ */
public int getProxyPort() { public int proxyPort() {
return proxyPort; return proxyPort;
} }
@ -125,7 +125,7 @@ public final class QueryResponse {
* *
* @return collection of players * @return collection of players
*/ */
public Collection<String> getPlayers() { public Collection<String> players() {
return players; return players;
} }
@ -134,7 +134,7 @@ public final class QueryResponse {
* *
* @return server software * @return server software
*/ */
public String getProxyVersion() { public String proxyVersion() {
return proxyVersion; return proxyVersion;
} }
@ -143,11 +143,10 @@ public final class QueryResponse {
* *
* @return collection of plugins * @return collection of plugins
*/ */
public Collection<PluginInformation> getPlugins() { public Collection<PluginInformation> plugins() {
return plugins; return plugins;
} }
/** /**
* Creates a new {@link Builder} instance from data represented by this response, so that you * Creates a new {@link Builder} instance from data represented by this response, so that you
* may create a new {@link QueryResponse} with new data. It is guaranteed that * may create a new {@link QueryResponse} with new data. It is guaranteed that
@ -158,16 +157,16 @@ public final class QueryResponse {
*/ */
public Builder toBuilder() { public Builder toBuilder() {
return QueryResponse.builder() return QueryResponse.builder()
.hostname(getHostname()) .hostname(hostname())
.gameVersion(getGameVersion()) .gameVersion(gameVersion())
.map(getMap()) .map(mapName())
.currentPlayers(getCurrentPlayers()) .onlinePlayers(onlinePlayers())
.maxPlayers(getMaxPlayers()) .maxPlayers(maxPlayers())
.proxyHost(getProxyHost()) .proxyHost(proxyHost())
.proxyPort(getProxyPort()) .proxyPort(proxyPort())
.players(getPlayers()) .players(players())
.proxyVersion(getProxyVersion()) .proxyVersion(proxyVersion())
.plugins(getPlugins()); .plugins(plugins());
} }
/** /**
@ -188,7 +187,7 @@ public final class QueryResponse {
return false; return false;
} }
QueryResponse response = (QueryResponse) o; QueryResponse response = (QueryResponse) o;
return currentPlayers == response.currentPlayers return onlinePlayers == response.onlinePlayers
&& maxPlayers == response.maxPlayers && maxPlayers == response.maxPlayers
&& proxyPort == response.proxyPort && proxyPort == response.proxyPort
&& hostname.equals(response.hostname) && hostname.equals(response.hostname)
@ -202,9 +201,8 @@ public final class QueryResponse {
@Override @Override
public int hashCode() { public int hashCode() {
return Objects return Objects.hash(hostname, gameVersion, map, onlinePlayers, maxPlayers, proxyHost,
.hash(hostname, gameVersion, map, currentPlayers, maxPlayers, proxyHost, proxyPort, players, proxyPort, players, proxyVersion, plugins);
proxyVersion, plugins);
} }
@Override @Override
@ -213,7 +211,7 @@ public final class QueryResponse {
+ "hostname='" + hostname + '\'' + "hostname='" + hostname + '\''
+ ", gameVersion='" + gameVersion + '\'' + ", gameVersion='" + gameVersion + '\''
+ ", map='" + map + '\'' + ", map='" + map + '\''
+ ", currentPlayers=" + currentPlayers + ", onlinePlayers=" + onlinePlayers
+ ", maxPlayers=" + maxPlayers + ", maxPlayers=" + maxPlayers
+ ", proxyHost='" + proxyHost + '\'' + ", proxyHost='" + proxyHost + '\''
+ ", proxyPort=" + proxyPort + ", proxyPort=" + proxyPort
@ -233,7 +231,7 @@ public final class QueryResponse {
private @MonotonicNonNull String proxyHost; private @MonotonicNonNull String proxyHost;
private @MonotonicNonNull String proxyVersion; private @MonotonicNonNull String proxyVersion;
private int currentPlayers; private int onlinePlayers;
private int maxPlayers; private int maxPlayers;
private int proxyPort; private int proxyPort;
@ -275,12 +273,12 @@ public final class QueryResponse {
/** /**
* Sets the players that are currently claimed to be online. * Sets the players that are currently claimed to be online.
* @param currentPlayers a non-negative number representing all players online * @param players a non-negative number representing all players online
* @return this builder, for chaining * @return this builder, for chaining
*/ */
public Builder currentPlayers(int currentPlayers) { public Builder onlinePlayers(int players) {
Preconditions.checkArgument(currentPlayers >= 0, "currentPlayers cannot be negative"); Preconditions.checkArgument(players >= 0, "currentPlayers cannot be negative");
this.currentPlayers = currentPlayers; this.onlinePlayers = players;
return this; return this;
} }
@ -338,7 +336,7 @@ public final class QueryResponse {
} }
/** /**
* Removes all players from the builder. This does not affect {@link #getCurrentPlayers()}. * Removes all players from the builder. This does not affect {@link #onlinePlayers()}.
* @return this builder, for chaining * @return this builder, for chaining
*/ */
public Builder clearPlayers() { public Builder clearPlayers() {
@ -397,7 +395,7 @@ public final class QueryResponse {
Preconditions.checkNotNull(hostname, "hostname"), Preconditions.checkNotNull(hostname, "hostname"),
Preconditions.checkNotNull(gameVersion, "gameVersion"), Preconditions.checkNotNull(gameVersion, "gameVersion"),
Preconditions.checkNotNull(map, "map"), Preconditions.checkNotNull(map, "map"),
currentPlayers, onlinePlayers,
maxPlayers, maxPlayers,
Preconditions.checkNotNull(proxyHost, "proxyHost"), Preconditions.checkNotNull(proxyHost, "proxyHost"),
proxyPort, proxyPort,

Datei anzeigen

@ -25,14 +25,14 @@ public interface RegisteredServer extends ChannelMessageSink, Audience {
* *
* @return the server info * @return the server info
*/ */
ServerInfo getServerInfo(); ServerInfo serverInfo();
/** /**
* Returns a list of all the players currently connected to this server on this proxy. * Returns a list of all the players currently connected to this server on this proxy.
* *
* @return the players on this proxy * @return the players on this proxy
*/ */
Collection<Player> getPlayersConnected(); Collection<Player> connectedPlayers();
/** /**
* Attempts to ping the remote server and return the server list ping result. * Attempts to ping the remote server and return the server list ping result.

Datei anzeigen

@ -8,7 +8,6 @@
package com.velocitypowered.api.proxy.server; package com.velocitypowered.api.proxy.server;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.Objects; import java.util.Objects;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -33,11 +32,11 @@ public final class ServerInfo implements Comparable<ServerInfo> {
this.address = Preconditions.checkNotNull(address, "address"); this.address = Preconditions.checkNotNull(address, "address");
} }
public final String getName() { public final String name() {
return name; return name;
} }
public final SocketAddress getAddress() { public final SocketAddress address() {
return address; return address;
} }
@ -69,6 +68,6 @@ public final class ServerInfo implements Comparable<ServerInfo> {
@Override @Override
public int compareTo(ServerInfo o) { public int compareTo(ServerInfo o) {
return this.name.compareTo(o.getName()); return this.name.compareTo(o.name());
} }
} }

Datei anzeigen

@ -56,23 +56,23 @@ public final class ServerPing {
this.modinfo = modinfo; this.modinfo = modinfo;
} }
public Version getVersion() { public Version version() {
return version; return version;
} }
public Optional<Players> getPlayers() { public Optional<Players> players() {
return Optional.ofNullable(players); return Optional.ofNullable(players);
} }
public Component getDescription() { public Component description() {
return description; return description;
} }
public Optional<Favicon> getFavicon() { public Optional<Favicon> favicon() {
return Optional.ofNullable(favicon); return Optional.ofNullable(favicon);
} }
public Optional<ModInfo> getModinfo() { public Optional<ModInfo> modInfo() {
return Optional.ofNullable(modinfo); return Optional.ofNullable(modinfo);
} }
@ -122,7 +122,7 @@ public final class ServerPing {
if (players != null) { if (players != null) {
builder.onlinePlayers = players.online; builder.onlinePlayers = players.online;
builder.maximumPlayers = players.max; builder.maximumPlayers = players.max;
builder.samplePlayers.addAll(players.getSample()); builder.samplePlayers.addAll(players.sample());
} else { } else {
builder.nullOutPlayers = true; builder.nullOutPlayers = true;
} }
@ -319,11 +319,11 @@ public final class ServerPing {
this.name = Preconditions.checkNotNull(name, "name"); this.name = Preconditions.checkNotNull(name, "name");
} }
public int getProtocol() { public int protocol() {
return protocol; return protocol;
} }
public String getName() { public String name() {
return name; return name;
} }
@ -371,15 +371,15 @@ public final class ServerPing {
this.sample = ImmutableList.copyOf(sample); this.sample = ImmutableList.copyOf(sample);
} }
public int getOnline() { public int online() {
return online; return online;
} }
public int getMax() { public int maximum() {
return max; return max;
} }
public List<SamplePlayer> getSample() { public List<SamplePlayer> sample() {
return sample == null ? ImmutableList.of() : sample; return sample == null ? ImmutableList.of() : sample;
} }
@ -421,11 +421,11 @@ public final class ServerPing {
this.id = id; this.id = id;
} }
public String getName() { public String name() {
return name; return name;
} }
public UUID getId() { public UUID id() {
return id; return id;
} }

Datei anzeigen

@ -103,17 +103,17 @@ public class Metrics {
Metrics metrics = new Metrics(logger, 4752, metricsConfig.isEnabled()); Metrics metrics = new Metrics(logger, 4752, metricsConfig.isEnabled());
metrics.addCustomChart( metrics.addCustomChart(
new SingleLineChart("players", server::getPlayerCount) new SingleLineChart("players", server::countConnectedPlayers)
); );
metrics.addCustomChart( metrics.addCustomChart(
new SingleLineChart("managed_servers", () -> server.getAllServers().size()) new SingleLineChart("managed_servers", () -> server.registeredServers().size())
); );
metrics.addCustomChart( metrics.addCustomChart(
new SimplePie("online_mode", new SimplePie("online_mode",
() -> server.getConfiguration().isOnlineMode() ? "online" : "offline") () -> server.configuration().isOnlineMode() ? "online" : "offline")
); );
metrics.addCustomChart(new SimplePie("velocity_version", metrics.addCustomChart(new SimplePie("velocity_version",
() -> server.getVersion().getVersion())); () -> server.version().getVersion()));
metrics.addCustomChart(new DrilldownPie("java_version", () -> { metrics.addCustomChart(new DrilldownPie("java_version", () -> {
Map<String, Map<String, Integer>> map = new HashMap<>(); Map<String, Map<String, Integer>> map = new HashMap<>();

Datei anzeigen

@ -84,7 +84,7 @@ public class Velocity {
double bootTime = (System.currentTimeMillis() - startTime) / 1000d; double bootTime = (System.currentTimeMillis() - startTime) / 1000d;
logger.info("Done ({}s)!", new DecimalFormat("#.##").format(bootTime)); logger.info("Done ({}s)!", new DecimalFormat("#.##").format(bootTime));
server.getConsoleCommandSource().start(); server.consoleCommandSource().start();
// If we don't have a console available (because SimpleTerminalConsole returned), then we still // If we don't have a console available (because SimpleTerminalConsole returned), then we still
// need to wait, otherwise the JVM will reap us as no non-daemon threads will be active once the // need to wait, otherwise the JVM will reap us as no non-daemon threads will be active once the

Datei anzeigen

@ -155,12 +155,12 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
} }
@Override @Override
public VelocityConfiguration getConfiguration() { public VelocityConfiguration configuration() {
return this.configuration; return this.configuration;
} }
@Override @Override
public ProxyVersion getVersion() { public ProxyVersion version() {
Package pkg = VelocityServer.class.getPackage(); Package pkg = VelocityServer.class.getPackage();
String implName; String implName;
String implVersion; String implVersion;
@ -179,7 +179,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
} }
@Override @Override
public VelocityCommandManager getCommandManager() { public VelocityCommandManager commandManager() {
return commandManager; return commandManager;
} }
@ -190,7 +190,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
@EnsuresNonNull({"serverKeyPair", "servers", "pluginManager", "eventManager", "scheduler", @EnsuresNonNull({"serverKeyPair", "servers", "pluginManager", "eventManager", "scheduler",
"console", "cm", "configuration"}) "console", "cm", "configuration"})
void start() { void start() {
logger.info("Booting up {} {}...", getVersion().getName(), getVersion().getVersion()); logger.info("Booting up {} {}...", version().getName(), version().getVersion());
console.setupStreams(); console.setupStreams();
serverKeyPair = EncryptionUtils.createRsaKeyPair(1024); serverKeyPair = EncryptionUtils.createRsaKeyPair(1024);
@ -278,13 +278,13 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
// Register the plugin main classes so that we can fire the proxy initialize event // Register the plugin main classes so that we can fire the proxy initialize event
for (PluginContainer plugin : pluginManager.getPlugins()) { for (PluginContainer plugin : pluginManager.getPlugins()) {
Optional<?> instance = plugin.getInstance(); Optional<?> instance = plugin.instance();
if (instance.isPresent()) { if (instance.isPresent()) {
try { try {
eventManager.register(instance.get(), instance.get()); eventManager.register(instance.get(), instance.get());
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to register plugin listener for {}", logger.error("Unable to register plugin listener for {}",
plugin.getDescription().getName().orElse(plugin.getDescription().getId()), e); plugin.description().name().orElse(plugin.description().id()), e);
} }
} }
} }
@ -327,15 +327,15 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
Optional<RegisteredServer> rs = servers.getServer(entry.getKey()); Optional<RegisteredServer> rs = servers.getServer(entry.getKey());
if (!rs.isPresent()) { if (!rs.isPresent()) {
servers.register(newInfo); servers.register(newInfo);
} else if (!rs.get().getServerInfo().equals(newInfo)) { } else if (!rs.get().serverInfo().equals(newInfo)) {
for (Player player : rs.get().getPlayersConnected()) { for (Player player : rs.get().connectedPlayers()) {
if (!(player instanceof ConnectedPlayer)) { if (!(player instanceof ConnectedPlayer)) {
throw new IllegalStateException("ConnectedPlayer not found for player " + player throw new IllegalStateException("ConnectedPlayer not found for player " + player
+ " in server " + rs.get().getServerInfo().getName()); + " in server " + rs.get().serverInfo().name());
} }
evacuate.add((ConnectedPlayer) player); evacuate.add((ConnectedPlayer) player);
} }
servers.unregister(rs.get().getServerInfo()); servers.unregister(rs.get().serverInfo());
servers.register(newInfo); servers.register(newInfo);
} }
} }
@ -518,9 +518,9 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
if (configuration.isOnlineMode() && configuration.isOnlineModeKickExistingPlayers()) { if (configuration.isOnlineMode() && configuration.isOnlineModeKickExistingPlayers()) {
return true; return true;
} }
String lowerName = connection.getUsername().toLowerCase(Locale.US); String lowerName = connection.username().toLowerCase(Locale.US);
return !(connectionsByName.containsKey(lowerName) return !(connectionsByName.containsKey(lowerName)
|| connectionsByUuid.containsKey(connection.getUniqueId())); || connectionsByUuid.containsKey(connection.id()));
} }
/** /**
@ -529,25 +529,25 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
* @return {@code true} if we registered the connection, {@code false} if not * @return {@code true} if we registered the connection, {@code false} if not
*/ */
public boolean registerConnection(ConnectedPlayer connection) { public boolean registerConnection(ConnectedPlayer connection) {
String lowerName = connection.getUsername().toLowerCase(Locale.US); String lowerName = connection.username().toLowerCase(Locale.US);
if (!this.configuration.isOnlineModeKickExistingPlayers()) { if (!this.configuration.isOnlineModeKickExistingPlayers()) {
if (connectionsByName.putIfAbsent(lowerName, connection) != null) { if (connectionsByName.putIfAbsent(lowerName, connection) != null) {
return false; return false;
} }
if (connectionsByUuid.putIfAbsent(connection.getUniqueId(), connection) != null) { if (connectionsByUuid.putIfAbsent(connection.id(), connection) != null) {
connectionsByName.remove(lowerName, connection); connectionsByName.remove(lowerName, connection);
return false; return false;
} }
} else { } else {
ConnectedPlayer existing = connectionsByUuid.get(connection.getUniqueId()); ConnectedPlayer existing = connectionsByUuid.get(connection.id());
if (existing != null) { if (existing != null) {
existing.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login")); existing.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login"));
} }
// We can now replace the entries as needed. // We can now replace the entries as needed.
connectionsByName.put(lowerName, connection); connectionsByName.put(lowerName, connection);
connectionsByUuid.put(connection.getUniqueId(), connection); connectionsByUuid.put(connection.id(), connection);
} }
return true; return true;
} }
@ -558,8 +558,8 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
* @param connection the connection to unregister * @param connection the connection to unregister
*/ */
public void unregisterConnection(ConnectedPlayer connection) { public void unregisterConnection(ConnectedPlayer connection) {
connectionsByName.remove(connection.getUsername().toLowerCase(Locale.US), connection); connectionsByName.remove(connection.username().toLowerCase(Locale.US), connection);
connectionsByUuid.remove(connection.getUniqueId(), connection); connectionsByUuid.remove(connection.id(), connection);
bossBarManager.onDisconnect(connection); bossBarManager.onDisconnect(connection);
} }
@ -579,7 +579,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
public Collection<Player> matchPlayer(String partialName) { public Collection<Player> matchPlayer(String partialName) {
Objects.requireNonNull(partialName); Objects.requireNonNull(partialName);
return getAllPlayers().stream().filter(p -> p.getUsername() return connectedPlayers().stream().filter(p -> p.username()
.regionMatches(true, 0, partialName, 0, partialName.length())) .regionMatches(true, 0, partialName, 0, partialName.length()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@ -588,28 +588,28 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
public Collection<RegisteredServer> matchServer(String partialName) { public Collection<RegisteredServer> matchServer(String partialName) {
Objects.requireNonNull(partialName); Objects.requireNonNull(partialName);
return getAllServers().stream().filter(s -> s.getServerInfo().getName() return registeredServers().stream().filter(s -> s.serverInfo().name()
.regionMatches(true, 0, partialName, 0, partialName.length())) .regionMatches(true, 0, partialName, 0, partialName.length()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public Collection<Player> getAllPlayers() { public Collection<Player> connectedPlayers() {
return ImmutableList.copyOf(connectionsByUuid.values()); return ImmutableList.copyOf(connectionsByUuid.values());
} }
@Override @Override
public int getPlayerCount() { public int countConnectedPlayers() {
return connectionsByUuid.size(); return connectionsByUuid.size();
} }
@Override @Override
public Optional<RegisteredServer> getServer(String name) { public Optional<RegisteredServer> server(String name) {
return servers.getServer(name); return servers.getServer(name);
} }
@Override @Override
public Collection<RegisteredServer> getAllServers() { public Collection<RegisteredServer> registeredServers() {
return servers.getAllServers(); return servers.getAllServers();
} }
@ -624,44 +624,35 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
} }
@Override @Override
public VelocityConsole getConsoleCommandSource() { public VelocityConsole consoleCommandSource() {
return console; return console;
} }
@Override @Override
public PluginManager getPluginManager() { public PluginManager pluginManager() {
return pluginManager; return pluginManager;
} }
@Override @Override
public EventManager getEventManager() { public EventManager eventManager() {
return eventManager; return eventManager;
} }
@Override @Override
public VelocityScheduler getScheduler() { public VelocityScheduler scheduler() {
return scheduler; return scheduler;
} }
@Override @Override
public VelocityChannelRegistrar getChannelRegistrar() { public VelocityChannelRegistrar channelRegistrar() {
return channelRegistrar; return channelRegistrar;
} }
@Override
public SocketAddress getBoundAddress() {
if (configuration == null) {
throw new IllegalStateException(
"No configuration"); // even though you'll never get the chance... heh, heh
}
return configuration.getBind();
}
@Override @Override
public @NonNull Iterable<? extends Audience> audiences() { public @NonNull Iterable<? extends Audience> audiences() {
Collection<Audience> audiences = new ArrayList<>(this.getPlayerCount() + 1); Collection<Audience> audiences = new ArrayList<>(this.countConnectedPlayers() + 1);
audiences.add(this.console); audiences.add(this.console);
audiences.addAll(this.getAllPlayers()); audiences.addAll(this.connectedPlayers());
return audiences; return audiences;
} }

Datei anzeigen

@ -78,7 +78,7 @@ public class VelocityCommandManager implements CommandManager {
Preconditions.checkNotNull(meta, "meta"); Preconditions.checkNotNull(meta, "meta");
Preconditions.checkNotNull(command, "command"); Preconditions.checkNotNull(command, "command");
Iterator<String> aliasIterator = meta.getAliases().iterator(); Iterator<String> aliasIterator = meta.aliases().iterator();
String primaryAlias = aliasIterator.next(); String primaryAlias = aliasIterator.next();
LiteralCommandNode<CommandSource> node = null; LiteralCommandNode<CommandSource> node = null;
@ -94,7 +94,7 @@ public class VelocityCommandManager implements CommandManager {
} }
if (!(command instanceof BrigadierCommand)) { if (!(command instanceof BrigadierCommand)) {
for (CommandNode<CommandSource> hint : meta.getHints()) { for (CommandNode<CommandSource> hint : meta.hints()) {
node.addChild(BrigadierUtils.wrapForHinting(hint, node.getCommand())); node.addChild(BrigadierUtils.wrapForHinting(hint, node.getCommand()));
} }
} }
@ -160,11 +160,11 @@ public class VelocityCommandManager implements CommandManager {
Preconditions.checkNotNull(cmdLine, "cmdLine"); Preconditions.checkNotNull(cmdLine, "cmdLine");
return callCommandEvent(source, cmdLine).thenApplyAsync(event -> { return callCommandEvent(source, cmdLine).thenApplyAsync(event -> {
CommandResult commandResult = event.getResult(); CommandResult commandResult = event.result();
if (commandResult.isForwardToServer() || !commandResult.isAllowed()) { if (commandResult.isForwardToServer() || !commandResult.isAllowed()) {
return false; return false;
} }
return executeImmediately0(source, commandResult.getCommand().orElse(event.getCommand())); return executeImmediately0(source, commandResult.modifiedCommand().orElse(event.rawCommand()));
}, eventManager.getAsyncExecutor()); }, eventManager.getAsyncExecutor());
} }

Datei anzeigen

@ -76,12 +76,12 @@ final class VelocityCommandMeta implements CommandMeta {
} }
@Override @Override
public Collection<String> getAliases() { public Collection<String> aliases() {
return aliases; return aliases;
} }
@Override @Override
public Collection<CommandNode<CommandSource>> getHints() { public Collection<CommandNode<CommandSource>> hints() {
return hints; return hints;
} }
} }

Datei anzeigen

@ -31,8 +31,8 @@ class BuiltinCommandUtil {
} }
static List<RegisteredServer> sortedServerList(ProxyServer proxy) { static List<RegisteredServer> sortedServerList(ProxyServer proxy) {
List<RegisteredServer> servers = new ArrayList<>(proxy.getAllServers()); List<RegisteredServer> servers = new ArrayList<>(proxy.registeredServers());
servers.sort(Comparator.comparing(RegisteredServer::getServerInfo)); servers.sort(Comparator.comparing(RegisteredServer::serverInfo));
return Collections.unmodifiableList(servers); return Collections.unmodifiableList(servers);
} }
} }

Datei anzeigen

@ -56,14 +56,14 @@ public class GlistCommand {
LiteralCommandNode<CommandSource> totalNode = LiteralArgumentBuilder LiteralCommandNode<CommandSource> totalNode = LiteralArgumentBuilder
.<CommandSource>literal("glist") .<CommandSource>literal("glist")
.requires(source -> .requires(source ->
source.getPermissionValue("velocity.command.glist") == Tristate.TRUE) source.evaluatePermission("velocity.command.glist") == Tristate.TRUE)
.executes(this::totalCount) .executes(this::totalCount)
.build(); .build();
ArgumentCommandNode<CommandSource, String> serverNode = RequiredArgumentBuilder ArgumentCommandNode<CommandSource, String> serverNode = RequiredArgumentBuilder
.<CommandSource, String>argument(SERVER_ARG, StringArgumentType.string()) .<CommandSource, String>argument(SERVER_ARG, StringArgumentType.string())
.suggests((context, builder) -> { .suggests((context, builder) -> {
for (RegisteredServer server : server.getAllServers()) { for (RegisteredServer server : server.registeredServers()) {
builder.suggest(server.getServerInfo().getName()); builder.suggest(server.serverInfo().name());
} }
builder.suggest("all"); builder.suggest("all");
return builder.buildFuture(); return builder.buildFuture();
@ -71,7 +71,7 @@ public class GlistCommand {
.executes(this::serverCount) .executes(this::serverCount)
.build(); .build();
totalNode.addChild(serverNode); totalNode.addChild(serverNode);
server.getCommandManager().register(new BrigadierCommand(totalNode)); server.commandManager().register(new BrigadierCommand(totalNode));
} }
private int totalCount(final CommandContext<CommandSource> context) { private int totalCount(final CommandContext<CommandSource> context) {
@ -95,7 +95,7 @@ public class GlistCommand {
} }
sendTotalProxyCount(source); sendTotalProxyCount(source);
} else { } else {
Optional<RegisteredServer> registeredServer = server.getServer(serverName); Optional<RegisteredServer> registeredServer = server.server(serverName);
if (!registeredServer.isPresent()) { if (!registeredServer.isPresent()) {
source.sendMessage(Identity.nil(), source.sendMessage(Identity.nil(),
Component.text("Server " + serverName + " doesn't exist.", NamedTextColor.RED)); Component.text("Server " + serverName + " doesn't exist.", NamedTextColor.RED));
@ -109,19 +109,19 @@ public class GlistCommand {
private void sendTotalProxyCount(CommandSource target) { private void sendTotalProxyCount(CommandSource target) {
target.sendMessage(Identity.nil(), Component.text() target.sendMessage(Identity.nil(), Component.text()
.content("There are ").color(NamedTextColor.YELLOW) .content("There are ").color(NamedTextColor.YELLOW)
.append(Component.text(server.getAllPlayers().size(), NamedTextColor.GREEN)) .append(Component.text(server.connectedPlayers().size(), NamedTextColor.GREEN))
.append(Component.text(" player(s) online.", NamedTextColor.YELLOW)) .append(Component.text(" player(s) online.", NamedTextColor.YELLOW))
.build()); .build());
} }
private void sendServerPlayers(CommandSource target, RegisteredServer server, boolean fromAll) { private void sendServerPlayers(CommandSource target, RegisteredServer server, boolean fromAll) {
List<Player> onServer = ImmutableList.copyOf(server.getPlayersConnected()); List<Player> onServer = ImmutableList.copyOf(server.connectedPlayers());
if (onServer.isEmpty() && fromAll) { if (onServer.isEmpty() && fromAll) {
return; return;
} }
TextComponent.Builder builder = Component.text() TextComponent.Builder builder = Component.text()
.append(Component.text("[" + server.getServerInfo().getName() + "] ", .append(Component.text("[" + server.serverInfo().name() + "] ",
NamedTextColor.DARK_AQUA)) NamedTextColor.DARK_AQUA))
.append(Component.text("(" + onServer.size() + ")", NamedTextColor.GRAY)) .append(Component.text("(" + onServer.size() + ")", NamedTextColor.GRAY))
.append(Component.text(": ")) .append(Component.text(": "))
@ -129,7 +129,7 @@ public class GlistCommand {
for (int i = 0; i < onServer.size(); i++) { for (int i = 0; i < onServer.size(); i++) {
Player player = onServer.get(i); Player player = onServer.get(i);
builder.append(Component.text(player.getUsername())); builder.append(Component.text(player.username()));
if (i + 1 < onServer.size()) { if (i + 1 < onServer.size()) {
builder.append(Component.text(", ")); builder.append(Component.text(", "));

Datei anzeigen

@ -62,7 +62,7 @@ public class ServerCommand implements SimpleCommand {
if (args.length == 1) { if (args.length == 1) {
// Trying to connect to a server. // Trying to connect to a server.
String serverName = args[0]; String serverName = args[0];
Optional<RegisteredServer> toConnect = server.getServer(serverName); Optional<RegisteredServer> toConnect = server.server(serverName);
if (!toConnect.isPresent()) { if (!toConnect.isPresent()) {
player.sendMessage(Identity.nil(), player.sendMessage(Identity.nil(),
Component.text("Server " + serverName + " doesn't exist.", NamedTextColor.RED)); Component.text("Server " + serverName + " doesn't exist.", NamedTextColor.RED));
@ -76,8 +76,8 @@ public class ServerCommand implements SimpleCommand {
} }
private void outputServerInformation(Player executor) { private void outputServerInformation(Player executor) {
String currentServer = executor.getCurrentServer().map(ServerConnection::getServerInfo) String currentServer = executor.connectedServer().map(ServerConnection::serverInfo)
.map(ServerInfo::getName).orElse("<unknown>"); .map(ServerInfo::name).orElse("<unknown>");
executor.sendMessage(Identity.nil(), Component.text( executor.sendMessage(Identity.nil(), Component.text(
"You are currently connected to " + currentServer + ".", NamedTextColor.YELLOW)); "You are currently connected to " + currentServer + ".", NamedTextColor.YELLOW));
@ -103,18 +103,18 @@ public class ServerCommand implements SimpleCommand {
} }
private TextComponent formatServerComponent(String currentPlayerServer, RegisteredServer server) { private TextComponent formatServerComponent(String currentPlayerServer, RegisteredServer server) {
ServerInfo serverInfo = server.getServerInfo(); ServerInfo serverInfo = server.serverInfo();
TextComponent serverTextComponent = Component.text(serverInfo.getName()); TextComponent serverTextComponent = Component.text(serverInfo.name());
String playersText = server.getPlayersConnected().size() + " player(s) online"; String playersText = server.connectedPlayers().size() + " player(s) online";
if (serverInfo.getName().equals(currentPlayerServer)) { if (serverInfo.name().equals(currentPlayerServer)) {
serverTextComponent = serverTextComponent.color(NamedTextColor.GREEN) serverTextComponent = serverTextComponent.color(NamedTextColor.GREEN)
.hoverEvent( .hoverEvent(
showText(Component.text("Currently connected to this server\n" + playersText)) showText(Component.text("Currently connected to this server\n" + playersText))
); );
} else { } else {
serverTextComponent = serverTextComponent.color(NamedTextColor.GRAY) serverTextComponent = serverTextComponent.color(NamedTextColor.GRAY)
.clickEvent(ClickEvent.runCommand("/server " + serverInfo.getName())) .clickEvent(ClickEvent.runCommand("/server " + serverInfo.name()))
.hoverEvent( .hoverEvent(
showText(Component.text("Click to connect to this server\n" + playersText)) showText(Component.text("Click to connect to this server\n" + playersText))
); );
@ -125,8 +125,8 @@ public class ServerCommand implements SimpleCommand {
@Override @Override
public List<String> suggest(final SimpleCommand.Invocation invocation) { public List<String> suggest(final SimpleCommand.Invocation invocation) {
final String[] currentArgs = invocation.arguments(); final String[] currentArgs = invocation.arguments();
Stream<String> possibilities = server.getAllServers().stream() Stream<String> possibilities = server.registeredServers().stream()
.map(rs -> rs.getServerInfo().getName()); .map(rs -> rs.serverInfo().name());
if (currentArgs.length == 0) { if (currentArgs.length == 0) {
return possibilities.collect(Collectors.toList()); return possibilities.collect(Collectors.toList());
@ -141,6 +141,6 @@ public class ServerCommand implements SimpleCommand {
@Override @Override
public boolean hasPermission(final SimpleCommand.Invocation invocation) { public boolean hasPermission(final SimpleCommand.Invocation invocation) {
return invocation.source().getPermissionValue("velocity.command.server") != Tristate.FALSE; return invocation.source().evaluatePermission("velocity.command.server") != Tristate.FALSE;
} }
} }

Datei anzeigen

@ -41,6 +41,6 @@ public class ShutdownCommand implements RawCommand {
@Override @Override
public boolean hasPermission(final Invocation invocation) { public boolean hasPermission(final Invocation invocation) {
return invocation.source() == server.getConsoleCommandSource(); return invocation.source() == server.consoleCommandSource();
} }
} }

Datei anzeigen

@ -197,7 +197,7 @@ public class VelocityCommand implements SimpleCommand {
@Override @Override
public boolean hasPermission(final CommandSource source, final String @NonNull [] args) { public boolean hasPermission(final CommandSource source, final String @NonNull [] args) {
return source.getPermissionValue("velocity.command.reload") == Tristate.TRUE; return source.evaluatePermission("velocity.command.reload") == Tristate.TRUE;
} }
} }
@ -217,7 +217,7 @@ public class VelocityCommand implements SimpleCommand {
return; return;
} }
ProxyVersion version = server.getVersion(); ProxyVersion version = server.version();
TextComponent velocity = Component.text().content(version.getName() + " ") TextComponent velocity = Component.text().content(version.getName() + " ")
.decoration(TextDecoration.BOLD, true) .decoration(TextDecoration.BOLD, true)
@ -251,7 +251,7 @@ public class VelocityCommand implements SimpleCommand {
@Override @Override
public boolean hasPermission(final CommandSource source, final String @NonNull [] args) { public boolean hasPermission(final CommandSource source, final String @NonNull [] args) {
return source.getPermissionValue("velocity.command.info") != Tristate.FALSE; return source.evaluatePermission("velocity.command.info") != Tristate.FALSE;
} }
} }
@ -270,7 +270,7 @@ public class VelocityCommand implements SimpleCommand {
return; return;
} }
List<PluginContainer> plugins = ImmutableList.copyOf(server.getPluginManager().getPlugins()); List<PluginContainer> plugins = ImmutableList.copyOf(server.pluginManager().getPlugins());
int pluginCount = plugins.size(); int pluginCount = plugins.size();
if (pluginCount == 0) { if (pluginCount == 0) {
@ -283,7 +283,7 @@ public class VelocityCommand implements SimpleCommand {
.color(NamedTextColor.YELLOW); .color(NamedTextColor.YELLOW);
for (int i = 0; i < pluginCount; i++) { for (int i = 0; i < pluginCount; i++) {
PluginContainer plugin = plugins.get(i); PluginContainer plugin = plugins.get(i);
output.append(componentForPlugin(plugin.getDescription())); output.append(componentForPlugin(plugin.description()));
if (i + 1 < pluginCount) { if (i + 1 < pluginCount) {
output.append(Component.text(", ")); output.append(Component.text(", "));
} }
@ -293,37 +293,37 @@ public class VelocityCommand implements SimpleCommand {
} }
private TextComponent componentForPlugin(PluginDescription description) { private TextComponent componentForPlugin(PluginDescription description) {
String pluginInfo = description.getName().orElse(description.getId()) String pluginInfo = description.name().orElse(description.id())
+ description.getVersion().map(v -> " " + v).orElse(""); + description.version().map(v -> " " + v).orElse("");
TextComponent.Builder hoverText = Component.text().content(pluginInfo); TextComponent.Builder hoverText = Component.text().content(pluginInfo);
description.getUrl().ifPresent(url -> { description.url().ifPresent(url -> {
hoverText.append(Component.newline()); hoverText.append(Component.newline());
hoverText.append(Component.text("Website: " + url)); hoverText.append(Component.text("Website: " + url));
}); });
if (!description.getAuthors().isEmpty()) { if (!description.authors().isEmpty()) {
hoverText.append(Component.newline()); hoverText.append(Component.newline());
if (description.getAuthors().size() == 1) { if (description.authors().size() == 1) {
hoverText.append(Component.text("Author: " + description.getAuthors().get(0))); hoverText.append(Component.text("Author: " + description.authors().get(0)));
} else { } else {
hoverText.append(Component.text("Authors: " + Joiner.on(", ") hoverText.append(Component.text("Authors: " + Joiner.on(", ")
.join(description.getAuthors()))); .join(description.authors())));
} }
} }
description.getDescription().ifPresent(pdesc -> { description.description().ifPresent(pdesc -> {
hoverText.append(Component.newline()); hoverText.append(Component.newline());
hoverText.append(Component.newline()); hoverText.append(Component.newline());
hoverText.append(Component.text(pdesc)); hoverText.append(Component.text(pdesc));
}); });
return Component.text(description.getId(), NamedTextColor.GRAY) return Component.text(description.id(), NamedTextColor.GRAY)
.hoverEvent(HoverEvent.showText(hoverText.build())); .hoverEvent(HoverEvent.showText(hoverText.build()));
} }
@Override @Override
public boolean hasPermission(final CommandSource source, final String @NonNull [] args) { public boolean hasPermission(final CommandSource source, final String @NonNull [] args) {
return source.getPermissionValue("velocity.command.plugins") == Tristate.TRUE; return source.evaluatePermission("velocity.command.plugins") == Tristate.TRUE;
} }
} }
@ -343,27 +343,27 @@ public class VelocityCommand implements SimpleCommand {
return; return;
} }
Collection<RegisteredServer> allServers = ImmutableSet.copyOf(server.getAllServers()); Collection<RegisteredServer> allServers = ImmutableSet.copyOf(server.registeredServers());
JsonObject servers = new JsonObject(); JsonObject servers = new JsonObject();
for (RegisteredServer iter : allServers) { for (RegisteredServer iter : allServers) {
servers.add(iter.getServerInfo().getName(), servers.add(iter.serverInfo().name(),
InformationUtils.collectServerInfo(iter)); InformationUtils.collectServerInfo(iter));
} }
JsonArray connectOrder = new JsonArray(); JsonArray connectOrder = new JsonArray();
List<String> attemptedConnectionOrder = ImmutableList.copyOf( List<String> attemptedConnectionOrder = ImmutableList.copyOf(
server.getConfiguration().getAttemptConnectionOrder()); server.configuration().getAttemptConnectionOrder());
for (int i = 0; i < attemptedConnectionOrder.size(); i++) { for (int i = 0; i < attemptedConnectionOrder.size(); i++) {
connectOrder.add(attemptedConnectionOrder.get(i)); connectOrder.add(attemptedConnectionOrder.get(i));
} }
JsonObject proxyConfig = InformationUtils.collectProxyConfig(server.getConfiguration()); JsonObject proxyConfig = InformationUtils.collectProxyConfig(server.configuration());
proxyConfig.add("servers", servers); proxyConfig.add("servers", servers);
proxyConfig.add("connectOrder", connectOrder); proxyConfig.add("connectOrder", connectOrder);
proxyConfig.add("forcedHosts", proxyConfig.add("forcedHosts",
InformationUtils.collectForcedHosts(server.getConfiguration())); InformationUtils.collectForcedHosts(server.configuration()));
JsonObject dump = new JsonObject(); JsonObject dump = new JsonObject();
dump.add("versionInfo", InformationUtils.collectProxyInfo(server.getVersion())); dump.add("versionInfo", InformationUtils.collectProxyInfo(server.version()));
dump.add("platform", InformationUtils.collectEnvironmentInfo()); dump.add("platform", InformationUtils.collectEnvironmentInfo());
dump.add("config", proxyConfig); dump.add("config", proxyConfig);
dump.add("plugins", InformationUtils.collectPluginInfo(server)); dump.add("plugins", InformationUtils.collectPluginInfo(server));
@ -374,8 +374,8 @@ public class VelocityCommand implements SimpleCommand {
BoundRequestBuilder request = BoundRequestBuilder request =
httpClient.preparePost("https://dump.velocitypowered.com/documents"); httpClient.preparePost("https://dump.velocitypowered.com/documents");
request.setHeader("Content-Type", "text/plain"); request.setHeader("Content-Type", "text/plain");
request.addHeader("User-Agent", server.getVersion().getName() + "/" request.addHeader("User-Agent", server.version().getName() + "/"
+ server.getVersion().getVersion()); + server.version().getVersion());
request.setBody( request.setBody(
InformationUtils.toHumanReadableString(dump).getBytes(StandardCharsets.UTF_8)); InformationUtils.toHumanReadableString(dump).getBytes(StandardCharsets.UTF_8));
@ -459,7 +459,7 @@ public class VelocityCommand implements SimpleCommand {
@Override @Override
public boolean hasPermission(final CommandSource source, final String @NonNull [] args) { public boolean hasPermission(final CommandSource source, final String @NonNull [] args) {
return source.getPermissionValue("velocity.command.plugins") == Tristate.TRUE; return source.evaluatePermission("velocity.command.plugins") == Tristate.TRUE;
} }
} }
} }

Datei anzeigen

@ -414,7 +414,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter {
decoder.setThreshold(threshold); decoder.setThreshold(threshold);
encoder.setThreshold(threshold); encoder.setThreshold(threshold);
} else { } else {
int level = server.getConfiguration().getCompressionLevel(); int level = server.configuration().getCompressionLevel();
VelocityCompressor compressor = Natives.compress.get().create(level); VelocityCompressor compressor = Natives.compress.get().create(level);
encoder = new MinecraftCompressEncoder(threshold, compressor); encoder = new MinecraftCompressEncoder(threshold, compressor);

Datei anzeigen

@ -26,6 +26,7 @@ import com.mojang.brigadier.tree.RootCommandNode;
import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.command.PlayerAvailableCommandsEventImpl; import com.velocitypowered.api.event.command.PlayerAvailableCommandsEventImpl;
import com.velocitypowered.api.event.connection.PluginMessageEvent; import com.velocitypowered.api.event.connection.PluginMessageEvent;
import com.velocitypowered.api.event.connection.PluginMessageEventImpl;
import com.velocitypowered.api.network.ProtocolVersion; import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.proxy.VelocityServer; import com.velocitypowered.proxy.VelocityServer;
@ -68,7 +69,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
BackendPlaySessionHandler(VelocityServer server, VelocityServerConnection serverConn) { BackendPlaySessionHandler(VelocityServer server, VelocityServerConnection serverConn) {
this.server = server; this.server = server;
this.serverConn = serverConn; this.serverConn = serverConn;
this.playerConnection = serverConn.getPlayer().getConnection(); this.playerConnection = serverConn.player().getConnection();
MinecraftSessionHandler psh = playerConnection.getSessionHandler(); MinecraftSessionHandler psh = playerConnection.getSessionHandler();
if (!(psh instanceof ClientPlaySessionHandler)) { if (!(psh instanceof ClientPlaySessionHandler)) {
@ -78,14 +79,14 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
this.playerSessionHandler = (ClientPlaySessionHandler) psh; this.playerSessionHandler = (ClientPlaySessionHandler) psh;
this.bungeecordMessageResponder = new BungeeCordMessageResponder(server, this.bungeecordMessageResponder = new BungeeCordMessageResponder(server,
serverConn.getPlayer()); serverConn.player());
} }
@Override @Override
public void activated() { public void activated() {
serverConn.getServer().addPlayer(serverConn.getPlayer()); serverConn.target().addPlayer(serverConn.player());
if (server.getConfiguration().isBungeePluginChannelEnabled()) { if (server.configuration().isBungeePluginChannelEnabled()) {
MinecraftConnection serverMc = serverConn.ensureConnected(); MinecraftConnection serverMc = serverConn.ensureConnected();
serverMc.write(PluginMessageUtil.constructChannelsPacket(serverMc.getProtocolVersion(), serverMc.write(PluginMessageUtil.constructChannelsPacket(serverMc.getProtocolVersion(),
ImmutableList.of(getBungeeCordChannel(serverMc.getProtocolVersion())), ImmutableList.of(getBungeeCordChannel(serverMc.getProtocolVersion())),
@ -112,7 +113,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundDisconnectPacket packet) { public boolean handle(ClientboundDisconnectPacket packet) {
serverConn.disconnect(); serverConn.disconnect();
serverConn.getPlayer().handleConnectionException(serverConn.getServer(), packet, true); serverConn.player().handleConnectionException(serverConn.target(), packet, true);
return true; return true;
} }
@ -132,7 +133,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
return true; return true;
} }
if (!serverConn.getPlayer().canForwardPluginMessage(serverConn.ensureConnected() if (!serverConn.player().canForwardPluginMessage(serverConn.ensureConnected()
.getProtocolVersion(), packet)) { .getProtocolVersion(), packet)) {
return true; return true;
} }
@ -140,36 +141,36 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
// We need to specially handle REGISTER and UNREGISTER packets. Later on, we'll write them to // We need to specially handle REGISTER and UNREGISTER packets. Later on, we'll write them to
// the client. // the client.
if (PluginMessageUtil.isRegister(packet)) { if (PluginMessageUtil.isRegister(packet)) {
serverConn.getPlayer().getKnownChannels().addAll(PluginMessageUtil.getChannels(packet)); serverConn.player().getKnownChannels().addAll(PluginMessageUtil.getChannels(packet));
return false; return false;
} else if (PluginMessageUtil.isUnregister(packet)) { } else if (PluginMessageUtil.isUnregister(packet)) {
serverConn.getPlayer().getKnownChannels().removeAll(PluginMessageUtil.getChannels(packet)); serverConn.player().getKnownChannels().removeAll(PluginMessageUtil.getChannels(packet));
return false; return false;
} }
if (PluginMessageUtil.isMcBrand(packet)) { if (PluginMessageUtil.isMcBrand(packet)) {
AbstractPluginMessagePacket<?> rewritten = PluginMessageUtil.rewriteMinecraftBrand(packet, AbstractPluginMessagePacket<?> rewritten = PluginMessageUtil.rewriteMinecraftBrand(packet,
server.getVersion(), playerConnection.getProtocolVersion(), ClientboundPluginMessagePacket.FACTORY); server.version(), playerConnection.getProtocolVersion(), ClientboundPluginMessagePacket.FACTORY);
playerConnection.write(rewritten); playerConnection.write(rewritten);
return true; return true;
} }
if (serverConn.getPhase().handle(serverConn, serverConn.getPlayer(), packet)) { if (serverConn.getPhase().handle(serverConn, serverConn.player(), packet)) {
// Handled. // Handled.
return true; return true;
} }
ChannelIdentifier id = server.getChannelRegistrar().getFromId(packet.getChannel()); ChannelIdentifier id = server.channelRegistrar().getFromId(packet.getChannel());
if (id == null) { if (id == null) {
return false; return false;
} }
byte[] copy = ByteBufUtil.getBytes(packet.content()); byte[] copy = ByteBufUtil.getBytes(packet.content());
PluginMessageEvent event = new PluginMessageEvent(serverConn, serverConn.getPlayer(), id, PluginMessageEvent event = new PluginMessageEventImpl(serverConn, serverConn.player(), id,
copy); copy);
server.getEventManager().fire(event) server.eventManager().fire(event)
.thenAcceptAsync(pme -> { .thenAcceptAsync(pme -> {
if (pme.getResult().isAllowed() && !playerConnection.isClosed()) { if (pme.result().isAllowed() && !playerConnection.isClosed()) {
ClientboundPluginMessagePacket copied = new ClientboundPluginMessagePacket(packet.getChannel(), ClientboundPluginMessagePacket copied = new ClientboundPluginMessagePacket(packet.getChannel(),
Unpooled.wrappedBuffer(copy)); Unpooled.wrappedBuffer(copy));
playerConnection.write(copied); playerConnection.write(copied);
@ -190,18 +191,18 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundPlayerListItemPacket packet) { public boolean handle(ClientboundPlayerListItemPacket packet) {
serverConn.getPlayer().getTabList().processBackendPacket(packet); serverConn.player().tabList().processBackendPacket(packet);
return false; //Forward packet to player return false; //Forward packet to player
} }
@Override @Override
public boolean handle(ClientboundAvailableCommandsPacket commands) { public boolean handle(ClientboundAvailableCommandsPacket commands) {
RootCommandNode<CommandSource> rootNode = commands.getRootNode(); RootCommandNode<CommandSource> rootNode = commands.getRootNode();
if (server.getConfiguration().isAnnounceProxyCommands()) { if (server.configuration().isAnnounceProxyCommands()) {
// Inject commands from the proxy. // Inject commands from the proxy.
RootCommandNode<CommandSource> dispatcherRootNode = RootCommandNode<CommandSource> dispatcherRootNode =
(RootCommandNode<CommandSource>) (RootCommandNode<CommandSource>)
filterNode(server.getCommandManager().getDispatcher().getRoot()); filterNode(server.commandManager().getDispatcher().getRoot());
assert dispatcherRootNode != null : "Filtering root node returned null."; assert dispatcherRootNode != null : "Filtering root node returned null.";
Collection<CommandNode<CommandSource>> proxyNodes = dispatcherRootNode.getChildren(); Collection<CommandNode<CommandSource>> proxyNodes = dispatcherRootNode.getChildren();
for (CommandNode<CommandSource> node : proxyNodes) { for (CommandNode<CommandSource> node : proxyNodes) {
@ -213,8 +214,8 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
} }
} }
server.getEventManager().fire( server.eventManager().fire(
new PlayerAvailableCommandsEventImpl(serverConn.getPlayer(), rootNode)) new PlayerAvailableCommandsEventImpl(serverConn.player(), rootNode))
.thenAcceptAsync(event -> playerConnection.write(commands), playerConnection.eventLoop()) .thenAcceptAsync(event -> playerConnection.write(commands), playerConnection.eventLoop())
.exceptionally((ex) -> { .exceptionally((ex) -> {
logger.error("Exception while handling available commands for {}", playerConnection, ex); logger.error("Exception while handling available commands for {}", playerConnection, ex);
@ -237,7 +238,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
} else { } else {
if (source.getRequirement() != null) { if (source.getRequirement() != null) {
try { try {
if (!source.getRequirement().test(serverConn.getPlayer())) { if (!source.getRequirement().test(serverConn.player())) {
return null; return null;
} }
} catch (Throwable e) { } catch (Throwable e) {
@ -288,7 +289,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public void exception(Throwable throwable) { public void exception(Throwable throwable) {
exceptionTriggered = true; exceptionTriggered = true;
serverConn.getPlayer().handleConnectionException(serverConn.getServer(), throwable, serverConn.player().handleConnectionException(serverConn.target(), throwable,
!(throwable instanceof ReadTimeoutException)); !(throwable instanceof ReadTimeoutException));
} }
@ -298,14 +299,14 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public void disconnected() { public void disconnected() {
serverConn.getServer().removePlayer(serverConn.getPlayer()); serverConn.target().removePlayer(serverConn.player());
if (!serverConn.isGracefulDisconnect() && !exceptionTriggered) { if (!serverConn.isGracefulDisconnect() && !exceptionTriggered) {
if (server.getConfiguration().isFailoverOnUnexpectedServerDisconnect()) { if (server.configuration().isFailoverOnUnexpectedServerDisconnect()) {
serverConn.getPlayer().handleConnectionException(serverConn.getServer(), serverConn.player().handleConnectionException(serverConn.target(),
ClientboundDisconnectPacket.create(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR, ClientboundDisconnectPacket.create(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR,
ProtocolVersion.MINECRAFT_1_16), true); ProtocolVersion.MINECRAFT_1_16), true);
} else { } else {
serverConn.getPlayer().disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); serverConn.player().disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
} }
} }
} }

Datei anzeigen

@ -64,13 +64,13 @@ public class BungeeCordMessageResponder {
} }
public static boolean isBungeeCordMessage(AbstractPluginMessagePacket<?> message) { public static boolean isBungeeCordMessage(AbstractPluginMessagePacket<?> message) {
return MODERN_CHANNEL.getId().equals(message.getChannel()) || LEGACY_CHANNEL.getId() return MODERN_CHANNEL.id().equals(message.getChannel()) || LEGACY_CHANNEL.id()
.equals(message.getChannel()); .equals(message.getChannel());
} }
private void processConnect(ByteBufDataInput in) { private void processConnect(ByteBufDataInput in) {
String serverName = in.readUTF(); String serverName = in.readUTF();
proxy.getServer(serverName).ifPresent(server -> player.createConnectionRequest(server) proxy.server(serverName).ifPresent(server -> player.createConnectionRequest(server)
.fireAndForget()); .fireAndForget());
} }
@ -79,7 +79,7 @@ public class BungeeCordMessageResponder {
String serverName = in.readUTF(); String serverName = in.readUTF();
Optional<Player> referencedPlayer = proxy.getPlayer(playerName); Optional<Player> referencedPlayer = proxy.getPlayer(playerName);
Optional<RegisteredServer> referencedServer = proxy.getServer(serverName); Optional<RegisteredServer> referencedServer = proxy.server(serverName);
if (referencedPlayer.isPresent() && referencedServer.isPresent()) { if (referencedPlayer.isPresent() && referencedServer.isPresent()) {
referencedPlayer.get().createConnectionRequest(referencedServer.get()).fireAndForget(); referencedPlayer.get().createConnectionRequest(referencedServer.get()).fireAndForget();
} }
@ -90,7 +90,7 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf); ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("IP"); out.writeUTF("IP");
SocketAddress address = player.getRemoteAddress(); SocketAddress address = player.remoteAddress();
if (address instanceof InetSocketAddress) { if (address instanceof InetSocketAddress) {
InetSocketAddress serverInetAddr = (InetSocketAddress) address; InetSocketAddress serverInetAddr = (InetSocketAddress) address;
out.writeUTF(serverInetAddr.getHostString()); out.writeUTF(serverInetAddr.getHostString());
@ -110,12 +110,12 @@ public class BungeeCordMessageResponder {
if (target.equals("ALL")) { if (target.equals("ALL")) {
out.writeUTF("PlayerCount"); out.writeUTF("PlayerCount");
out.writeUTF("ALL"); out.writeUTF("ALL");
out.writeInt(proxy.getPlayerCount()); out.writeInt(proxy.countConnectedPlayers());
} else { } else {
proxy.getServer(target).ifPresent(rs -> { proxy.server(target).ifPresent(rs -> {
int playersOnServer = rs.getPlayersConnected().size(); int playersOnServer = rs.connectedPlayers().size();
out.writeUTF("PlayerCount"); out.writeUTF("PlayerCount");
out.writeUTF(rs.getServerInfo().getName()); out.writeUTF(rs.serverInfo().name());
out.writeInt(playersOnServer); out.writeInt(playersOnServer);
}); });
} }
@ -137,18 +137,18 @@ public class BungeeCordMessageResponder {
out.writeUTF("ALL"); out.writeUTF("ALL");
StringJoiner joiner = new StringJoiner(", "); StringJoiner joiner = new StringJoiner(", ");
for (Player online : proxy.getAllPlayers()) { for (Player online : proxy.connectedPlayers()) {
joiner.add(online.getUsername()); joiner.add(online.username());
} }
out.writeUTF(joiner.toString()); out.writeUTF(joiner.toString());
} else { } else {
proxy.getServer(target).ifPresent(info -> { proxy.server(target).ifPresent(info -> {
out.writeUTF("PlayerList"); out.writeUTF("PlayerList");
out.writeUTF(info.getServerInfo().getName()); out.writeUTF(info.serverInfo().name());
StringJoiner joiner = new StringJoiner(", "); StringJoiner joiner = new StringJoiner(", ");
for (Player online : info.getPlayersConnected()) { for (Player online : info.connectedPlayers()) {
joiner.add(online.getUsername()); joiner.add(online.username());
} }
out.writeUTF(joiner.toString()); out.writeUTF(joiner.toString());
}); });
@ -163,8 +163,8 @@ public class BungeeCordMessageResponder {
private void processGetServers() { private void processGetServers() {
StringJoiner joiner = new StringJoiner(", "); StringJoiner joiner = new StringJoiner(", ");
for (RegisteredServer server : proxy.getAllServers()) { for (RegisteredServer server : proxy.registeredServers()) {
joiner.add(server.getServerInfo().getName()); joiner.add(server.serverInfo().name());
} }
ByteBuf buf = Unpooled.buffer(); ByteBuf buf = Unpooled.buffer();
@ -202,7 +202,7 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf); ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("GetServer"); out.writeUTF("GetServer");
out.writeUTF(player.ensureAndGetCurrentServer().getServerInfo().getName()); out.writeUTF(player.ensureAndGetCurrentServer().serverInfo().name());
sendResponseOnConnection(buf); sendResponseOnConnection(buf);
} }
@ -212,7 +212,7 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf); ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("UUID"); out.writeUTF("UUID");
out.writeUTF(UuidUtils.toUndashed(player.getUniqueId())); out.writeUTF(UuidUtils.toUndashed(player.id()));
sendResponseOnConnection(buf); sendResponseOnConnection(buf);
} }
@ -223,8 +223,8 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf); ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("UUIDOther"); out.writeUTF("UUIDOther");
out.writeUTF(player.getUsername()); out.writeUTF(player.username());
out.writeUTF(UuidUtils.toUndashed(player.getUniqueId())); out.writeUTF(UuidUtils.toUndashed(player.id()));
sendResponseOnConnection(buf); sendResponseOnConnection(buf);
}); });
@ -236,8 +236,8 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf); ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("IPOther"); out.writeUTF("IPOther");
out.writeUTF(player.getUsername()); out.writeUTF(player.username());
SocketAddress address = player.getRemoteAddress(); SocketAddress address = player.remoteAddress();
if (address instanceof InetSocketAddress) { if (address instanceof InetSocketAddress) {
InetSocketAddress serverInetAddr = (InetSocketAddress) address; InetSocketAddress serverInetAddr = (InetSocketAddress) address;
out.writeUTF(serverInetAddr.getHostString()); out.writeUTF(serverInetAddr.getHostString());
@ -252,13 +252,13 @@ public class BungeeCordMessageResponder {
} }
private void processServerIp(ByteBufDataInput in) { private void processServerIp(ByteBufDataInput in) {
proxy.getServer(in.readUTF()).ifPresent(info -> { proxy.server(in.readUTF()).ifPresent(info -> {
ByteBuf buf = Unpooled.buffer(); ByteBuf buf = Unpooled.buffer();
ByteBufDataOutput out = new ByteBufDataOutput(buf); ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("ServerIP"); out.writeUTF("ServerIP");
out.writeUTF(info.getServerInfo().getName()); out.writeUTF(info.serverInfo().name());
SocketAddress address = info.getServerInfo().getAddress(); SocketAddress address = info.serverInfo().address();
if (address instanceof InetSocketAddress) { if (address instanceof InetSocketAddress) {
InetSocketAddress serverInetAddr = (InetSocketAddress) address; InetSocketAddress serverInetAddr = (InetSocketAddress) address;
out.writeUTF(serverInetAddr.getHostString()); out.writeUTF(serverInetAddr.getHostString());
@ -292,7 +292,7 @@ public class BungeeCordMessageResponder {
ByteBuf toForward = in.unwrap().copy(); ByteBuf toForward = in.unwrap().copy();
if (target.equals("ALL")) { if (target.equals("ALL")) {
try { try {
for (RegisteredServer rs : proxy.getAllServers()) { for (RegisteredServer rs : proxy.registeredServers()) {
((VelocityRegisteredServer) rs).sendPluginMessage(LEGACY_CHANNEL, ((VelocityRegisteredServer) rs).sendPluginMessage(LEGACY_CHANNEL,
toForward.retainedSlice()); toForward.retainedSlice());
} }
@ -300,7 +300,7 @@ public class BungeeCordMessageResponder {
toForward.release(); toForward.release();
} }
} else { } else {
Optional<RegisteredServer> server = proxy.getServer(target); Optional<RegisteredServer> server = proxy.server(target);
if (server.isPresent()) { if (server.isPresent()) {
((VelocityRegisteredServer) server.get()).sendPluginMessage(LEGACY_CHANNEL, toForward); ((VelocityRegisteredServer) server.get()).sendPluginMessage(LEGACY_CHANNEL, toForward);
} else { } else {
@ -310,8 +310,8 @@ public class BungeeCordMessageResponder {
} }
static String getBungeeCordChannel(ProtocolVersion version) { static String getBungeeCordChannel(ProtocolVersion version) {
return version.gte(ProtocolVersion.MINECRAFT_1_13) ? MODERN_CHANNEL.getId() return version.gte(ProtocolVersion.MINECRAFT_1_13) ? MODERN_CHANNEL.id()
: LEGACY_CHANNEL.getId(); : LEGACY_CHANNEL.id();
} }
// Note: this method will always release the buffer! // Note: this method will always release the buffer!
@ -328,7 +328,7 @@ public class BungeeCordMessageResponder {
} }
boolean process(AbstractPluginMessagePacket<?> message) { boolean process(AbstractPluginMessagePacket<?> message) {
if (!proxy.getConfiguration().isBungeePluginChannelEnabled()) { if (!proxy.configuration().isBungeePluginChannelEnabled()) {
return false; return false;
} }

Datei anzeigen

@ -73,12 +73,12 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundLoginPluginMessagePacket packet) { public boolean handle(ClientboundLoginPluginMessagePacket packet) {
MinecraftConnection mc = serverConn.ensureConnected(); MinecraftConnection mc = serverConn.ensureConnected();
VelocityConfiguration configuration = server.getConfiguration(); VelocityConfiguration configuration = server.configuration();
if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && packet if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN && packet
.getChannel().equals(VelocityConstants.VELOCITY_IP_FORWARDING_CHANNEL)) { .getChannel().equals(VelocityConstants.VELOCITY_IP_FORWARDING_CHANNEL)) {
ByteBuf forwardingData = createForwardingData(configuration.getForwardingSecret(), ByteBuf forwardingData = createForwardingData(configuration.getForwardingSecret(),
cleanRemoteAddress(serverConn.getPlayer().getRemoteAddress()), cleanRemoteAddress(serverConn.player().remoteAddress()),
serverConn.getPlayer().getGameProfile()); serverConn.player().gameProfile());
ServerboundLoginPluginResponsePacket response = new ServerboundLoginPluginResponsePacket( ServerboundLoginPluginResponsePacket response = new ServerboundLoginPluginResponsePacket(
packet.getId(), true, forwardingData); packet.getId(), true, forwardingData);
mc.write(response); mc.write(response);
@ -93,7 +93,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundDisconnectPacket packet) { public boolean handle(ClientboundDisconnectPacket packet) {
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.target()));
serverConn.disconnect(); serverConn.disconnect();
return true; return true;
} }
@ -106,10 +106,10 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundServerLoginSuccessPacket packet) { public boolean handle(ClientboundServerLoginSuccessPacket packet) {
if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN if (server.configuration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN
&& !informationForwarded) { && !informationForwarded) {
resultFuture.complete(ConnectionRequestResults.forDisconnect(MODERN_IP_FORWARDING_FAILURE, resultFuture.complete(ConnectionRequestResults.forDisconnect(MODERN_IP_FORWARDING_FAILURE,
serverConn.getServer())); serverConn.target()));
serverConn.disconnect(); serverConn.disconnect();
return true; return true;
} }
@ -133,7 +133,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
@Override @Override
public void disconnected() { public void disconnected() {
if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.LEGACY) { if (server.configuration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.LEGACY) {
resultFuture.completeExceptionally( resultFuture.completeExceptionally(
new QuietRuntimeException("The connection to the remote server was unexpectedly closed.\n" new QuietRuntimeException("The connection to the remote server was unexpectedly closed.\n"
+ "This is usually because the remote server does not have BungeeCord IP forwarding " + "This is usually because the remote server does not have BungeeCord IP forwarding "

Datei anzeigen

@ -85,9 +85,9 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundJoinGamePacket packet) { public boolean handle(ClientboundJoinGamePacket packet) {
MinecraftConnection smc = serverConn.ensureConnected(); MinecraftConnection smc = serverConn.ensureConnected();
VelocityServerConnection existingConnection = serverConn.getPlayer().getConnectedServer(); VelocityServerConnection existingConnection = serverConn.player().getConnectedServer();
final ConnectedPlayer player = serverConn.getPlayer(); final ConnectedPlayer player = serverConn.player();
if (existingConnection != null) { if (existingConnection != null) {
// Shut down the existing server connection. // Shut down the existing server connection.
@ -100,9 +100,9 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
// The goods are in hand! We got JoinGame. Let's transition completely to the new state. // The goods are in hand! We got JoinGame. Let's transition completely to the new state.
smc.setAutoReading(false); smc.setAutoReading(false);
server.getEventManager() server.eventManager()
.fire(new ServerConnectedEventImpl(player, serverConn.getServer(), .fire(new ServerConnectedEventImpl(player, serverConn.target(),
existingConnection != null ? existingConnection.getServer() : null)) existingConnection != null ? existingConnection.target() : null))
.thenRunAsync(() -> { .thenRunAsync(() -> {
// Make sure we can still transition (player might have disconnected here). // Make sure we can still transition (player might have disconnected here).
if (!serverConn.isActive()) { if (!serverConn.isActive()) {
@ -129,17 +129,17 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
smc.setAutoReading(true); smc.setAutoReading(true);
// Now set the connected server. // Now set the connected server.
serverConn.getPlayer().setConnectedServer(serverConn); serverConn.player().setConnectedServer(serverConn);
// We're done! :) // We're done! :)
server.getEventManager().fireAndForget(new ServerPostConnectEventImpl(player, server.eventManager().fireAndForget(new ServerPostConnectEventImpl(player,
existingConnection == null ? null : existingConnection.getServer())); existingConnection == null ? null : existingConnection.target()));
resultFuture.complete(ConnectionRequestResults.successful(serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.successful(serverConn.target()));
}, smc.eventLoop()) }, smc.eventLoop())
.exceptionally(exc -> { .exceptionally(exc -> {
logger.error("Unable to switch to new server {} for {}", logger.error("Unable to switch to new server {} for {}",
serverConn.getServerInfo().getName(), serverConn.serverInfo().name(),
player.getUsername(), exc); player.username(), exc);
player.disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); player.disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
resultFuture.completeExceptionally(exc); resultFuture.completeExceptionally(exc);
return null; return null;
@ -158,9 +158,9 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
if (connection.getType() == ConnectionTypes.LEGACY_FORGE if (connection.getType() == ConnectionTypes.LEGACY_FORGE
&& !serverConn.getPhase().consideredComplete()) { && !serverConn.getPhase().consideredComplete()) {
resultFuture.complete(ConnectionRequestResults.forUnsafeDisconnect(packet, resultFuture.complete(ConnectionRequestResults.forUnsafeDisconnect(packet,
serverConn.getServer())); serverConn.target()));
} else { } else {
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.target()));
} }
return true; return true;
@ -168,35 +168,35 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ClientboundPluginMessagePacket packet) { public boolean handle(ClientboundPluginMessagePacket packet) {
if (!serverConn.getPlayer().canForwardPluginMessage(serverConn.ensureConnected() if (!serverConn.player().canForwardPluginMessage(serverConn.ensureConnected()
.getProtocolVersion(), packet)) { .getProtocolVersion(), packet)) {
return true; return true;
} }
if (PluginMessageUtil.isRegister(packet)) { if (PluginMessageUtil.isRegister(packet)) {
serverConn.getPlayer().getKnownChannels().addAll(PluginMessageUtil.getChannels(packet)); serverConn.player().getKnownChannels().addAll(PluginMessageUtil.getChannels(packet));
} else if (PluginMessageUtil.isUnregister(packet)) { } else if (PluginMessageUtil.isUnregister(packet)) {
serverConn.getPlayer().getKnownChannels().removeAll(PluginMessageUtil.getChannels(packet)); serverConn.player().getKnownChannels().removeAll(PluginMessageUtil.getChannels(packet));
} }
// We always need to handle plugin messages, for Forge compatibility. // We always need to handle plugin messages, for Forge compatibility.
if (serverConn.getPhase().handle(serverConn, serverConn.getPlayer(), packet)) { if (serverConn.getPhase().handle(serverConn, serverConn.player(), packet)) {
// Handled, but check the server connection phase. // Handled, but check the server connection phase.
if (serverConn.getPhase() == HELLO) { if (serverConn.getPhase() == HELLO) {
VelocityServerConnection existingConnection = serverConn.getPlayer().getConnectedServer(); VelocityServerConnection existingConnection = serverConn.player().getConnectedServer();
if (existingConnection != null && existingConnection.getPhase() != IN_TRANSITION) { if (existingConnection != null && existingConnection.getPhase() != IN_TRANSITION) {
// Indicate that this connection is "in transition" // Indicate that this connection is "in transition"
existingConnection.setConnectionPhase(IN_TRANSITION); existingConnection.setConnectionPhase(IN_TRANSITION);
// Tell the player that we're leaving and we just aren't coming back. // Tell the player that we're leaving and we just aren't coming back.
existingConnection.getPhase().onDepartForNewServer(existingConnection, existingConnection.getPhase().onDepartForNewServer(existingConnection,
serverConn.getPlayer()); serverConn.player());
} }
} }
return true; return true;
} }
serverConn.getPlayer().getConnection().write(packet.retain()); serverConn.player().getConnection().write(packet.retain());
return true; return true;
} }

Datei anzeigen

@ -91,7 +91,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
CompletableFuture<Impl> result = new CompletableFuture<>(); CompletableFuture<Impl> result = new CompletableFuture<>();
// Note: we use the event loop for the connection the player is on. This reduces context // Note: we use the event loop for the connection the player is on. This reduces context
// switches. // switches.
SocketAddress destinationAddress = registeredServer.getServerInfo().getAddress(); SocketAddress destinationAddress = registeredServer.serverInfo().address();
server.createBootstrap(proxyPlayer.getConnection().eventLoop(), destinationAddress) server.createBootstrap(proxyPlayer.getConnection().eventLoop(), destinationAddress)
.handler(server.getBackendChannelInitializer()) .handler(server.getBackendChannelInitializer())
.connect(destinationAddress) .connect(destinationAddress)
@ -118,26 +118,26 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
} }
private String getHandshakeRemoteAddress() { private String getHandshakeRemoteAddress() {
return proxyPlayer.getVirtualHost().map(InetSocketAddress::getHostString).orElse(""); return proxyPlayer.connectedHost().map(InetSocketAddress::getHostString).orElse("");
} }
private String createLegacyForwardingAddress(UnaryOperator<List<Property>> propertiesTransform) { private String createLegacyForwardingAddress(UnaryOperator<List<Property>> propertiesTransform) {
// BungeeCord IP forwarding is simply a special injection after the "address" in the handshake, // BungeeCord IP forwarding is simply a special injection after the "address" in the handshake,
// separated by \0 (the null byte). In order, you send the original host, the player's IP, their // separated by \0 (the null byte). In order, you send the original host, the player's IP, their
// UUID (undashed), and if you are in online-mode, their login properties (from Mojang). // UUID (undashed), and if you are in online-mode, their login properties (from Mojang).
SocketAddress playerRemoteAddress = proxyPlayer.getRemoteAddress(); SocketAddress playerRemoteAddress = proxyPlayer.remoteAddress();
if (!(playerRemoteAddress instanceof InetSocketAddress)) { if (!(playerRemoteAddress instanceof InetSocketAddress)) {
return getHandshakeRemoteAddress(); return getHandshakeRemoteAddress();
} }
StringBuilder data = new StringBuilder() StringBuilder data = new StringBuilder()
.append(getHandshakeRemoteAddress()) .append(getHandshakeRemoteAddress())
.append('\0') .append('\0')
.append(((InetSocketAddress) proxyPlayer.getRemoteAddress()).getHostString()) .append(((InetSocketAddress) proxyPlayer.remoteAddress()).getHostString())
.append('\0') .append('\0')
.append(proxyPlayer.getGameProfile().getUndashedId()) .append(proxyPlayer.gameProfile().getUndashedId())
.append('\0'); .append('\0');
GENERAL_GSON GENERAL_GSON
.toJson(propertiesTransform.apply(proxyPlayer.getGameProfile().getProperties()), data); .toJson(propertiesTransform.apply(proxyPlayer.gameProfile().getProperties()), data);
return data.toString(); return data.toString();
} }
@ -157,7 +157,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
private void startHandshake() { private void startHandshake() {
final MinecraftConnection mc = ensureConnected(); final MinecraftConnection mc = ensureConnected();
PlayerInfoForwarding forwardingMode = server.getConfiguration().getPlayerInfoForwardingMode(); PlayerInfoForwarding forwardingMode = server.configuration().getPlayerInfoForwardingMode();
// Initiate the handshake. // Initiate the handshake.
ProtocolVersion protocolVersion = proxyPlayer.getConnection().getProtocolVersion(); ProtocolVersion protocolVersion = proxyPlayer.getConnection().getProtocolVersion();
@ -167,7 +167,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
if (forwardingMode == PlayerInfoForwarding.LEGACY) { if (forwardingMode == PlayerInfoForwarding.LEGACY) {
handshake.setServerAddress(createLegacyForwardingAddress()); handshake.setServerAddress(createLegacyForwardingAddress());
} else if (forwardingMode == PlayerInfoForwarding.BUNGEEGUARD) { } else if (forwardingMode == PlayerInfoForwarding.BUNGEEGUARD) {
byte[] secret = server.getConfiguration().getForwardingSecret(); byte[] secret = server.configuration().getForwardingSecret();
handshake.setServerAddress(createBungeeGuardForwardingAddress(secret)); handshake.setServerAddress(createBungeeGuardForwardingAddress(secret));
} else if (proxyPlayer.getConnection().getType() == ConnectionTypes.LEGACY_FORGE) { } else if (proxyPlayer.getConnection().getType() == ConnectionTypes.LEGACY_FORGE) {
handshake.setServerAddress(getHandshakeRemoteAddress() + HANDSHAKE_HOSTNAME_TOKEN); handshake.setServerAddress(getHandshakeRemoteAddress() + HANDSHAKE_HOSTNAME_TOKEN);
@ -175,7 +175,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
handshake.setServerAddress(getHandshakeRemoteAddress()); handshake.setServerAddress(getHandshakeRemoteAddress());
} }
SocketAddress destinationAddr = registeredServer.getServerInfo().getAddress(); SocketAddress destinationAddr = registeredServer.serverInfo().address();
if (destinationAddr instanceof InetSocketAddress) { if (destinationAddr instanceof InetSocketAddress) {
handshake.setPort(((InetSocketAddress) destinationAddr).getPort()); handshake.setPort(((InetSocketAddress) destinationAddr).getPort());
} }
@ -183,7 +183,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
mc.setProtocolVersion(protocolVersion); mc.setProtocolVersion(protocolVersion);
mc.setState(StateRegistry.LOGIN); mc.setState(StateRegistry.LOGIN);
mc.delayedWrite(new ServerboundServerLoginPacket(proxyPlayer.getUsername())); mc.delayedWrite(new ServerboundServerLoginPacket(proxyPlayer.username()));
mc.flush(); mc.flush();
} }
@ -204,17 +204,17 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
} }
@Override @Override
public VelocityRegisteredServer getServer() { public VelocityRegisteredServer target() {
return registeredServer; return registeredServer;
} }
@Override @Override
public ServerInfo getServerInfo() { public ServerInfo serverInfo() {
return registeredServer.getServerInfo(); return registeredServer.serverInfo();
} }
@Override @Override
public ConnectedPlayer getPlayer() { public ConnectedPlayer player() {
return proxyPlayer; return proxyPlayer;
} }
@ -231,8 +231,8 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
@Override @Override
public String toString() { public String toString() {
return "[server connection] " + proxyPlayer.getGameProfile().getName() + " -> " return "[server connection] " + proxyPlayer.gameProfile().getName() + " -> "
+ registeredServer.getServerInfo().getName(); + registeredServer.serverInfo().name();
} }
@Override @Override
@ -252,7 +252,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
MinecraftConnection mc = ensureConnected(); MinecraftConnection mc = ensureConnected();
ServerboundPluginMessagePacket message = new ServerboundPluginMessagePacket(identifier.getId(), data); ServerboundPluginMessagePacket message = new ServerboundPluginMessagePacket(identifier.id(), data);
mc.write(message); mc.write(message);
return true; return true;
} }

Datei anzeigen

@ -25,6 +25,7 @@ import static com.velocitypowered.proxy.network.PluginMessageUtil.constructChann
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.velocitypowered.api.event.command.CommandExecuteEvent.CommandResult; import com.velocitypowered.api.event.command.CommandExecuteEvent.CommandResult;
import com.velocitypowered.api.event.connection.PluginMessageEvent; import com.velocitypowered.api.event.connection.PluginMessageEvent;
import com.velocitypowered.api.event.connection.PluginMessageEventImpl;
import com.velocitypowered.api.event.player.PlayerChannelRegisterEventImpl; import com.velocitypowered.api.event.player.PlayerChannelRegisterEventImpl;
import com.velocitypowered.api.event.player.PlayerChatEvent; import com.velocitypowered.api.event.player.PlayerChatEvent;
import com.velocitypowered.api.event.player.PlayerChatEventImpl; import com.velocitypowered.api.event.player.PlayerChatEventImpl;
@ -104,10 +105,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public void activated() { public void activated() {
Collection<String> channels = server.getChannelRegistrar().getChannelsForProtocol(player Collection<String> channels = server.channelRegistrar().getChannelsForProtocol(player
.getProtocolVersion()); .protocolVersion());
if (!channels.isEmpty()) { if (!channels.isEmpty()) {
AbstractPluginMessagePacket<?> register = constructChannelsPacket(player.getProtocolVersion(), AbstractPluginMessagePacket<?> register = constructChannelsPacket(player.protocolVersion(),
channels, ClientboundPluginMessagePacket.FACTORY); channels, ClientboundPluginMessagePacket.FACTORY);
player.getConnection().write(register); player.getConnection().write(register);
player.getKnownChannels().addAll(channels); player.getKnownChannels().addAll(channels);
@ -157,17 +158,17 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
String msg = packet.getMessage(); String msg = packet.getMessage();
if (msg.startsWith("/")) { if (msg.startsWith("/")) {
String originalCommand = msg.substring(1); String originalCommand = msg.substring(1);
server.getCommandManager().callCommandEvent(player, msg.substring(1)) server.commandManager().callCommandEvent(player, msg.substring(1))
.thenComposeAsync(event -> processCommandExecuteResult(originalCommand, .thenComposeAsync(event -> processCommandExecuteResult(originalCommand,
event.getResult())) event.result()))
.whenComplete((ignored, throwable) -> { .whenComplete((ignored, throwable) -> {
if (server.getConfiguration().isLogCommandExecutions()) { if (server.configuration().isLogCommandExecutions()) {
logger.info("{} -> executed command /{}", player, originalCommand); logger.info("{} -> executed command /{}", player, originalCommand);
} }
}) })
.exceptionally(e -> { .exceptionally(e -> {
logger.info("Exception occurred while running command for {}", logger.info("Exception occurred while running command for {}",
player.getUsername(), e); player.username(), e);
player.sendMessage(Identity.nil(), player.sendMessage(Identity.nil(),
Component.text("An error occurred while running this command.", Component.text("An error occurred while running this command.",
NamedTextColor.RED)); NamedTextColor.RED));
@ -175,11 +176,11 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
}); });
} else { } else {
PlayerChatEvent event = new PlayerChatEventImpl(player, msg); PlayerChatEvent event = new PlayerChatEventImpl(player, msg);
server.getEventManager().fire(event) server.eventManager().fire(event)
.thenAcceptAsync(pme -> { .thenAcceptAsync(pme -> {
PlayerChatEventImpl.ChatResult chatResult = pme.getResult(); PlayerChatEventImpl.ChatResult chatResult = pme.result();
if (chatResult.isAllowed()) { if (chatResult.isAllowed()) {
Optional<String> eventMsg = pme.getResult().getMessage(); Optional<String> eventMsg = pme.result().modifiedMessage();
if (eventMsg.isPresent()) { if (eventMsg.isPresent()) {
smc.write(new ServerboundChatPacket(eventMsg.get())); smc.write(new ServerboundChatPacket(eventMsg.get()));
} else { } else {
@ -225,7 +226,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
channelIdentifiers.add(new LegacyChannelIdentifier(channel)); channelIdentifiers.add(new LegacyChannelIdentifier(channel));
} }
} }
server.getEventManager().fireAndForget(new PlayerChannelRegisterEventImpl(player, server.eventManager().fireAndForget(new PlayerChannelRegisterEventImpl(player,
ImmutableList.copyOf(channelIdentifiers))); ImmutableList.copyOf(channelIdentifiers)));
backendConn.write(packet.retain()); backendConn.write(packet.retain());
} else if (PluginMessageUtil.isUnregister(packet)) { } else if (PluginMessageUtil.isUnregister(packet)) {
@ -233,7 +234,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
backendConn.write(packet.retain()); backendConn.write(packet.retain());
} else if (PluginMessageUtil.isMcBrand(packet)) { } else if (PluginMessageUtil.isMcBrand(packet)) {
backendConn.write(PluginMessageUtil backendConn.write(PluginMessageUtil
.rewriteMinecraftBrand(packet, server.getVersion(), player.getProtocolVersion(), ServerboundPluginMessagePacket.FACTORY)); .rewriteMinecraftBrand(packet, server.version(), player.protocolVersion(), ServerboundPluginMessagePacket.FACTORY));
} else if (BungeeCordMessageResponder.isBungeeCordMessage(packet)) { } else if (BungeeCordMessageResponder.isBungeeCordMessage(packet)) {
return true; return true;
} else { } else {
@ -258,14 +259,14 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
// appropriately. // appropriately.
loginPluginMessages.add(packet.retain()); loginPluginMessages.add(packet.retain());
} else { } else {
ChannelIdentifier id = server.getChannelRegistrar().getFromId(packet.getChannel()); ChannelIdentifier id = server.channelRegistrar().getFromId(packet.getChannel());
if (id == null) { if (id == null) {
backendConn.write(packet.retain()); backendConn.write(packet.retain());
} else { } else {
byte[] copy = ByteBufUtil.getBytes(packet.content()); byte[] copy = ByteBufUtil.getBytes(packet.content());
PluginMessageEvent event = new PluginMessageEvent(player, serverConn, id, copy); PluginMessageEvent event = new PluginMessageEventImpl(player, serverConn, id, copy);
server.getEventManager().fire(event).thenAcceptAsync(pme -> { server.eventManager().fire(event).thenAcceptAsync(pme -> {
if (pme.getResult().isAllowed()) { if (pme.result().isAllowed()) {
ServerboundPluginMessagePacket message = new ServerboundPluginMessagePacket(packet.getChannel(), ServerboundPluginMessagePacket message = new ServerboundPluginMessagePacket(packet.getChannel(),
Unpooled.wrappedBuffer(copy)); Unpooled.wrappedBuffer(copy));
backendConn.write(message); backendConn.write(message);
@ -287,7 +288,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ServerboundResourcePackResponsePacket packet) { public boolean handle(ServerboundResourcePackResponsePacket packet) {
server.getEventManager().fireAndForget(new PlayerResourcePackStatusEventImpl(player, server.eventManager().fireAndForget(new PlayerResourcePackStatusEventImpl(player,
packet.getStatus())); packet.getStatus()));
return false; return false;
} }
@ -330,7 +331,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public void exception(Throwable throwable) { public void exception(Throwable throwable) {
player.disconnect(server.getConfiguration().getMessages().getGenericConnectionError()); player.disconnect(server.configuration().getMessages().getGenericConnectionError());
} }
@Override @Override
@ -371,7 +372,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
player.getPhase().onFirstJoin(player); player.getPhase().onFirstJoin(player);
} else { } else {
// Clear tab list to avoid duplicate entries // Clear tab list to avoid duplicate entries
player.getTabList().clearAll(); player.tabList().clearAll();
if (player.getConnection().getType() == ConnectionTypes.LEGACY_FORGE) { if (player.getConnection().getType() == ConnectionTypes.LEGACY_FORGE) {
this.doSafeClientServerSwitch(joinGame); this.doSafeClientServerSwitch(joinGame);
} else { } else {
@ -403,9 +404,9 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
} }
// Clear any title from the previous server. // Clear any title from the previous server.
if (player.getProtocolVersion().gte(MINECRAFT_1_8)) { if (player.protocolVersion().gte(MINECRAFT_1_8)) {
player.getConnection() player.getConnection()
.delayedWrite(ClientboundTitlePacket.reset(player.getProtocolVersion())); .delayedWrite(ClientboundTitlePacket.reset(player.protocolVersion()));
} }
// Flush everything // Flush everything
@ -424,7 +425,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
// to perform entity ID rewrites, eliminating potential issues from rewriting packets and // to perform entity ID rewrites, eliminating potential issues from rewriting packets and
// improving compatibility with mods. // improving compatibility with mods.
int sentOldDim = joinGame.getDimension(); int sentOldDim = joinGame.getDimension();
if (player.getProtocolVersion().lt(MINECRAFT_1_16)) { if (player.protocolVersion().lt(MINECRAFT_1_16)) {
// Before Minecraft 1.16, we could not switch to the same dimension without sending an // Before Minecraft 1.16, we could not switch to the same dimension without sending an
// additional respawn. On older versions of Minecraft this forces the client to perform // additional respawn. On older versions of Minecraft this forces the client to perform
// garbage collection which adds additional latency. // garbage collection which adds additional latency.
@ -476,8 +477,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
} }
String commandLabel = command.substring(0, commandEndPosition); String commandLabel = command.substring(0, commandEndPosition);
if (!server.getCommandManager().hasCommand(commandLabel)) { if (!server.commandManager().hasCommand(commandLabel)) {
if (player.getProtocolVersion().lt(MINECRAFT_1_13)) { if (player.protocolVersion().lt(MINECRAFT_1_13)) {
// Outstanding tab completes are recorded for use with 1.12 clients and below to provide // Outstanding tab completes are recorded for use with 1.12 clients and below to provide
// additional tab completion support. // additional tab completion support.
outstandingTabComplete = packet; outstandingTabComplete = packet;
@ -485,7 +486,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
return false; return false;
} }
server.getCommandManager().offerSuggestions(player, command) server.commandManager().offerSuggestions(player, command)
.thenAcceptAsync(suggestions -> { .thenAcceptAsync(suggestions -> {
if (suggestions.isEmpty()) { if (suggestions.isEmpty()) {
return; return;
@ -514,7 +515,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
} }
private boolean handleRegularTabComplete(ServerboundTabCompleteRequestPacket packet) { private boolean handleRegularTabComplete(ServerboundTabCompleteRequestPacket packet) {
if (player.getProtocolVersion().lt(MINECRAFT_1_13)) { if (player.protocolVersion().lt(MINECRAFT_1_13)) {
// Outstanding tab completes are recorded for use with 1.12 clients and below to provide // Outstanding tab completes are recorded for use with 1.12 clients and below to provide
// additional tab completion support. // additional tab completion support.
outstandingTabComplete = packet; outstandingTabComplete = packet;
@ -544,9 +545,9 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
private void finishCommandTabComplete(ServerboundTabCompleteRequestPacket request, private void finishCommandTabComplete(ServerboundTabCompleteRequestPacket request,
ClientboundTabCompleteResponsePacket response) { ClientboundTabCompleteResponsePacket response) {
String command = request.getCommand().substring(1); String command = request.getCommand().substring(1);
server.getCommandManager().offerSuggestions(player, command) server.commandManager().offerSuggestions(player, command)
.thenAcceptAsync(offers -> { .thenAcceptAsync(offers -> {
boolean legacy = player.getProtocolVersion().lt(MINECRAFT_1_13); boolean legacy = player.protocolVersion().lt(MINECRAFT_1_13);
try { try {
for (String offer : offers) { for (String offer : offers) {
offer = legacy && !offer.startsWith("/") ? "/" + offer : offer; offer = legacy && !offer.startsWith("/") ? "/" + offer : offer;
@ -559,7 +560,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
player.getConnection().write(response); player.getConnection().write(response);
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to provide tab list completions for {} for command '{}'", logger.error("Unable to provide tab list completions for {} for command '{}'",
player.getUsername(), player.username(),
command, e); command, e);
} }
}, player.getConnection().eventLoop()) }, player.getConnection().eventLoop())
@ -577,10 +578,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
for (Offer offer : response.getOffers()) { for (Offer offer : response.getOffers()) {
offers.add(offer.getText()); offers.add(offer.getText());
} }
server.getEventManager().fire(new TabCompleteEventImpl(player, request.getCommand(), offers)) server.eventManager().fire(new TabCompleteEventImpl(player, request.getCommand(), offers))
.thenAcceptAsync(e -> { .thenAcceptAsync(e -> {
response.getOffers().clear(); response.getOffers().clear();
for (String s : e.getSuggestions()) { for (String s : e.suggestions()) {
response.getOffers().add(new Offer(s)); response.getOffers().add(new Offer(s));
} }
player.getConnection().write(response); player.getConnection().write(response);
@ -600,12 +601,12 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
} }
MinecraftConnection smc = player.ensureAndGetCurrentServer().ensureConnected(); MinecraftConnection smc = player.ensureAndGetCurrentServer().ensureConnected();
String commandToRun = result.getCommand().orElse(originalCommand); String commandToRun = result.modifiedCommand().orElse(originalCommand);
if (result.isForwardToServer()) { if (result.isForwardToServer()) {
return CompletableFuture.runAsync(() -> smc.write(new ServerboundChatPacket("/" return CompletableFuture.runAsync(() -> smc.write(new ServerboundChatPacket("/"
+ commandToRun)), smc.eventLoop()); + commandToRun)), smc.eventLoop());
} else { } else {
return server.getCommandManager().executeImmediately(player, commandToRun) return server.commandManager().executeImmediately(player, commandToRun)
.thenAcceptAsync(hasRun -> { .thenAcceptAsync(hasRun -> {
if (!hasRun) { if (!hasRun) {
smc.write(new ServerboundChatPacket("/" + commandToRun)); smc.write(new ServerboundChatPacket("/" + commandToRun));

Datei anzeigen

@ -17,15 +17,15 @@
package com.velocitypowered.proxy.connection.client; package com.velocitypowered.proxy.connection.client;
import com.velocitypowered.api.proxy.player.PlayerSettings; import com.velocitypowered.api.proxy.player.ClientSettings;
import com.velocitypowered.api.proxy.player.SkinParts; import com.velocitypowered.api.proxy.player.SkinParts;
import com.velocitypowered.proxy.network.packet.serverbound.ServerboundClientSettingsPacket; import com.velocitypowered.proxy.network.packet.serverbound.ServerboundClientSettingsPacket;
import java.util.Locale; import java.util.Locale;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
public class ClientSettingsWrapper implements PlayerSettings { public class ClientSettingsWrapper implements ClientSettings {
static final PlayerSettings DEFAULT = new ClientSettingsWrapper( static final ClientSettings DEFAULT = new ClientSettingsWrapper(
new ServerboundClientSettingsPacket("en_US", (byte) 10, 0, true, (short) 127, 1)); new ServerboundClientSettingsPacket("en_US", (byte) 10, 0, true, (short) 127, 1));
private final ServerboundClientSettingsPacket settings; private final ServerboundClientSettingsPacket settings;

Datei anzeigen

@ -32,8 +32,8 @@ import com.velocitypowered.api.event.player.KickedFromServerEvent.Notify;
import com.velocitypowered.api.event.player.KickedFromServerEvent.RedirectPlayer; import com.velocitypowered.api.event.player.KickedFromServerEvent.RedirectPlayer;
import com.velocitypowered.api.event.player.KickedFromServerEvent.ServerKickResult; import com.velocitypowered.api.event.player.KickedFromServerEvent.ServerKickResult;
import com.velocitypowered.api.event.player.KickedFromServerEventImpl; import com.velocitypowered.api.event.player.KickedFromServerEventImpl;
import com.velocitypowered.api.event.player.PlayerClientSettingsChangedEventImpl;
import com.velocitypowered.api.event.player.PlayerModInfoEventImpl; import com.velocitypowered.api.event.player.PlayerModInfoEventImpl;
import com.velocitypowered.api.event.player.PlayerSettingsChangedEventImpl;
import com.velocitypowered.api.event.player.ServerPreConnectEvent; import com.velocitypowered.api.event.player.ServerPreConnectEvent;
import com.velocitypowered.api.event.player.ServerPreConnectEventImpl; import com.velocitypowered.api.event.player.ServerPreConnectEventImpl;
import com.velocitypowered.api.network.ProtocolVersion; import com.velocitypowered.api.network.ProtocolVersion;
@ -43,8 +43,8 @@ import com.velocitypowered.api.permission.Tristate;
import com.velocitypowered.api.proxy.connection.Player; import com.velocitypowered.api.proxy.connection.Player;
import com.velocitypowered.api.proxy.connection.ServerConnection; import com.velocitypowered.api.proxy.connection.ServerConnection;
import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.player.ClientSettings;
import com.velocitypowered.api.proxy.player.ConnectionRequestBuilder; import com.velocitypowered.api.proxy.player.ConnectionRequestBuilder;
import com.velocitypowered.api.proxy.player.PlayerSettings;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.util.GameProfile; import com.velocitypowered.api.util.GameProfile;
import com.velocitypowered.api.util.ModInfo; import com.velocitypowered.api.util.ModInfo;
@ -122,7 +122,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
private final boolean onlineMode; private final boolean onlineMode;
private @Nullable VelocityServerConnection connectedServer; private @Nullable VelocityServerConnection connectedServer;
private @Nullable VelocityServerConnection connectionInFlight; private @Nullable VelocityServerConnection connectionInFlight;
private @Nullable PlayerSettings settings; private @Nullable ClientSettings settings;
private @Nullable ModInfo modInfo; private @Nullable ModInfo modInfo;
private Component playerListHeader = Component.empty(); private Component playerListHeader = Component.empty();
private Component playerListFooter = Component.empty(); private Component playerListFooter = Component.empty();
@ -157,17 +157,17 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public String getUsername() { public String username() {
return profile.getName(); return profile.getName();
} }
@Override @Override
public UUID getUniqueId() { public UUID id() {
return profile.getId(); return profile.getId();
} }
@Override @Override
public Optional<ServerConnection> getCurrentServer() { public Optional<ServerConnection> connectedServer() {
return Optional.ofNullable(connectedServer); return Optional.ofNullable(connectedServer);
} }
@ -184,7 +184,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public GameProfile getGameProfile() { public GameProfile gameProfile() {
return profile; return profile;
} }
@ -193,7 +193,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public long getPing() { public long ping() {
return this.ping; return this.ping;
} }
@ -202,38 +202,38 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public boolean isOnlineMode() { public boolean onlineMode() {
return onlineMode; return onlineMode;
} }
@Override @Override
public PlayerSettings getPlayerSettings() { public ClientSettings clientSettings() {
return settings == null ? ClientSettingsWrapper.DEFAULT : this.settings; return settings == null ? ClientSettingsWrapper.DEFAULT : this.settings;
} }
void setPlayerSettings(ServerboundClientSettingsPacket settings) { void setPlayerSettings(ServerboundClientSettingsPacket settings) {
ClientSettingsWrapper cs = new ClientSettingsWrapper(settings); ClientSettingsWrapper cs = new ClientSettingsWrapper(settings);
this.settings = cs; this.settings = cs;
server.getEventManager().fireAndForget(new PlayerSettingsChangedEventImpl(this, cs)); server.eventManager().fireAndForget(new PlayerClientSettingsChangedEventImpl(this, cs));
} }
@Override @Override
public Optional<ModInfo> getModInfo() { public Optional<ModInfo> modInfo() {
return Optional.ofNullable(modInfo); return Optional.ofNullable(modInfo);
} }
public void setModInfo(ModInfo modInfo) { public void setModInfo(ModInfo modInfo) {
this.modInfo = modInfo; this.modInfo = modInfo;
server.getEventManager().fireAndForget(new PlayerModInfoEventImpl(this, modInfo)); server.eventManager().fireAndForget(new PlayerModInfoEventImpl(this, modInfo));
} }
@Override @Override
public SocketAddress getRemoteAddress() { public SocketAddress remoteAddress() {
return connection.getRemoteAddress(); return connection.getRemoteAddress();
} }
@Override @Override
public Optional<InetSocketAddress> getVirtualHost() { public Optional<InetSocketAddress> connectedHost() {
return Optional.ofNullable(virtualHost); return Optional.ofNullable(virtualHost);
} }
@ -247,7 +247,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return connection.getProtocolVersion(); return connection.getProtocolVersion();
} }
@ -258,7 +258,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
Preconditions.checkNotNull(type, "type"); Preconditions.checkNotNull(type, "type");
connection.write(new ClientboundChatPacket( connection.write(new ClientboundChatPacket(
ProtocolUtils.getJsonChatSerializer(this.getProtocolVersion()).serialize(message), ProtocolUtils.getJsonChatSerializer(this.protocolVersion()).serialize(message),
type == MessageType.CHAT type == MessageType.CHAT
? ClientboundChatPacket.CHAT_TYPE ? ClientboundChatPacket.CHAT_TYPE
: ClientboundChatPacket.SYSTEM_TYPE, : ClientboundChatPacket.SYSTEM_TYPE,
@ -268,7 +268,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
@Override @Override
public void sendActionBar(net.kyori.adventure.text.@NonNull Component message) { public void sendActionBar(net.kyori.adventure.text.@NonNull Component message) {
ProtocolVersion playerVersion = getProtocolVersion(); ProtocolVersion playerVersion = protocolVersion();
if (playerVersion.gte(ProtocolVersion.MINECRAFT_1_11)) { if (playerVersion.gte(ProtocolVersion.MINECRAFT_1_11)) {
// Use the title packet instead. // Use the title packet instead.
connection.write(new ClientboundTitlePacket( connection.write(new ClientboundTitlePacket(
@ -307,9 +307,9 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
@Override @Override
public void showTitle(net.kyori.adventure.title.@NonNull Title title) { public void showTitle(net.kyori.adventure.title.@NonNull Title title) {
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
GsonComponentSerializer serializer = ProtocolUtils.getJsonChatSerializer(this GsonComponentSerializer serializer = ProtocolUtils.getJsonChatSerializer(this
.getProtocolVersion()); .protocolVersion());
connection.delayedWrite(new ClientboundTitlePacket( connection.delayedWrite(new ClientboundTitlePacket(
ClientboundTitlePacket.SET_TITLE, ClientboundTitlePacket.SET_TITLE,
@ -323,7 +323,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
net.kyori.adventure.title.Title.Times times = title.times(); net.kyori.adventure.title.Title.Times times = title.times();
if (times != null) { if (times != null) {
connection.delayedWrite(ClientboundTitlePacket.times(this.getProtocolVersion(), times)); connection.delayedWrite(ClientboundTitlePacket.times(this.protocolVersion(), times));
} }
connection.flush(); connection.flush();
@ -332,28 +332,28 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
@Override @Override
public void clearTitle() { public void clearTitle() {
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
connection.write(ClientboundTitlePacket.hide(this.getProtocolVersion())); connection.write(ClientboundTitlePacket.hide(this.protocolVersion()));
} }
} }
@Override @Override
public void resetTitle() { public void resetTitle() {
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
connection.write(ClientboundTitlePacket.reset(this.getProtocolVersion())); connection.write(ClientboundTitlePacket.reset(this.protocolVersion()));
} }
} }
@Override @Override
public void hideBossBar(@NonNull BossBar bar) { public void hideBossBar(@NonNull BossBar bar) {
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_9) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_9) >= 0) {
this.server.getBossBarManager().removeBossBar(this, bar); this.server.getBossBarManager().removeBossBar(this, bar);
} }
} }
@Override @Override
public void showBossBar(@NonNull BossBar bar) { public void showBossBar(@NonNull BossBar bar) {
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_9) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_9) >= 0) {
this.server.getBossBarManager().addBossBar(this, bar); this.server.getBossBarManager().addBossBar(this, bar);
} }
} }
@ -369,7 +369,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public VelocityTabList getTabList() { public VelocityTabList tabList() {
return tabList; return tabList;
} }
@ -390,7 +390,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
public void disconnect0(Component reason, boolean duringLogin) { public void disconnect0(Component reason, boolean duringLogin) {
logger.info("{} has disconnected: {}", this, logger.info("{} has disconnected: {}", this,
LegacyComponentSerializer.legacySection().serialize(reason)); LegacyComponentSerializer.legacySection().serialize(reason));
connection.closeWith(ClientboundDisconnectPacket.create(reason, this.getProtocolVersion())); connection.closeWith(ClientboundDisconnectPacket.create(reason, this.protocolVersion()));
} }
public @Nullable VelocityServerConnection getConnectedServer() { public @Nullable VelocityServerConnection getConnectedServer() {
@ -430,13 +430,13 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
} }
String userMessage; String userMessage;
if (connectedServer != null && connectedServer.getServerInfo().equals(server.getServerInfo())) { if (connectedServer != null && connectedServer.serverInfo().equals(server.serverInfo())) {
userMessage = "Your connection to " + server.getServerInfo().getName() + " encountered an " userMessage = "Your connection to " + server.serverInfo().name() + " encountered an "
+ "error."; + "error.";
} else { } else {
logger.error("{}: unable to connect to server {}", this, server.getServerInfo().getName(), logger.error("{}: unable to connect to server {}", this, server.serverInfo().name(),
wrapped); wrapped);
userMessage = "Unable to connect to " + server.getServerInfo().getName() + ". Try again " userMessage = "Unable to connect to " + server.serverInfo().name() + ". Try again "
+ "later."; + "later.";
} }
handleConnectionException(server, null, Component.text(userMessage, handleConnectionException(server, null, Component.text(userMessage,
@ -456,23 +456,23 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
return; return;
} }
VelocityConfiguration.Messages messages = this.server.getConfiguration().getMessages(); VelocityConfiguration.Messages messages = this.server.configuration().getMessages();
Component disconnectReason = GsonComponentSerializer.gson().deserialize(disconnect.getReason()); Component disconnectReason = GsonComponentSerializer.gson().deserialize(disconnect.getReason());
String plainTextReason = PASS_THRU_TRANSLATE.serialize(disconnectReason); String plainTextReason = PASS_THRU_TRANSLATE.serialize(disconnectReason);
if (connectedServer != null && connectedServer.getServerInfo().equals(server.getServerInfo())) { if (connectedServer != null && connectedServer.serverInfo().equals(server.serverInfo())) {
logger.error("{}: kicked from server {}: {}", this, server.getServerInfo().getName(), logger.error("{}: kicked from server {}: {}", this, server.serverInfo().name(),
plainTextReason); plainTextReason);
handleConnectionException(server, disconnectReason, Component.text() handleConnectionException(server, disconnectReason, Component.text()
.append(messages.getKickPrefix(server.getServerInfo().getName()) .append(messages.getKickPrefix(server.serverInfo().name())
.colorIfAbsent(NamedTextColor.RED)) .colorIfAbsent(NamedTextColor.RED))
.color(NamedTextColor.RED) .color(NamedTextColor.RED)
.append(disconnectReason) .append(disconnectReason)
.build(), safe); .build(), safe);
} else { } else {
logger.error("{}: disconnected while connecting to {}: {}", this, logger.error("{}: disconnected while connecting to {}: {}", this,
server.getServerInfo().getName(), plainTextReason); server.serverInfo().name(), plainTextReason);
handleConnectionException(server, disconnectReason, Component.text() handleConnectionException(server, disconnectReason, Component.text()
.append(messages.getDisconnectPrefix(server.getServerInfo().getName()) .append(messages.getDisconnectPrefix(server.serverInfo().name())
.colorIfAbsent(NamedTextColor.RED)) .colorIfAbsent(NamedTextColor.RED))
.append(disconnectReason) .append(disconnectReason)
.build(), safe); .build(), safe);
@ -494,7 +494,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
return; return;
} }
boolean kickedFromCurrent = connectedServer == null || connectedServer.getServer().equals(rs); boolean kickedFromCurrent = connectedServer == null || connectedServer.target().equals(rs);
ServerKickResult result; ServerKickResult result;
if (kickedFromCurrent) { if (kickedFromCurrent) {
Optional<RegisteredServer> next = getNextServerToTry(rs); Optional<RegisteredServer> next = getNextServerToTry(rs);
@ -502,7 +502,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
.orElseGet(() -> DisconnectPlayer.create(friendlyReason)); .orElseGet(() -> DisconnectPlayer.create(friendlyReason));
} else { } else {
// If we were kicked by going to another server, the connection should not be in flight // If we were kicked by going to another server, the connection should not be in flight
if (connectionInFlight != null && connectionInFlight.getServer().equals(rs)) { if (connectionInFlight != null && connectionInFlight.target().equals(rs)) {
resetInFlightConnection(); resetInFlightConnection();
} }
result = Notify.create(friendlyReason); result = Notify.create(friendlyReason);
@ -514,7 +514,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
private void handleKickEvent(KickedFromServerEvent originalEvent, Component friendlyReason, private void handleKickEvent(KickedFromServerEvent originalEvent, Component friendlyReason,
boolean kickedFromCurrent) { boolean kickedFromCurrent) {
server.getEventManager().fire(originalEvent) server.eventManager().fire(originalEvent)
.thenAcceptAsync(event -> { .thenAcceptAsync(event -> {
// There can't be any connection in flight now. // There can't be any connection in flight now.
connectionInFlight = null; connectionInFlight = null;
@ -530,36 +530,36 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
return; return;
} }
if (event.getResult() instanceof DisconnectPlayer) { if (event.result() instanceof DisconnectPlayer) {
DisconnectPlayer res = (DisconnectPlayer) event.getResult(); DisconnectPlayer res = (DisconnectPlayer) event.result();
disconnect(res.getReason()); disconnect(res.message());
} else if (event.getResult() instanceof RedirectPlayer) { } else if (event.result() instanceof RedirectPlayer) {
RedirectPlayer res = (RedirectPlayer) event.getResult(); RedirectPlayer res = (RedirectPlayer) event.result();
createConnectionRequest(res.getServer()) createConnectionRequest(res.getServer())
.connect() .connect()
.whenCompleteAsync((status, throwable) -> { .whenCompleteAsync((status, throwable) -> {
if (throwable != null) { if (throwable != null) {
handleConnectionException(status != null ? status.getAttemptedConnection() handleConnectionException(status != null ? status.finalTarget()
: res.getServer(), throwable, true); : res.getServer(), throwable, true);
return; return;
} }
switch (status.getStatus()) { switch (status.status()) {
// Impossible/nonsensical cases // Impossible/nonsensical cases
case ALREADY_CONNECTED: case ALREADY_CONNECTED:
case CONNECTION_IN_PROGRESS: case CONNECTION_IN_PROGRESS:
// Fatal case // Fatal case
case CONNECTION_CANCELLED: case CONNECTION_CANCELLED:
disconnect(status.getReason().orElse(res.getMessage())); disconnect(status.failureReason().orElse(res.message()));
break; break;
case SERVER_DISCONNECTED: case SERVER_DISCONNECTED:
Component reason = status.getReason() Component reason = status.failureReason()
.orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); .orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
handleConnectionException(res.getServer(), ClientboundDisconnectPacket.create(reason, handleConnectionException(res.getServer(), ClientboundDisconnectPacket.create(reason,
getProtocolVersion()), ((Impl) status).isSafe()); protocolVersion()), ((Impl) status).isSafe());
break; break;
case SUCCESS: case SUCCESS:
sendMessage(Identity.nil(), server.getConfiguration().getMessages() sendMessage(Identity.nil(), server.configuration().getMessages()
.getMovedToNewServerPrefix().append(friendlyReason)); .getMovedToNewServerPrefix().append(friendlyReason));
break; break;
default: default:
@ -567,12 +567,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
break; break;
} }
}, connection.eventLoop()); }, connection.eventLoop());
} else if (event.getResult() instanceof Notify) { } else if (event.result() instanceof Notify) {
Notify res = (Notify) event.getResult(); Notify res = (Notify) event.result();
if (event.kickedDuringServerConnect() && previouslyConnected) { if (event.kickedDuringServerConnect() && previouslyConnected) {
sendMessage(Identity.nil(), res.getMessage()); sendMessage(Identity.nil(), res.message());
} else { } else {
disconnect(res.getMessage()); disconnect(res.message());
} }
} else { } else {
// In case someone gets creative, assume we want to disconnect the player. // In case someone gets creative, assume we want to disconnect the player.
@ -601,31 +601,31 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
*/ */
private Optional<RegisteredServer> getNextServerToTry(@Nullable RegisteredServer current) { private Optional<RegisteredServer> getNextServerToTry(@Nullable RegisteredServer current) {
if (serversToTry == null) { if (serversToTry == null) {
String virtualHostStr = getVirtualHost().map(InetSocketAddress::getHostString).orElse(""); String virtualHostStr = connectedHost().map(InetSocketAddress::getHostString).orElse("");
serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(virtualHostStr, serversToTry = server.configuration().getForcedHosts().getOrDefault(virtualHostStr,
Collections.emptyList()); Collections.emptyList());
} }
if (serversToTry.isEmpty()) { if (serversToTry.isEmpty()) {
serversToTry = server.getConfiguration().getAttemptConnectionOrder(); serversToTry = server.configuration().getAttemptConnectionOrder();
} }
for (int i = tryIndex; i < serversToTry.size(); i++) { for (int i = tryIndex; i < serversToTry.size(); i++) {
String toTryName = serversToTry.get(i); String toTryName = serversToTry.get(i);
if ((connectedServer != null && hasSameName(connectedServer.getServer(), toTryName)) if ((connectedServer != null && hasSameName(connectedServer.target(), toTryName))
|| (connectionInFlight != null && hasSameName(connectionInFlight.getServer(), toTryName)) || (connectionInFlight != null && hasSameName(connectionInFlight.target(), toTryName))
|| (current != null && hasSameName(current, toTryName))) { || (current != null && hasSameName(current, toTryName))) {
continue; continue;
} }
tryIndex = i; tryIndex = i;
return server.getServer(toTryName); return server.server(toTryName);
} }
return Optional.empty(); return Optional.empty();
} }
private static boolean hasSameName(RegisteredServer server, String name) { private static boolean hasSameName(RegisteredServer server, String name) {
return server.getServerInfo().getName().equalsIgnoreCase(name); return server.serverInfo().name().equalsIgnoreCase(name);
} }
/** /**
@ -668,12 +668,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
connectedServer.disconnect(); connectedServer.disconnect();
} }
Optional<Player> connectedPlayer = server.getPlayer(this.getUniqueId()); Optional<Player> connectedPlayer = server.getPlayer(this.id());
server.unregisterConnection(this); server.unregisterConnection(this);
DisconnectEventImpl.LoginStatus status; DisconnectEventImpl.LoginStatus status;
if (connectedPlayer.isPresent()) { if (connectedPlayer.isPresent()) {
if (!connectedPlayer.get().getCurrentServer().isPresent()) { if (!connectedPlayer.get().connectedServer().isPresent()) {
status = LoginStatus.PRE_SERVER_JOIN; status = LoginStatus.PRE_SERVER_JOIN;
} else { } else {
status = connectedPlayer.get() == this ? LoginStatus.SUCCESSFUL_LOGIN status = connectedPlayer.get() == this ? LoginStatus.SUCCESSFUL_LOGIN
@ -685,7 +685,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
DisconnectEvent event = new DisconnectEventImpl(this, status); DisconnectEvent event = new DisconnectEventImpl(this, status);
server.getEventManager().fire(event).whenComplete((val, ex) -> { server.eventManager().fire(event).whenComplete((val, ex) -> {
if (ex == null) { if (ex == null) {
this.teardownFuture.complete(null); this.teardownFuture.complete(null);
} else { } else {
@ -700,19 +700,19 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
@Override @Override
public String toString() { public String toString() {
return "[connected player] " + profile.getName() + " (" + getRemoteAddress() + ")"; return "[connected player] " + profile.getName() + " (" + remoteAddress() + ")";
} }
@Override @Override
public Tristate getPermissionValue(String permission) { public Tristate evaluatePermission(String permission) {
return permissionFunction.getPermissionValue(permission); return permissionFunction.evaluatePermission(permission);
} }
@Override @Override
public boolean sendPluginMessage(ChannelIdentifier identifier, byte[] data) { public boolean sendPluginMessage(ChannelIdentifier identifier, byte[] data) {
Preconditions.checkNotNull(identifier, "identifier"); Preconditions.checkNotNull(identifier, "identifier");
Preconditions.checkNotNull(data, "data"); Preconditions.checkNotNull(data, "data");
ClientboundPluginMessagePacket message = new ClientboundPluginMessagePacket(identifier.getId(), ClientboundPluginMessagePacket message = new ClientboundPluginMessagePacket(identifier.id(),
Unpooled.wrappedBuffer(data)); Unpooled.wrappedBuffer(data));
connection.write(message); connection.write(message);
return true; return true;
@ -730,7 +730,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
public void sendResourcePack(String url) { public void sendResourcePack(String url) {
Preconditions.checkNotNull(url, "url"); Preconditions.checkNotNull(url, "url");
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
connection.write(new ClientboundResourcePackRequestPacket(url, "")); connection.write(new ClientboundResourcePackRequestPacket(url, ""));
} }
} }
@ -741,7 +741,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
Preconditions.checkNotNull(hash, "hash"); Preconditions.checkNotNull(hash, "hash");
Preconditions.checkArgument(hash.length == 20, "Hash length is not 20"); Preconditions.checkArgument(hash.length == 20, "Hash length is not 20");
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
connection.write(new ClientboundResourcePackRequestPacket(url, ByteBufUtil.hexDump(hash))); connection.write(new ClientboundResourcePackRequestPacket(url, ByteBufUtil.hexDump(hash)));
} }
} }
@ -813,7 +813,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
private class IdentityImpl implements Identity { private class IdentityImpl implements Identity {
@Override @Override
public @NonNull UUID uuid() { public @NonNull UUID uuid() {
return ConnectedPlayer.this.getUniqueId(); return ConnectedPlayer.this.id();
} }
} }
@ -826,7 +826,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
} }
@Override @Override
public RegisteredServer getServer() { public RegisteredServer target() {
return toConnect; return toConnect;
} }
@ -837,7 +837,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
&& !connectedServer.hasCompletedJoin())) { && !connectedServer.hasCompletedJoin())) {
return Optional.of(ConnectionRequestBuilder.Status.CONNECTION_IN_PROGRESS); return Optional.of(ConnectionRequestBuilder.Status.CONNECTION_IN_PROGRESS);
} }
if (connectedServer != null && connectedServer.getServer().equals(server)) { if (connectedServer != null && connectedServer.target().equals(server)) {
return Optional.of(ALREADY_CONNECTED); return Optional.of(ALREADY_CONNECTED);
} }
return Optional.empty(); return Optional.empty();
@ -856,9 +856,9 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
ServerPreConnectEvent event = new ServerPreConnectEventImpl(ConnectedPlayer.this, ServerPreConnectEvent event = new ServerPreConnectEventImpl(ConnectedPlayer.this,
toConnect); toConnect);
return server.getEventManager().fire(event) return server.eventManager().fire(event)
.thenComposeAsync(newEvent -> { .thenComposeAsync(newEvent -> {
Optional<RegisteredServer> newDest = newEvent.getResult().getServer(); Optional<RegisteredServer> newDest = newEvent.result().target();
if (!newDest.isPresent()) { if (!newDest.isPresent()) {
return completedFuture( return completedFuture(
plainResult(ConnectionRequestBuilder.Status.CONNECTION_CANCELLED, toConnect) plainResult(ConnectionRequestBuilder.Status.CONNECTION_CANCELLED, toConnect)
@ -895,7 +895,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
.whenCompleteAsync((status, throwable) -> { .whenCompleteAsync((status, throwable) -> {
if (status != null && !status.isSuccessful()) { if (status != null && !status.isSuccessful()) {
if (!status.isSafe()) { if (!status.isSafe()) {
handleConnectionException(status.getAttemptedConnection(), throwable, false); handleConnectionException(status.finalTarget(), throwable, false);
return; return;
} }
} }
@ -912,12 +912,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
.whenCompleteAsync((status, throwable) -> { .whenCompleteAsync((status, throwable) -> {
if (throwable != null) { if (throwable != null) {
// TODO: The exception handling from this is not very good. Find a better way. // TODO: The exception handling from this is not very good. Find a better way.
handleConnectionException(status != null ? status.getAttemptedConnection() handleConnectionException(status != null ? status.finalTarget()
: toConnect, throwable, true); : toConnect, throwable, true);
return; return;
} }
switch (status.getStatus()) { switch (status.status()) {
case ALREADY_CONNECTED: case ALREADY_CONNECTED:
sendMessage(Identity.nil(), ConnectionMessages.ALREADY_CONNECTED); sendMessage(Identity.nil(), ConnectionMessages.ALREADY_CONNECTED);
break; break;
@ -928,10 +928,10 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player {
// Ignored; the plugin probably already handled this. // Ignored; the plugin probably already handled this.
break; break;
case SERVER_DISCONNECTED: case SERVER_DISCONNECTED:
Component reason = status.getReason() Component reason = status.failureReason()
.orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); .orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
handleConnectionException(toConnect, ClientboundDisconnectPacket.create(reason, handleConnectionException(toConnect, ClientboundDisconnectPacket.create(reason,
getProtocolVersion()), status.isSafe()); protocolVersion()), status.isSafe());
break; break;
default: default:
// The only remaining value is successful (no need to do anything!) // The only remaining value is successful (no need to do anything!)

Datei anzeigen

@ -130,13 +130,13 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
// If the proxy is configured for modern forwarding, we must deny connections from 1.12.2 // If the proxy is configured for modern forwarding, we must deny connections from 1.12.2
// and lower, otherwise IP information will never get forwarded. // and lower, otherwise IP information will never get forwarded.
if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN if (server.configuration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN
&& handshake.getProtocolVersion().lt(ProtocolVersion.MINECRAFT_1_13)) { && handshake.getProtocolVersion().lt(ProtocolVersion.MINECRAFT_1_13)) {
ic.disconnectQuietly(Component.text("This server is only compatible with 1.13 and above.")); ic.disconnectQuietly(Component.text("This server is only compatible with 1.13 and above."));
return; return;
} }
server.getEventManager().fireAndForget(new ConnectionHandshakeEventImpl(ic)); server.eventManager().fireAndForget(new ConnectionHandshakeEventImpl(ic));
connection.setSessionHandler(new LoginSessionHandler(server, connection, ic)); connection.setSessionHandler(new LoginSessionHandler(server, connection, ic));
} }
@ -204,12 +204,12 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
} }
@Override @Override
public InetSocketAddress getRemoteAddress() { public InetSocketAddress remoteAddress() {
return (InetSocketAddress) connection.getRemoteAddress(); return (InetSocketAddress) connection.getRemoteAddress();
} }
@Override @Override
public Optional<InetSocketAddress> getVirtualHost() { public Optional<InetSocketAddress> connectedHost() {
return Optional.ofNullable(ping.getVhost()); return Optional.ofNullable(ping.getVhost());
} }
@ -219,7 +219,7 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return ProtocolVersion.LEGACY; return ProtocolVersion.LEGACY;
} }
} }

Datei anzeigen

@ -47,12 +47,12 @@ public final class InitialInboundConnection implements InboundConnection,
} }
@Override @Override
public InetSocketAddress getRemoteAddress() { public InetSocketAddress remoteAddress() {
return (InetSocketAddress) connection.getRemoteAddress(); return (InetSocketAddress) connection.getRemoteAddress();
} }
@Override @Override
public Optional<InetSocketAddress> getVirtualHost() { public Optional<InetSocketAddress> connectedHost() {
return Optional.of(InetSocketAddress.createUnresolved(cleanedAddress, handshake.getPort())); return Optional.of(InetSocketAddress.createUnresolved(cleanedAddress, handshake.getPort()));
} }
@ -62,7 +62,7 @@ public final class InitialInboundConnection implements InboundConnection,
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return connection.getProtocolVersion(); return connection.getProtocolVersion();
} }
@ -78,7 +78,7 @@ public final class InitialInboundConnection implements InboundConnection,
public void disconnect(Component reason) { public void disconnect(Component reason) {
logger.info("{} has disconnected: {}", this, logger.info("{} has disconnected: {}", this,
LegacyComponentSerializer.legacySection().serialize(reason)); LegacyComponentSerializer.legacySection().serialize(reason));
connection.closeWith(ClientboundDisconnectPacket.create(reason, getProtocolVersion())); connection.closeWith(ClientboundDisconnectPacket.create(reason, protocolVersion()));
} }
/** /**
@ -86,6 +86,6 @@ public final class InitialInboundConnection implements InboundConnection,
* @param reason the reason for disconnecting * @param reason the reason for disconnecting
*/ */
public void disconnectQuietly(Component reason) { public void disconnectQuietly(Component reason) {
connection.closeWith(ClientboundDisconnectPacket.create(reason, getProtocolVersion())); connection.closeWith(ClientboundDisconnectPacket.create(reason, protocolVersion()));
} }
} }

Datei anzeigen

@ -123,7 +123,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
String url = String.format(MOJANG_HASJOINED_URL, String url = String.format(MOJANG_HASJOINED_URL,
urlFormParameterEscaper().escape(login.getUsername()), serverId); urlFormParameterEscaper().escape(login.getUsername()), serverId);
if (server.getConfiguration().shouldPreventClientProxyConnections()) { if (server.configuration().shouldPreventClientProxyConnections()) {
url += "&ip=" + urlFormParameterEscaper().escape(playerIp); url += "&ip=" + urlFormParameterEscaper().escape(playerIp);
} }
@ -151,7 +151,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
GameProfile.class), true); GameProfile.class), true);
} else if (profileResponse.getStatusCode() == 204) { } else if (profileResponse.getStatusCode() == 204) {
// Apparently an offline-mode user logged onto this online-mode proxy. // Apparently an offline-mode user logged onto this online-mode proxy.
inbound.disconnect(server.getConfiguration().getMessages().getOnlineModeOnly()); inbound.disconnect(server.configuration().getMessages().getOnlineModeOnly());
} else { } else {
// Something else went wrong // Something else went wrong
logger.error( logger.error(
@ -180,23 +180,23 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
throw new IllegalStateException("No ServerLogin packet received yet."); throw new IllegalStateException("No ServerLogin packet received yet.");
} }
PreLoginEvent event = new PreLoginEventImpl(inbound, login.getUsername()); PreLoginEvent event = new PreLoginEventImpl(inbound, login.getUsername());
server.getEventManager().fire(event) server.eventManager().fire(event)
.thenRunAsync(() -> { .thenRunAsync(() -> {
if (mcConnection.isClosed()) { if (mcConnection.isClosed()) {
// The player was disconnected // The player was disconnected
return; return;
} }
PreLoginComponentResult result = event.getResult(); PreLoginComponentResult result = event.result();
Optional<Component> disconnectReason = result.getReason(); Optional<Component> disconnectReason = result.denialReason();
if (disconnectReason.isPresent()) { if (disconnectReason.isPresent()) {
// The component is guaranteed to be provided if the connection was denied. // The component is guaranteed to be provided if the connection was denied.
mcConnection.closeWith(ClientboundDisconnectPacket.create(disconnectReason.get(), mcConnection.closeWith(ClientboundDisconnectPacket.create(disconnectReason.get(),
inbound.getProtocolVersion())); inbound.protocolVersion()));
return; return;
} }
if (!result.isForceOfflineMode() && (server.getConfiguration().isOnlineMode() || result if (!result.isForceOfflineMode() && (server.configuration().isOnlineMode() || result
.isOnlineModeAllowed())) { .isOnlineModeAllowed())) {
// Request encryption. // Request encryption.
ClientboundEncryptionRequestPacket request = generateEncryptionRequest(); ClientboundEncryptionRequestPacket request = generateEncryptionRequest();
@ -225,29 +225,29 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
private void initializePlayer(GameProfile profile, boolean onlineMode) { private void initializePlayer(GameProfile profile, boolean onlineMode) {
// Some connection types may need to alter the game profile. // Some connection types may need to alter the game profile.
profile = mcConnection.getType().addGameProfileTokensIfRequired(profile, profile = mcConnection.getType().addGameProfileTokensIfRequired(profile,
server.getConfiguration().getPlayerInfoForwardingMode()); server.configuration().getPlayerInfoForwardingMode());
GameProfileRequestEvent profileRequestEvent = new GameProfileRequestEventImpl(inbound, profile, GameProfileRequestEvent profileRequestEvent = new GameProfileRequestEventImpl(inbound, profile,
onlineMode); onlineMode);
final GameProfile finalProfile = profile; final GameProfile finalProfile = profile;
server.getEventManager().fire(profileRequestEvent).thenComposeAsync(profileEvent -> { server.eventManager().fire(profileRequestEvent).thenComposeAsync(profileEvent -> {
if (mcConnection.isClosed()) { if (mcConnection.isClosed()) {
// The player disconnected after we authenticated them. // The player disconnected after we authenticated them.
return CompletableFuture.completedFuture(null); return CompletableFuture.completedFuture(null);
} }
// Initiate a regular connection and move over to it. // Initiate a regular connection and move over to it.
ConnectedPlayer player = new ConnectedPlayer(server, profileEvent.getGameProfile(), ConnectedPlayer player = new ConnectedPlayer(server, profileEvent.gameProfile(),
mcConnection, inbound.getVirtualHost().orElse(null), onlineMode); mcConnection, inbound.connectedHost().orElse(null), onlineMode);
this.connectedPlayer = player; this.connectedPlayer = player;
if (!server.canRegisterConnection(player)) { if (!server.canRegisterConnection(player)) {
player.disconnect0(server.getConfiguration().getMessages().getAlreadyConnected(), true); player.disconnect0(server.configuration().getMessages().getAlreadyConnected(), true);
return CompletableFuture.completedFuture(null); return CompletableFuture.completedFuture(null);
} }
logger.info("{} has connected", player); logger.info("{} has connected", player);
return server.getEventManager() return server.eventManager()
.fire(new PermissionsSetupEventImpl(player, ConnectedPlayer.DEFAULT_PERMISSIONS)) .fire(new PermissionsSetupEventImpl(player, ConnectedPlayer.DEFAULT_PERMISSIONS))
.thenAcceptAsync(event -> { .thenAcceptAsync(event -> {
if (!mcConnection.isClosed()) { if (!mcConnection.isClosed()) {
@ -258,8 +258,8 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
"A plugin permission provider {} provided an invalid permission function" "A plugin permission provider {} provided an invalid permission function"
+ " for player {}. This is a bug in the plugin, not in Velocity. Falling" + " for player {}. This is a bug in the plugin, not in Velocity. Falling"
+ " back to the default permission function.", + " back to the default permission function.",
event.getProvider().getClass().getName(), event.provider().getClass().getName(),
player.getUsername()); player.username());
} else { } else {
player.setPermissionFunction(function); player.setPermissionFunction(function);
} }
@ -273,42 +273,42 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
} }
private void completeLoginProtocolPhaseAndInitialize(ConnectedPlayer player) { private void completeLoginProtocolPhaseAndInitialize(ConnectedPlayer player) {
int threshold = server.getConfiguration().getCompressionThreshold(); int threshold = server.configuration().getCompressionThreshold();
if (threshold >= 0 && mcConnection.getProtocolVersion().gte(MINECRAFT_1_8)) { if (threshold >= 0 && mcConnection.getProtocolVersion().gte(MINECRAFT_1_8)) {
mcConnection.write(new ClientboundSetCompressionPacket(threshold)); mcConnection.write(new ClientboundSetCompressionPacket(threshold));
mcConnection.setCompressionThreshold(threshold); mcConnection.setCompressionThreshold(threshold);
} }
VelocityConfiguration configuration = server.getConfiguration(); VelocityConfiguration configuration = server.configuration();
UUID playerUniqueId = player.getUniqueId(); UUID playerUniqueId = player.id();
if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.NONE) { if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.NONE) {
playerUniqueId = UuidUtils.generateOfflinePlayerUuid(player.getUsername()); playerUniqueId = UuidUtils.generateOfflinePlayerUuid(player.username());
} }
mcConnection.write(new ClientboundServerLoginSuccessPacket(playerUniqueId, player.getUsername())); mcConnection.write(new ClientboundServerLoginSuccessPacket(playerUniqueId, player.username()));
mcConnection.setAssociation(player); mcConnection.setAssociation(player);
mcConnection.setState(StateRegistry.PLAY); mcConnection.setState(StateRegistry.PLAY);
server.getEventManager().fire(new LoginEventImpl(player)) server.eventManager().fire(new LoginEventImpl(player))
.thenAcceptAsync(event -> { .thenAcceptAsync(event -> {
if (mcConnection.isClosed()) { if (mcConnection.isClosed()) {
// The player was disconnected // The player was disconnected
server.getEventManager().fireAndForget(new DisconnectEventImpl(player, server.eventManager().fireAndForget(new DisconnectEventImpl(player,
LoginStatus.CANCELLED_BY_USER_BEFORE_COMPLETE)); LoginStatus.CANCELLED_BY_USER_BEFORE_COMPLETE));
return; return;
} }
Optional<Component> reason = event.getResult().getReason(); Optional<Component> reason = event.result().reason();
if (reason.isPresent()) { if (reason.isPresent()) {
player.disconnect0(reason.get(), true); player.disconnect0(reason.get(), true);
} else { } else {
if (!server.registerConnection(player)) { if (!server.registerConnection(player)) {
player.disconnect0(server.getConfiguration().getMessages() player.disconnect0(server.configuration().getMessages()
.getAlreadyConnected(), true); .getAlreadyConnected(), true);
return; return;
} }
mcConnection.setSessionHandler(new InitialConnectSessionHandler(player)); mcConnection.setSessionHandler(new InitialConnectSessionHandler(player));
server.getEventManager().fire(new PostLoginEventImpl(player)) server.eventManager().fire(new PostLoginEventImpl(player))
.thenCompose((ignored) -> connectToInitialServer(player)) .thenCompose((ignored) -> connectToInitialServer(player))
.exceptionally((ex) -> { .exceptionally((ex) -> {
logger.error("Exception while connecting {} to initial server", player, ex); logger.error("Exception while connecting {} to initial server", player, ex);
@ -327,11 +327,11 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
PlayerChooseInitialServerEvent event = new PlayerChooseInitialServerEventImpl(player, PlayerChooseInitialServerEvent event = new PlayerChooseInitialServerEventImpl(player,
initialFromConfig.orElse(null)); initialFromConfig.orElse(null));
return server.getEventManager().fire(event) return server.eventManager().fire(event)
.thenRunAsync(() -> { .thenRunAsync(() -> {
Optional<RegisteredServer> toTry = event.getInitialServer(); Optional<RegisteredServer> toTry = event.initialServer();
if (!toTry.isPresent()) { if (!toTry.isPresent()) {
player.disconnect0(server.getConfiguration().getMessages() player.disconnect0(server.configuration().getMessages()
.getNoAvailableServers(), true); .getNoAvailableServers(), true);
return; return;
} }

Datei anzeigen

@ -67,18 +67,18 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
@Override @Override
public void activated() { public void activated() {
if (server.getConfiguration().isShowPingRequests()) { if (server.configuration().isShowPingRequests()) {
logger.info("{} is pinging the server with version {}", this.inbound, logger.info("{} is pinging the server with version {}", this.inbound,
this.connection.getProtocolVersion()); this.connection.getProtocolVersion());
} }
} }
private ServerPing constructLocalPing(ProtocolVersion version) { private ServerPing constructLocalPing(ProtocolVersion version) {
VelocityConfiguration configuration = server.getConfiguration(); VelocityConfiguration configuration = server.configuration();
return new ServerPing( return new ServerPing(
new ServerPing.Version(version.getProtocol(), new ServerPing.Version(version.protocol(),
"Velocity " + ProtocolVersion.SUPPORTED_VERSION_STRING), "Velocity " + ProtocolVersion.SUPPORTED_VERSION_STRING),
new ServerPing.Players(server.getPlayerCount(), configuration.getShowMaxPlayers(), new ServerPing.Players(server.countConnectedPlayers(), configuration.getShowMaxPlayers(),
ImmutableList.of()), ImmutableList.of()),
configuration.getMotd(), configuration.getMotd(),
configuration.getFavicon().orElse(null), configuration.getFavicon().orElse(null),
@ -91,7 +91,7 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
ServerPing fallback = constructLocalPing(pingingVersion); ServerPing fallback = constructLocalPing(pingingVersion);
List<CompletableFuture<ServerPing>> pings = new ArrayList<>(); List<CompletableFuture<ServerPing>> pings = new ArrayList<>();
for (String s : servers) { for (String s : servers) {
Optional<RegisteredServer> rs = server.getServer(s); Optional<RegisteredServer> rs = server.server(s);
if (!rs.isPresent()) { if (!rs.isPresent()) {
continue; continue;
} }
@ -123,7 +123,7 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
if (response == fallback) { if (response == fallback) {
continue; continue;
} }
Optional<ModInfo> modInfo = response.getModinfo(); Optional<ModInfo> modInfo = response.modInfo();
if (modInfo.isPresent()) { if (modInfo.isPresent()) {
return fallback.asBuilder().mods(modInfo.get()).build(); return fallback.asBuilder().mods(modInfo.get()).build();
} }
@ -138,16 +138,16 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
continue; continue;
} }
if (response.getDescription() == null) { if (response.description() == null) {
continue; continue;
} }
return new ServerPing( return new ServerPing(
fallback.getVersion(), fallback.version(),
fallback.getPlayers().orElse(null), fallback.players().orElse(null),
response.getDescription(), response.description(),
fallback.getFavicon().orElse(null), fallback.favicon().orElse(null),
response.getModinfo().orElse(null) response.modInfo().orElse(null)
); );
} }
return fallback; return fallback;
@ -159,7 +159,7 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
} }
private CompletableFuture<ServerPing> getInitialPing() { private CompletableFuture<ServerPing> getInitialPing() {
VelocityConfiguration configuration = server.getConfiguration(); VelocityConfiguration configuration = server.configuration();
ProtocolVersion shownVersion = ProtocolVersion.isSupported(connection.getProtocolVersion()) ProtocolVersion shownVersion = ProtocolVersion.isSupported(connection.getProtocolVersion())
? connection.getProtocolVersion() : ProtocolVersion.MAXIMUM_VERSION; ? connection.getProtocolVersion() : ProtocolVersion.MAXIMUM_VERSION;
PingPassthroughMode passthrough = configuration.getPingPassthrough(); PingPassthroughMode passthrough = configuration.getPingPassthrough();
@ -167,10 +167,10 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
if (passthrough == PingPassthroughMode.DISABLED) { if (passthrough == PingPassthroughMode.DISABLED) {
return CompletableFuture.completedFuture(constructLocalPing(shownVersion)); return CompletableFuture.completedFuture(constructLocalPing(shownVersion));
} else { } else {
String virtualHostStr = inbound.getVirtualHost().map(InetSocketAddress::getHostString) String virtualHostStr = inbound.connectedHost().map(InetSocketAddress::getHostString)
.orElse(""); .orElse("");
List<String> serversToTry = server.getConfiguration().getForcedHosts().getOrDefault( List<String> serversToTry = server.configuration().getForcedHosts().getOrDefault(
virtualHostStr, server.getConfiguration().getAttemptConnectionOrder()); virtualHostStr, server.configuration().getAttemptConnectionOrder());
return attemptPingPassthrough(configuration.getPingPassthrough(), serversToTry, shownVersion); return attemptPingPassthrough(configuration.getPingPassthrough(), serversToTry, shownVersion);
} }
} }
@ -182,9 +182,9 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
} }
this.pingReceived = true; this.pingReceived = true;
getInitialPing() getInitialPing()
.thenCompose(ping -> server.getEventManager().fire(new ProxyPingEventImpl(inbound, ping))) .thenCompose(ping -> server.eventManager().fire(new ProxyPingEventImpl(inbound, ping)))
.thenAcceptAsync(event -> connection.closeWith( .thenAcceptAsync(event -> connection.closeWith(
LegacyDisconnectPacket.fromServerPing(event.getPing(), packet.getVersion())), LegacyDisconnectPacket.fromServerPing(event.ping(), packet.getVersion())),
connection.eventLoop()) connection.eventLoop())
.exceptionally((ex) -> { .exceptionally((ex) -> {
logger.error("Exception while handling legacy ping {}", packet, ex); logger.error("Exception while handling legacy ping {}", packet, ex);
@ -207,12 +207,12 @@ public class StatusSessionHandler implements MinecraftSessionHandler {
this.pingReceived = true; this.pingReceived = true;
getInitialPing() getInitialPing()
.thenCompose(ping -> server.getEventManager().fire(new ProxyPingEventImpl(inbound, ping))) .thenCompose(ping -> server.eventManager().fire(new ProxyPingEventImpl(inbound, ping)))
.thenAcceptAsync( .thenAcceptAsync(
(event) -> { (event) -> {
StringBuilder json = new StringBuilder(); StringBuilder json = new StringBuilder();
VelocityServer.getPingGsonInstance(connection.getProtocolVersion()) VelocityServer.getPingGsonInstance(connection.getProtocolVersion())
.toJson(event.getPing(), json); .toJson(event.ping(), json);
connection.write(new ClientboundStatusResponsePacket(json)); connection.write(new ClientboundStatusResponsePacket(json));
}, },
connection.eventLoop()) connection.eventLoop())

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden Mehr anzeigen