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

Start tearing out the prefixes

Dieser Commit ist enthalten in:
Andrew Steinborn 2023-10-27 23:58:13 -04:00
Ursprung 908dd96015
Commit 437c505cd8
149 geänderte Dateien mit 1112 neuen und 1135 gelöschten Zeilen

Datei anzeigen

@ -49,7 +49,7 @@ public final class BrigadierCommand implements Command {
* *
* @return the command node * @return the command node
*/ */
public LiteralCommandNode<CommandSource> getNode() { public LiteralCommandNode<CommandSource> node() {
return node; return node;
} }
} }

Datei anzeigen

@ -24,7 +24,7 @@ public interface CommandManager {
* @param alias the first command alias * @param alias the first command alias
* @return a {@link CommandMeta} builder * @return a {@link CommandMeta} builder
*/ */
CommandMeta.Builder metaBuilder(String alias); CommandMeta.Builder buildMeta(String alias);
/** /**
* Returns a builder to create a {@link CommandMeta} for * Returns a builder to create a {@link CommandMeta} for
@ -33,7 +33,7 @@ public interface CommandManager {
* @param command the command * @param command the command
* @return a {@link CommandMeta} builder * @return a {@link CommandMeta} builder
*/ */
CommandMeta.Builder metaBuilder(BrigadierCommand command); CommandMeta.Builder buildMeta(BrigadierCommand command);
/** /**
* Registers the specified command with the specified aliases. * Registers the specified command with the specified aliases.
@ -46,7 +46,7 @@ public interface CommandManager {
* @see Command for a list of registrable subinterfaces * @see Command for a list of registrable subinterfaces
*/ */
default void register(String alias, Command command, String... otherAliases) { default void register(String alias, Command command, String... otherAliases) {
register(metaBuilder(alias).aliases(otherAliases).build(), command); register(buildMeta(alias).aliases(otherAliases).build(), command);
} }
/** /**
@ -88,7 +88,7 @@ public interface CommandManager {
* @param alias the command alias to lookup * @param alias the command alias to lookup
* @return an {@link CommandMeta} of the alias * @return an {@link CommandMeta} of the alias
*/ */
@Nullable CommandMeta getCommandMeta(String alias); @Nullable CommandMeta commandMeta(String alias);
/** /**
* Attempts to asynchronously execute a command from the given {@code cmdLine}. * Attempts to asynchronously execute a command from the given {@code cmdLine}.
@ -117,7 +117,7 @@ public interface CommandManager {
* *
* @return the registered aliases * @return the registered aliases
*/ */
Collection<String> getAliases(); Collection<String> aliases();
/** /**
* Returns whether the given alias is registered on this manager. * Returns whether the given alias is registered on this manager.

Datei anzeigen

@ -22,7 +22,7 @@ public interface CommandMeta {
* *
* @return the command aliases * @return the command aliases
*/ */
Collection<String> getAliases(); Collection<String> aliases();
/** /**
* Returns an immutable collection containing command nodes that provide * Returns an immutable collection containing command nodes that provide
@ -31,7 +31,7 @@ public interface CommandMeta {
* *
* @return the hinting command nodes * @return the hinting command nodes
*/ */
Collection<CommandNode<CommandSource>> getHints(); Collection<CommandNode<CommandSource>> hints();
/** /**
* Returns the plugin who registered the command. * Returns the plugin who registered the command.
@ -39,7 +39,7 @@ public interface CommandMeta {
* *
* @return the registering plugin * @return the registering plugin
*/ */
@Nullable Object getPlugin(); @Nullable Object plugin();
/** /**
* Provides a fluent interface to create {@link CommandMeta}s. * Provides a fluent interface to create {@link CommandMeta}s.

Datei anzeigen

@ -12,7 +12,11 @@ package com.velocitypowered.api.event;
*/ */
public class PostOrder { public class PostOrder {
public static final short FIRST = -32768; private PostOrder() {
}
public static final short FIRST = -32767;
public static final short EARLY = -16384; public static final short EARLY = -16384;
public static final short NORMAL = 0; public static final short NORMAL = 0;
public static final short LATE = 16834; public static final short LATE = 16834;

Datei anzeigen

@ -8,7 +8,6 @@
package com.velocitypowered.api.event; package com.velocitypowered.api.event;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import java.util.Optional;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -23,7 +22,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.
@ -38,12 +37,12 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
interface Result { interface Result {
/** /**
* Returns whether or not the event is allowed to proceed. Plugins may choose to skip denied * Returns whether the event is allowed to proceed. Plugins may choose to skip denied
* events, and the proxy will respect the result of this method. * events, and the proxy will respect the result of this method.
* *
* @return whether or not the event is allowed to proceed * @return whether the event is allowed to proceed
*/ */
boolean isAllowed(); boolean allowed();
} }
/** /**
@ -61,7 +60,7 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return status; return status;
} }
@ -70,11 +69,11 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
return status ? "allowed" : "denied"; return status ? "allowed" : "denied";
} }
public static GenericResult allowed() { public static GenericResult allow() {
return ALLOWED; return ALLOWED;
} }
public static GenericResult denied() { public static GenericResult deny() {
return DENIED; return DENIED;
} }
} }
@ -87,20 +86,20 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
private static final ComponentResult ALLOWED = new ComponentResult(true, null); private static final ComponentResult ALLOWED = new ComponentResult(true, null);
private final boolean status; private final boolean status;
private final @Nullable Component reason; private final @Nullable Component explanation;
protected ComponentResult(boolean status, @Nullable Component reason) { private ComponentResult(boolean status, @Nullable Component explanation) {
this.status = status; this.status = status;
this.reason = reason; this.explanation = explanation;
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return status; return status;
} }
public Optional<Component> getReasonComponent() { public @Nullable Component explanation() {
return Optional.ofNullable(reason); return explanation;
} }
@Override @Override
@ -108,19 +107,19 @@ public interface ResultedEvent<R extends ResultedEvent.Result> {
if (status) { if (status) {
return "allowed"; return "allowed";
} }
if (reason != null) { if (explanation != null) {
return "denied: " + PlainTextComponentSerializer.plainText().serialize(reason); return "denied: " + PlainTextComponentSerializer.plainText().serialize(explanation);
} }
return "denied"; return "denied";
} }
public static ComponentResult allowed() { public static ComponentResult allow() {
return ALLOWED; return ALLOWED;
} }
public static ComponentResult denied(Component reason) { public static ComponentResult deny(Component explanation) {
Preconditions.checkNotNull(reason, "reason"); Preconditions.checkNotNull(explanation, "explanation");
return new ComponentResult(false, reason); return new ComponentResult(false, explanation);
} }
} }
} }

Datei anzeigen

@ -36,7 +36,7 @@ public final class CommandExecuteEvent implements ResultedEvent<CommandResult> {
public CommandExecuteEvent(CommandSource commandSource, String command) { public CommandExecuteEvent(CommandSource commandSource, String command) {
this.commandSource = Preconditions.checkNotNull(commandSource, "commandSource"); this.commandSource = Preconditions.checkNotNull(commandSource, "commandSource");
this.command = Preconditions.checkNotNull(command, "command"); this.command = Preconditions.checkNotNull(command, "command");
this.result = CommandResult.allowed(); this.result = CommandResult.allow();
} }
public CommandSource getCommandSource() { public CommandSource getCommandSource() {
@ -53,7 +53,7 @@ public final class CommandExecuteEvent implements ResultedEvent<CommandResult> {
} }
@Override @Override
public CommandResult getResult() { public CommandResult result() {
return result; return result;
} }
@ -99,7 +99,7 @@ public final class CommandExecuteEvent implements ResultedEvent<CommandResult> {
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return status; return status;
} }
@ -113,7 +113,7 @@ public final class CommandExecuteEvent implements ResultedEvent<CommandResult> {
* *
* @return the allowed result * @return the allowed result
*/ */
public static CommandResult allowed() { public static CommandResult allow() {
return ALLOWED; return ALLOWED;
} }
@ -122,7 +122,7 @@ public final class CommandExecuteEvent implements ResultedEvent<CommandResult> {
* *
* @return the denied result * @return the denied result
*/ */
public static CommandResult denied() { public static CommandResult deny() {
return DENIED; return DENIED;
} }

Datei anzeigen

@ -12,6 +12,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta; import com.google.common.annotations.Beta;
import com.mojang.brigadier.tree.RootCommandNode; import com.mojang.brigadier.tree.RootCommandNode;
import com.velocitypowered.api.event.annotation.AwaitingEvent; import com.velocitypowered.api.event.annotation.AwaitingEvent;
import com.velocitypowered.api.event.player.PlayerReferentEvent;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
/** /**
@ -22,7 +23,7 @@ import com.velocitypowered.api.proxy.Player;
*/ */
@AwaitingEvent @AwaitingEvent
@Beta @Beta
public class PlayerAvailableCommandsEvent { public class PlayerAvailableCommandsEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final RootCommandNode<?> rootNode; private final RootCommandNode<?> rootNode;
@ -39,7 +40,8 @@ public class PlayerAvailableCommandsEvent {
this.rootNode = checkNotNull(rootNode, "rootNode"); this.rootNode = checkNotNull(rootNode, "rootNode");
} }
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }

Datei anzeigen

@ -23,7 +23,7 @@ public final class ConnectionHandshakeEvent {
this.connection = Preconditions.checkNotNull(connection, "connection"); this.connection = Preconditions.checkNotNull(connection, "connection");
} }
public InboundConnection getConnection() { public InboundConnection connection() {
return connection; return connection;
} }

Datei anzeigen

@ -35,11 +35,11 @@ public final class DisconnectEvent {
this.loginStatus = Preconditions.checkNotNull(loginStatus, "loginStatus"); this.loginStatus = Preconditions.checkNotNull(loginStatus, "loginStatus");
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }
public LoginStatus getLoginStatus() { public LoginStatus loginStatus() {
return loginStatus; return loginStatus;
} }

Datei anzeigen

@ -10,6 +10,7 @@ package com.velocitypowered.api.event.connection;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.velocitypowered.api.event.ResultedEvent; import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.event.annotation.AwaitingEvent; import com.velocitypowered.api.event.annotation.AwaitingEvent;
import com.velocitypowered.api.event.player.PlayerReferentEvent;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
/** /**
@ -19,22 +20,23 @@ import com.velocitypowered.api.proxy.Player;
* process. * process.
*/ */
@AwaitingEvent @AwaitingEvent
public final class LoginEvent implements ResultedEvent<ResultedEvent.ComponentResult> { public final class LoginEvent implements ResultedEvent<ResultedEvent.ComponentResult>,
PlayerReferentEvent {
private final Player player; private final Player player;
private ComponentResult result; private ComponentResult result;
public LoginEvent(Player player) { public LoginEvent(Player player) {
this.player = Preconditions.checkNotNull(player, "player"); this.player = Preconditions.checkNotNull(player, "player");
this.result = ComponentResult.allowed(); this.result = ComponentResult.allow();
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }
@Override @Override
public ComponentResult getResult() { public ComponentResult result() {
return result; return result;
} }

Datei anzeigen

@ -52,7 +52,7 @@ public final class PluginMessageEvent implements ResultedEvent<PluginMessageEven
} }
@Override @Override
public ForwardResult getResult() { public ForwardResult result() {
return result; return result;
} }
@ -61,19 +61,19 @@ public final class PluginMessageEvent implements ResultedEvent<PluginMessageEven
this.result = Preconditions.checkNotNull(result, "result"); this.result = Preconditions.checkNotNull(result, "result");
} }
public ChannelMessageSource getSource() { public ChannelMessageSource source() {
return source; return source;
} }
public ChannelMessageSink getTarget() { public ChannelMessageSink target() {
return target; return target;
} }
public ChannelIdentifier getIdentifier() { public ChannelIdentifier identifier() {
return identifier; return identifier;
} }
public byte[] getData() { public byte[] rawData() {
return Arrays.copyOf(data, data.length); return Arrays.copyOf(data, data.length);
} }
@ -111,7 +111,7 @@ public final class PluginMessageEvent implements ResultedEvent<PluginMessageEven
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return status; return status;
} }

Datei anzeigen

@ -9,6 +9,7 @@ package com.velocitypowered.api.event.connection;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.velocitypowered.api.event.annotation.AwaitingEvent; import com.velocitypowered.api.event.annotation.AwaitingEvent;
import com.velocitypowered.api.event.player.PlayerReferentEvent;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
/** /**
@ -19,7 +20,7 @@ import com.velocitypowered.api.proxy.Player;
* that fires during the login process. * that fires during the login process.
*/ */
@AwaitingEvent @AwaitingEvent
public final class PostLoginEvent { public final class PostLoginEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
@ -27,7 +28,7 @@ public final class PostLoginEvent {
this.player = Preconditions.checkNotNull(player, "player"); this.player = Preconditions.checkNotNull(player, "player");
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }

Datei anzeigen

@ -11,7 +11,7 @@ import com.google.common.base.Preconditions;
import com.velocitypowered.api.event.ResultedEvent; import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.event.annotation.AwaitingEvent; import com.velocitypowered.api.event.annotation.AwaitingEvent;
import com.velocitypowered.api.proxy.InboundConnection; import com.velocitypowered.api.proxy.InboundConnection;
import java.util.Optional; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -44,7 +44,7 @@ public final class PreLoginEvent implements ResultedEvent<PreLoginEvent.PreLogin
public PreLoginEvent(InboundConnection connection, String username) { public PreLoginEvent(InboundConnection connection, String username) {
this.connection = Preconditions.checkNotNull(connection, "connection"); this.connection = Preconditions.checkNotNull(connection, "connection");
this.username = Preconditions.checkNotNull(username, "username"); this.username = Preconditions.checkNotNull(username, "username");
this.result = PreLoginComponentResult.allowed(); this.result = PreLoginComponentResult.allow();
} }
public InboundConnection getConnection() { public InboundConnection getConnection() {
@ -56,7 +56,7 @@ public final class PreLoginEvent implements ResultedEvent<PreLoginEvent.PreLogin
} }
@Override @Override
public PreLoginComponentResult getResult() { public PreLoginComponentResult result() {
return result; return result;
} }
@ -88,7 +88,7 @@ public final class PreLoginEvent implements ResultedEvent<PreLoginEvent.PreLogin
Result.FORCE_OFFLINE, null); Result.FORCE_OFFLINE, null);
private final Result result; private final Result result;
private final net.kyori.adventure.text.Component reason; private final Component reason;
private PreLoginComponentResult(Result result, private PreLoginComponentResult(Result result,
net.kyori.adventure.text.@Nullable Component reason) { net.kyori.adventure.text.@Nullable Component reason) {
@ -97,12 +97,12 @@ public final class PreLoginEvent implements ResultedEvent<PreLoginEvent.PreLogin
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return result != Result.DISALLOWED; return result != Result.DISALLOWED;
} }
public Optional<net.kyori.adventure.text.Component> getReasonComponent() { public @Nullable Component explanation() {
return Optional.ofNullable(reason); return reason;
} }
public boolean isOnlineModeAllowed() { public boolean isOnlineModeAllowed() {
@ -132,14 +132,14 @@ public final class PreLoginEvent implements ResultedEvent<PreLoginEvent.PreLogin
* *
* @return the allowed result * @return the allowed result
*/ */
public static PreLoginComponentResult allowed() { public static PreLoginComponentResult allow() {
return ALLOWED; return ALLOWED;
} }
/** /**
* Returns a result indicating the connection will be allowed through the proxy, but the * Returns a result indicating the connection will be allowed through the proxy, but the
* connection will be forced to use online mode provided that the proxy is in offline mode. This * connection will be forced to use online mode provided that the proxy is in offline mode. This
* acts similarly to {@link #allowed()} on an online-mode proxy. * acts similarly to {@link #allow()} on an online-mode proxy.
* *
* @return the result * @return the result
*/ */
@ -160,12 +160,12 @@ public final class PreLoginEvent implements ResultedEvent<PreLoginEvent.PreLogin
/** /**
* Denies the login with the specified reason. * Denies the login with the specified reason.
* *
* @param reason the reason for disallowing the connection * @param explanation the reason for disallowing the connection
* @return a new result * @return a new result
*/ */
public static PreLoginComponentResult denied(net.kyori.adventure.text.Component reason) { public static PreLoginComponentResult deny(Component explanation) {
Preconditions.checkNotNull(reason, "reason"); Preconditions.checkNotNull(explanation, "explanation");
return new PreLoginComponentResult(Result.DISALLOWED, reason); return new PreLoginComponentResult(Result.DISALLOWED, explanation);
} }
private enum Result { private enum Result {

Datei anzeigen

@ -39,7 +39,7 @@ public final class PermissionsSetupEvent {
this.provider = this.defaultProvider = Preconditions.checkNotNull(provider, "provider"); this.provider = this.defaultProvider = Preconditions.checkNotNull(provider, "provider");
} }
public PermissionSubject getSubject() { public PermissionSubject subject() {
return this.subject; return this.subject;
} }
@ -53,7 +53,7 @@ public final class PermissionsSetupEvent {
return this.provider.createChecker(subject); return this.provider.createChecker(subject);
} }
public PermissionProvider getProvider() { public PermissionProvider provider() {
return this.provider; return this.provider;
} }

Datei anzeigen

@ -44,23 +44,23 @@ public final class GameProfileRequestEvent {
boolean onlineMode) { boolean onlineMode) {
this.connection = Preconditions.checkNotNull(connection, "connection"); this.connection = Preconditions.checkNotNull(connection, "connection");
this.originalProfile = Preconditions.checkNotNull(originalProfile, "originalProfile"); this.originalProfile = Preconditions.checkNotNull(originalProfile, "originalProfile");
this.username = originalProfile.getName(); this.username = originalProfile.name();
this.onlineMode = onlineMode; this.onlineMode = onlineMode;
} }
public InboundConnection getConnection() { public InboundConnection connection() {
return connection; return connection;
} }
public String getUsername() { public String username() {
return username; return username;
} }
public GameProfile getOriginalProfile() { public GameProfile originalProfile() {
return originalProfile; return originalProfile;
} }
public boolean isOnlineMode() { public boolean onlineMode() {
return onlineMode; return onlineMode;
} }
@ -71,7 +71,7 @@ public final class GameProfileRequestEvent {
* *
* @return the user's {@link GameProfile} * @return the user's {@link GameProfile}
*/ */
public GameProfile getGameProfile() { public GameProfile profileToUse() {
return gameProfile == null ? originalProfile : gameProfile; return gameProfile == null ? originalProfile : gameProfile;
} }
@ -80,7 +80,7 @@ public final class GameProfileRequestEvent {
* *
* @param gameProfile the profile for this connection, {@code null} uses the original profile * @param gameProfile the profile for this connection, {@code null} uses the original profile
*/ */
public void setGameProfile(@Nullable GameProfile gameProfile) { public void setProfileToUse(@Nullable GameProfile gameProfile) {
this.gameProfile = gameProfile; this.gameProfile = gameProfile;
} }

Datei anzeigen

@ -12,7 +12,7 @@ import com.velocitypowered.api.event.ResultedEvent;
import com.velocitypowered.api.event.annotation.AwaitingEvent; import com.velocitypowered.api.event.annotation.AwaitingEvent;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.Optional; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -25,11 +25,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/ */
@AwaitingEvent @AwaitingEvent
public final class KickedFromServerEvent implements public final class KickedFromServerEvent implements
ResultedEvent<KickedFromServerEvent.ServerKickResult> { ResultedEvent<KickedFromServerEvent.ServerKickResult>, PlayerReferentEvent {
private final Player player; private final Player player;
private final RegisteredServer server; private final RegisteredServer server;
private final net.kyori.adventure.text.@Nullable Component originalReason; private final @Nullable Component originalReason;
private final boolean duringServerConnect; private final boolean duringServerConnect;
private ServerKickResult result; private ServerKickResult result;
@ -43,8 +43,8 @@ public final class KickedFromServerEvent implements
* @param result the initial result * @param result the initial result
*/ */
public KickedFromServerEvent(Player player, RegisteredServer server, public KickedFromServerEvent(Player player, RegisteredServer server,
net.kyori.adventure.text.@Nullable Component originalReason, @Nullable Component originalReason, boolean duringServerConnect,
boolean duringServerConnect, ServerKickResult result) { ServerKickResult result) {
this.player = Preconditions.checkNotNull(player, "player"); this.player = Preconditions.checkNotNull(player, "player");
this.server = Preconditions.checkNotNull(server, "server"); this.server = Preconditions.checkNotNull(server, "server");
this.originalReason = originalReason; this.originalReason = originalReason;
@ -53,7 +53,7 @@ public final class KickedFromServerEvent implements
} }
@Override @Override
public ServerKickResult getResult() { public ServerKickResult result() {
return result; return result;
} }
@ -62,16 +62,16 @@ public final class KickedFromServerEvent implements
this.result = Preconditions.checkNotNull(result, "result"); this.result = Preconditions.checkNotNull(result, "result");
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }
public RegisteredServer getServer() { public RegisteredServer server() {
return server; return server;
} }
public Optional<net.kyori.adventure.text.Component> getServerKickReason() { public @Nullable Component kickReason() {
return Optional.ofNullable(originalReason); return originalReason;
} }
/** /**
@ -107,18 +107,18 @@ public final class KickedFromServerEvent implements
*/ */
public static final class DisconnectPlayer implements ServerKickResult { public static final class DisconnectPlayer implements ServerKickResult {
private final net.kyori.adventure.text.Component component; private final Component component;
private DisconnectPlayer(net.kyori.adventure.text.Component component) { private DisconnectPlayer(Component component) {
this.component = Preconditions.checkNotNull(component, "component"); this.component = Preconditions.checkNotNull(component, "component");
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return true; return true;
} }
public net.kyori.adventure.text.Component getReasonComponent() { public Component reason() {
return component; return component;
} }
@ -128,7 +128,7 @@ public final class KickedFromServerEvent implements
* @param reason the reason to use when disconnecting the player * @param reason the reason to use when disconnecting the player
* @return the disconnect result * @return the disconnect result
*/ */
public static DisconnectPlayer create(net.kyori.adventure.text.Component reason) { public static DisconnectPlayer disconnect(Component reason) {
return new DisconnectPlayer(reason); return new DisconnectPlayer(reason);
} }
} }
@ -138,17 +138,17 @@ public final class KickedFromServerEvent implements
*/ */
public static final class RedirectPlayer implements ServerKickResult { public static final class RedirectPlayer implements ServerKickResult {
private final net.kyori.adventure.text.Component message; private final Component message;
private final RegisteredServer server; private final RegisteredServer server;
private RedirectPlayer(RegisteredServer server, private RedirectPlayer(RegisteredServer server,
net.kyori.adventure.text.@Nullable Component message) { @Nullable Component message) {
this.server = Preconditions.checkNotNull(server, "server"); this.server = Preconditions.checkNotNull(server, "server");
this.message = message; this.message = message;
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return false; return false;
} }
@ -156,7 +156,7 @@ public final class KickedFromServerEvent implements
return server; return server;
} }
public net.kyori.adventure.text.@Nullable Component getMessageComponent() { public @Nullable Component getMessageComponent() {
return message; return message;
} }
@ -169,8 +169,8 @@ public final class KickedFromServerEvent implements
* @param message the message will be sent to the player after redirecting * @param message the message will be sent to the player after redirecting
* @return the redirect result * @return the redirect result
*/ */
public static RedirectPlayer create(RegisteredServer server, public static RedirectPlayer redirect(RegisteredServer server,
net.kyori.adventure.text.Component message) { Component message) {
return new RedirectPlayer(server, message); return new RedirectPlayer(server, message);
} }
@ -181,7 +181,7 @@ public final class KickedFromServerEvent implements
* @param server the server to send the player to * @param server the server to send the player to
* @return the redirect result * @return the redirect result
*/ */
public static ServerKickResult create(RegisteredServer server) { public static ServerKickResult redirect(RegisteredServer server) {
return new RedirectPlayer(server, null); return new RedirectPlayer(server, null);
} }
} }
@ -193,18 +193,18 @@ public final class KickedFromServerEvent implements
*/ */
public static final class Notify implements ServerKickResult { public static final class Notify implements ServerKickResult {
private final net.kyori.adventure.text.Component message; private final Component message;
private Notify(net.kyori.adventure.text.Component message) { private Notify(Component message) {
this.message = Preconditions.checkNotNull(message, "message"); this.message = Preconditions.checkNotNull(message, "message");
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return false; return false;
} }
public net.kyori.adventure.text.Component getMessageComponent() { public Component reason() {
return message; return message;
} }
@ -214,7 +214,7 @@ public final class KickedFromServerEvent implements
* @param message the server to send the player to * @param message the server to send the player to
* @return the redirect result * @return the redirect result
*/ */
public static Notify create(net.kyori.adventure.text.Component message) { public static Notify notify(Component message) {
return new Notify(message); return new Notify(message);
} }
} }

Datei anzeigen

@ -16,7 +16,7 @@ import java.util.List;
* This event is fired when a client ({@link Player}) sends a plugin message through the * This event is fired when a client ({@link Player}) sends a plugin message through the
* register channel. Velocity will not wait on this event to finish firing. * register channel. Velocity will not wait on this event to finish firing.
*/ */
public final class PlayerChannelRegisterEvent { public final class PlayerChannelRegisterEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final List<ChannelIdentifier> channels; private final List<ChannelIdentifier> channels;
@ -26,11 +26,11 @@ public final class PlayerChannelRegisterEvent {
this.channels = Preconditions.checkNotNull(channels, "channels"); this.channels = Preconditions.checkNotNull(channels, "channels");
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }
public List<ChannelIdentifier> getChannels() { public List<ChannelIdentifier> channels() {
return channels; return channels;
} }

Datei anzeigen

@ -20,7 +20,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* to finish firing before forwarding it to the server, if the result allows it. * to finish firing before forwarding it to the server, if the result allows it.
*/ */
@AwaitingEvent @AwaitingEvent
public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.ChatResult> { public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.ChatResult>,
PlayerReferentEvent {
private final Player player; private final Player player;
private final String message; private final String message;
@ -35,19 +36,19 @@ public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.Chat
public PlayerChatEvent(Player player, String message) { public PlayerChatEvent(Player player, String message) {
this.player = Preconditions.checkNotNull(player, "player"); this.player = Preconditions.checkNotNull(player, "player");
this.message = Preconditions.checkNotNull(message, "message"); this.message = Preconditions.checkNotNull(message, "message");
this.result = ChatResult.allowed(); this.result = ChatResult.allow();
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }
public String getMessage() { public String message() {
return message; return message;
} }
@Override @Override
public ChatResult getResult() { public ChatResult result() {
return result; return result;
} }
@ -81,12 +82,12 @@ public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.Chat
this.message = message; this.message = message;
} }
public Optional<String> getMessage() { public Optional<String> modifiedMessage() {
return Optional.ofNullable(message); return Optional.ofNullable(message);
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return status; return status;
} }
@ -100,7 +101,7 @@ public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.Chat
* *
* @return the allowed result * @return the allowed result
*/ */
public static ChatResult allowed() { public static ChatResult allow() {
return ALLOWED; return ALLOWED;
} }
@ -109,7 +110,7 @@ public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.Chat
* *
* @return the denied result * @return the denied result
*/ */
public static ChatResult denied() { public static ChatResult deny() {
return DENIED; return DENIED;
} }
@ -119,7 +120,7 @@ public final class PlayerChatEvent implements ResultedEvent<PlayerChatEvent.Chat
* @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 modify(@NonNull String message) {
Preconditions.checkNotNull(message, "message"); Preconditions.checkNotNull(message, "message");
return new ChatResult(true, message); return new ChatResult(true, message);
} }

Datei anzeigen

@ -21,7 +21,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* {@link KickedFromServerEvent} as normal. * {@link KickedFromServerEvent} as normal.
*/ */
@AwaitingEvent @AwaitingEvent
public class PlayerChooseInitialServerEvent { public class PlayerChooseInitialServerEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private @Nullable RegisteredServer initialServer; private @Nullable RegisteredServer initialServer;
@ -37,7 +37,8 @@ public class PlayerChooseInitialServerEvent {
this.initialServer = initialServer; this.initialServer = initialServer;
} }
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }

Datei anzeigen

@ -14,7 +14,7 @@ import com.velocitypowered.api.proxy.Player;
* Fired when a {@link Player} sends the <code>minecraft:brand</code> plugin message. Velocity will * Fired when a {@link Player} sends the <code>minecraft:brand</code> plugin message. Velocity will
* not wait on the result of this event. * not wait on the result of this event.
*/ */
public final class PlayerClientBrandEvent { public final class PlayerClientBrandEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final String brand; private final String brand;
@ -29,7 +29,8 @@ public final class PlayerClientBrandEvent {
this.brand = Preconditions.checkNotNull(brand); this.brand = Preconditions.checkNotNull(brand);
} }
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }

Datei anzeigen

@ -16,7 +16,7 @@ import com.velocitypowered.api.util.ModInfo;
* This event is fired when a Forge client sends its mods to the proxy while connecting to a server. * This event is fired when a Forge client sends its mods to the proxy while connecting to a server.
* Velocity will not wait on this event to finish firing. * Velocity will not wait on this event to finish firing.
*/ */
public final class PlayerModInfoEvent { public final class PlayerModInfoEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final ModInfo modInfo; private final ModInfo modInfo;
@ -26,11 +26,12 @@ public final class PlayerModInfoEvent {
this.modInfo = Preconditions.checkNotNull(modInfo, "modInfo"); this.modInfo = Preconditions.checkNotNull(modInfo, "modInfo");
} }
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }
public ModInfo getModInfo() { public ModInfo modInfo() {
return modInfo; return modInfo;
} }

Datei anzeigen

@ -0,0 +1,18 @@
/*
* Copyright (C) 2023 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.player;
import com.velocitypowered.api.proxy.Player;
/**
* Defines any event that refers to a player.
*/
public interface PlayerReferentEvent {
Player player();
}

Datei anzeigen

@ -21,26 +21,13 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* the player may be kicked from the server. * the player may be kicked from the server.
*/ */
@AwaitingEvent @AwaitingEvent
public class PlayerResourcePackStatusEvent { public class PlayerResourcePackStatusEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final Status status; private final Status status;
private final @MonotonicNonNull ResourcePackInfo packInfo; private final @MonotonicNonNull ResourcePackInfo packInfo;
private boolean overwriteKick; private boolean overwriteKick;
/**
* Instantiates this event.
*
* @deprecated Use {@link PlayerResourcePackStatusEvent#PlayerResourcePackStatusEvent
* (Player, Status, ResourcePackInfo)} instead.
*/
@Deprecated
public PlayerResourcePackStatusEvent(Player player, Status status) {
this.player = Preconditions.checkNotNull(player, "player");
this.status = Preconditions.checkNotNull(status, "status");
this.packInfo = null;
}
/** /**
* Instantiates this event. * Instantiates this event.
*/ */
@ -55,7 +42,8 @@ public class PlayerResourcePackStatusEvent {
* *
* @return the player * @return the player
*/ */
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }
@ -80,7 +68,7 @@ public class PlayerResourcePackStatusEvent {
/** /**
* Gets whether or not to override the kick resulting from * Gets whether or not to override the kick resulting from
* {@link ResourcePackInfo#getShouldForce()} being true. * {@link ResourcePackInfo#required()} being true.
* *
* @return whether or not to overwrite the result * @return whether or not to overwrite the result
*/ */
@ -89,7 +77,7 @@ public class PlayerResourcePackStatusEvent {
} }
/** /**
* Set to true to prevent {@link ResourcePackInfo#getShouldForce()} * Set to true to prevent {@link ResourcePackInfo#required()}
* from kicking the player. * from kicking the player.
* Overwriting this kick is only possible on versions older than 1.17, * Overwriting this kick is only possible on versions older than 1.17,
* as the client or server will enforce this regardless. Cancelling the resulting * as the client or server will enforce this regardless. Cancelling the resulting
@ -99,7 +87,7 @@ public class PlayerResourcePackStatusEvent {
* @throws IllegalArgumentException if the player version is 1.17 or newer * @throws IllegalArgumentException if the player version is 1.17 or newer
*/ */
public void setOverwriteKick(boolean overwriteKick) { public void setOverwriteKick(boolean overwriteKick) {
Preconditions.checkArgument(player.getProtocolVersion() Preconditions.checkArgument(player.protocolVersion()
.compareTo(ProtocolVersion.MINECRAFT_1_17) < 0, .compareTo(ProtocolVersion.MINECRAFT_1_17) < 0,
"overwriteKick is not supported on 1.17 or newer"); "overwriteKick is not supported on 1.17 or newer");
this.overwriteKick = overwriteKick; this.overwriteKick = overwriteKick;

Datei anzeigen

@ -17,7 +17,7 @@ import com.velocitypowered.api.proxy.player.PlayerSettings;
* and typically will be fired multiple times per connection. Velocity will not wait on this event * and typically will be fired multiple times per connection. Velocity will not wait on this event
* to finish firing. * to finish firing.
*/ */
public final class PlayerSettingsChangedEvent { public final class PlayerSettingsChangedEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final PlayerSettings playerSettings; private final PlayerSettings playerSettings;
@ -27,7 +27,8 @@ public final class PlayerSettingsChangedEvent {
this.playerSettings = Preconditions.checkNotNull(playerSettings, "playerSettings"); this.playerSettings = Preconditions.checkNotNull(playerSettings, "playerSettings");
} }
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }

Datei anzeigen

@ -11,7 +11,6 @@ import com.google.common.base.Preconditions;
import com.velocitypowered.api.event.annotation.AwaitingEvent; import com.velocitypowered.api.event.annotation.AwaitingEvent;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.Optional;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
@ -25,7 +24,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* </p> * </p>
*/ */
@AwaitingEvent @AwaitingEvent
public final class ServerConnectedEvent { public final class ServerConnectedEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final RegisteredServer server; private final RegisteredServer server;
@ -45,16 +44,16 @@ public final class ServerConnectedEvent {
this.previousServer = previousServer; this.previousServer = previousServer;
} }
public Player getPlayer() { public Player player() {
return player; return player;
} }
public RegisteredServer getServer() { public RegisteredServer newServer() {
return server; return server;
} }
public Optional<RegisteredServer> getPreviousServer() { public @Nullable RegisteredServer previousServer() {
return Optional.ofNullable(previousServer); return previousServer;
} }
@Override @Override

Datei anzeigen

@ -54,7 +54,7 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
} }
@Override @Override
public ResponseResult getResult() { public ResponseResult result() {
return this.result; return this.result;
} }
@ -63,11 +63,11 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
this.result = checkNotNull(result, "result"); this.result = checkNotNull(result, "result");
} }
public ServerConnection getConnection() { public ServerConnection connection() {
return connection; return connection;
} }
public ChannelIdentifier getIdentifier() { public ChannelIdentifier identifier() {
return identifier; return identifier;
} }
@ -76,7 +76,7 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
* *
* @return the contents of the message * @return the contents of the message
*/ */
public byte[] getContents() { public byte[] rawData() {
return contents.clone(); return contents.clone();
} }
@ -86,7 +86,7 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
* *
* @return the contents of the message as a stream * @return the contents of the message as a stream
*/ */
public ByteArrayInputStream contentsAsInputStream() { public ByteArrayInputStream dataAsInputStream() {
return new ByteArrayInputStream(contents); return new ByteArrayInputStream(contents);
} }
@ -96,11 +96,11 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
* *
* @return the contents of the message as a {@link java.io.DataInput} * @return the contents of the message as a {@link java.io.DataInput}
*/ */
public ByteArrayDataInput contentsAsDataStream() { public ByteArrayDataInput dataAsDataInput() {
return ByteStreams.newDataInput(contents); return ByteStreams.newDataInput(contents);
} }
public int getSequenceId() { public int sequenceId() {
return sequenceId; return sequenceId;
} }
@ -129,7 +129,7 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return response != null; return response != null;
} }
@ -139,7 +139,7 @@ public class ServerLoginPluginMessageEvent implements ResultedEvent<ResponseResu
* @return the response to the message * @return the response to the message
* @throws IllegalStateException if there is no reply (an unknown message) * @throws IllegalStateException if there is no reply (an unknown message)
*/ */
public byte[] getResponse() { public byte[] response() {
if (response == null) { if (response == null) {
throw new IllegalStateException("Fetching response of unknown message result"); throw new IllegalStateException("Fetching response of unknown message result");
} }

Datei anzeigen

@ -7,7 +7,6 @@
package com.velocitypowered.api.event.player; package com.velocitypowered.api.event.player;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
@ -15,11 +14,10 @@ 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()}. Velocity will not wait on this event to finish * available in {@link Player#connectedServer()}. Velocity will not wait on this event to finish
* firing. * firing.
*/ */
@Beta public class ServerPostConnectEvent implements PlayerReferentEvent {
public class ServerPostConnectEvent {
private final Player player; private final Player player;
private final RegisteredServer previousServer; private final RegisteredServer previousServer;
@ -34,7 +32,7 @@ public class ServerPostConnectEvent {
* *
* @return the player * @return the player
*/ */
public Player getPlayer() { public Player player() {
return player; return player;
} }
@ -44,7 +42,7 @@ public class ServerPostConnectEvent {
* *
* @return the previous server the player was connected to * @return the previous server the player was connected to
*/ */
public @Nullable RegisteredServer getPreviousServer() { public @Nullable RegisteredServer previousServer() {
return previousServer; return previousServer;
} }

Datei anzeigen

@ -24,7 +24,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/ */
@AwaitingEvent @AwaitingEvent
public final class ServerPreConnectEvent implements public final class ServerPreConnectEvent implements
ResultedEvent<ServerPreConnectEvent.ServerResult> { ResultedEvent<ServerPreConnectEvent.ServerResult>, PlayerReferentEvent {
private final Player player; private final Player player;
private final RegisteredServer originalServer; private final RegisteredServer originalServer;
@ -39,7 +39,7 @@ public final class ServerPreConnectEvent implements
*/ */
public ServerPreConnectEvent(Player player, RegisteredServer originalServer) { public ServerPreConnectEvent(Player player, RegisteredServer originalServer) {
this(player, originalServer, this(player, originalServer,
player.getCurrentServer().map(ServerConnection::getServer).orElse(null)); player.connectedServer().map(ServerConnection::server).orElse(null));
} }
/** /**
@ -54,7 +54,7 @@ public final class ServerPreConnectEvent implements
this.player = Preconditions.checkNotNull(player, "player"); this.player = Preconditions.checkNotNull(player, "player");
this.originalServer = Preconditions.checkNotNull(originalServer, "originalServer"); this.originalServer = Preconditions.checkNotNull(originalServer, "originalServer");
this.previousServer = previousServer; this.previousServer = previousServer;
this.result = ServerResult.allowed(originalServer); this.result = ServerResult.connectTo(originalServer);
} }
/** /**
@ -62,12 +62,13 @@ public final class ServerPreConnectEvent implements
* *
* @return the player connecting to the server * @return the player connecting to the server
*/ */
public Player getPlayer() { @Override
public Player player() {
return player; return player;
} }
@Override @Override
public ServerResult getResult() { public ServerResult result() {
return result; return result;
} }
@ -89,7 +90,7 @@ public final class ServerPreConnectEvent implements
/** /**
* Returns the server that the player is currently connected to. Prefer this method over using * Returns the server that the player is currently connected to. Prefer this method over using
* {@link Player#getCurrentServer()} as the current server might get reset after server kicks to * {@link Player#connectedServer()} as the current server might get reset after server kicks to
* prevent connection issues. This is {@code null} if they were not connected to another server * prevent connection issues. This is {@code null} if they were not connected to another server
* beforehand (for instance, if the player has just joined the proxy). * beforehand (for instance, if the player has just joined the proxy).
* *
@ -122,7 +123,7 @@ public final class ServerPreConnectEvent implements
} }
@Override @Override
public boolean isAllowed() { public boolean allowed() {
return server != null; return server != null;
} }
@ -133,7 +134,7 @@ public final class ServerPreConnectEvent implements
@Override @Override
public String toString() { public String toString() {
if (server != null) { if (server != null) {
return "allowed: connect to " + server.getServerInfo().getName(); return "allowed: connect to " + server.serverInfo().name();
} }
return "denied"; return "denied";
} }
@ -145,7 +146,7 @@ public final class ServerPreConnectEvent implements
* *
* @return a result to deny conneections * @return a result to deny conneections
*/ */
public static ServerResult denied() { public static ServerResult deny() {
return DENIED; return DENIED;
} }
@ -155,7 +156,7 @@ public final class ServerPreConnectEvent implements
* @param server the new server to connect to * @param server 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 connectTo(RegisteredServer server) {
Preconditions.checkNotNull(server, "server"); Preconditions.checkNotNull(server, "server");
return new ServerResult(server); return new ServerResult(server);
} }

Datei anzeigen

@ -36,21 +36,21 @@ public class ServerResourcePackSendEvent implements ResultedEvent<ResultedEvent.
ResourcePackInfo receivedResourcePack, ResourcePackInfo receivedResourcePack,
ServerConnection serverConnection ServerConnection serverConnection
) { ) {
this.result = ResultedEvent.GenericResult.allowed(); this.result = ResultedEvent.GenericResult.allow();
this.receivedResourcePack = receivedResourcePack; this.receivedResourcePack = receivedResourcePack;
this.serverConnection = serverConnection; this.serverConnection = serverConnection;
this.providedResourcePack = receivedResourcePack; this.providedResourcePack = receivedResourcePack;
} }
public ServerConnection getServerConnection() { public ServerConnection connection() {
return serverConnection; return serverConnection;
} }
public ResourcePackInfo getReceivedResourcePack() { public ResourcePackInfo receivedResourcePack() {
return receivedResourcePack; return receivedResourcePack;
} }
public ResourcePackInfo getProvidedResourcePack() { public ResourcePackInfo providedResourcePack() {
return providedResourcePack; return providedResourcePack;
} }
@ -59,7 +59,7 @@ public class ServerResourcePackSendEvent implements ResultedEvent<ResultedEvent.
} }
@Override @Override
public GenericResult getResult() { public GenericResult result() {
return this.result; return this.result;
} }

Datei anzeigen

@ -22,7 +22,7 @@ import java.util.List;
* the tab complete results. * the tab complete results.
*/ */
@AwaitingEvent @AwaitingEvent
public class TabCompleteEvent { public class TabCompleteEvent implements PlayerReferentEvent {
private final Player player; private final Player player;
private final String partialMessage; private final String partialMessage;
private final List<String> suggestions; private final List<String> suggestions;
@ -45,7 +45,7 @@ public class TabCompleteEvent {
* *
* @return the requesting player * @return the requesting player
*/ */
public Player getPlayer() { public Player player() {
return player; return player;
} }
@ -54,7 +54,7 @@ public class TabCompleteEvent {
* *
* @return the partial message * @return the partial message
*/ */
public String getPartialMessage() { public String partialMessage() {
return partialMessage; return partialMessage;
} }
@ -63,7 +63,7 @@ public class TabCompleteEvent {
* *
* @return the suggestions * @return the suggestions
*/ */
public List<String> getSuggestions() { public List<String> suggestions() {
return suggestions; return suggestions;
} }

Datei anzeigen

@ -24,11 +24,11 @@ public final class ListenerBoundEvent {
this.listenerType = Preconditions.checkNotNull(listenerType, "listenerType"); this.listenerType = Preconditions.checkNotNull(listenerType, "listenerType");
} }
public SocketAddress getAddress() { public SocketAddress address() {
return address; return address;
} }
public ListenerType getListenerType() { public ListenerType listenerType() {
return listenerType; return listenerType;
} }

Datei anzeigen

@ -24,11 +24,11 @@ public final class ListenerCloseEvent {
this.listenerType = Preconditions.checkNotNull(listenerType, "listenerType"); this.listenerType = Preconditions.checkNotNull(listenerType, "listenerType");
} }
public SocketAddress getAddress() { public SocketAddress address() {
return address; return address;
} }
public ListenerType getListenerType() { public ListenerType listenerType() {
return listenerType; return listenerType;
} }

Datei anzeigen

@ -30,11 +30,11 @@ public final class ProxyPingEvent {
this.ping = Preconditions.checkNotNull(ping, "ping"); this.ping = Preconditions.checkNotNull(ping, "ping");
} }
public InboundConnection getConnection() { public InboundConnection connection() {
return connection; return connection;
} }
public ServerPing getPing() { public ServerPing ping() {
return ping; return ping;
} }

Datei anzeigen

@ -41,7 +41,7 @@ public final class ProxyQueryEvent {
* *
* @return query type * @return query type
*/ */
public QueryType getQueryType() { public QueryType queryType() {
return queryType; return queryType;
} }
@ -50,7 +50,7 @@ public final class ProxyQueryEvent {
* *
* @return querier address * @return querier address
*/ */
public InetAddress getQuerierAddress() { public InetAddress remoteAddress() {
return querierAddress; return querierAddress;
} }
@ -59,7 +59,7 @@ public final class ProxyQueryEvent {
* *
* @return the current query response * @return the current query response
*/ */
public QueryResponse getResponse() { public QueryResponse response() {
return response; return response;
} }

Datei anzeigen

@ -22,7 +22,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 this.getPermissionChecker().test(permission); return this.permissionChecker().test(permission);
} }
/** /**
@ -32,7 +32,7 @@ public interface PermissionSubject {
* @return the value the permission is set to * @return the value the permission is set to
*/ */
default TriState getPermissionValue(String permission) { default TriState getPermissionValue(String permission) {
return this.getPermissionChecker().value(permission); return this.permissionChecker().value(permission);
} }
/** /**
@ -40,5 +40,5 @@ public interface PermissionSubject {
* *
* @return subject's permission checker * @return subject's permission checker
*/ */
PermissionChecker getPermissionChecker(); PermissionChecker permissionChecker();
} }

Datei anzeigen

@ -20,14 +20,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();
} }
@ -37,5 +37,5 @@ public interface PluginContainer {
* *
* @return an {@link ExecutorService} associated with this plugin * @return an {@link ExecutorService} associated with this plugin
*/ */
ExecutorService getExecutorService(); ExecutorService executorService();
} }

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,11 +92,11 @@ 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();
} }
default Optional<PluginDependency> getDependency(String id) { default Optional<PluginDependency> dependency(String id) {
return Optional.empty(); return Optional.empty();
} }

Datei anzeigen

@ -32,14 +32,14 @@ public interface PluginManager {
* @param id the plugin ID * @param id the plugin ID
* @return the plugin, if available * @return the plugin, if available
*/ */
Optional<PluginContainer> getPlugin(String id); Optional<PluginContainer> plugin(String id);
/** /**
* Gets a {@link Collection} of all {@link PluginContainer}s. * Gets a {@link Collection} of all {@link PluginContainer}s.
* *
* @return the plugins * @return the plugins
*/ */
Collection<PluginContainer> getPlugins(); Collection<PluginContainer> plugins();
/** /**
* Checks if a plugin is loaded based on its ID. * Checks if a plugin is loaded based on its ID.

Datei anzeigen

@ -44,7 +44,7 @@ public final class PluginDependency {
* *
* @return the plugin ID * @return the plugin ID
*/ */
public String getId() { public String id() {
return id; return id;
} }
@ -53,7 +53,7 @@ public final class PluginDependency {
* *
* @return an {@link Optional} with the plugin version, may be empty * @return an {@link Optional} with the plugin version, may be empty
*/ */
public Optional<String> getVersion() { public Optional<String> version() {
return Optional.ofNullable(version); return Optional.ofNullable(version);
} }
@ -62,7 +62,7 @@ public final class PluginDependency {
* *
* @return true if dependency is optional * @return true if dependency is optional
*/ */
public boolean isOptional() { public boolean optional() {
return optional; return optional;
} }

Datei anzeigen

@ -10,6 +10,7 @@ package com.velocitypowered.api.proxy;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import net.kyori.adventure.text.Component;
/** /**
* Provides a fluent interface to send a connection request to another server on the proxy. A * Provides a fluent interface to send a connection request to another server on the proxy. A
@ -22,7 +23,7 @@ public interface ConnectionRequestBuilder {
* *
* @return the server this request will connect to * @return the server this request will connect to
*/ */
RegisteredServer getServer(); RegisteredServer server();
/** /**
* 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
@ -59,7 +60,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;
} }
/** /**
@ -67,21 +68,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<net.kyori.adventure.text.Component> getReasonComponent(); Optional<Component> reason();
/** /**
* 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 attemptedConnectedTo();
} }
/** /**

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> virtualHost();
/** /**
* 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

@ -47,17 +47,17 @@ public interface Player extends
* *
* @return the username * @return the username
*/ */
String getUsername(); String username();
/** /**
* Returns the locale the proxy will use to send messages translated via the Adventure global * Returns the locale the proxy will use to send messages translated via the Adventure global
* translator. By default, the value of {@link PlayerSettings#getLocale()} is used. * translator. By default, the value of {@link PlayerSettings#locale()} is used.
* *
* <p>This can be {@code null} when the client has not yet connected to any server.</p> * <p>This can be {@code null} when the client has not yet connected to any server.</p>
* *
* @return the locale. * @return the locale.
*/ */
@Nullable Locale getEffectiveLocale(); @Nullable Locale effectiveLocale();
/** /**
* Change the locale the proxy will be translating its messages to. * Change the locale the proxy will be translating its messages to.
@ -71,21 +71,21 @@ public interface Player extends
* *
* @return the UUID * @return the UUID
*/ */
UUID getUniqueId(); UUID uuid();
/** /**
* 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(); PlayerSettings settings();
/** /**
* Returns whether the player has sent its client settings. * Returns whether the player has sent its client settings.
@ -99,14 +99,14 @@ public interface Player extends
* *
* @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();
/** /**
* Gets the player's estimated ping in milliseconds. * Gets the player's estimated ping in milliseconds.
* *
* @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.
@ -130,29 +130,19 @@ public interface Player extends
* *
* @return the player's profile properties * @return the player's profile properties
*/ */
List<GameProfile.Property> getGameProfileProperties(); List<GameProfile.Property> profileProperties();
/** /**
* Sets the player's profile properties. * Sets the player's profile properties.
* *
* @param properties the properties * @param properties the properties
*/ */
void setGameProfileProperties(List<GameProfile.Property> properties); void setProfileProperties(List<GameProfile.Property> properties);
/** /**
* Returns the player's game profile. * Returns the player's game profile.
*/ */
GameProfile getGameProfile(); GameProfile profile();
/**
* Clears the tab list header and footer for the player.
*
* @deprecated Use {@link Player#clearPlayerListHeaderAndFooter()}.
*/
@Deprecated
default void clearHeaderAndFooter() {
clearPlayerListHeaderAndFooter();
}
/** /**
* Clears the player list header and footer. * Clears the player list header and footer.
@ -178,7 +168,7 @@ public interface Player extends
* *
* @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
@ -186,7 +176,7 @@ public interface Player extends
* *
* @param reason component with the reason * @param reason component with the reason
*/ */
void disconnect(net.kyori.adventure.text.Component reason); void disconnect(Component reason);
/** /**
* Sends chat input onto the players current server as if they typed it into the client chat box. * Sends chat input onto the players current server as if they typed it into the client chat box.
@ -195,29 +185,6 @@ public interface Player extends
*/ */
void spoofChatInput(String input); void spoofChatInput(String input);
/**
* Sends the specified resource pack from {@code url} to the user. If at all possible, send the
* resource pack using {@link #sendResourcePack(String, byte[])}. To monitor the status of the
* sent resource pack, subscribe to {@link PlayerResourcePackStatusEvent}.
*
* @param url the URL for the resource pack
* @deprecated Use {@link #sendResourcePackOffer(ResourcePackInfo)} instead
*/
@Deprecated
void sendResourcePack(String url);
/**
* Sends the specified resource pack from {@code url} to the user, using the specified 20-byte
* SHA-1 hash. To monitor the status of the sent resource pack, subscribe to
* {@link PlayerResourcePackStatusEvent}.
*
* @param url the URL for the resource pack
* @param hash the SHA-1 hash value for the resource pack
* @deprecated Use {@link #sendResourcePackOffer(ResourcePackInfo)} instead
*/
@Deprecated
void sendResourcePack(String url, byte[] hash);
/** /**
* Queues and sends a new Resource-pack offer to the player. * Queues and sends a new Resource-pack offer to the player.
* To monitor the status of the sent resource pack, subscribe to * To monitor the status of the sent resource pack, subscribe to
@ -236,7 +203,7 @@ public interface Player extends
* @return the applied resource pack or null if none. * @return the applied resource pack or null if none.
*/ */
@Nullable @Nullable
ResourcePackInfo getAppliedResourcePack(); ResourcePackInfo appliedResourcePack();
/** /**
* Gets the {@link ResourcePackInfo} of the resource pack * Gets the {@link ResourcePackInfo} of the resource pack
@ -246,14 +213,14 @@ public interface Player extends
* @return the pending resource pack or null if none * @return the pending resource pack or null if none
*/ */
@Nullable @Nullable
ResourcePackInfo getPendingResourcePack(); ResourcePackInfo pendingResourcePack();
/** /**
* <strong>Note that this method does not send a plugin message to the server the player * <strong>Note that this method does not send a plugin message to the server the player
* is connected to.</strong> You should only use this method if you are trying to communicate * is connected to.</strong> You should only use this method if you are trying to communicate
* with a mod that is installed on the player's client. To send a plugin message to the server * with a mod that is installed on the player's client. To send a plugin message to the server
* from the player, you should use the equivalent method on the instance returned by * from the player, you should use the equivalent method on the instance returned by
* {@link #getCurrentServer()}. * {@link #connectedServer()}.
* *
* @inheritDoc * @inheritDoc
*/ */
@ -268,8 +235,8 @@ public interface Player extends
@Override @Override
default @NotNull HoverEvent<HoverEvent.ShowEntity> asHoverEvent( default @NotNull HoverEvent<HoverEvent.ShowEntity> asHoverEvent(
@NotNull UnaryOperator<HoverEvent.ShowEntity> op) { @NotNull UnaryOperator<HoverEvent.ShowEntity> op) {
return HoverEvent.showEntity(op.apply(HoverEvent.ShowEntity.of(this, getUniqueId(), return HoverEvent.showEntity(op.apply(HoverEvent.ShowEntity.showEntity(this, uuid(),
Component.text(getUsername())))); Component.text(username()))));
} }

Datei anzeigen

@ -214,7 +214,7 @@ public interface ProxyServer extends Audience {
* *
* <p>Do also make sure that the resource pack is in the correct format for the version * <p>Do also make sure that the resource pack is in the correct format for the version
* of the client. It is also highly recommended to always provide the resource-pack SHA-1 hash * of the client. It is also highly recommended to always provide the resource-pack SHA-1 hash
* of the resource pack with {@link ResourcePackInfo.Builder#setHash(byte[])} * of the resource pack with {@link ResourcePackInfo.Builder#hash(byte[])}
* whenever possible to save bandwidth. If a hash is present the client will first check * whenever possible to save bandwidth. If a hash is present the client will first check
* if it already has a resource pack by that hash cached.</p> * if it already has a resource pack by that hash cached.</p>
* *

Datei anzeigen

@ -23,7 +23,7 @@ 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 server();
/** /**
* Returns the server that the player associated with this connection was connected to before * Returns the server that the player associated with this connection was connected to before
@ -31,19 +31,19 @@ public interface ServerConnection extends ChannelMessageSource, ChannelMessageSi
* *
* @return the server the player was connected to. * @return the server the player was connected to.
*/ */
Optional<RegisteredServer> getPreviousServer(); Optional<RegisteredServer> previousServer();
/** /**
* 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

@ -12,6 +12,7 @@ import com.velocitypowered.api.util.Favicon;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import net.kyori.adventure.text.Component;
/** /**
* Exposes certain proxy configuration information that plugins may use. * Exposes certain proxy configuration information that plugins may use.
@ -51,7 +52,7 @@ public interface ProxyConfig {
* *
* @return the motd component * @return the motd component
*/ */
net.kyori.adventure.text.Component getMotd(); Component getMotd();
/** /**
* Get the maximum players shown in the tab list. * Get the maximum players shown in the tab list.

Datei anzeigen

@ -25,7 +25,7 @@ public interface IdentifiedKey extends KeySigned {
* *
* @return the RSA public key in question * @return the RSA public key in question
*/ */
PublicKey getSignedPublicKey(); PublicKey publicKey();
/** /**
@ -45,14 +45,14 @@ public interface IdentifiedKey extends KeySigned {
* @return the holder UUID or null if not present * @return the holder UUID or null if not present
*/ */
@Nullable @Nullable
UUID getSignatureHolder(); UUID signatureHolder();
/** /**
* Retrieves the key revision. * Retrieves the key revision.
* *
* @return the key revision * @return the key revision
*/ */
Revision getKeyRevision(); Revision revision();
/** /**
* The different versions of player keys, per Minecraft version. * The different versions of player keys, per Minecraft version.
@ -69,11 +69,11 @@ public interface IdentifiedKey extends KeySigned {
this.applicableTo = applicableTo; this.applicableTo = applicableTo;
} }
public Set<Revision> getBackwardsCompatibleTo() { public Set<Revision> backwardsCompatibleTo() {
return backwardsCompatibleTo; return backwardsCompatibleTo;
} }
public Set<ProtocolVersion> getApplicableTo() { public Set<ProtocolVersion> applicableTo() {
return applicableTo; return applicableTo;
} }
} }

Datei anzeigen

@ -20,5 +20,5 @@ public interface KeyIdentifiable {
* *
* @return the key or null if not available * @return the key or null if not available
*/ */
@Nullable IdentifiedKey getIdentifiedKey(); @Nullable IdentifiedKey identifiedKey();
} }

Datei anzeigen

@ -22,7 +22,7 @@ public interface KeySigned {
* *
* @return the key * @return the key
*/ */
PublicKey getSigner(); PublicKey signer();
/** /**
* Returns the expiry time point of the key. * Returns the expiry time point of the key.
@ -32,7 +32,7 @@ public interface KeySigned {
* *
* @return the expiry time point * @return the expiry time point
*/ */
Instant getExpiryTemporal(); Instant signatureExpiry();
/** /**
@ -41,7 +41,7 @@ public interface KeySigned {
* @return true if proxy time is after expiry time * @return true if proxy time is after expiry time
*/ */
default boolean hasExpired() { default boolean hasExpired() {
return Instant.now().isAfter(getExpiryTemporal()); return Instant.now().isAfter(signatureExpiry());
} }
/** /**
@ -50,7 +50,7 @@ public interface KeySigned {
* @return an RSA signature * @return an RSA signature
*/ */
@Nullable @Nullable
byte[] getSignature(); byte[] signature();
/** /**
* Validates the signature, expiry temporal and key against the * Validates the signature, expiry temporal and key against the
@ -71,7 +71,7 @@ public interface KeySigned {
* *
* @return signature salt or null * @return signature salt or null
*/ */
default byte[] getSalt() { default byte[] salt() {
return null; return null;
} }

Datei anzeigen

@ -19,14 +19,14 @@ public interface SignedMessage extends KeySigned {
* *
* @return the message * @return the message
*/ */
String getMessage(); String message();
/** /**
* Returns the signers UUID. * Returns the signers UUID.
* *
* @return the uuid * @return the uuid
*/ */
UUID getSignerUuid(); UUID signerUuid();
/** /**
* If true the signature of this message applies to a stylized component instead. * If true the signature of this message applies to a stylized component instead.

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

@ -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

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

Datei anzeigen

@ -19,5 +19,5 @@ public interface ChatSession extends KeyIdentifiable {
* *
* @return the session UUID * @return the session UUID
*/ */
UUID getSessionId(); UUID sessionId();
} }

Datei anzeigen

@ -19,7 +19,7 @@ public interface PlayerSettings {
* *
* @return the client locale * @return the client locale
*/ */
Locale getLocale(); Locale locale();
/** /**
* Returns the client's view distance. This does not guarantee the client will see this many * Returns the client's view distance. This does not guarantee the client will see this many
@ -27,14 +27,14 @@ public interface PlayerSettings {
* *
* @return the client view distance * @return the client view distance
*/ */
byte getViewDistance(); byte viewDistance();
/** /**
* Returns the chat setting for the client. * Returns the chat setting for the client.
* *
* @return the chat setting * @return the chat setting
*/ */
ChatMode getChatMode(); ChatMode chatMode();
/** /**
* Returns whether or not the client has chat colors disabled. * Returns whether or not the client has chat colors disabled.
@ -48,14 +48,14 @@ public interface PlayerSettings {
* *
* @return the skin parts for the client * @return the skin parts for the client
*/ */
SkinParts getSkinParts(); SkinParts skinParts();
/** /**
* Returns the primary hand of the client. * Returns the primary hand of the client.
* *
* @return the primary hand of the client * @return the primary hand of the client
*/ */
MainHand getMainHand(); MainHand mainHand();
/** /**
* Returns whether the client explicitly allows listing on the * Returns whether the client explicitly allows listing on the

Datei anzeigen

@ -20,7 +20,7 @@ public interface ResourcePackInfo {
* *
* @return the location of the resource-pack * @return the location of the resource-pack
*/ */
String getUrl(); String url();
/** /**
* Gets the {@link Component} that is displayed on the resource-pack prompt. * Gets the {@link Component} that is displayed on the resource-pack prompt.
@ -29,31 +29,31 @@ public interface ResourcePackInfo {
* @return the prompt if present or null otherwise * @return the prompt if present or null otherwise
*/ */
@Nullable @Nullable
Component getPrompt(); Component prompt();
/** /**
* Gets whether or not the acceptance of the resource-pack is enforced. * Gets whether or not the acceptance of the resource-pack is enforced.
* See {@link Builder#setShouldForce(boolean)} for more information. * See {@link Builder#required(boolean)} for more information.
* *
* @return whether or not to force usage of this resource-pack * @return whether or not to force usage of this resource-pack
*/ */
boolean getShouldForce(); boolean required();
/** /**
* Gets the SHA-1 hash of the resource-pack * Gets the SHA-1 hash of the resource-pack
* See {@link Builder#setHash(byte[])} for more information. * See {@link Builder#hash(byte[])} for more information.
* *
* @return the hash if present or null otherwise * @return the hash if present or null otherwise
*/ */
@Nullable @Nullable
byte[] getHash(); byte[] hash();
/** /**
* Gets the {@link Origin} of this resource-pack. * Gets the {@link Origin} of this resource-pack.
* *
* @return the origin of the resource pack * @return the origin of the resource pack
*/ */
Origin getOrigin(); Origin origin();
/** /**
* Gets the original {@link Origin} of the resource-pack. * Gets the original {@link Origin} of the resource-pack.
@ -62,16 +62,15 @@ public interface ResourcePackInfo {
* *
* @return the origin of the resource pack * @return the origin of the resource pack
*/ */
Origin getOriginalOrigin(); Origin originalOrigin();
/** /**
* Returns a copy of this {@link ResourcePackInfo} instance as a builder so that it can * Returns a copy of this {@link ResourcePackInfo} instance as a builder so that it can
* be modified. * be modified.
* It is <b>not</b> guaranteed that * It is <b>not</b> guaranteed that
* {@code resourcePackInfo.asBuilder().build().equals(resourcePackInfo)} is true. That is due to * {@code resourcePackInfo.asBuilder().build().equals(resourcePackInfo)} is true. That is due to
* the transient {@link ResourcePackInfo#getOrigin()} and * the transient {@link ResourcePackInfo#origin()} and
* {@link ResourcePackInfo#getOriginalOrigin()} fields. * {@link ResourcePackInfo#originalOrigin()} fields.
*
* *
* @return a content-copy of this instance as a {@link ResourcePackInfo.Builder} * @return a content-copy of this instance as a {@link ResourcePackInfo.Builder}
*/ */
@ -82,8 +81,8 @@ public interface ResourcePackInfo {
* <p/> * <p/>
* It is <b>not</b> guaranteed that * It is <b>not</b> guaranteed that
* {@code resourcePackInfo.asBuilder(resourcePackInfo.getUrl()).build().equals(resourcePackInfo)} * {@code resourcePackInfo.asBuilder(resourcePackInfo.getUrl()).build().equals(resourcePackInfo)}
* is true, because the {@link ResourcePackInfo#getOrigin()} and * is true, because the {@link ResourcePackInfo#origin()} and
* {@link ResourcePackInfo#getOriginalOrigin()} fields are transient. * {@link ResourcePackInfo#originalOrigin()} fields are transient.
* *
* @param newUrl The new URL to use in the updated builder. * @param newUrl The new URL to use in the updated builder.
* *
@ -114,7 +113,7 @@ public interface ResourcePackInfo {
* *
* @param shouldForce whether or not to force the client to accept the resource pack * @param shouldForce whether or not to force the client to accept the resource pack
*/ */
Builder setShouldForce(boolean shouldForce); Builder required(boolean shouldForce);
/** /**
* Sets the SHA-1 hash of the provided resource pack. * Sets the SHA-1 hash of the provided resource pack.
@ -126,7 +125,7 @@ public interface ResourcePackInfo {
* *
* @param hash the SHA-1 hash of the resource-pack * @param hash the SHA-1 hash of the resource-pack
*/ */
Builder setHash(@Nullable byte[] hash); Builder hash(@Nullable byte[] hash);
/** /**
* Sets a {@link Component} to display on the download prompt. * Sets a {@link Component} to display on the download prompt.
@ -134,7 +133,7 @@ public interface ResourcePackInfo {
* *
* @param prompt the component to display * @param prompt the component to display
*/ */
Builder setPrompt(@Nullable Component prompt); Builder prompt(@Nullable Component prompt);
/** /**
* Builds the {@link ResourcePackInfo} from the provided info for use with * Builds the {@link ResourcePackInfo} from the provided info for use with

Datei anzeigen

@ -97,7 +97,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();
/** /**
* Clears all entries from the tab list. * Clears all entries from the tab list.

Datei anzeigen

@ -26,12 +26,12 @@ public interface TabListEntry extends KeyIdentifiable {
@Nullable ChatSession getChatSession(); @Nullable ChatSession getChatSession();
@Override @Override
default IdentifiedKey getIdentifiedKey() { default IdentifiedKey identifiedKey() {
ChatSession session = getChatSession(); ChatSession session = getChatSession();
if (session == null) { if (session == null) {
return null; return null;
} }
return getChatSession().getIdentifiedKey(); return getChatSession().identifiedKey();
} }
/** /**
@ -53,7 +53,7 @@ public interface TabListEntry extends KeyIdentifiable {
/** /**
* Returns {@link Optional} text {@link net.kyori.adventure.text.Component}, which if present is * Returns {@link Optional} text {@link net.kyori.adventure.text.Component}, which if present is
* the text displayed for {@code this} entry in the {@link TabList}, otherwise * the text displayed for {@code this} entry in the {@link TabList}, otherwise
* {@link GameProfile#getName()} is shown. * {@link GameProfile#name()} is shown.
* *
* @return {@link Optional} text {@link net.kyori.adventure.text.Component} of name displayed in * @return {@link Optional} text {@link net.kyori.adventure.text.Component} of name displayed in
* the tab list * the tab list
@ -62,7 +62,7 @@ public interface TabListEntry extends KeyIdentifiable {
/** /**
* 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
* {@code null}, {@link GameProfile#getName()} will be shown. * {@code null}, {@link GameProfile#name()} will be shown.
* *
* @param displayName to show in the {@link TabList} for {@code this} entry * @param displayName to show in the {@link TabList} for {@code this} entry
* @return {@code this}, for chaining * @return {@code this}, for chaining

Datei anzeigen

@ -41,7 +41,7 @@ public final class PingOptions {
* *
* @return the emulated Minecraft version * @return the emulated Minecraft version
*/ */
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return this.protocolVersion; return this.protocolVersion;
} }
@ -50,7 +50,7 @@ public final class PingOptions {
* *
* @return the server ping timeout in milliseconds * @return the server ping timeout in milliseconds
*/ */
public long getTimeout() { public long timeout() {
return this.timeout; return this.timeout;
} }

Datei anzeigen

@ -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 map() {
return map; return map;
} }
@ -89,7 +89,7 @@ public final class QueryResponse {
* *
* @return online player count * @return online player count
*/ */
public int getCurrentPlayers() { public int currentPlayers() {
return currentPlayers; return currentPlayers;
} }
@ -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,7 +143,7 @@ public final class QueryResponse {
* *
* @return collection of plugins * @return collection of plugins
*/ */
public Collection<PluginInformation> getPlugins() { public Collection<PluginInformation> plugins() {
return plugins; return plugins;
} }
@ -158,16 +158,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(map())
.currentPlayers(getCurrentPlayers()) .currentPlayers(currentPlayers())
.maxPlayers(getMaxPlayers()) .maxPlayers(maxPlayers())
.proxyHost(getProxyHost()) .proxyHost(proxyHost())
.proxyPort(getProxyPort()) .proxyPort(proxyPort())
.players(getPlayers()) .players(players())
.proxyVersion(getProxyVersion()) .proxyVersion(proxyVersion())
.plugins(getPlugins()); .plugins(plugins());
} }
/** /**
@ -347,7 +347,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 #currentPlayers()}.
* *
* @return this builder, for chaining * @return this builder, for chaining
*/ */

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> players();
/** /**
* 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

@ -32,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 String name() {
return name; return name;
} }
public final SocketAddress getAddress() { public SocketAddress address() {
return address; return address;
} }
@ -68,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

@ -18,6 +18,7 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
@ -27,12 +28,12 @@ public final class ServerPing {
private final Version version; private final Version version;
private final @Nullable Players players; private final @Nullable Players players;
private final net.kyori.adventure.text.Component description; private final Component description;
private final @Nullable Favicon favicon; private final @Nullable Favicon favicon;
private final @Nullable ModInfo modinfo; private final @Nullable ModInfo modinfo;
public ServerPing(Version version, @Nullable Players players, public ServerPing(Version version, @Nullable Players players,
net.kyori.adventure.text.Component description, @Nullable Favicon favicon) { Component description, @Nullable Favicon favicon) {
this(version, players, description, favicon, ModInfo.DEFAULT); this(version, players, description, favicon, ModInfo.DEFAULT);
} }
@ -46,7 +47,7 @@ public final class ServerPing {
* @param modinfo the mods this server runs * @param modinfo the mods this server runs
*/ */
public ServerPing(Version version, @Nullable Players players, public ServerPing(Version version, @Nullable Players players,
net.kyori.adventure.text.Component description, @Nullable Favicon favicon, Component description, @Nullable Favicon favicon,
@Nullable ModInfo modinfo) { @Nullable ModInfo modinfo) {
this.version = Preconditions.checkNotNull(version, "version"); this.version = Preconditions.checkNotNull(version, "version");
this.players = players; this.players = players;
@ -55,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 net.kyori.adventure.text.Component getDescriptionComponent() { 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);
} }
@ -129,8 +130,8 @@ public final class ServerPing {
builder.favicon = favicon; builder.favicon = favicon;
builder.nullOutModinfo = modinfo == null; builder.nullOutModinfo = modinfo == null;
if (modinfo != null) { if (modinfo != null) {
builder.modType = modinfo.getType(); builder.modType = modinfo.type();
builder.mods.addAll(modinfo.getMods()); builder.mods.addAll(modinfo.mods());
} }
return builder; return builder;
} }
@ -150,7 +151,7 @@ public final class ServerPing {
private final List<SamplePlayer> samplePlayers = new ArrayList<>(); private final List<SamplePlayer> samplePlayers = new ArrayList<>();
private String modType = "FML"; private String modType = "FML";
private final List<ModInfo.Mod> mods = new ArrayList<>(); private final List<ModInfo.Mod> mods = new ArrayList<>();
private net.kyori.adventure.text.Component description; private Component description;
private @Nullable Favicon favicon; private @Nullable Favicon favicon;
private boolean nullOutPlayers; private boolean nullOutPlayers;
private boolean nullOutModinfo; private boolean nullOutModinfo;
@ -197,9 +198,9 @@ public final class ServerPing {
*/ */
public Builder mods(ModInfo mods) { public Builder mods(ModInfo mods) {
Preconditions.checkNotNull(mods, "mods"); Preconditions.checkNotNull(mods, "mods");
this.modType = mods.getType(); this.modType = mods.type();
this.mods.clear(); this.mods.clear();
this.mods.addAll(mods.getMods()); this.mods.addAll(mods.mods());
return this; return this;
} }
@ -223,7 +224,7 @@ public final class ServerPing {
return this; return this;
} }
public Builder description(net.kyori.adventure.text.Component description) { public Builder description(Component description) {
this.description = Preconditions.checkNotNull(description, "description"); this.description = Preconditions.checkNotNull(description, "description");
return this; return this;
} }
@ -272,7 +273,7 @@ public final class ServerPing {
return samplePlayers; return samplePlayers;
} }
public Optional<net.kyori.adventure.text.Component> getDescriptionComponent() { public Optional<Component> getDescriptionComponent() {
return Optional.ofNullable(description); return Optional.ofNullable(description);
} }

Datei anzeigen

@ -39,11 +39,11 @@ public final class Favicon {
} }
/** /**
* Returns the Base64-encoded URI for this image. * Returns the Base64-encoded URL for this image.
* *
* @return a URL representing this favicon * @return a URL representing this favicon
*/ */
public String getBase64Url() { public String url() {
return base64Url; return base64Url;
} }

Datei anzeigen

@ -58,7 +58,7 @@ public final class GameProfile {
* *
* @return the undashed UUID * @return the undashed UUID
*/ */
public String getUndashedId() { public String undashedId() {
return undashedId; return undashedId;
} }
@ -67,7 +67,7 @@ public final class GameProfile {
* *
* @return the UUID * @return the UUID
*/ */
public UUID getId() { public UUID uuid() {
return id; return id;
} }
@ -76,7 +76,7 @@ public final class GameProfile {
* *
* @return the username * @return the username
*/ */
public String getName() { public String name() {
return name; return name;
} }
@ -85,7 +85,7 @@ public final class GameProfile {
* *
* @return the properties associated with this profile * @return the properties associated with this profile
*/ */
public List<Property> getProperties() { public List<Property> properties() {
return properties; return properties;
} }
@ -200,15 +200,15 @@ public final class GameProfile {
this.signature = Preconditions.checkNotNull(signature, "signature"); this.signature = Preconditions.checkNotNull(signature, "signature");
} }
public String getName() { public String name() {
return name; return name;
} }
public String getValue() { public String value() {
return value; return value;
} }
public String getSignature() { public String signature() {
return signature; return signature;
} }

Datei anzeigen

@ -34,11 +34,11 @@ public final class ModInfo {
this.modList = ImmutableList.copyOf(modList); this.modList = ImmutableList.copyOf(modList);
} }
public String getType() { public String type() {
return type; return type;
} }
public List<Mod> getMods() { public List<Mod> mods() {
return modList; return modList;
} }
@ -81,11 +81,11 @@ public final class ModInfo {
this.version = Preconditions.checkNotNull(version, "version"); this.version = Preconditions.checkNotNull(version, "version");
} }
public String getId() { public String id() {
return id; return id;
} }
public String getVersion() { public String version() {
return version; return version;
} }

Datei anzeigen

@ -33,15 +33,15 @@ public final class ProxyVersion {
this.version = Preconditions.checkNotNull(version, "version"); this.version = Preconditions.checkNotNull(version, "version");
} }
public String getName() { public String name() {
return name; return name;
} }
public String getVendor() { public String vendor() {
return vendor; return vendor;
} }
public String getVersion() { public String version() {
return version; return version;
} }

Datei anzeigen

@ -116,7 +116,7 @@ public class Metrics {
() -> server.getConfiguration().isOnlineMode() ? "online" : "offline") () -> server.getConfiguration().isOnlineMode() ? "online" : "offline")
); );
metrics.addCustomChart(new SimplePie("velocity_version", metrics.addCustomChart(new SimplePie("velocity_version",
() -> server.getVersion().getVersion())); () -> server.getVersion().version()));
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

@ -200,7 +200,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 {} {}...", getVersion().name(), getVersion().version());
console.setupStreams(); console.setupStreams();
registerTranslations(); registerTranslations();
@ -350,19 +350,19 @@ 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.plugins()) {
Optional<?> instance = plugin.getInstance(); Optional<?> instance = plugin.instance();
if (instance.isPresent()) { if (instance.isPresent()) {
try { try {
eventManager.registerInternally(plugin, instance.get()); eventManager.registerInternally(plugin, 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);
} }
} }
} }
logger.info("Loaded {} plugins", pluginManager.getPlugins().size()); logger.info("Loaded {} plugins", pluginManager.plugins().size());
} }
public Bootstrap createBootstrap(@Nullable EventLoopGroup group, SocketAddress target) { public Bootstrap createBootstrap(@Nullable EventLoopGroup group, SocketAddress target) {
@ -404,15 +404,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().players()) {
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);
} }
} }
@ -591,9 +591,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.uuid()));
} }
/** /**
@ -603,25 +603,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.uuid(), 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.uuid());
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.uuid(), connection);
} }
return true; return true;
} }
@ -632,8 +632,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.uuid(), connection);
bossBarManager.onDisconnect(connection); bossBarManager.onDisconnect(connection);
} }
@ -653,7 +653,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 getAllPlayers().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());
} }
@ -662,7 +662,7 @@ 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 getAllServers().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());
} }

Datei anzeigen

@ -97,21 +97,21 @@ public class VelocityCommandManager implements CommandManager {
} }
@Override @Override
public CommandMeta.Builder metaBuilder(final String alias) { public CommandMeta.Builder buildMeta(final String alias) {
Preconditions.checkNotNull(alias, "alias"); Preconditions.checkNotNull(alias, "alias");
return new VelocityCommandMeta.Builder(alias); return new VelocityCommandMeta.Builder(alias);
} }
@Override @Override
public CommandMeta.Builder metaBuilder(final BrigadierCommand command) { public CommandMeta.Builder buildMeta(final BrigadierCommand command) {
Preconditions.checkNotNull(command, "command"); Preconditions.checkNotNull(command, "command");
return new VelocityCommandMeta.Builder(command.getNode().getName()); return new VelocityCommandMeta.Builder(command.node().getName());
} }
@Override @Override
public void register(final BrigadierCommand command) { public void register(final BrigadierCommand command) {
Preconditions.checkNotNull(command, "command"); Preconditions.checkNotNull(command, "command");
register(metaBuilder(command).build(), command); register(buildMeta(command).build(), command);
} }
@Override @Override
@ -151,7 +151,7 @@ public class VelocityCommandManager implements CommandManager {
final Command command, final CommandMeta meta) { final Command command, final CommandMeta meta) {
final Class<T> superInterface = registrar.registrableSuperInterface(); final Class<T> superInterface = registrar.registrableSuperInterface();
registrar.register(meta, superInterface.cast(command)); registrar.register(meta, superInterface.cast(command));
for (String alias : meta.getAliases()) { for (String alias : meta.aliases()) {
commandMetas.put(alias, meta); commandMetas.put(alias, meta);
} }
} }
@ -188,7 +188,7 @@ public class VelocityCommandManager implements CommandManager {
try { try {
// The literals of secondary aliases will preserve the children of // The literals of secondary aliases will preserve the children of
// the removed literal in the graph. // the removed literal in the graph.
for (String alias : meta.getAliases()) { for (String alias : meta.aliases()) {
final String lowercased = alias.toLowerCase(Locale.ENGLISH); final String lowercased = alias.toLowerCase(Locale.ENGLISH);
if (commandMetas.remove(lowercased, meta)) { if (commandMetas.remove(lowercased, meta)) {
dispatcher.getRoot().removeChildByName(lowercased); dispatcher.getRoot().removeChildByName(lowercased);
@ -200,7 +200,7 @@ public class VelocityCommandManager implements CommandManager {
} }
@Override @Override
public @Nullable CommandMeta getCommandMeta(String alias) { public @Nullable CommandMeta commandMeta(String alias) {
Preconditions.checkNotNull(alias, "alias"); Preconditions.checkNotNull(alias, "alias");
return commandMetas.get(alias); return commandMetas.get(alias);
} }
@ -250,8 +250,8 @@ 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.allowed()) {
return false; return false;
} }
return executeImmediately0(source, commandResult.getCommand().orElse(event.getCommand())); return executeImmediately0(source, commandResult.getCommand().orElse(event.getCommand()));
@ -321,7 +321,7 @@ public class VelocityCommandManager implements CommandManager {
} }
@Override @Override
public Collection<String> getAliases() { public Collection<String> aliases() {
lock.readLock().lock(); lock.readLock().lock();
try { try {
// A RootCommandNode may only contain LiteralCommandNode children instances // A RootCommandNode may only contain LiteralCommandNode children instances

Datei anzeigen

@ -120,7 +120,7 @@ public final class VelocityCommandMeta implements CommandMeta {
*/ */
// This is a static method because most methods take a CommandMeta. // This is a static method because most methods take a CommandMeta.
public static Stream<CommandNode<CommandSource>> copyHints(final CommandMeta meta) { public static Stream<CommandNode<CommandSource>> copyHints(final CommandMeta meta) {
return meta.getHints().stream().map(VelocityCommandMeta::copyForHinting); return meta.hints().stream().map(VelocityCommandMeta::copyForHinting);
} }
private final Set<String> aliases; private final Set<String> aliases;
@ -138,17 +138,17 @@ public final class VelocityCommandMeta implements CommandMeta {
} }
@Override @Override
public Collection<String> getAliases() { public Collection<String> aliases() {
return this.aliases; return this.aliases;
} }
@Override @Override
public Collection<CommandNode<CommandSource>> getHints() { public Collection<CommandNode<CommandSource>> hints() {
return this.hints; return this.hints;
} }
@Override @Override
public @Nullable Object getPlugin() { public @Nullable Object plugin() {
return plugin; return plugin;
} }

Datei anzeigen

@ -32,7 +32,7 @@ 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.getAllServers());
servers.sort(Comparator.comparing(RegisteredServer::getServerInfo)); servers.sort(Comparator.comparing(RegisteredServer::serverInfo));
return Collections.unmodifiableList(servers); return Collections.unmodifiableList(servers);
} }
} }

Datei anzeigen

@ -67,7 +67,7 @@ public class GlistCommand {
.<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.getAllServers()) {
builder.suggest(server.getServerInfo().getName()); builder.suggest(server.serverInfo().name());
} }
builder.suggest("all"); builder.suggest("all");
return builder.buildFuture(); return builder.buildFuture();
@ -116,13 +116,13 @@ public class GlistCommand {
} }
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.players());
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(": "))
@ -130,7 +130,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

@ -77,8 +77,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(Component.translatable( executor.sendMessage(Component.translatable(
"velocity.command.server-current-server", "velocity.command.server-current-server",
NamedTextColor.YELLOW, NamedTextColor.YELLOW,
@ -108,10 +108,10 @@ 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());
int connectedPlayers = server.getPlayersConnected().size(); int connectedPlayers = server.players().size();
TranslatableComponent playersTextComponent; TranslatableComponent playersTextComponent;
if (connectedPlayers == 1) { if (connectedPlayers == 1) {
playersTextComponent = Component.translatable( playersTextComponent = Component.translatable(
@ -121,7 +121,7 @@ public class ServerCommand implements SimpleCommand {
"velocity.command.server-tooltip-players-online"); "velocity.command.server-tooltip-players-online");
} }
playersTextComponent = playersTextComponent.args(Component.text(connectedPlayers)); playersTextComponent = playersTextComponent.args(Component.text(connectedPlayers));
if (serverInfo.getName().equals(currentPlayerServer)) { if (serverInfo.name().equals(currentPlayerServer)) {
serverTextComponent = serverTextComponent.color(NamedTextColor.GREEN) serverTextComponent = serverTextComponent.color(NamedTextColor.GREEN)
.hoverEvent( .hoverEvent(
showText( showText(
@ -131,7 +131,7 @@ public class ServerCommand implements SimpleCommand {
); );
} 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( showText(
Component.translatable("velocity.command.server-tooltip-offer-connect-server") Component.translatable("velocity.command.server-tooltip-offer-connect-server")
@ -146,7 +146,7 @@ public class ServerCommand implements SimpleCommand {
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.getAllServers().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());

Datei anzeigen

@ -222,19 +222,19 @@ public class VelocityCommand implements SimpleCommand {
ProxyVersion version = server.getVersion(); ProxyVersion version = server.getVersion();
Component velocity = Component.text().content(version.getName() + " ") Component velocity = Component.text().content(version.name() + " ")
.decoration(TextDecoration.BOLD, true) .decoration(TextDecoration.BOLD, true)
.color(VELOCITY_COLOR) .color(VELOCITY_COLOR)
.append(Component.text(version.getVersion()).decoration(TextDecoration.BOLD, false)) .append(Component.text(version.version()).decoration(TextDecoration.BOLD, false))
.build(); .build();
Component copyright = Component Component copyright = Component
.translatable("velocity.command.version-copyright", .translatable("velocity.command.version-copyright",
Component.text(version.getVendor()), Component.text(version.vendor()),
Component.text(version.getName())); Component.text(version.name()));
source.sendMessage(velocity); source.sendMessage(velocity);
source.sendMessage(copyright); source.sendMessage(copyright);
if (version.getName().equals("Velocity")) { if (version.name().equals("Velocity")) {
TextComponent embellishment = Component.text() TextComponent embellishment = Component.text()
.append(Component.text().content("velocitypowered.com") .append(Component.text().content("velocitypowered.com")
.color(NamedTextColor.GREEN) .color(NamedTextColor.GREEN)
@ -274,7 +274,7 @@ public class VelocityCommand implements SimpleCommand {
return; return;
} }
List<PluginContainer> plugins = ImmutableList.copyOf(server.getPluginManager().getPlugins()); List<PluginContainer> plugins = ImmutableList.copyOf(server.getPluginManager().plugins());
int pluginCount = plugins.size(); int pluginCount = plugins.size();
if (pluginCount == 0) { if (pluginCount == 0) {
@ -286,7 +286,7 @@ public class VelocityCommand implements SimpleCommand {
TextComponent.Builder listBuilder = Component.text(); TextComponent.Builder listBuilder = Component.text();
for (int i = 0; i < pluginCount; i++) { for (int i = 0; i < pluginCount; i++) {
PluginContainer plugin = plugins.get(i); PluginContainer plugin = plugins.get(i);
listBuilder.append(componentForPlugin(plugin.getDescription())); listBuilder.append(componentForPlugin(plugin.description()));
if (i + 1 < pluginCount) { if (i + 1 < pluginCount) {
listBuilder.append(Component.text(", ")); listBuilder.append(Component.text(", "));
} }
@ -300,37 +300,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.translatable( hoverText.append(Component.translatable(
"velocity.command.plugin-tooltip-website", "velocity.command.plugin-tooltip-website",
Component.text(url))); Component.text(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.translatable("velocity.command.plugin-tooltip-author", hoverText.append(Component.translatable("velocity.command.plugin-tooltip-author",
Component.text(description.getAuthors().get(0)))); Component.text(description.authors().get(0))));
} else { } else {
hoverText.append( hoverText.append(
Component.translatable("velocity.command.plugin-tooltip-author", Component.translatable("velocity.command.plugin-tooltip-author",
Component.text(String.join(", ", description.getAuthors())) Component.text(String.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()));
} }
@ -359,7 +359,7 @@ public class VelocityCommand implements SimpleCommand {
Collection<RegisteredServer> allServers = ImmutableSet.copyOf(server.getAllServers()); Collection<RegisteredServer> allServers = ImmutableSet.copyOf(server.getAllServers());
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();

Datei anzeigen

@ -39,14 +39,14 @@ public final class BrigadierCommandRegistrar extends AbstractCommandRegistrar<Br
// The literal name might not match any aliases on the given meta. // The literal name might not match any aliases on the given meta.
// Register it (if valid), since it's probably what the user expects. // Register it (if valid), since it's probably what the user expects.
// If invalid, the metadata contains the same alias, but in lowercase. // If invalid, the metadata contains the same alias, but in lowercase.
final LiteralCommandNode<CommandSource> literal = command.getNode(); final LiteralCommandNode<CommandSource> literal = command.node();
final String primaryAlias = literal.getName(); final String primaryAlias = literal.getName();
if (VelocityCommands.isValidAlias(primaryAlias)) { if (VelocityCommands.isValidAlias(primaryAlias)) {
// Register directly without copying // Register directly without copying
this.register(literal); this.register(literal);
} }
for (final String alias : meta.getAliases()) { for (final String alias : meta.aliases()) {
if (primaryAlias.equals(alias)) { if (primaryAlias.equals(alias)) {
continue; continue;
} }

Datei anzeigen

@ -57,7 +57,7 @@ abstract class InvocableCommandRegistrar<T extends InvocableCommand<I>,
@Override @Override
public void register(final CommandMeta meta, final T command) { public void register(final CommandMeta meta, final T command) {
final Iterator<String> aliases = meta.getAliases().iterator(); final Iterator<String> aliases = meta.aliases().iterator();
final String primaryAlias = aliases.next(); final String primaryAlias = aliases.next();
final LiteralCommandNode<CommandSource> literal = final LiteralCommandNode<CommandSource> literal =

Datei anzeigen

@ -88,7 +88,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.getActiveSessionHandler(); MinecraftSessionHandler psh = playerConnection.getActiveSessionHandler();
if (!(psh instanceof ClientPlaySessionHandler)) { if (!(psh instanceof ClientPlaySessionHandler)) {
@ -98,12 +98,12 @@ 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.server().addPlayer(serverConn.player());
MinecraftConnection serverMc = serverConn.ensureConnected(); MinecraftConnection serverMc = serverConn.ensureConnected();
if (server.getConfiguration().isBungeePluginChannelEnabled()) { if (server.getConfiguration().isBungeePluginChannelEnabled()) {
@ -130,7 +130,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
smc.setAutoReading(false); smc.setAutoReading(false);
// Even when not auto reading messages are still decoded. Decode them with the correct state // Even when not auto reading messages are still decoded. Decode them with the correct state
smc.getChannel().pipeline().get(MinecraftDecoder.class).setState(StateRegistry.CONFIG); smc.getChannel().pipeline().get(MinecraftDecoder.class).setState(StateRegistry.CONFIG);
serverConn.getPlayer().switchToConfigState(); serverConn.player().switchToConfigState();
return true; return true;
} }
@ -149,7 +149,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(Disconnect packet) { public boolean handle(Disconnect packet) {
serverConn.disconnect(); serverConn.disconnect();
serverConn.getPlayer().handleConnectionException(serverConn.getServer(), packet, true); serverConn.player().handleConnectionException(serverConn.server(), packet, true);
return true; return true;
} }
@ -167,14 +167,14 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
public boolean handle(ResourcePackRequest packet) { public boolean handle(ResourcePackRequest packet) {
ResourcePackInfo.Builder builder = new VelocityResourcePackInfo.BuilderImpl( ResourcePackInfo.Builder builder = new VelocityResourcePackInfo.BuilderImpl(
Preconditions.checkNotNull(packet.getUrl())) Preconditions.checkNotNull(packet.getUrl()))
.setPrompt(packet.getPrompt()) .prompt(packet.getPrompt())
.setShouldForce(packet.isRequired()) .required(packet.isRequired())
.setOrigin(ResourcePackInfo.Origin.DOWNSTREAM_SERVER); .setOrigin(ResourcePackInfo.Origin.DOWNSTREAM_SERVER);
String hash = packet.getHash(); String hash = packet.getHash();
if (hash != null && !hash.isEmpty()) { if (hash != null && !hash.isEmpty()) {
if (PLAUSIBLE_SHA1_HASH.matcher(hash).matches()) { if (PLAUSIBLE_SHA1_HASH.matcher(hash).matches()) {
builder.setHash(ByteBufUtil.decodeHexDump(hash)); builder.hash(ByteBufUtil.decodeHexDump(hash));
} }
} }
@ -185,14 +185,14 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
if (playerConnection.isClosed()) { if (playerConnection.isClosed()) {
return; return;
} }
if (serverResourcePackSendEvent.getResult().isAllowed()) { if (serverResourcePackSendEvent.result().allowed()) {
ResourcePackInfo toSend = serverResourcePackSendEvent.getProvidedResourcePack(); ResourcePackInfo toSend = serverResourcePackSendEvent.providedResourcePack();
if (toSend != serverResourcePackSendEvent.getReceivedResourcePack()) { if (toSend != serverResourcePackSendEvent.receivedResourcePack()) {
((VelocityResourcePackInfo) toSend) ((VelocityResourcePackInfo) toSend)
.setOriginalOrigin(ResourcePackInfo.Origin.DOWNSTREAM_SERVER); .setOriginalOrigin(ResourcePackInfo.Origin.DOWNSTREAM_SERVER);
} }
serverConn.getPlayer().queueResourcePack(toSend); serverConn.player().queueResourcePack(toSend);
} else if (serverConn.getConnection() != null) { } else if (serverConn.getConnection() != null) {
serverConn.getConnection().write(new ResourcePackResponse( serverConn.getConnection().write(new ResourcePackResponse(
packet.getHash(), packet.getHash(),
@ -231,7 +231,7 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
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;
} }
@ -242,9 +242,9 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
} }
byte[] copy = ByteBufUtil.getBytes(packet.content()); byte[] copy = ByteBufUtil.getBytes(packet.content());
PluginMessageEvent event = new PluginMessageEvent(serverConn, serverConn.getPlayer(), id, copy); PluginMessageEvent event = new PluginMessageEvent(serverConn, serverConn.player(), id, copy);
server.getEventManager().fire(event).thenAcceptAsync(pme -> { server.getEventManager().fire(event).thenAcceptAsync(pme -> {
if (pme.getResult().isAllowed() && !playerConnection.isClosed()) { if (pme.result().allowed() && !playerConnection.isClosed()) {
PluginMessage copied = new PluginMessage(packet.getChannel(), Unpooled.wrappedBuffer(copy)); PluginMessage copied = new PluginMessage(packet.getChannel(), Unpooled.wrappedBuffer(copy));
playerConnection.write(copied); playerConnection.write(copied);
} }
@ -263,19 +263,19 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(LegacyPlayerListItem packet) { public boolean handle(LegacyPlayerListItem packet) {
serverConn.getPlayer().getTabList().processLegacy(packet); serverConn.player().tabList().processLegacy(packet);
return false; return false;
} }
@Override @Override
public boolean handle(UpsertPlayerInfo packet) { public boolean handle(UpsertPlayerInfo packet) {
serverConn.getPlayer().getTabList().processUpdate(packet); serverConn.player().tabList().processUpdate(packet);
return false; return false;
} }
@Override @Override
public boolean handle(RemovePlayerInfo packet) { public boolean handle(RemovePlayerInfo packet) {
serverConn.getPlayer().getTabList().processRemove(packet); serverConn.player().tabList().processRemove(packet);
return false; return false;
} }
@ -285,11 +285,11 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
if (server.getConfiguration().isAnnounceProxyCommands()) { if (server.getConfiguration().isAnnounceProxyCommands()) {
// Inject commands from the proxy. // Inject commands from the proxy.
final CommandGraphInjector<CommandSource> injector = server.getCommandManager().getInjector(); final CommandGraphInjector<CommandSource> injector = server.getCommandManager().getInjector();
injector.inject(rootNode, serverConn.getPlayer()); injector.inject(rootNode, serverConn.player());
} }
server.getEventManager().fire( server.getEventManager().fire(
new PlayerAvailableCommandsEvent(serverConn.getPlayer(), rootNode)) new PlayerAvailableCommandsEvent(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);
@ -300,12 +300,12 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ServerData packet) { public boolean handle(ServerData packet) {
server.getServerListPingHandler().getInitialPing(this.serverConn.getPlayer()).thenComposeAsync( server.getServerListPingHandler().getInitialPing(this.serverConn.player()).thenComposeAsync(
ping -> server.getEventManager() ping -> server.getEventManager()
.fire(new ProxyPingEvent(this.serverConn.getPlayer(), ping)), .fire(new ProxyPingEvent(this.serverConn.player(), ping)),
playerConnection.eventLoop()).thenAcceptAsync(pingEvent -> this.playerConnection.write( playerConnection.eventLoop()).thenAcceptAsync(pingEvent -> this.playerConnection.write(
new ServerData(pingEvent.getPing().getDescriptionComponent(), new ServerData(pingEvent.ping().description(),
pingEvent.getPing().getFavicon().orElse(null), packet.isSecureChatEnforced())), pingEvent.ping().favicon().orElse(null), packet.isSecureChatEnforced())),
playerConnection.eventLoop()); playerConnection.eventLoop());
return true; return true;
} }
@ -340,7 +340,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.server(), throwable,
!(throwable instanceof ReadTimeoutException)); !(throwable instanceof ReadTimeoutException));
} }
@ -350,14 +350,14 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler {
@Override @Override
public void disconnected() { public void disconnected() {
serverConn.getServer().removePlayer(serverConn.getPlayer()); serverConn.server().removePlayer(serverConn.player());
if (!serverConn.isGracefulDisconnect() && !exceptionTriggered) { if (!serverConn.isGracefulDisconnect() && !exceptionTriggered) {
if (server.getConfiguration().isFailoverOnUnexpectedServerDisconnect()) { if (server.getConfiguration().isFailoverOnUnexpectedServerDisconnect()) {
serverConn.getPlayer().handleConnectionException(serverConn.getServer(), serverConn.player().handleConnectionException(serverConn.server(),
Disconnect.create(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR, Disconnect.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

@ -72,7 +72,7 @@ public class BungeeCordMessageResponder {
} }
public static boolean isBungeeCordMessage(PluginMessage message) { public static boolean isBungeeCordMessage(PluginMessage 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());
} }
@ -98,7 +98,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());
@ -121,9 +121,9 @@ public class BungeeCordMessageResponder {
out.writeInt(proxy.getPlayerCount()); out.writeInt(proxy.getPlayerCount());
} else { } else {
proxy.getServer(target).ifPresent(rs -> { proxy.getServer(target).ifPresent(rs -> {
int playersOnServer = rs.getPlayersConnected().size(); int playersOnServer = rs.players().size();
out.writeUTF("PlayerCount"); out.writeUTF("PlayerCount");
out.writeUTF(rs.getServerInfo().getName()); out.writeUTF(rs.serverInfo().name());
out.writeInt(playersOnServer); out.writeInt(playersOnServer);
}); });
} }
@ -146,17 +146,17 @@ public class BungeeCordMessageResponder {
StringJoiner joiner = new StringJoiner(", "); StringJoiner joiner = new StringJoiner(", ");
for (Player online : proxy.getAllPlayers()) { for (Player online : proxy.getAllPlayers()) {
joiner.add(online.getUsername()); joiner.add(online.username());
} }
out.writeUTF(joiner.toString()); out.writeUTF(joiner.toString());
} else { } else {
proxy.getServer(target).ifPresent(info -> { proxy.getServer(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.players()) {
joiner.add(online.getUsername()); joiner.add(online.username());
} }
out.writeUTF(joiner.toString()); out.writeUTF(joiner.toString());
}); });
@ -172,7 +172,7 @@ 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.getAllServers()) {
joiner.add(server.getServerInfo().getName()); joiner.add(server.serverInfo().name());
} }
ByteBuf buf = Unpooled.buffer(); ByteBuf buf = Unpooled.buffer();
@ -210,7 +210,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);
} }
@ -220,7 +220,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.uuid()));
sendResponseOnConnection(buf); sendResponseOnConnection(buf);
} }
@ -231,8 +231,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.uuid()));
sendResponseOnConnection(buf); sendResponseOnConnection(buf);
}); });
@ -244,8 +244,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());
@ -265,8 +265,8 @@ public class BungeeCordMessageResponder {
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());
@ -298,12 +298,12 @@ public class BungeeCordMessageResponder {
private void processForwardToServer(ByteBufDataInput in) { private void processForwardToServer(ByteBufDataInput in) {
String target = in.readUTF(); String target = in.readUTF();
ByteBuf toForward = in.unwrap().copy(); ByteBuf toForward = in.unwrap().copy();
final ServerInfo currentUserServer = player.getCurrentServer() final ServerInfo currentUserServer = player.connectedServer()
.map(ServerConnection::getServerInfo).orElse(null); .map(ServerConnection::serverInfo).orElse(null);
if (target.equals("ALL") || target.equals("ONLINE")) { if (target.equals("ALL") || target.equals("ONLINE")) {
try { try {
for (RegisteredServer rs : proxy.getAllServers()) { for (RegisteredServer rs : proxy.getAllServers()) {
if (!rs.getServerInfo().equals(currentUserServer)) { if (!rs.serverInfo().equals(currentUserServer)) {
((VelocityRegisteredServer) rs).sendPluginMessage(LEGACY_CHANNEL, ((VelocityRegisteredServer) rs).sendPluginMessage(LEGACY_CHANNEL,
toForward.retainedSlice()); toForward.retainedSlice());
} }
@ -322,8 +322,8 @@ public class BungeeCordMessageResponder {
} }
static String getBungeeCordChannel(ProtocolVersion version) { static String getBungeeCordChannel(ProtocolVersion version) {
return version.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0 ? MODERN_CHANNEL.getId() return version.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0 ? 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!

Datei anzeigen

@ -81,8 +81,8 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
@Override @Override
public void activated() { public void activated() {
resourcePackToApply = serverConn.getPlayer().getAppliedResourcePack(); resourcePackToApply = serverConn.player().appliedResourcePack();
serverConn.getPlayer().clearAppliedResourcePack(); serverConn.player().clearAppliedResourcePack();
} }
@Override @Override
@ -103,7 +103,7 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(TagsUpdate packet) { public boolean handle(TagsUpdate packet) {
serverConn.getPlayer().getConnection().write(packet); serverConn.player().getConnection().write(packet);
return true; return true;
} }
@ -115,7 +115,7 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(ResourcePackRequest packet) { public boolean handle(ResourcePackRequest packet) {
final MinecraftConnection playerConnection = serverConn.getPlayer().getConnection(); final MinecraftConnection playerConnection = serverConn.player().getConnection();
ServerResourcePackSendEvent event = ServerResourcePackSendEvent event =
new ServerResourcePackSendEvent(packet.toServerPromptedPack(), this.serverConn); new ServerResourcePackSendEvent(packet.toServerPromptedPack(), this.serverConn);
@ -124,15 +124,15 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
if (playerConnection.isClosed()) { if (playerConnection.isClosed()) {
return; return;
} }
if (serverResourcePackSendEvent.getResult().isAllowed()) { if (serverResourcePackSendEvent.result().allowed()) {
ResourcePackInfo toSend = serverResourcePackSendEvent.getProvidedResourcePack(); ResourcePackInfo toSend = serverResourcePackSendEvent.providedResourcePack();
if (toSend != serverResourcePackSendEvent.getReceivedResourcePack()) { if (toSend != serverResourcePackSendEvent.receivedResourcePack()) {
((VelocityResourcePackInfo) toSend).setOriginalOrigin( ((VelocityResourcePackInfo) toSend).setOriginalOrigin(
ResourcePackInfo.Origin.DOWNSTREAM_SERVER); ResourcePackInfo.Origin.DOWNSTREAM_SERVER);
} }
resourcePackToApply = null; resourcePackToApply = null;
serverConn.getPlayer().queueResourcePack(toSend); serverConn.player().queueResourcePack(toSend);
} else if (serverConn.getConnection() != null) { } else if (serverConn.getConnection() != null) {
serverConn.getConnection().write(new ResourcePackResponse(packet.getHash(), serverConn.getConnection().write(new ResourcePackResponse(packet.getHash(),
PlayerResourcePackStatusEvent.Status.DECLINED)); PlayerResourcePackStatusEvent.Status.DECLINED));
@ -152,7 +152,7 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(FinishedUpdate packet) { public boolean handle(FinishedUpdate packet) {
MinecraftConnection smc = serverConn.ensureConnected(); MinecraftConnection smc = serverConn.ensureConnected();
ConnectedPlayer player = serverConn.getPlayer(); ConnectedPlayer player = serverConn.player();
ClientConfigSessionHandler configHandler = ClientConfigSessionHandler configHandler =
(ClientConfigSessionHandler) player.getConnection().getActiveSessionHandler(); (ClientConfigSessionHandler) player.getConnection().getActiveSessionHandler();
@ -165,12 +165,12 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
player.sendPlayerListHeaderAndFooter( player.sendPlayerListHeaderAndFooter(
player.getPlayerListHeader(), player.getPlayerListFooter()); player.getPlayerListHeader(), player.getPlayerListFooter());
// The client cleared the tab list. TODO: Restore changes done via TabList API // The client cleared the tab list. TODO: Restore changes done via TabList API
player.getTabList().clearAllSilent(); player.tabList().clearAllSilent();
} else { } else {
smc.setActiveSessionHandler(StateRegistry.PLAY, smc.setActiveSessionHandler(StateRegistry.PLAY,
new TransitionSessionHandler(server, serverConn, resultFuture)); new TransitionSessionHandler(server, serverConn, resultFuture));
} }
if (player.getAppliedResourcePack() == null && resourcePackToApply != null) { if (player.appliedResourcePack() == null && resourcePackToApply != null) {
player.queueResourcePack(resourcePackToApply); player.queueResourcePack(resourcePackToApply);
} }
smc.setAutoReading(true); smc.setAutoReading(true);
@ -181,25 +181,25 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(Disconnect packet) { public boolean handle(Disconnect packet) {
serverConn.disconnect(); serverConn.disconnect();
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.server()));
return true; return true;
} }
@Override @Override
public boolean handle(PluginMessage packet) { public boolean handle(PluginMessage packet) {
if (PluginMessageUtil.isMcBrand(packet)) { if (PluginMessageUtil.isMcBrand(packet)) {
serverConn.getPlayer().getConnection().write( serverConn.player().getConnection().write(
PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(), PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(),
serverConn.getPlayer().getProtocolVersion())); serverConn.player().protocolVersion()));
} else { } else {
serverConn.getPlayer().getConnection().write(packet.retain()); serverConn.player().getConnection().write(packet.retain());
} }
return true; return true;
} }
@Override @Override
public boolean handle(RegistrySync packet) { public boolean handle(RegistrySync packet) {
serverConn.getPlayer().getConnection().write(packet.retain()); serverConn.player().getConnection().write(packet.retain());
return true; return true;
} }
@ -211,13 +211,13 @@ public class ConfigSessionHandler implements MinecraftSessionHandler {
@Override @Override
public void handleGeneric(MinecraftPacket packet) { public void handleGeneric(MinecraftPacket packet) {
serverConn.getPlayer().getConnection().write(packet); serverConn.player().getConnection().write(packet);
} }
private void switchFailure(Throwable cause) { private void switchFailure(Throwable cause) {
logger.error("Unable to switch to new server {} for {}", serverConn.getServerInfo().getName(), logger.error("Unable to switch to new server {} for {}", serverConn.serverInfo().name(),
serverConn.getPlayer().getUsername(), cause); serverConn.player().username(), cause);
serverConn.getPlayer().disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); serverConn.player().disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
resultFuture.completeExceptionally(cause); resultFuture.completeExceptionally(cause);
} }

Datei anzeigen

@ -94,7 +94,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
requestedForwardingVersion = packet.content().readByte(); requestedForwardingVersion = packet.content().readByte();
} }
ByteBuf forwardingData = createForwardingData(configuration.getForwardingSecret(), ByteBuf forwardingData = createForwardingData(configuration.getForwardingSecret(),
serverConn.getPlayerRemoteAddressAsString(), serverConn.getPlayer(), serverConn.getPlayerRemoteAddressAsString(), serverConn.player(),
requestedForwardingVersion); requestedForwardingVersion);
LoginPluginResponse response = new LoginPluginResponse(packet.getId(), true, forwardingData); LoginPluginResponse response = new LoginPluginResponse(packet.getId(), true, forwardingData);
@ -113,9 +113,9 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
this.server.getEventManager().fire(new ServerLoginPluginMessageEvent(serverConn, identifier, this.server.getEventManager().fire(new ServerLoginPluginMessageEvent(serverConn, identifier,
contents, packet.getId())) contents, packet.getId()))
.thenAcceptAsync(event -> { .thenAcceptAsync(event -> {
if (event.getResult().isAllowed()) { if (event.result().allowed()) {
mc.write(new LoginPluginResponse(packet.getId(), true, Unpooled mc.write(new LoginPluginResponse(packet.getId(), true, Unpooled
.wrappedBuffer(event.getResult().getResponse()))); .wrappedBuffer(event.result().response())));
} else { } else {
mc.write(new LoginPluginResponse(packet.getId(), false, Unpooled.EMPTY_BUFFER)); mc.write(new LoginPluginResponse(packet.getId(), false, Unpooled.EMPTY_BUFFER));
} }
@ -126,7 +126,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(Disconnect packet) { public boolean handle(Disconnect packet) {
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.server()));
serverConn.disconnect(); serverConn.disconnect();
return true; return true;
} }
@ -142,7 +142,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN if (server.getConfiguration().getPlayerInfoForwardingMode() == PlayerInfoForwarding.MODERN
&& !informationForwarded) { && !informationForwarded) {
resultFuture.complete(ConnectionRequestResults.forDisconnect(MODERN_IP_FORWARDING_FAILURE, resultFuture.complete(ConnectionRequestResults.forDisconnect(MODERN_IP_FORWARDING_FAILURE,
serverConn.getServer())); serverConn.server()));
serverConn.disconnect(); serverConn.disconnect();
return true; return true;
} }
@ -159,7 +159,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
smc.write(new LoginAcknowledged()); smc.write(new LoginAcknowledged());
smc.setActiveSessionHandler(StateRegistry.CONFIG, smc.setActiveSessionHandler(StateRegistry.CONFIG,
new ConfigSessionHandler(server, serverConn, resultFuture)); new ConfigSessionHandler(server, serverConn, resultFuture));
ConnectedPlayer player = serverConn.getPlayer(); ConnectedPlayer player = serverConn.player();
if (player.getClientSettingsPacket() != null) { if (player.getClientSettingsPacket() != null) {
smc.write(player.getClientSettingsPacket()); smc.write(player.getClientSettingsPacket());
} }
@ -200,14 +200,14 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
// Ensure we are in range // Ensure we are in range
requested = Math.min(requested, VelocityConstants.MODERN_FORWARDING_MAX_VERSION); requested = Math.min(requested, VelocityConstants.MODERN_FORWARDING_MAX_VERSION);
if (requested > VelocityConstants.MODERN_FORWARDING_DEFAULT) { if (requested > VelocityConstants.MODERN_FORWARDING_DEFAULT) {
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) { if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
return requested >= VelocityConstants.MODERN_LAZY_SESSION return requested >= VelocityConstants.MODERN_LAZY_SESSION
? VelocityConstants.MODERN_LAZY_SESSION ? VelocityConstants.MODERN_LAZY_SESSION
: VelocityConstants.MODERN_FORWARDING_DEFAULT; : VelocityConstants.MODERN_FORWARDING_DEFAULT;
} }
if (player.getIdentifiedKey() != null) { if (player.identifiedKey() != null) {
// No enhanced switch on java 11 // No enhanced switch on java 11
switch (player.getIdentifiedKey().getKeyRevision()) { switch (player.identifiedKey().revision()) {
case GENERIC_V1: case GENERIC_V1:
return VelocityConstants.MODERN_FORWARDING_WITH_KEY; return VelocityConstants.MODERN_FORWARDING_WITH_KEY;
// Since V2 is not backwards compatible we have to throw the key if v2 and requested is v1 // Since V2 is not backwards compatible we have to throw the key if v2 and requested is v1
@ -233,15 +233,15 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
ProtocolUtils.writeVarInt(forwarded, actualVersion); ProtocolUtils.writeVarInt(forwarded, actualVersion);
ProtocolUtils.writeString(forwarded, address); ProtocolUtils.writeString(forwarded, address);
ProtocolUtils.writeUuid(forwarded, player.getGameProfile().getId()); ProtocolUtils.writeUuid(forwarded, player.profile().uuid());
ProtocolUtils.writeString(forwarded, player.getGameProfile().getName()); ProtocolUtils.writeString(forwarded, player.profile().name());
ProtocolUtils.writeProperties(forwarded, player.getGameProfile().getProperties()); ProtocolUtils.writeProperties(forwarded, player.profile().properties());
// This serves as additional redundancy. The key normally is stored in the // This serves as additional redundancy. The key normally is stored in the
// login start to the server, but some setups require this. // login start to the server, but some setups require this.
if (actualVersion >= VelocityConstants.MODERN_FORWARDING_WITH_KEY if (actualVersion >= VelocityConstants.MODERN_FORWARDING_WITH_KEY
&& actualVersion < VelocityConstants.MODERN_LAZY_SESSION) { && actualVersion < VelocityConstants.MODERN_LAZY_SESSION) {
IdentifiedKey key = player.getIdentifiedKey(); IdentifiedKey key = player.identifiedKey();
assert key != null; assert key != null;
ProtocolUtils.writePlayerKey(forwarded, key); ProtocolUtils.writePlayerKey(forwarded, key);
@ -249,9 +249,9 @@ public class LoginSessionHandler implements MinecraftSessionHandler {
// assigned UUID. Doing that breaks the signatures anyway but the server // assigned UUID. Doing that breaks the signatures anyway but the server
// should be able to verify the key independently. // should be able to verify the key independently.
if (actualVersion >= VelocityConstants.MODERN_FORWARDING_WITH_KEY_V2) { if (actualVersion >= VelocityConstants.MODERN_FORWARDING_WITH_KEY_V2) {
if (key.getSignatureHolder() != null) { if (key.signatureHolder() != null) {
forwarded.writeBoolean(true); forwarded.writeBoolean(true);
ProtocolUtils.writeUuid(forwarded, key.getSignatureHolder()); ProtocolUtils.writeUuid(forwarded, key.signatureHolder());
} else { } else {
// Should only not be provided if the player was connected // Should only not be provided if the player was connected
// as offline-mode and the signer UUID was not backfilled // as offline-mode and the signer UUID was not backfilled

Datei anzeigen

@ -69,7 +69,7 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
this.serverConn = serverConn; this.serverConn = serverConn;
this.resultFuture = resultFuture; this.resultFuture = resultFuture;
this.bungeecordMessageResponder = new BungeeCordMessageResponder(server, this.bungeecordMessageResponder = new BungeeCordMessageResponder(server,
serverConn.getPlayer()); serverConn.player());
} }
@Override @Override
@ -91,10 +91,10 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
@Override @Override
public boolean handle(JoinGame packet) { public boolean handle(JoinGame packet) {
MinecraftConnection smc = serverConn.ensureConnected(); MinecraftConnection smc = serverConn.ensureConnected();
RegisteredServer previousServer = serverConn.getPreviousServer().orElse(null); RegisteredServer previousServer = serverConn.previousServer().orElse(null);
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.
@ -111,7 +111,7 @@ 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.getEventManager()
.fire(new ServerConnectedEvent(player, serverConn.getServer(), previousServer)) .fire(new ServerConnectedEvent(player, serverConn.server(), previousServer))
.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()) {
@ -142,7 +142,7 @@ 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);
// Send client settings. In 1.20.2+ this is done in the config state. // Send client settings. In 1.20.2+ this is done in the config state.
if (smc.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_20_2) < 0 if (smc.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_20_2) < 0
@ -153,11 +153,11 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
// We're done! :) // We're done! :)
server.getEventManager().fireAndForget(new ServerPostConnectEvent(player, server.getEventManager().fireAndForget(new ServerPostConnectEvent(player,
previousServer)); previousServer));
resultFuture.complete(ConnectionRequestResults.successful(serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.successful(serverConn.server()));
}, smc.eventLoop()).exceptionally(exc -> { }, smc.eventLoop()).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;
@ -176,9 +176,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.server()));
} else { } else {
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.getServer())); resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.server()));
} }
return true; return true;
@ -191,23 +191,23 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
} }
// 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

@ -102,7 +102,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)
@ -135,7 +135,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
} }
String getPlayerRemoteAddressAsString() { String getPlayerRemoteAddressAsString() {
final SocketAddress address = proxyPlayer.getRemoteAddress(); final SocketAddress address = proxyPlayer.remoteAddress();
if (!(address instanceof InetSocketAddress)) { if (!(address instanceof InetSocketAddress)) {
return address.toString(); return address.toString();
} }
@ -148,9 +148,9 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
} }
private String getHandshakeRemoteAddress() { private String getHandshakeRemoteAddress() {
return proxyPlayer.getVirtualHost() return proxyPlayer.virtualHost()
.map(InetSocketAddress::getHostString) .map(InetSocketAddress::getHostString)
.or(() -> Optional.of(registeredServer.getServerInfo().getAddress()) .or(() -> Optional.of(registeredServer.serverInfo().address())
.filter(addr -> addr instanceof InetSocketAddress) .filter(addr -> addr instanceof InetSocketAddress)
.map(addr -> ((InetSocketAddress) addr).getHostString())) .map(addr -> ((InetSocketAddress) addr).getHostString()))
.orElse(""); .orElse("");
@ -160,7 +160,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
// 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();
} }
@ -169,10 +169,10 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
.append('\0') .append('\0')
.append(getPlayerRemoteAddressAsString()) .append(getPlayerRemoteAddressAsString())
.append('\0') .append('\0')
.append(proxyPlayer.getGameProfile().getUndashedId()) .append(proxyPlayer.profile().undashedId())
.append('\0'); .append('\0');
GENERAL_GSON GENERAL_GSON
.toJson(propertiesTransform.apply(proxyPlayer.getGameProfile().getProperties()), data); .toJson(propertiesTransform.apply(proxyPlayer.profile().properties()), data);
return data.toString(); return data.toString();
} }
@ -208,7 +208,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());
} }
@ -216,11 +216,11 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
mc.setProtocolVersion(protocolVersion); mc.setProtocolVersion(protocolVersion);
mc.setActiveSessionHandler(StateRegistry.LOGIN); mc.setActiveSessionHandler(StateRegistry.LOGIN);
if (proxyPlayer.getIdentifiedKey() == null if (proxyPlayer.identifiedKey() == null
&& proxyPlayer.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) { && proxyPlayer.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
mc.delayedWrite(new ServerLogin(proxyPlayer.getUsername(), proxyPlayer.getUniqueId())); mc.delayedWrite(new ServerLogin(proxyPlayer.username(), proxyPlayer.uuid()));
} else { } else {
mc.delayedWrite(new ServerLogin(proxyPlayer.getUsername(), proxyPlayer.getIdentifiedKey())); mc.delayedWrite(new ServerLogin(proxyPlayer.username(), proxyPlayer.identifiedKey()));
} }
mc.flush(); mc.flush();
} }
@ -243,22 +243,22 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
} }
@Override @Override
public VelocityRegisteredServer getServer() { public VelocityRegisteredServer server() {
return registeredServer; return registeredServer;
} }
@Override @Override
public Optional<RegisteredServer> getPreviousServer() { public Optional<RegisteredServer> previousServer() {
return Optional.ofNullable(this.previousServer); return Optional.ofNullable(this.previousServer);
} }
@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;
} }
@ -275,8 +275,8 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
@Override @Override
public String toString() { public String toString() {
return "[server connection] " + proxyPlayer.getGameProfile().getName() + " -> " return "[server connection] " + proxyPlayer.profile().name() + " -> "
+ registeredServer.getServerInfo().getName(); + registeredServer.serverInfo().name();
} }
@Override @Override
@ -297,7 +297,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation,
MinecraftConnection mc = ensureConnected(); MinecraftConnection mc = ensureConnected();
PluginMessage message = new PluginMessage(identifier.getId(), data); PluginMessage message = new PluginMessage(identifier.id(), data);
mc.write(message); mc.write(message);
return true; return true;
} }

Datei anzeigen

@ -52,6 +52,7 @@ import net.kyori.adventure.text.format.NamedTextColor;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
* A session handler that is activated to complete the login phase. * A session handler that is activated to complete the login phase.
@ -93,9 +94,9 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
} }
// 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.profileToUse(),
mcConnection, inbound.getVirtualHost().orElse(null), onlineMode, mcConnection, inbound.virtualHost().orElse(null), onlineMode,
inbound.getIdentifiedKey()); inbound.identifiedKey());
this.connectedPlayer = player; this.connectedPlayer = player;
if (!server.canRegisterConnection(player)) { if (!server.canRegisterConnection(player)) {
player.disconnect0( player.disconnect0(
@ -117,8 +118,8 @@ public class AuthSessionHandler 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.setPermissionChecker(checker); player.setPermissionChecker(checker);
} }
@ -138,32 +139,32 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
mcConnection.setCompressionThreshold(threshold); mcConnection.setCompressionThreshold(threshold);
} }
VelocityConfiguration configuration = server.getConfiguration(); VelocityConfiguration configuration = server.getConfiguration();
UUID playerUniqueId = player.getUniqueId(); UUID playerUniqueId = player.uuid();
if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.NONE) { if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.NONE) {
playerUniqueId = UuidUtils.generateOfflinePlayerUuid(player.getUsername()); playerUniqueId = UuidUtils.generateOfflinePlayerUuid(player.username());
} }
if (player.getIdentifiedKey() != null) { if (player.identifiedKey() != null) {
IdentifiedKey playerKey = player.getIdentifiedKey(); IdentifiedKey playerKey = player.identifiedKey();
if (playerKey.getSignatureHolder() == null) { if (playerKey.signatureHolder() == null) {
if (playerKey instanceof IdentifiedKeyImpl) { if (playerKey instanceof IdentifiedKeyImpl) {
IdentifiedKeyImpl unlinkedKey = (IdentifiedKeyImpl) playerKey; IdentifiedKeyImpl unlinkedKey = (IdentifiedKeyImpl) playerKey;
// Failsafe // Failsafe
if (!unlinkedKey.internalAddHolder(player.getUniqueId())) { if (!unlinkedKey.internalAddHolder(player.uuid())) {
if (onlineMode) { if (onlineMode) {
inbound.disconnect( inbound.disconnect(
Component.translatable("multiplayer.disconnect.invalid_public_key")); Component.translatable("multiplayer.disconnect.invalid_public_key"));
return; return;
} else { } else {
logger.warn("Key for player " + player.getUsername() + " could not be verified!"); logger.warn("Key for player " + player.username() + " could not be verified!");
} }
} }
} else { } else {
logger.warn("A custom key type has been set for player " + player.getUsername()); logger.warn("A custom key type has been set for player " + player.username());
} }
} else { } else {
if (!Objects.equals(playerKey.getSignatureHolder(), playerUniqueId)) { if (!Objects.equals(playerKey.signatureHolder(), playerUniqueId)) {
logger.warn("UUID for Player " + player.getUsername() + " mismatches! " logger.warn("UUID for Player " + player.username() + " mismatches! "
+ "Chat/Commands signatures will not work correctly for this player!"); + "Chat/Commands signatures will not work correctly for this player!");
} }
} }
@ -201,9 +202,9 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
return; return;
} }
Optional<Component> reason = event.getResult().getReasonComponent(); @Nullable Component explanation = event.result().explanation();
if (reason.isPresent()) { if (explanation != null) {
player.disconnect0(reason.get(), true); player.disconnect0(explanation, true);
} else { } else {
if (!server.registerConnection(player)) { if (!server.registerConnection(player)) {
player.disconnect0(Component.translatable("velocity.error.already-connected-proxy"), player.disconnect0(Component.translatable("velocity.error.already-connected-proxy"),
@ -212,13 +213,13 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
} }
ServerLoginSuccess success = new ServerLoginSuccess(); ServerLoginSuccess success = new ServerLoginSuccess();
success.setUsername(player.getUsername()); success.setUsername(player.username());
success.setProperties(player.getGameProfileProperties()); success.setProperties(player.profileProperties());
success.setUuid(player.getUniqueId()); success.setUuid(player.uuid());
mcConnection.write(success); mcConnection.write(success);
loginState = State.SUCCESS_SENT; loginState = State.SUCCESS_SENT;
if (inbound.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_20_2) < 0) { if (inbound.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_20_2) < 0) {
loginState = State.ACKNOWLEDGED; loginState = State.ACKNOWLEDGED;
mcConnection.setActiveSessionHandler(StateRegistry.PLAY, mcConnection.setActiveSessionHandler(StateRegistry.PLAY,
new InitialConnectSessionHandler(player, server)); new InitialConnectSessionHandler(player, server));

Datei anzeigen

@ -116,10 +116,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
this.player = player; this.player = player;
this.server = server; this.server = server;
if (this.player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) { if (this.player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
this.chatHandler = new SessionChatHandler(this.player, this.server); this.chatHandler = new SessionChatHandler(this.player, this.server);
this.commandHandler = new SessionCommandHandler(this.player, this.server); this.commandHandler = new SessionCommandHandler(this.player, this.server);
} else if (this.player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0) { } else if (this.player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0) {
this.chatHandler = new KeyedChatHandler(this.server, this.player); this.chatHandler = new KeyedChatHandler(this.server, this.player);
this.commandHandler = new KeyedCommandHandler(this.player, this.server); this.commandHandler = new KeyedCommandHandler(this.player, this.server);
} else { } else {
@ -154,9 +154,9 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
public void activated() { public void activated() {
configSwitchFuture = new CompletableFuture<>(); configSwitchFuture = new CompletableFuture<>();
Collection<String> channels = Collection<String> channels =
server.getChannelRegistrar().getChannelsForProtocol(player.getProtocolVersion()); server.getChannelRegistrar().getChannelsForProtocol(player.protocolVersion());
if (!channels.isEmpty()) { if (!channels.isEmpty()) {
PluginMessage register = constructChannelsPacket(player.getProtocolVersion(), channels); PluginMessage register = constructChannelsPacket(player.protocolVersion(), channels);
player.getConnection().write(register); player.getConnection().write(register);
} }
} }
@ -320,7 +320,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
player.setClientBrand(brand); player.setClientBrand(brand);
backendConn.write( backendConn.write(
PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(), PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(),
player.getProtocolVersion())); player.protocolVersion()));
} else if (BungeeCordMessageResponder.isBungeeCordMessage(packet)) { } else if (BungeeCordMessageResponder.isBungeeCordMessage(packet)) {
return true; return true;
} else { } else {
@ -355,7 +355,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
byte[] copy = ByteBufUtil.getBytes(packet.content()); byte[] copy = ByteBufUtil.getBytes(packet.content());
PluginMessageEvent event = new PluginMessageEvent(player, serverConn, id, copy); PluginMessageEvent event = new PluginMessageEvent(player, serverConn, id, copy);
server.getEventManager().fire(event).thenAcceptAsync(pme -> { server.getEventManager().fire(event).thenAcceptAsync(pme -> {
if (pme.getResult().isAllowed()) { if (pme.result().allowed()) {
PluginMessage message = new PluginMessage(packet.getChannel(), PluginMessage message = new PluginMessage(packet.getChannel(),
Unpooled.wrappedBuffer(copy)); Unpooled.wrappedBuffer(copy));
if (!player.getPhase().consideredComplete() || !serverConn.getPhase() if (!player.getPhase().consideredComplete() || !serverConn.getPhase()
@ -486,7 +486,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
spawned = false; spawned = false;
serverBossBars.clear(); serverBossBars.clear();
player.clearPlayerListHeaderAndFooterSilent(); player.clearPlayerListHeaderAndFooterSilent();
player.getTabList().clearAllSilent(); player.tabList().clearAllSilent();
} }
player.switchToConfigState(); player.switchToConfigState();
@ -513,7 +513,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();
// The player is switching from a server already, so we need to tell the client to change // The player is switching from a server already, so we need to tell the client to change
// entity IDs and send new dimension information. // entity IDs and send new dimension information.
@ -551,10 +551,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
} }
// Clear any title from the previous server. // Clear any title from the previous server.
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
player.getConnection().delayedWrite( player.getConnection().delayedWrite(
GenericTitlePacket.constructTitlePacket(GenericTitlePacket.ActionType.RESET, GenericTitlePacket.constructTitlePacket(GenericTitlePacket.ActionType.RESET,
player.getProtocolVersion())); player.protocolVersion()));
} }
// Flush everything // Flush everything
@ -574,7 +574,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
// improving compatibility with mods. // improving compatibility with mods.
final Respawn respawn = Respawn.fromJoinGame(joinGame); final Respawn respawn = Respawn.fromJoinGame(joinGame);
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_16) < 0) { if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_16) < 0) {
// 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.
@ -616,7 +616,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
String commandLabel = command.substring(0, commandEndPosition); String commandLabel = command.substring(0, commandEndPosition);
if (!server.getCommandManager().hasCommand(commandLabel)) { if (!server.getCommandManager().hasCommand(commandLabel)) {
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0) { if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0) {
// 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;
@ -658,7 +658,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
} }
private boolean handleRegularTabComplete(TabCompleteRequest packet) { private boolean handleRegularTabComplete(TabCompleteRequest packet) {
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0) { if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0) {
// 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;
@ -690,7 +690,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
server.getCommandManager().offerBrigadierSuggestions(player, command) server.getCommandManager().offerBrigadierSuggestions(player, command)
.thenAcceptAsync(offers -> { .thenAcceptAsync(offers -> {
boolean legacy = boolean legacy =
player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0; player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0;
try { try {
for (Suggestion suggestion : offers.getList()) { for (Suggestion suggestion : offers.getList()) {
String offer = suggestion.getText(); String offer = suggestion.getText();
@ -709,7 +709,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(), command, player.username(), command,
e); e);
} }
}, player.getConnection().eventLoop()).exceptionally((ex) -> { }, player.getConnection().eventLoop()).exceptionally((ex) -> {
@ -729,7 +729,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
server.getEventManager().fire(new TabCompleteEvent(player, request.getCommand(), offers)) server.getEventManager().fire(new TabCompleteEvent(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);

Datei anzeigen

@ -42,7 +42,7 @@ public class ClientSettingsWrapper implements PlayerSettings {
} }
@Override @Override
public Locale getLocale() { public Locale locale() {
if (locale == null) { if (locale == null) {
locale = Locale.forLanguageTag(settings.getLocale().replaceAll("_", "-")); locale = Locale.forLanguageTag(settings.getLocale().replaceAll("_", "-"));
} }
@ -50,12 +50,12 @@ public class ClientSettingsWrapper implements PlayerSettings {
} }
@Override @Override
public byte getViewDistance() { public byte viewDistance() {
return settings.getViewDistance(); return settings.getViewDistance();
} }
@Override @Override
public ChatMode getChatMode() { public ChatMode chatMode() {
int chat = settings.getChatVisibility(); int chat = settings.getChatVisibility();
if (chat < 0 || chat > 2) { if (chat < 0 || chat > 2) {
return ChatMode.SHOWN; return ChatMode.SHOWN;
@ -69,12 +69,12 @@ public class ClientSettingsWrapper implements PlayerSettings {
} }
@Override @Override
public SkinParts getSkinParts() { public SkinParts skinParts() {
return parts; return parts;
} }
@Override @Override
public MainHand getMainHand() { public MainHand mainHand() {
return settings.getMainHand() == 1 ? MainHand.RIGHT : MainHand.LEFT; return settings.getMainHand() == 1 ? MainHand.RIGHT : MainHand.LEFT;
} }

Datei anzeigen

@ -51,7 +51,6 @@ import com.velocitypowered.proxy.VelocityServer;
import com.velocitypowered.proxy.connection.MinecraftConnection; import com.velocitypowered.proxy.connection.MinecraftConnection;
import com.velocitypowered.proxy.connection.MinecraftConnectionAssociation; import com.velocitypowered.proxy.connection.MinecraftConnectionAssociation;
import com.velocitypowered.proxy.connection.backend.VelocityServerConnection; import com.velocitypowered.proxy.connection.backend.VelocityServerConnection;
import com.velocitypowered.proxy.connection.player.VelocityResourcePackInfo;
import com.velocitypowered.proxy.connection.util.ConnectionMessages; import com.velocitypowered.proxy.connection.util.ConnectionMessages;
import com.velocitypowered.proxy.connection.util.ConnectionRequestResults.Impl; import com.velocitypowered.proxy.connection.util.ConnectionRequestResults.Impl;
import com.velocitypowered.proxy.connection.util.VelocityInboundConnection; import com.velocitypowered.proxy.connection.util.VelocityInboundConnection;
@ -162,10 +161,10 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
private @Nullable ResourcePackInfo pendingResourcePack; private @Nullable ResourcePackInfo pendingResourcePack;
private @Nullable ResourcePackInfo appliedResourcePack; private @Nullable ResourcePackInfo appliedResourcePack;
private final @NotNull Pointers pointers = Player.super.pointers().toBuilder() private final @NotNull Pointers pointers = Player.super.pointers().toBuilder()
.withDynamic(Identity.UUID, this::getUniqueId) .withDynamic(Identity.UUID, this::uuid)
.withDynamic(Identity.NAME, this::getUsername) .withDynamic(Identity.NAME, this::username)
.withDynamic(Identity.DISPLAY_NAME, () -> Component.text(this.getUsername())) .withDynamic(Identity.DISPLAY_NAME, () -> Component.text(this.username()))
.withDynamic(Identity.LOCALE, this::getEffectiveLocale) .withDynamic(Identity.LOCALE, this::effectiveLocale)
.withDynamic(PermissionChecker.POINTER, () -> this.permissionChecker) .withDynamic(PermissionChecker.POINTER, () -> this.permissionChecker)
.withStatic(FacetPointers.TYPE, Type.PLAYER) .withStatic(FacetPointers.TYPE, Type.PLAYER)
.build(); .build();
@ -196,7 +195,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
this.playerKey = playerKey; this.playerKey = playerKey;
this.chatQueue = new ChatQueue(this); this.chatQueue = new ChatQueue(this);
this.chatBuilderFactory = new ChatBuilderFactory(this.getProtocolVersion()); this.chatBuilderFactory = new ChatBuilderFactory(this.protocolVersion());
} }
public ChatBuilderFactory getChatBuilderFactory() { public ChatBuilderFactory getChatBuilderFactory() {
@ -213,14 +212,14 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public String getUsername() { public String username() {
return profile.getName(); return profile.name();
} }
@Override @Override
public Locale getEffectiveLocale() { public Locale effectiveLocale() {
if (effectiveLocale == null && settings != null) { if (effectiveLocale == null && settings != null) {
return settings.getLocale(); return settings.locale();
} }
return effectiveLocale; return effectiveLocale;
} }
@ -231,12 +230,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public UUID getUniqueId() { public UUID uuid() {
return profile.getId(); return profile.uuid();
} }
@Override @Override
public Optional<ServerConnection> getCurrentServer() { public Optional<ServerConnection> connectedServer() {
return Optional.ofNullable(connectedServer); return Optional.ofNullable(connectedServer);
} }
@ -254,7 +253,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public GameProfile getGameProfile() { public GameProfile profile() {
return profile; return profile;
} }
@ -263,7 +262,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public long getPing() { public long ping() {
return this.ping; return this.ping;
} }
@ -277,7 +276,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public PlayerSettings getPlayerSettings() { public PlayerSettings settings() {
return settings == null ? ClientSettingsWrapper.DEFAULT : this.settings; return settings == null ? ClientSettingsWrapper.DEFAULT : this.settings;
} }
@ -301,7 +300,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public Optional<ModInfo> getModInfo() { public Optional<ModInfo> modInfo() {
return Optional.ofNullable(modInfo); return Optional.ofNullable(modInfo);
} }
@ -316,12 +315,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public SocketAddress getRemoteAddress() { public SocketAddress remoteAddress() {
return connection.getRemoteAddress(); return connection.getRemoteAddress();
} }
@Override @Override
public Optional<InetSocketAddress> getVirtualHost() { public Optional<InetSocketAddress> virtualHost() {
return Optional.ofNullable(virtualHost); return Optional.ofNullable(virtualHost);
} }
@ -335,7 +334,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return connection.getProtocolVersion(); return connection.getProtocolVersion();
} }
@ -347,7 +346,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
*/ */
public Component translateMessage(Component message) { public Component translateMessage(Component message) {
Locale locale = ClosestLocaleMatcher.INSTANCE Locale locale = ClosestLocaleMatcher.INSTANCE
.lookupClosest(getEffectiveLocale() == null ? Locale.getDefault() : getEffectiveLocale()); .lookupClosest(effectiveLocale() == null ? Locale.getDefault() : effectiveLocale());
return GlobalTranslator.render(message, locale); return GlobalTranslator.render(message, locale);
} }
@ -377,7 +376,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
public void sendActionBar(net.kyori.adventure.text.@NonNull Component message) { public void sendActionBar(net.kyori.adventure.text.@NonNull Component message) {
Component translated = translateMessage(message); Component translated = translateMessage(message);
ProtocolVersion playerVersion = getProtocolVersion(); ProtocolVersion playerVersion = protocolVersion();
if (playerVersion.compareTo(ProtocolVersion.MINECRAFT_1_11) >= 0) { if (playerVersion.compareTo(ProtocolVersion.MINECRAFT_1_11) >= 0) {
// Use the title packet instead. // Use the title packet instead.
GenericTitlePacket pkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket pkt = GenericTitlePacket.constructTitlePacket(
@ -424,18 +423,18 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
Component translatedFooter = translateMessage(footer); Component translatedFooter = translateMessage(footer);
this.playerListHeader = translatedHeader; this.playerListHeader = translatedHeader;
this.playerListFooter = translatedFooter; this.playerListFooter = translatedFooter;
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
this.connection.write(HeaderAndFooter.create(header, footer, this.getProtocolVersion())); this.connection.write(HeaderAndFooter.create(header, footer, this.protocolVersion()));
} }
} }
@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());
GenericTitlePacket timesPkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket timesPkt = GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.SET_TIMES, this.getProtocolVersion()); GenericTitlePacket.ActionType.SET_TIMES, this.protocolVersion());
net.kyori.adventure.title.Title.Times times = title.times(); net.kyori.adventure.title.Title.Times times = title.times();
if (times != null) { if (times != null) {
timesPkt.setFadeIn((int) DurationUtils.toTicks(times.fadeIn())); timesPkt.setFadeIn((int) DurationUtils.toTicks(times.fadeIn()));
@ -445,12 +444,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
connection.delayedWrite(timesPkt); connection.delayedWrite(timesPkt);
GenericTitlePacket subtitlePkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket subtitlePkt = GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.SET_SUBTITLE, this.getProtocolVersion()); GenericTitlePacket.ActionType.SET_SUBTITLE, this.protocolVersion());
subtitlePkt.setComponent(serializer.serialize(translateMessage(title.subtitle()))); subtitlePkt.setComponent(serializer.serialize(translateMessage(title.subtitle())));
connection.delayedWrite(subtitlePkt); connection.delayedWrite(subtitlePkt);
GenericTitlePacket titlePkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket titlePkt = GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.SET_TITLE, this.getProtocolVersion()); GenericTitlePacket.ActionType.SET_TITLE, this.protocolVersion());
titlePkt.setComponent(serializer.serialize(translateMessage(title.title()))); titlePkt.setComponent(serializer.serialize(translateMessage(title.title())));
connection.delayedWrite(titlePkt); connection.delayedWrite(titlePkt);
@ -467,27 +466,27 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
throw new NullPointerException("value"); throw new NullPointerException("value");
} }
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) < 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) < 0) {
return; return;
} }
GsonComponentSerializer serializer = ProtocolUtils.getJsonChatSerializer(this GsonComponentSerializer serializer = ProtocolUtils.getJsonChatSerializer(this
.getProtocolVersion()); .protocolVersion());
if (part == TitlePart.TITLE) { if (part == TitlePart.TITLE) {
GenericTitlePacket titlePkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket titlePkt = GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.SET_TITLE, this.getProtocolVersion()); GenericTitlePacket.ActionType.SET_TITLE, this.protocolVersion());
titlePkt.setComponent(serializer.serialize(translateMessage((Component) value))); titlePkt.setComponent(serializer.serialize(translateMessage((Component) value)));
connection.write(titlePkt); connection.write(titlePkt);
} else if (part == TitlePart.SUBTITLE) { } else if (part == TitlePart.SUBTITLE) {
GenericTitlePacket titlePkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket titlePkt = GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.SET_SUBTITLE, this.getProtocolVersion()); GenericTitlePacket.ActionType.SET_SUBTITLE, this.protocolVersion());
titlePkt.setComponent(serializer.serialize(translateMessage((Component) value))); titlePkt.setComponent(serializer.serialize(translateMessage((Component) value)));
connection.write(titlePkt); connection.write(titlePkt);
} else if (part == TitlePart.TIMES) { } else if (part == TitlePart.TIMES) {
Times times = (Times) value; Times times = (Times) value;
GenericTitlePacket timesPkt = GenericTitlePacket.constructTitlePacket( GenericTitlePacket timesPkt = GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.SET_TIMES, this.getProtocolVersion()); GenericTitlePacket.ActionType.SET_TIMES, this.protocolVersion());
timesPkt.setFadeIn((int) DurationUtils.toTicks(times.fadeIn())); timesPkt.setFadeIn((int) DurationUtils.toTicks(times.fadeIn()));
timesPkt.setStay((int) DurationUtils.toTicks(times.stay())); timesPkt.setStay((int) DurationUtils.toTicks(times.stay()));
timesPkt.setFadeOut((int) DurationUtils.toTicks(times.fadeOut())); timesPkt.setFadeOut((int) DurationUtils.toTicks(times.fadeOut()));
@ -499,30 +498,30 @@ 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(GenericTitlePacket.constructTitlePacket( connection.write(GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.HIDE, this.getProtocolVersion())); GenericTitlePacket.ActionType.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(GenericTitlePacket.constructTitlePacket( connection.write(GenericTitlePacket.constructTitlePacket(
GenericTitlePacket.ActionType.RESET, this.getProtocolVersion())); GenericTitlePacket.ActionType.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);
} }
} }
@ -538,19 +537,19 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public List<GameProfile.Property> getGameProfileProperties() { public List<GameProfile.Property> profileProperties() {
return this.profile.getProperties(); return this.profile.properties();
} }
@Override @Override
public void setGameProfileProperties(List<GameProfile.Property> properties) { public void setProfileProperties(List<GameProfile.Property> properties) {
this.profile = profile.withProperties(Preconditions.checkNotNull(properties)); this.profile = profile.withProperties(Preconditions.checkNotNull(properties));
} }
@Override @Override
public void clearPlayerListHeaderAndFooter() { public void clearPlayerListHeaderAndFooter() {
clearPlayerListHeaderAndFooterSilent(); clearPlayerListHeaderAndFooterSilent();
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
this.connection.write(HeaderAndFooter.reset()); this.connection.write(HeaderAndFooter.reset());
} }
} }
@ -561,7 +560,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public InternalTabList getTabList() { public InternalTabList tabList() {
return tabList; return tabList;
} }
@ -587,7 +586,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
logger.info("{} has disconnected: {}", this, logger.info("{} has disconnected: {}", this,
LegacyComponentSerializer.legacySection().serialize(translated)); LegacyComponentSerializer.legacySection().serialize(translated));
} }
connection.closeWith(Disconnect.create(translated, this.getProtocolVersion())); connection.closeWith(Disconnect.create(translated, this.protocolVersion()));
} }
public @Nullable VelocityServerConnection getConnectedServer() { public @Nullable VelocityServerConnection getConnectedServer() {
@ -629,14 +628,14 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
Component friendlyError; Component friendlyError;
if (connectedServer != null && connectedServer.getServerInfo().equals(server.getServerInfo())) { if (connectedServer != null && connectedServer.serverInfo().equals(server.serverInfo())) {
friendlyError = Component.translatable("velocity.error.connected-server-error", friendlyError = Component.translatable("velocity.error.connected-server-error",
Component.text(server.getServerInfo().getName())); Component.text(server.serverInfo().name()));
} 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);
friendlyError = Component.translatable("velocity.error.connecting-server-error", friendlyError = Component.translatable("velocity.error.connecting-server-error",
Component.text(server.getServerInfo().getName())); Component.text(server.serverInfo().name()));
} }
handleConnectionException(server, null, friendlyError.color(NamedTextColor.RED), safe); handleConnectionException(server, null, friendlyError.color(NamedTextColor.RED), safe);
} }
@ -657,19 +656,19 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
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.info("{}: kicked from server {}: {}", this, server.getServerInfo().getName(), logger.info("{}: kicked from server {}: {}", this, server.serverInfo().name(),
plainTextReason); plainTextReason);
handleConnectionException(server, disconnectReason, handleConnectionException(server, disconnectReason,
Component.translatable("velocity.error.moved-to-new-server", NamedTextColor.RED, Component.translatable("velocity.error.moved-to-new-server", NamedTextColor.RED,
Component.text(server.getServerInfo().getName()), Component.text(server.serverInfo().name()),
disconnectReason), safe); disconnectReason), 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, handleConnectionException(server, disconnectReason,
Component.translatable("velocity.error.cant-connect", NamedTextColor.RED, Component.translatable("velocity.error.cant-connect", NamedTextColor.RED,
Component.text(server.getServerInfo().getName()), Component.text(server.serverInfo().name()),
disconnectReason), safe); disconnectReason), safe);
} }
} }
@ -689,18 +688,18 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
return; return;
} }
boolean kickedFromCurrent = connectedServer == null || connectedServer.getServer().equals(rs); boolean kickedFromCurrent = connectedServer == null || connectedServer.server().equals(rs);
ServerKickResult result; ServerKickResult result;
if (kickedFromCurrent) { if (kickedFromCurrent) {
Optional<RegisteredServer> next = getNextServerToTry(rs); Optional<RegisteredServer> next = getNextServerToTry(rs);
result = result = next.map(RedirectPlayer::redirect)
next.map(RedirectPlayer::create).orElseGet(() -> DisconnectPlayer.create(friendlyReason)); .orElseGet(() -> DisconnectPlayer.disconnect(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.server().equals(rs)) {
resetInFlightConnection(); resetInFlightConnection();
} }
result = Notify.create(friendlyReason); result = Notify.notify(friendlyReason);
} }
KickedFromServerEvent originalEvent = new KickedFromServerEvent(this, rs, kickReason, KickedFromServerEvent originalEvent = new KickedFromServerEvent(this, rs, kickReason,
!kickedFromCurrent, result); !kickedFromCurrent, result);
@ -724,25 +723,25 @@ 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.getReasonComponent()); disconnect(res.reason());
} 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(), previousConnection).connect() createConnectionRequest(res.getServer(), previousConnection).connect()
.whenCompleteAsync((status, throwable) -> { .whenCompleteAsync((status, throwable) -> {
if (throwable != null) { if (throwable != null) {
handleConnectionException( handleConnectionException(
status != null ? status.getAttemptedConnection() : res.getServer(), throwable, status != null ? status.attemptedConnectedTo() : res.getServer(), throwable,
true); true);
return; return;
} }
switch (status.getStatus()) { switch (status.status()) {
// Impossible/nonsensical cases // Impossible/nonsensical cases
case ALREADY_CONNECTED: case ALREADY_CONNECTED:
logger.error("{}: already connected to {}", this, logger.error("{}: already connected to {}", this,
status.getAttemptedConnection().getServerInfo().getName()); status.attemptedConnectedTo().serverInfo().name());
break; break;
case CONNECTION_IN_PROGRESS: case CONNECTION_IN_PROGRESS:
// Fatal case // Fatal case
@ -751,13 +750,13 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
if (fallbackMsg == null) { if (fallbackMsg == null) {
fallbackMsg = friendlyReason; fallbackMsg = friendlyReason;
} }
disconnect(status.getReasonComponent().orElse(fallbackMsg)); disconnect(status.reason().orElse(fallbackMsg));
break; break;
case SERVER_DISCONNECTED: case SERVER_DISCONNECTED:
Component reason = status.getReasonComponent() Component reason = status.reason()
.orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); .orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
handleConnectionException(res.getServer(), handleConnectionException(res.getServer(),
Disconnect.create(reason, getProtocolVersion()), ((Impl) status).isSafe()); Disconnect.create(reason, protocolVersion()), ((Impl) status).isSafe());
break; break;
case SUCCESS: case SUCCESS:
Component requestedMessage = res.getMessageComponent(); Component requestedMessage = res.getMessageComponent();
@ -773,12 +772,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() && previousConnection != null) { if (event.kickedDuringServerConnect() && previousConnection != null) {
sendMessage(Identity.nil(), res.getMessageComponent()); sendMessage(Identity.nil(), res.reason());
} else { } else {
disconnect(res.getMessageComponent()); disconnect(res.reason());
} }
} 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.
@ -806,7 +805,7 @@ 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) String virtualHostStr = virtualHost().map(InetSocketAddress::getHostString)
.orElse("") .orElse("")
.toLowerCase(Locale.ROOT); .toLowerCase(Locale.ROOT);
serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(virtualHostStr, serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(virtualHostStr,
@ -824,8 +823,8 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
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.server(), toTryName))
|| (connectionInFlight != null && hasSameName(connectionInFlight.getServer(), toTryName)) || (connectionInFlight != null && hasSameName(connectionInFlight.server(), toTryName))
|| (current != null && hasSameName(current, toTryName))) { || (current != null && hasSameName(current, toTryName))) {
continue; continue;
} }
@ -837,7 +836,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
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);
} }
/** /**
@ -880,12 +879,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
connectedServer.disconnect(); connectedServer.disconnect();
} }
Optional<Player> connectedPlayer = server.getPlayer(this.getUniqueId()); Optional<Player> connectedPlayer = server.getPlayer(this.uuid());
server.unregisterConnection(this); server.unregisterConnection(this);
DisconnectEvent.LoginStatus status; DisconnectEvent.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
@ -915,12 +914,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
boolean isPlayerAddressLoggingEnabled = server.getConfiguration() boolean isPlayerAddressLoggingEnabled = server.getConfiguration()
.isPlayerAddressLoggingEnabled(); .isPlayerAddressLoggingEnabled();
String playerIp = String playerIp =
isPlayerAddressLoggingEnabled ? getRemoteAddress().toString() : "<ip address withheld>"; isPlayerAddressLoggingEnabled ? remoteAddress().toString() : "<ip address withheld>";
return "[connected player] " + profile.getName() + " (" + playerIp + ")"; return "[connected player] " + profile.name() + " (" + playerIp + ")";
} }
@Override @Override
public PermissionChecker getPermissionChecker() { public PermissionChecker permissionChecker() {
return this.permissionChecker; return this.permissionChecker;
} }
@ -928,7 +927,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
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");
PluginMessage message = new PluginMessage(identifier.getId(), Unpooled.wrappedBuffer(data)); PluginMessage message = new PluginMessage(identifier.id(), Unpooled.wrappedBuffer(data));
connection.write(message); connection.write(message);
return true; return true;
} }
@ -947,7 +946,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
Preconditions.checkArgument(input.length() <= LegacyChat.MAX_SERVERBOUND_MESSAGE_LENGTH, Preconditions.checkArgument(input.length() <= LegacyChat.MAX_SERVERBOUND_MESSAGE_LENGTH,
"input cannot be greater than " + LegacyChat.MAX_SERVERBOUND_MESSAGE_LENGTH "input cannot be greater than " + LegacyChat.MAX_SERVERBOUND_MESSAGE_LENGTH
+ " characters in length"); + " characters in length");
if (getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0) { if (protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0) {
this.chatQueue.hijack(getChatBuilderFactory().builder().asPlayer(this).message(input), this.chatQueue.hijack(getChatBuilderFactory().builder().asPlayer(this).message(input),
(instant, item) -> { (instant, item) -> {
item.setTimestamp(instant); item.setTimestamp(instant);
@ -959,21 +958,9 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
} }
@Override
@Deprecated
public void sendResourcePack(String url) {
sendResourcePackOffer(new VelocityResourcePackInfo.BuilderImpl(url).build());
}
@Override
@Deprecated
public void sendResourcePack(String url, byte[] hash) {
sendResourcePackOffer(new VelocityResourcePackInfo.BuilderImpl(url).setHash(hash).build());
}
@Override @Override
public void sendResourcePackOffer(ResourcePackInfo packInfo) { public void sendResourcePackOffer(ResourcePackInfo packInfo) {
if (this.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { if (this.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
Preconditions.checkNotNull(packInfo, "packInfo"); Preconditions.checkNotNull(packInfo, "packInfo");
queueResourcePack(packInfo); queueResourcePack(packInfo);
} }
@ -1000,7 +987,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
// Unless its 1.17+ and forced it will come back denied anyway // Unless its 1.17+ and forced it will come back denied anyway
while (!outstandingResourcePacks.isEmpty()) { while (!outstandingResourcePacks.isEmpty()) {
queued = outstandingResourcePacks.peek(); queued = outstandingResourcePacks.peek();
if (queued.getShouldForce() && getProtocolVersion() if (queued.required() && protocolVersion()
.compareTo(ProtocolVersion.MINECRAFT_1_17) >= 0) { .compareTo(ProtocolVersion.MINECRAFT_1_17) >= 0) {
break; break;
} }
@ -1014,26 +1001,26 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
ResourcePackRequest request = new ResourcePackRequest(); ResourcePackRequest request = new ResourcePackRequest();
request.setUrl(queued.getUrl()); request.setUrl(queued.url());
if (queued.getHash() != null) { if (queued.hash() != null) {
request.setHash(ByteBufUtil.hexDump(queued.getHash())); request.setHash(ByteBufUtil.hexDump(queued.hash()));
} else { } else {
request.setHash(""); request.setHash("");
} }
request.setRequired(queued.getShouldForce()); request.setRequired(queued.required());
request.setPrompt(queued.getPrompt()); request.setPrompt(queued.prompt());
connection.write(request); connection.write(request);
} }
} }
@Override @Override
public @Nullable ResourcePackInfo getAppliedResourcePack() { public @Nullable ResourcePackInfo appliedResourcePack() {
return appliedResourcePack; return appliedResourcePack;
} }
@Override @Override
public @Nullable ResourcePackInfo getPendingResourcePack() { public @Nullable ResourcePackInfo pendingResourcePack() {
return pendingResourcePack; return pendingResourcePack;
} }
@ -1055,11 +1042,11 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
server.getEventManager().fire(new PlayerResourcePackStatusEvent(this, status, queued)) server.getEventManager().fire(new PlayerResourcePackStatusEvent(this, status, queued))
.thenAcceptAsync(event -> { .thenAcceptAsync(event -> {
if (event.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED if (event.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED
&& event.getPackInfo() != null && event.getPackInfo().getShouldForce() && event.getPackInfo() != null && event.getPackInfo().required()
&& (!event.isOverwriteKick() || event.getPlayer() && (!event.isOverwriteKick() || event.player()
.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_17) >= 0) .protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_17) >= 0)
) { ) {
event.getPlayer().disconnect(Component event.player().disconnect(Component
.translatable("multiplayer.requiredTexturePrompt.disconnect")); .translatable("multiplayer.requiredTexturePrompt.disconnect"));
} }
}); });
@ -1088,7 +1075,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
return queued != null return queued != null
&& queued.getOriginalOrigin() != ResourcePackInfo.Origin.DOWNSTREAM_SERVER; && queued.originalOrigin() != ResourcePackInfo.Origin.DOWNSTREAM_SERVER;
} }
/** /**
@ -1147,7 +1134,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
} }
@Override @Override
public @Nullable IdentifiedKey getIdentifiedKey() { public @Nullable IdentifiedKey identifiedKey() {
return playerKey; return playerKey;
} }
@ -1155,7 +1142,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
@Override @Override
public @NonNull UUID uuid() { public @NonNull UUID uuid() {
return ConnectedPlayer.this.getUniqueId(); return ConnectedPlayer.this.uuid();
} }
} }
@ -1167,11 +1154,11 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
ConnectionRequestBuilderImpl(RegisteredServer toConnect, ConnectionRequestBuilderImpl(RegisteredServer toConnect,
@Nullable VelocityServerConnection previousConnection) { @Nullable VelocityServerConnection previousConnection) {
this.toConnect = Preconditions.checkNotNull(toConnect, "info"); this.toConnect = Preconditions.checkNotNull(toConnect, "info");
this.previousServer = previousConnection == null ? null : previousConnection.getServer(); this.previousServer = previousConnection == null ? null : previousConnection.server();
} }
@Override @Override
public RegisteredServer getServer() { public RegisteredServer server() {
return toConnect; return toConnect;
} }
@ -1183,7 +1170,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
return Optional.of(ConnectionRequestBuilder.Status.CONNECTION_IN_PROGRESS); return Optional.of(ConnectionRequestBuilder.Status.CONNECTION_IN_PROGRESS);
} }
if (connectedServer != null if (connectedServer != null
&& connectedServer.getServer().getServerInfo().equals(server.getServerInfo())) { && connectedServer.server().serverInfo().equals(server.serverInfo())) {
return Optional.of(ALREADY_CONNECTED); return Optional.of(ALREADY_CONNECTED);
} }
return Optional.empty(); return Optional.empty();
@ -1202,7 +1189,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
ServerPreConnectEvent event = ServerPreConnectEvent event =
new ServerPreConnectEvent(ConnectedPlayer.this, toConnect, previousServer); new ServerPreConnectEvent(ConnectedPlayer.this, toConnect, previousServer);
return server.getEventManager().fire(event).thenComposeAsync(newEvent -> { return server.getEventManager().fire(event).thenComposeAsync(newEvent -> {
Optional<RegisteredServer> newDest = newEvent.getResult().getServer(); Optional<RegisteredServer> newDest = newEvent.result().getServer();
if (!newDest.isPresent()) { if (!newDest.isPresent()) {
return completedFuture( return completedFuture(
plainResult(ConnectionRequestBuilder.Status.CONNECTION_CANCELLED, toConnect)); plainResult(ConnectionRequestBuilder.Status.CONNECTION_CANCELLED, toConnect));
@ -1235,7 +1222,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
return this.internalConnect().whenCompleteAsync((status, throwable) -> { return this.internalConnect().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.attemptedConnectedTo(), throwable, false);
} }
} }
}, connection.eventLoop()).thenApply(x -> x); }, connection.eventLoop()).thenApply(x -> x);
@ -1246,12 +1233,12 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player,
return internalConnect().whenCompleteAsync((status, throwable) -> { return internalConnect().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() : toConnect, handleConnectionException(status != null ? status.attemptedConnectedTo() : toConnect,
throwable, true); 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;
@ -1262,9 +1249,9 @@ 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.getReasonComponent() Component reason = status.reason()
.orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); .orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
handleConnectionException(toConnect, Disconnect.create(reason, getProtocolVersion()), handleConnectionException(toConnect, Disconnect.create(reason, protocolVersion()),
status.isSafe()); status.isSafe());
break; break;
default: default:

Datei anzeigen

@ -215,12 +215,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> virtualHost() {
return Optional.ofNullable(ping.getVhost()); return Optional.ofNullable(ping.getVhost());
} }
@ -230,13 +230,13 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler {
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return ProtocolVersion.LEGACY; return ProtocolVersion.LEGACY;
} }
@Override @Override
public String toString() { public String toString() {
return "[legacy connection] " + this.getRemoteAddress().toString(); return "[legacy connection] " + this.remoteAddress().toString();
} }
@Override @Override

Datei anzeigen

@ -65,11 +65,11 @@ public class InitialConnectSessionHandler implements MinecraftSessionHandler {
} }
byte[] copy = ByteBufUtil.getBytes(packet.content()); byte[] copy = ByteBufUtil.getBytes(packet.content());
PluginMessageEvent event = new PluginMessageEvent(serverConn, serverConn.getPlayer(), id, PluginMessageEvent event = new PluginMessageEvent(serverConn, serverConn.player(), id,
copy); copy);
server.getEventManager().fire(event) server.getEventManager().fire(event)
.thenAcceptAsync(pme -> { .thenAcceptAsync(pme -> {
if (pme.getResult().isAllowed() && serverConn.isActive()) { if (pme.result().allowed() && serverConn.isActive()) {
PluginMessage copied = new PluginMessage(packet.getChannel(), PluginMessage copied = new PluginMessage(packet.getChannel(),
Unpooled.wrappedBuffer(copy)); Unpooled.wrappedBuffer(copy));
serverConn.ensureConnected().write(copied); serverConn.ensureConnected().write(copied);

Datei anzeigen

@ -54,12 +54,12 @@ public final class InitialInboundConnection implements VelocityInboundConnection
} }
@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> virtualHost() {
return Optional.of(InetSocketAddress.createUnresolved(cleanedAddress, handshake.getPort())); return Optional.of(InetSocketAddress.createUnresolved(cleanedAddress, handshake.getPort()));
} }
@ -69,7 +69,7 @@ public final class InitialInboundConnection implements VelocityInboundConnection
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return connection.getProtocolVersion(); return connection.getProtocolVersion();
} }
@ -95,7 +95,7 @@ public final class InitialInboundConnection implements VelocityInboundConnection
logger.info("{} has disconnected: {}", this, logger.info("{} has disconnected: {}", this,
LegacyComponentSerializer.legacySection().serialize(translated)); LegacyComponentSerializer.legacySection().serialize(translated));
} }
connection.closeWith(Disconnect.create(translated, getProtocolVersion())); connection.closeWith(Disconnect.create(translated, protocolVersion()));
} }
/** /**
@ -106,6 +106,6 @@ public final class InitialInboundConnection implements VelocityInboundConnection
public void disconnectQuietly(Component reason) { public void disconnectQuietly(Component reason) {
Component translated = GlobalTranslator.render(reason, ClosestLocaleMatcher.INSTANCE Component translated = GlobalTranslator.render(reason, ClosestLocaleMatcher.INSTANCE
.lookupClosest(Locale.getDefault())); .lookupClosest(Locale.getDefault()));
connection.closeWith(Disconnect.create(translated, getProtocolVersion())); connection.closeWith(Disconnect.create(translated, protocolVersion()));
} }
} }

Datei anzeigen

@ -46,7 +46,6 @@ import java.security.GeneralSecurityException;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.util.Arrays; import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@ -56,6 +55,7 @@ import org.apache.logging.log4j.Logger;
import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response; import org.asynchttpclient.Response;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
* Handles authenticating the player to Mojang's servers. * Handles authenticating the player to Mojang's servers.
@ -99,7 +99,7 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler {
} }
boolean isKeyValid; boolean isKeyValid;
if (playerKey.getKeyRevision() == IdentifiedKey.Revision.LINKED_V2 if (playerKey.revision() == IdentifiedKey.Revision.LINKED_V2
&& playerKey instanceof IdentifiedKeyImpl) { && playerKey instanceof IdentifiedKeyImpl) {
IdentifiedKeyImpl keyImpl = (IdentifiedKeyImpl) playerKey; IdentifiedKeyImpl keyImpl = (IdentifiedKeyImpl) playerKey;
isKeyValid = keyImpl.internalAddHolder(packet.getHolderUuid()); isKeyValid = keyImpl.internalAddHolder(packet.getHolderUuid());
@ -127,11 +127,11 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler {
return; return;
} }
PreLoginComponentResult result = event.getResult(); PreLoginComponentResult result = event.result();
Optional<Component> disconnectReason = result.getReasonComponent(); @Nullable Component disconnectReason = result.explanation();
if (disconnectReason.isPresent()) { if (disconnectReason != null) {
// The component is guaranteed to be provided if the connection was denied. // The component is guaranteed to be provided if the connection was denied.
inbound.disconnect(disconnectReason.get()); inbound.disconnect(disconnectReason);
return; return;
} }
@ -185,8 +185,8 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler {
try { try {
KeyPair serverKeyPair = server.getServerKeyPair(); KeyPair serverKeyPair = server.getServerKeyPair();
if (inbound.getIdentifiedKey() != null) { if (inbound.identifiedKey() != null) {
IdentifiedKey playerKey = inbound.getIdentifiedKey(); IdentifiedKey playerKey = inbound.identifiedKey();
if (!playerKey.verifyDataSignature(packet.getVerifyToken(), verify, if (!playerKey.verifyDataSignature(packet.getVerifyToken(), verify,
Longs.toByteArray(packet.getSalt()))) { Longs.toByteArray(packet.getSalt()))) {
throw new IllegalStateException("Invalid client public signature."); throw new IllegalStateException("Invalid client public signature.");
@ -235,11 +235,11 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler {
final GameProfile profile = GENERAL_GSON.fromJson(profileResponse.getResponseBody(), final GameProfile profile = GENERAL_GSON.fromJson(profileResponse.getResponseBody(),
GameProfile.class); GameProfile.class);
// Not so fast, now we verify the public key for 1.19.1+ // Not so fast, now we verify the public key for 1.19.1+
if (inbound.getIdentifiedKey() != null if (inbound.identifiedKey() != null
&& inbound.getIdentifiedKey().getKeyRevision() == IdentifiedKey.Revision.LINKED_V2 && inbound.identifiedKey().revision() == IdentifiedKey.Revision.LINKED_V2
&& inbound.getIdentifiedKey() instanceof IdentifiedKeyImpl) { && inbound.identifiedKey() instanceof IdentifiedKeyImpl) {
IdentifiedKeyImpl key = (IdentifiedKeyImpl) inbound.getIdentifiedKey(); IdentifiedKeyImpl key = (IdentifiedKeyImpl) inbound.identifiedKey();
if (!key.internalAddHolder(profile.getId())) { if (!key.internalAddHolder(profile.uuid())) {
inbound.disconnect( inbound.disconnect(
Component.translatable("multiplayer.disconnect.invalid_public_key")); Component.translatable("multiplayer.disconnect.invalid_public_key"));
} }

Datei anzeigen

@ -61,13 +61,13 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
} }
@Override @Override
public InetSocketAddress getRemoteAddress() { public InetSocketAddress remoteAddress() {
return delegate.getRemoteAddress(); return delegate.remoteAddress();
} }
@Override @Override
public Optional<InetSocketAddress> getVirtualHost() { public Optional<InetSocketAddress> virtualHost() {
return delegate.getVirtualHost(); return delegate.virtualHost();
} }
@Override @Override
@ -76,8 +76,8 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
} }
@Override @Override
public ProtocolVersion getProtocolVersion() { public ProtocolVersion protocolVersion() {
return delegate.getProtocolVersion(); return delegate.protocolVersion();
} }
@Override @Override
@ -92,7 +92,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
if (consumer == null) { if (consumer == null) {
throw new NullPointerException("consumer"); throw new NullPointerException("consumer");
} }
if (delegate.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0) { if (delegate.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0) {
throw new IllegalStateException("Login plugin messages can only be sent to clients running " throw new IllegalStateException("Login plugin messages can only be sent to clients running "
+ "Minecraft 1.13 and above"); + "Minecraft 1.13 and above");
} }
@ -100,7 +100,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
final int id = SEQUENCE_UPDATER.incrementAndGet(this); final int id = SEQUENCE_UPDATER.incrementAndGet(this);
this.outstandingResponses.put(id, consumer); this.outstandingResponses.put(id, consumer);
final LoginPluginMessage message = new LoginPluginMessage(id, identifier.getId(), final LoginPluginMessage message = new LoginPluginMessage(id, identifier.id(),
Unpooled.wrappedBuffer(contents)); Unpooled.wrappedBuffer(contents));
if (!this.loginEventFired) { if (!this.loginEventFired) {
this.loginMessagesToSend.add(message); this.loginMessagesToSend.add(message);
@ -163,7 +163,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
} }
@Override @Override
public IdentifiedKey getIdentifiedKey() { public IdentifiedKey identifiedKey() {
return playerKey; return playerKey;
} }
} }

Datei anzeigen

@ -59,7 +59,7 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase {
if (mc != null) { if (mc != null) {
mc.setType(ConnectionTypes.LEGACY_FORGE); mc.setType(ConnectionTypes.LEGACY_FORGE);
} }
connection.getPlayer().sendLegacyForgeHandshakeResetPacket(); connection.player().sendLegacyForgeHandshakeResetPacket();
} }
}, },

Datei anzeigen

@ -91,7 +91,7 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase {
PluginMessage message, PluginMessage message,
MinecraftConnection backendConn) { MinecraftConnection backendConn) {
// Read the mod list if we haven't already. // Read the mod list if we haven't already.
if (!player.getModInfo().isPresent()) { if (!player.modInfo().isPresent()) {
List<ModInfo.Mod> mods = LegacyForgeUtil.readModList(message); List<ModInfo.Mod> mods = LegacyForgeUtil.readModList(message);
if (!mods.isEmpty()) { if (!mods.isEmpty()) {
player.setModInfo(new ModInfo("FML", mods)); player.setModInfo(new ModInfo("FML", mods));

Datei anzeigen

@ -45,27 +45,27 @@ public final class VelocityResourcePackInfo implements ResourcePackInfo {
} }
@Override @Override
public String getUrl() { public String url() {
return url; return url;
} }
@Override @Override
public @Nullable Component getPrompt() { public @Nullable Component prompt() {
return prompt; return prompt;
} }
@Override @Override
public boolean getShouldForce() { public boolean required() {
return shouldForce; return shouldForce;
} }
@Override @Override
public @Nullable byte[] getHash() { public @Nullable byte[] hash() {
return hash == null ? null : hash.clone(); // Thanks spotbugs, very helpful. return hash == null ? null : hash.clone(); // Thanks spotbugs, very helpful.
} }
@Override @Override
public Origin getOrigin() { public Origin origin() {
return origin; return origin;
} }
@ -74,24 +74,24 @@ public final class VelocityResourcePackInfo implements ResourcePackInfo {
} }
@Override @Override
public Origin getOriginalOrigin() { public Origin originalOrigin() {
return originalOrigin; return originalOrigin;
} }
@Override @Override
public Builder asBuilder() { public Builder asBuilder() {
return new BuilderImpl(url) return new BuilderImpl(url)
.setShouldForce(shouldForce) .required(shouldForce)
.setHash(hash) .hash(hash)
.setPrompt(prompt); .prompt(prompt);
} }
@Override @Override
public Builder asBuilder(String newUrl) { public Builder asBuilder(String newUrl) {
return new BuilderImpl(newUrl) return new BuilderImpl(newUrl)
.setShouldForce(shouldForce) .required(shouldForce)
.setHash(hash) .hash(hash)
.setPrompt(prompt); .prompt(prompt);
} }
/** /**
@ -110,13 +110,13 @@ public final class VelocityResourcePackInfo implements ResourcePackInfo {
} }
@Override @Override
public BuilderImpl setShouldForce(boolean shouldForce) { public BuilderImpl required(boolean shouldForce) {
this.shouldForce = shouldForce; this.shouldForce = shouldForce;
return this; return this;
} }
@Override @Override
public BuilderImpl setHash(@Nullable byte[] hash) { public BuilderImpl hash(@Nullable byte[] hash) {
if (hash != null) { if (hash != null) {
Preconditions.checkArgument(hash.length == 20, "Hash length is not 20"); Preconditions.checkArgument(hash.length == 20, "Hash length is not 20");
this.hash = hash.clone(); // Thanks spotbugs, very helpful. this.hash = hash.clone(); // Thanks spotbugs, very helpful.
@ -127,7 +127,7 @@ public final class VelocityResourcePackInfo implements ResourcePackInfo {
} }
@Override @Override
public BuilderImpl setPrompt(@Nullable Component prompt) { public BuilderImpl prompt(@Nullable Component prompt) {
this.prompt = prompt; this.prompt = prompt;
return this; return this;
} }

Datei anzeigen

@ -92,17 +92,17 @@ public class ConnectionRequestResults {
} }
@Override @Override
public Status getStatus() { public Status status() {
return status; return status;
} }
@Override @Override
public Optional<Component> getReasonComponent() { public Optional<Component> reason() {
return Optional.ofNullable(component); return Optional.ofNullable(component);
} }
@Override @Override
public RegisteredServer getAttemptedConnection() { public RegisteredServer attemptedConnectedTo() {
return attemptedConnection; return attemptedConnection;
} }

Datei anzeigen

@ -66,7 +66,7 @@ public class ServerListPingHandler {
private CompletableFuture<ServerPing> attemptPingPassthrough(VelocityInboundConnection connection, private CompletableFuture<ServerPing> attemptPingPassthrough(VelocityInboundConnection connection,
PingPassthroughMode mode, List<String> servers, ProtocolVersion responseProtocolVersion) { PingPassthroughMode mode, List<String> servers, ProtocolVersion responseProtocolVersion) {
ServerPing fallback = constructLocalPing(connection.getProtocolVersion()); ServerPing fallback = constructLocalPing(connection.protocolVersion());
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.getServer(s);
@ -102,7 +102,7 @@ public class ServerListPingHandler {
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();
} }
@ -117,16 +117,16 @@ public class ServerListPingHandler {
continue; continue;
} }
if (response.getDescriptionComponent() == 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.getDescriptionComponent(), response.description(),
fallback.getFavicon().orElse(null), fallback.favicon().orElse(null),
response.getModinfo().orElse(null) response.modInfo().orElse(null)
); );
} }
return fallback; return fallback;
@ -145,14 +145,14 @@ public class ServerListPingHandler {
*/ */
public CompletableFuture<ServerPing> getInitialPing(VelocityInboundConnection connection) { public CompletableFuture<ServerPing> getInitialPing(VelocityInboundConnection connection) {
VelocityConfiguration configuration = server.getConfiguration(); VelocityConfiguration configuration = server.getConfiguration();
ProtocolVersion shownVersion = ProtocolVersion.isSupported(connection.getProtocolVersion()) ProtocolVersion shownVersion = ProtocolVersion.isSupported(connection.protocolVersion())
? connection.getProtocolVersion() : ProtocolVersion.MAXIMUM_VERSION; ? connection.protocolVersion() : ProtocolVersion.MAXIMUM_VERSION;
PingPassthroughMode passthroughMode = configuration.getPingPassthrough(); PingPassthroughMode passthroughMode = configuration.getPingPassthrough();
if (passthroughMode == PingPassthroughMode.DISABLED) { if (passthroughMode == PingPassthroughMode.DISABLED) {
return CompletableFuture.completedFuture(constructLocalPing(shownVersion)); return CompletableFuture.completedFuture(constructLocalPing(shownVersion));
} else { } else {
String virtualHostStr = connection.getVirtualHost().map(InetSocketAddress::getHostString) String virtualHostStr = connection.virtualHost().map(InetSocketAddress::getHostString)
.map(str -> str.toLowerCase(Locale.ROOT)) .map(str -> str.toLowerCase(Locale.ROOT))
.orElse(""); .orElse("");
List<String> serversToTry = server.getConfiguration().getForcedHosts().getOrDefault( List<String> serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(
@ -172,7 +172,7 @@ public class ServerListPingHandler {
public CompletableFuture<ServerPing> getPing(VelocityInboundConnection connection) { public CompletableFuture<ServerPing> getPing(VelocityInboundConnection connection) {
return this.getInitialPing(connection) return this.getInitialPing(connection)
.thenCompose(ping -> server.getEventManager().fire(new ProxyPingEvent(connection, ping))) .thenCompose(ping -> server.getEventManager().fire(new ProxyPingEvent(connection, ping)))
.thenApply(ProxyPingEvent::getPing); .thenApply(ProxyPingEvent::ping);
} }
/** /**
@ -187,7 +187,7 @@ public class ServerListPingHandler {
return this.getInitialPing(connection) return this.getInitialPing(connection)
.thenApply(ping -> { .thenApply(ping -> {
StringBuilder json = new StringBuilder(); StringBuilder json = new StringBuilder();
VelocityServer.getPingGsonInstance(connection.getProtocolVersion()) VelocityServer.getPingGsonInstance(connection.protocolVersion())
.toJson(ping, json); .toJson(ping, json);
return new StatusResponse(json); return new StatusResponse(json);
}); });

Datei anzeigen

@ -57,7 +57,7 @@ public final class VelocityConsole extends SimpleTerminalConsole implements Cons
private final VelocityServer server; private final VelocityServer server;
private PermissionChecker permissionChecker = PermissionChecker.always(TriState.TRUE); private PermissionChecker permissionChecker = PermissionChecker.always(TriState.TRUE);
private final @NotNull Pointers pointers = ConsoleCommandSource.super.pointers().toBuilder() private final @NotNull Pointers pointers = ConsoleCommandSource.super.pointers().toBuilder()
.withDynamic(PermissionChecker.POINTER, this::getPermissionChecker) .withDynamic(PermissionChecker.POINTER, this::permissionChecker)
.withDynamic(Identity.LOCALE, () -> ClosestLocaleMatcher.INSTANCE .withDynamic(Identity.LOCALE, () -> ClosestLocaleMatcher.INSTANCE
.lookupClosest(Locale.getDefault())) .lookupClosest(Locale.getDefault()))
.withStatic(FacetPointers.TYPE, Type.CONSOLE) .withStatic(FacetPointers.TYPE, Type.CONSOLE)
@ -74,7 +74,7 @@ public final class VelocityConsole extends SimpleTerminalConsole implements Cons
} }
@Override @Override
public PermissionChecker getPermissionChecker() { public PermissionChecker permissionChecker() {
return this.permissionChecker; return this.permissionChecker;
} }
@ -99,7 +99,7 @@ public final class VelocityConsole extends SimpleTerminalConsole implements Cons
"A plugin permission provider {} provided an invalid permission function" "A plugin permission provider {} provided an invalid permission function"
+ " for the console. This is a bug in the plugin, not in Velocity. Falling" + " for the console. 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());
this.permissionChecker = PermissionChecker.always(TriState.TRUE); this.permissionChecker = PermissionChecker.always(TriState.TRUE);
} }
} }

Datei anzeigen

@ -59,32 +59,32 @@ public class IdentifiedKeyImpl implements IdentifiedKey {
} }
@Override @Override
public PublicKey getSignedPublicKey() { public PublicKey publicKey() {
return publicKey; return publicKey;
} }
@Override @Override
public PublicKey getSigner() { public PublicKey signer() {
return EncryptionUtils.getYggdrasilSessionKey(); return EncryptionUtils.getYggdrasilSessionKey();
} }
@Override @Override
public Instant getExpiryTemporal() { public Instant signatureExpiry() {
return expiryTemporal; return expiryTemporal;
} }
@Override @Override
public byte[] getSignature() { public byte[] signature() {
return signature.clone(); return signature.clone();
} }
@Override @Override
public @Nullable UUID getSignatureHolder() { public @Nullable UUID signatureHolder() {
return holder; return holder;
} }
@Override @Override
public Revision getKeyRevision() { public Revision revision() {
return revision; return revision;
} }
@ -172,9 +172,9 @@ public class IdentifiedKeyImpl implements IdentifiedKey {
IdentifiedKey that = (IdentifiedKey) o; IdentifiedKey that = (IdentifiedKey) o;
return Objects.equal(this.getSignedPublicKey(), that.getSignedPublicKey()) return Objects.equal(this.publicKey(), that.publicKey())
&& Objects.equal(this.getExpiryTemporal(), that.getExpiryTemporal()) && Objects.equal(this.signatureExpiry(), that.signatureExpiry())
&& Arrays.equals(this.getSignature(), that.getSignature()) && Arrays.equals(this.signature(), that.signature())
&& Objects.equal(this.getSigner(), that.getSigner()); && Objects.equal(this.signer(), that.signer());
} }
} }

Datei anzeigen

@ -63,22 +63,22 @@ public class SignedChatCommand implements KeySigned {
} }
@Override @Override
public PublicKey getSigner() { public PublicKey signer() {
return signer; return signer;
} }
@Override @Override
public Instant getExpiryTemporal() { public Instant signatureExpiry() {
return expiry; return expiry;
} }
@Override @Override
public @Nullable byte[] getSignature() { public @Nullable byte[] signature() {
return null; return null;
} }
@Override @Override
public byte[] getSalt() { public byte[] salt() {
return salt; return salt;
} }

Datei anzeigen

@ -494,7 +494,7 @@ public class VelocityEventManager implements EventManager {
final E event, final HandlersCache handlersCache) { final E event, final HandlersCache handlersCache) {
final HandlerRegistration registration = handlersCache.handlers[0]; final HandlerRegistration registration = handlersCache.handlers[0];
if (registration.asyncType == AsyncType.ALWAYS) { if (registration.asyncType == AsyncType.ALWAYS) {
registration.plugin.getExecutorService().execute( registration.plugin.executorService().execute(
() -> fire(future, event, 0, true, handlersCache.handlers)); () -> fire(future, event, 0, true, handlersCache.handlers));
} else { } else {
fire(future, event, 0, false, handlersCache.handlers); fire(future, event, 0, false, handlersCache.handlers);
@ -613,7 +613,7 @@ public class VelocityEventManager implements EventManager {
if (currentThread == firedOnThread && next.asyncType != AsyncType.ALWAYS) { if (currentThread == firedOnThread && next.asyncType != AsyncType.ALWAYS) {
fire(future, event, index + 1, currentlyAsync, registrations); fire(future, event, index + 1, currentlyAsync, registrations);
} else { } else {
next.plugin.getExecutorService().execute(() -> next.plugin.executorService().execute(() ->
fire(future, event, index + 1, true, registrations)); fire(future, event, index + 1, true, registrations));
} }
} }
@ -641,7 +641,7 @@ public class VelocityEventManager implements EventManager {
continue; continue;
} }
} else { } else {
registration.plugin.getExecutorService().execute(continuationTask); registration.plugin.executorService().execute(continuationTask);
} }
// fire will continue in another thread once the async task is // fire will continue in another thread once the async task is
// executed and the continuation is resumed // executed and the continuation is resumed
@ -658,6 +658,6 @@ public class VelocityEventManager implements EventManager {
private static void logHandlerException( private static void logHandlerException(
final HandlerRegistration registration, final Throwable t) { final HandlerRegistration registration, final Throwable t) {
logger.error("Couldn't pass {} to {}", registration.eventType.getSimpleName(), logger.error("Couldn't pass {} to {}", registration.eventType.getSimpleName(),
registration.plugin.getDescription().getId(), t); registration.plugin.description().id(), t);
} }
} }

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