Start tearing out the prefixes

This commit is contained in:
Andrew Steinborn
2023-10-27 23:58:13 -04:00
parent 908dd96015
commit 437c505cd8
149 changed files with 1112 additions and 1135 deletions

View File

@@ -116,7 +116,7 @@ public class Metrics {
() -> server.getConfiguration().isOnlineMode() ? "online" : "offline")
);
metrics.addCustomChart(new SimplePie("velocity_version",
() -> server.getVersion().getVersion()));
() -> server.getVersion().version()));
metrics.addCustomChart(new DrilldownPie("java_version", () -> {
Map<String, Map<String, Integer>> map = new HashMap<>();

View File

@@ -200,7 +200,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
@EnsuresNonNull({"serverKeyPair", "servers", "pluginManager", "eventManager", "scheduler",
"console", "cm", "configuration"})
void start() {
logger.info("Booting up {} {}...", getVersion().getName(), getVersion().getVersion());
logger.info("Booting up {} {}...", getVersion().name(), getVersion().version());
console.setupStreams();
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
for (PluginContainer plugin : pluginManager.getPlugins()) {
Optional<?> instance = plugin.getInstance();
for (PluginContainer plugin : pluginManager.plugins()) {
Optional<?> instance = plugin.instance();
if (instance.isPresent()) {
try {
eventManager.registerInternally(plugin, instance.get());
} catch (Exception e) {
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) {
@@ -404,15 +404,15 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
Optional<RegisteredServer> rs = servers.getServer(entry.getKey());
if (!rs.isPresent()) {
servers.register(newInfo);
} else if (!rs.get().getServerInfo().equals(newInfo)) {
for (Player player : rs.get().getPlayersConnected()) {
} else if (!rs.get().serverInfo().equals(newInfo)) {
for (Player player : rs.get().players()) {
if (!(player instanceof ConnectedPlayer)) {
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);
}
servers.unregister(rs.get().getServerInfo());
servers.unregister(rs.get().serverInfo());
servers.register(newInfo);
}
}
@@ -591,9 +591,9 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
if (configuration.isOnlineMode() && configuration.isOnlineModeKickExistingPlayers()) {
return true;
}
String lowerName = connection.getUsername().toLowerCase(Locale.US);
String lowerName = connection.username().toLowerCase(Locale.US);
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
*/
public boolean registerConnection(ConnectedPlayer connection) {
String lowerName = connection.getUsername().toLowerCase(Locale.US);
String lowerName = connection.username().toLowerCase(Locale.US);
if (!this.configuration.isOnlineModeKickExistingPlayers()) {
if (connectionsByName.putIfAbsent(lowerName, connection) != null) {
return false;
}
if (connectionsByUuid.putIfAbsent(connection.getUniqueId(), connection) != null) {
if (connectionsByUuid.putIfAbsent(connection.uuid(), connection) != null) {
connectionsByName.remove(lowerName, connection);
return false;
}
} else {
ConnectedPlayer existing = connectionsByUuid.get(connection.getUniqueId());
ConnectedPlayer existing = connectionsByUuid.get(connection.uuid());
if (existing != null) {
existing.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login"));
}
// We can now replace the entries as needed.
connectionsByName.put(lowerName, connection);
connectionsByUuid.put(connection.getUniqueId(), connection);
connectionsByUuid.put(connection.uuid(), connection);
}
return true;
}
@@ -632,8 +632,8 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
* @param connection the connection to unregister
*/
public void unregisterConnection(ConnectedPlayer connection) {
connectionsByName.remove(connection.getUsername().toLowerCase(Locale.US), connection);
connectionsByUuid.remove(connection.getUniqueId(), connection);
connectionsByName.remove(connection.username().toLowerCase(Locale.US), connection);
connectionsByUuid.remove(connection.uuid(), connection);
bossBarManager.onDisconnect(connection);
}
@@ -653,7 +653,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
public Collection<Player> matchPlayer(String 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()))
.collect(Collectors.toList());
}
@@ -662,7 +662,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience {
public Collection<RegisteredServer> matchServer(String 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()))
.collect(Collectors.toList());
}

View File

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

View File

@@ -120,7 +120,7 @@ public final class VelocityCommandMeta implements CommandMeta {
*/
// This is a static method because most methods take a CommandMeta.
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;
@@ -138,17 +138,17 @@ public final class VelocityCommandMeta implements CommandMeta {
}
@Override
public Collection<String> getAliases() {
public Collection<String> aliases() {
return this.aliases;
}
@Override
public Collection<CommandNode<CommandSource>> getHints() {
public Collection<CommandNode<CommandSource>> hints() {
return this.hints;
}
@Override
public @Nullable Object getPlugin() {
public @Nullable Object plugin() {
return plugin;
}

View File

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

View File

@@ -67,7 +67,7 @@ public class GlistCommand {
.<CommandSource, String>argument(SERVER_ARG, StringArgumentType.string())
.suggests((context, builder) -> {
for (RegisteredServer server : server.getAllServers()) {
builder.suggest(server.getServerInfo().getName());
builder.suggest(server.serverInfo().name());
}
builder.suggest("all");
return builder.buildFuture();
@@ -116,13 +116,13 @@ public class GlistCommand {
}
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) {
return;
}
TextComponent.Builder builder = Component.text()
.append(Component.text("[" + server.getServerInfo().getName() + "] ",
.append(Component.text("[" + server.serverInfo().name() + "] ",
NamedTextColor.DARK_AQUA))
.append(Component.text("(" + onServer.size() + ")", NamedTextColor.GRAY))
.append(Component.text(": "))
@@ -130,7 +130,7 @@ public class GlistCommand {
for (int i = 0; i < onServer.size(); i++) {
Player player = onServer.get(i);
builder.append(Component.text(player.getUsername()));
builder.append(Component.text(player.username()));
if (i + 1 < onServer.size()) {
builder.append(Component.text(", "));

View File

@@ -77,8 +77,8 @@ public class ServerCommand implements SimpleCommand {
}
private void outputServerInformation(Player executor) {
String currentServer = executor.getCurrentServer().map(ServerConnection::getServerInfo)
.map(ServerInfo::getName).orElse("<unknown>");
String currentServer = executor.connectedServer().map(ServerConnection::serverInfo)
.map(ServerInfo::name).orElse("<unknown>");
executor.sendMessage(Component.translatable(
"velocity.command.server-current-server",
NamedTextColor.YELLOW,
@@ -108,10 +108,10 @@ public class ServerCommand implements SimpleCommand {
}
private TextComponent formatServerComponent(String currentPlayerServer, RegisteredServer server) {
ServerInfo serverInfo = server.getServerInfo();
TextComponent serverTextComponent = Component.text(serverInfo.getName());
ServerInfo serverInfo = server.serverInfo();
TextComponent serverTextComponent = Component.text(serverInfo.name());
int connectedPlayers = server.getPlayersConnected().size();
int connectedPlayers = server.players().size();
TranslatableComponent playersTextComponent;
if (connectedPlayers == 1) {
playersTextComponent = Component.translatable(
@@ -121,7 +121,7 @@ public class ServerCommand implements SimpleCommand {
"velocity.command.server-tooltip-players-online");
}
playersTextComponent = playersTextComponent.args(Component.text(connectedPlayers));
if (serverInfo.getName().equals(currentPlayerServer)) {
if (serverInfo.name().equals(currentPlayerServer)) {
serverTextComponent = serverTextComponent.color(NamedTextColor.GREEN)
.hoverEvent(
showText(
@@ -131,7 +131,7 @@ public class ServerCommand implements SimpleCommand {
);
} else {
serverTextComponent = serverTextComponent.color(NamedTextColor.GRAY)
.clickEvent(ClickEvent.runCommand("/server " + serverInfo.getName()))
.clickEvent(ClickEvent.runCommand("/server " + serverInfo.name()))
.hoverEvent(
showText(
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) {
final String[] currentArgs = invocation.arguments();
Stream<String> possibilities = server.getAllServers().stream()
.map(rs -> rs.getServerInfo().getName());
.map(rs -> rs.serverInfo().name());
if (currentArgs.length == 0) {
return possibilities.collect(Collectors.toList());

View File

@@ -222,19 +222,19 @@ public class VelocityCommand implements SimpleCommand {
ProxyVersion version = server.getVersion();
Component velocity = Component.text().content(version.getName() + " ")
Component velocity = Component.text().content(version.name() + " ")
.decoration(TextDecoration.BOLD, true)
.color(VELOCITY_COLOR)
.append(Component.text(version.getVersion()).decoration(TextDecoration.BOLD, false))
.append(Component.text(version.version()).decoration(TextDecoration.BOLD, false))
.build();
Component copyright = Component
.translatable("velocity.command.version-copyright",
Component.text(version.getVendor()),
Component.text(version.getName()));
Component.text(version.vendor()),
Component.text(version.name()));
source.sendMessage(velocity);
source.sendMessage(copyright);
if (version.getName().equals("Velocity")) {
if (version.name().equals("Velocity")) {
TextComponent embellishment = Component.text()
.append(Component.text().content("velocitypowered.com")
.color(NamedTextColor.GREEN)
@@ -274,7 +274,7 @@ public class VelocityCommand implements SimpleCommand {
return;
}
List<PluginContainer> plugins = ImmutableList.copyOf(server.getPluginManager().getPlugins());
List<PluginContainer> plugins = ImmutableList.copyOf(server.getPluginManager().plugins());
int pluginCount = plugins.size();
if (pluginCount == 0) {
@@ -286,7 +286,7 @@ public class VelocityCommand implements SimpleCommand {
TextComponent.Builder listBuilder = Component.text();
for (int i = 0; i < pluginCount; i++) {
PluginContainer plugin = plugins.get(i);
listBuilder.append(componentForPlugin(plugin.getDescription()));
listBuilder.append(componentForPlugin(plugin.description()));
if (i + 1 < pluginCount) {
listBuilder.append(Component.text(", "));
}
@@ -300,37 +300,37 @@ public class VelocityCommand implements SimpleCommand {
}
private TextComponent componentForPlugin(PluginDescription description) {
String pluginInfo = description.getName().orElse(description.getId())
+ description.getVersion().map(v -> " " + v).orElse("");
String pluginInfo = description.name().orElse(description.id())
+ description.version().map(v -> " " + v).orElse("");
TextComponent.Builder hoverText = Component.text().content(pluginInfo);
description.getUrl().ifPresent(url -> {
description.url().ifPresent(url -> {
hoverText.append(Component.newline());
hoverText.append(Component.translatable(
"velocity.command.plugin-tooltip-website",
Component.text(url)));
});
if (!description.getAuthors().isEmpty()) {
if (!description.authors().isEmpty()) {
hoverText.append(Component.newline());
if (description.getAuthors().size() == 1) {
if (description.authors().size() == 1) {
hoverText.append(Component.translatable("velocity.command.plugin-tooltip-author",
Component.text(description.getAuthors().get(0))));
Component.text(description.authors().get(0))));
} else {
hoverText.append(
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.text(pdesc));
});
return Component.text(description.getId(), NamedTextColor.GRAY)
return Component.text(description.id(), NamedTextColor.GRAY)
.hoverEvent(HoverEvent.showText(hoverText.build()));
}
@@ -359,7 +359,7 @@ public class VelocityCommand implements SimpleCommand {
Collection<RegisteredServer> allServers = ImmutableSet.copyOf(server.getAllServers());
JsonObject servers = new JsonObject();
for (RegisteredServer iter : allServers) {
servers.add(iter.getServerInfo().getName(),
servers.add(iter.serverInfo().name(),
InformationUtils.collectServerInfo(iter));
}
JsonArray connectOrder = new JsonArray();

View File

@@ -39,14 +39,14 @@ public final class BrigadierCommandRegistrar extends AbstractCommandRegistrar<Br
// The literal name might not match any aliases on the given meta.
// Register it (if valid), since it's probably what the user expects.
// 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();
if (VelocityCommands.isValidAlias(primaryAlias)) {
// Register directly without copying
this.register(literal);
}
for (final String alias : meta.getAliases()) {
for (final String alias : meta.aliases()) {
if (primaryAlias.equals(alias)) {
continue;
}

View File

@@ -57,7 +57,7 @@ abstract class InvocableCommandRegistrar<T extends InvocableCommand<I>,
@Override
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 LiteralCommandNode<CommandSource> literal =

View File

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

View File

@@ -72,7 +72,7 @@ public class BungeeCordMessageResponder {
}
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());
}
@@ -98,7 +98,7 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("IP");
SocketAddress address = player.getRemoteAddress();
SocketAddress address = player.remoteAddress();
if (address instanceof InetSocketAddress) {
InetSocketAddress serverInetAddr = (InetSocketAddress) address;
out.writeUTF(serverInetAddr.getHostString());
@@ -121,9 +121,9 @@ public class BungeeCordMessageResponder {
out.writeInt(proxy.getPlayerCount());
} else {
proxy.getServer(target).ifPresent(rs -> {
int playersOnServer = rs.getPlayersConnected().size();
int playersOnServer = rs.players().size();
out.writeUTF("PlayerCount");
out.writeUTF(rs.getServerInfo().getName());
out.writeUTF(rs.serverInfo().name());
out.writeInt(playersOnServer);
});
}
@@ -146,17 +146,17 @@ public class BungeeCordMessageResponder {
StringJoiner joiner = new StringJoiner(", ");
for (Player online : proxy.getAllPlayers()) {
joiner.add(online.getUsername());
joiner.add(online.username());
}
out.writeUTF(joiner.toString());
} else {
proxy.getServer(target).ifPresent(info -> {
out.writeUTF("PlayerList");
out.writeUTF(info.getServerInfo().getName());
out.writeUTF(info.serverInfo().name());
StringJoiner joiner = new StringJoiner(", ");
for (Player online : info.getPlayersConnected()) {
joiner.add(online.getUsername());
for (Player online : info.players()) {
joiner.add(online.username());
}
out.writeUTF(joiner.toString());
});
@@ -172,7 +172,7 @@ public class BungeeCordMessageResponder {
private void processGetServers() {
StringJoiner joiner = new StringJoiner(", ");
for (RegisteredServer server : proxy.getAllServers()) {
joiner.add(server.getServerInfo().getName());
joiner.add(server.serverInfo().name());
}
ByteBuf buf = Unpooled.buffer();
@@ -210,7 +210,7 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("GetServer");
out.writeUTF(player.ensureAndGetCurrentServer().getServerInfo().getName());
out.writeUTF(player.ensureAndGetCurrentServer().serverInfo().name());
sendResponseOnConnection(buf);
}
@@ -220,7 +220,7 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("UUID");
out.writeUTF(UuidUtils.toUndashed(player.getUniqueId()));
out.writeUTF(UuidUtils.toUndashed(player.uuid()));
sendResponseOnConnection(buf);
}
@@ -231,8 +231,8 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("UUIDOther");
out.writeUTF(player.getUsername());
out.writeUTF(UuidUtils.toUndashed(player.getUniqueId()));
out.writeUTF(player.username());
out.writeUTF(UuidUtils.toUndashed(player.uuid()));
sendResponseOnConnection(buf);
});
@@ -244,8 +244,8 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("IPOther");
out.writeUTF(player.getUsername());
SocketAddress address = player.getRemoteAddress();
out.writeUTF(player.username());
SocketAddress address = player.remoteAddress();
if (address instanceof InetSocketAddress) {
InetSocketAddress serverInetAddr = (InetSocketAddress) address;
out.writeUTF(serverInetAddr.getHostString());
@@ -265,8 +265,8 @@ public class BungeeCordMessageResponder {
ByteBufDataOutput out = new ByteBufDataOutput(buf);
out.writeUTF("ServerIP");
out.writeUTF(info.getServerInfo().getName());
SocketAddress address = info.getServerInfo().getAddress();
out.writeUTF(info.serverInfo().name());
SocketAddress address = info.serverInfo().address();
if (address instanceof InetSocketAddress) {
InetSocketAddress serverInetAddr = (InetSocketAddress) address;
out.writeUTF(serverInetAddr.getHostString());
@@ -298,12 +298,12 @@ public class BungeeCordMessageResponder {
private void processForwardToServer(ByteBufDataInput in) {
String target = in.readUTF();
ByteBuf toForward = in.unwrap().copy();
final ServerInfo currentUserServer = player.getCurrentServer()
.map(ServerConnection::getServerInfo).orElse(null);
final ServerInfo currentUserServer = player.connectedServer()
.map(ServerConnection::serverInfo).orElse(null);
if (target.equals("ALL") || target.equals("ONLINE")) {
try {
for (RegisteredServer rs : proxy.getAllServers()) {
if (!rs.getServerInfo().equals(currentUserServer)) {
if (!rs.serverInfo().equals(currentUserServer)) {
((VelocityRegisteredServer) rs).sendPluginMessage(LEGACY_CHANNEL,
toForward.retainedSlice());
}
@@ -322,8 +322,8 @@ public class BungeeCordMessageResponder {
}
static String getBungeeCordChannel(ProtocolVersion version) {
return version.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0 ? MODERN_CHANNEL.getId()
: LEGACY_CHANNEL.getId();
return version.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0 ? MODERN_CHANNEL.id()
: LEGACY_CHANNEL.id();
}
// Note: this method will always release the buffer!

View File

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

View File

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

View File

@@ -69,7 +69,7 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
this.serverConn = serverConn;
this.resultFuture = resultFuture;
this.bungeecordMessageResponder = new BungeeCordMessageResponder(server,
serverConn.getPlayer());
serverConn.player());
}
@Override
@@ -91,10 +91,10 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
@Override
public boolean handle(JoinGame packet) {
MinecraftConnection smc = serverConn.ensureConnected();
RegisteredServer previousServer = serverConn.getPreviousServer().orElse(null);
VelocityServerConnection existingConnection = serverConn.getPlayer().getConnectedServer();
RegisteredServer previousServer = serverConn.previousServer().orElse(null);
VelocityServerConnection existingConnection = serverConn.player().getConnectedServer();
final ConnectedPlayer player = serverConn.getPlayer();
final ConnectedPlayer player = serverConn.player();
if (existingConnection != null) {
// 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.
smc.setAutoReading(false);
server.getEventManager()
.fire(new ServerConnectedEvent(player, serverConn.getServer(), previousServer))
.fire(new ServerConnectedEvent(player, serverConn.server(), previousServer))
.thenRunAsync(() -> {
// Make sure we can still transition (player might have disconnected here).
if (!serverConn.isActive()) {
@@ -142,7 +142,7 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
smc.setAutoReading(true);
// 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.
if (smc.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_20_2) < 0
@@ -153,11 +153,11 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
// We're done! :)
server.getEventManager().fireAndForget(new ServerPostConnectEvent(player,
previousServer));
resultFuture.complete(ConnectionRequestResults.successful(serverConn.getServer()));
resultFuture.complete(ConnectionRequestResults.successful(serverConn.server()));
}, smc.eventLoop()).exceptionally(exc -> {
logger.error("Unable to switch to new server {} for {}",
serverConn.getServerInfo().getName(),
player.getUsername(), exc);
serverConn.serverInfo().name(),
player.username(), exc);
player.disconnect(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR);
resultFuture.completeExceptionally(exc);
return null;
@@ -176,9 +176,9 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
if (connection.getType() == ConnectionTypes.LEGACY_FORGE
&& !serverConn.getPhase().consideredComplete()) {
resultFuture.complete(ConnectionRequestResults.forUnsafeDisconnect(packet,
serverConn.getServer()));
serverConn.server()));
} else {
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.getServer()));
resultFuture.complete(ConnectionRequestResults.forDisconnect(packet, serverConn.server()));
}
return true;
@@ -191,23 +191,23 @@ public class TransitionSessionHandler implements MinecraftSessionHandler {
}
// 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.
if (serverConn.getPhase() == HELLO) {
VelocityServerConnection existingConnection = serverConn.getPlayer().getConnectedServer();
VelocityServerConnection existingConnection = serverConn.player().getConnectedServer();
if (existingConnection != null && existingConnection.getPhase() != IN_TRANSITION) {
// Indicate that this connection is "in transition"
existingConnection.setConnectionPhase(IN_TRANSITION);
// Tell the player that we're leaving and we just aren't coming back.
existingConnection.getPhase().onDepartForNewServer(existingConnection,
serverConn.getPlayer());
serverConn.player());
}
}
return true;
}
serverConn.getPlayer().getConnection().write(packet.retain());
serverConn.player().getConnection().write(packet.retain());
return true;
}

View File

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

View File

@@ -52,6 +52,7 @@ import net.kyori.adventure.text.format.NamedTextColor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.
@@ -93,9 +94,9 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
}
// Initiate a regular connection and move over to it.
ConnectedPlayer player = new ConnectedPlayer(server, profileEvent.getGameProfile(),
mcConnection, inbound.getVirtualHost().orElse(null), onlineMode,
inbound.getIdentifiedKey());
ConnectedPlayer player = new ConnectedPlayer(server, profileEvent.profileToUse(),
mcConnection, inbound.virtualHost().orElse(null), onlineMode,
inbound.identifiedKey());
this.connectedPlayer = player;
if (!server.canRegisterConnection(player)) {
player.disconnect0(
@@ -117,8 +118,8 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
"A plugin permission provider {} provided an invalid permission function"
+ " for player {}. This is a bug in the plugin, not in Velocity. Falling"
+ " back to the default permission function.",
event.getProvider().getClass().getName(),
player.getUsername());
event.provider().getClass().getName(),
player.username());
} else {
player.setPermissionChecker(checker);
}
@@ -138,32 +139,32 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
mcConnection.setCompressionThreshold(threshold);
}
VelocityConfiguration configuration = server.getConfiguration();
UUID playerUniqueId = player.getUniqueId();
UUID playerUniqueId = player.uuid();
if (configuration.getPlayerInfoForwardingMode() == PlayerInfoForwarding.NONE) {
playerUniqueId = UuidUtils.generateOfflinePlayerUuid(player.getUsername());
playerUniqueId = UuidUtils.generateOfflinePlayerUuid(player.username());
}
if (player.getIdentifiedKey() != null) {
IdentifiedKey playerKey = player.getIdentifiedKey();
if (playerKey.getSignatureHolder() == null) {
if (player.identifiedKey() != null) {
IdentifiedKey playerKey = player.identifiedKey();
if (playerKey.signatureHolder() == null) {
if (playerKey instanceof IdentifiedKeyImpl) {
IdentifiedKeyImpl unlinkedKey = (IdentifiedKeyImpl) playerKey;
// Failsafe
if (!unlinkedKey.internalAddHolder(player.getUniqueId())) {
if (!unlinkedKey.internalAddHolder(player.uuid())) {
if (onlineMode) {
inbound.disconnect(
Component.translatable("multiplayer.disconnect.invalid_public_key"));
return;
} else {
logger.warn("Key for player " + player.getUsername() + " could not be verified!");
logger.warn("Key for player " + player.username() + " could not be verified!");
}
}
} 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 {
if (!Objects.equals(playerKey.getSignatureHolder(), playerUniqueId)) {
logger.warn("UUID for Player " + player.getUsername() + " mismatches! "
if (!Objects.equals(playerKey.signatureHolder(), playerUniqueId)) {
logger.warn("UUID for Player " + player.username() + " mismatches! "
+ "Chat/Commands signatures will not work correctly for this player!");
}
}
@@ -201,9 +202,9 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
return;
}
Optional<Component> reason = event.getResult().getReasonComponent();
if (reason.isPresent()) {
player.disconnect0(reason.get(), true);
@Nullable Component explanation = event.result().explanation();
if (explanation != null) {
player.disconnect0(explanation, true);
} else {
if (!server.registerConnection(player)) {
player.disconnect0(Component.translatable("velocity.error.already-connected-proxy"),
@@ -212,13 +213,13 @@ public class AuthSessionHandler implements MinecraftSessionHandler {
}
ServerLoginSuccess success = new ServerLoginSuccess();
success.setUsername(player.getUsername());
success.setProperties(player.getGameProfileProperties());
success.setUuid(player.getUniqueId());
success.setUsername(player.username());
success.setProperties(player.profileProperties());
success.setUuid(player.uuid());
mcConnection.write(success);
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;
mcConnection.setActiveSessionHandler(StateRegistry.PLAY,
new InitialConnectSessionHandler(player, server));

View File

@@ -116,10 +116,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
this.player = player;
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.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.commandHandler = new KeyedCommandHandler(this.player, this.server);
} else {
@@ -154,9 +154,9 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
public void activated() {
configSwitchFuture = new CompletableFuture<>();
Collection<String> channels =
server.getChannelRegistrar().getChannelsForProtocol(player.getProtocolVersion());
server.getChannelRegistrar().getChannelsForProtocol(player.protocolVersion());
if (!channels.isEmpty()) {
PluginMessage register = constructChannelsPacket(player.getProtocolVersion(), channels);
PluginMessage register = constructChannelsPacket(player.protocolVersion(), channels);
player.getConnection().write(register);
}
}
@@ -320,7 +320,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
player.setClientBrand(brand);
backendConn.write(
PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(),
player.getProtocolVersion()));
player.protocolVersion()));
} else if (BungeeCordMessageResponder.isBungeeCordMessage(packet)) {
return true;
} else {
@@ -355,7 +355,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
byte[] copy = ByteBufUtil.getBytes(packet.content());
PluginMessageEvent event = new PluginMessageEvent(player, serverConn, id, copy);
server.getEventManager().fire(event).thenAcceptAsync(pme -> {
if (pme.getResult().isAllowed()) {
if (pme.result().allowed()) {
PluginMessage message = new PluginMessage(packet.getChannel(),
Unpooled.wrappedBuffer(copy));
if (!player.getPhase().consideredComplete() || !serverConn.getPhase()
@@ -486,7 +486,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
spawned = false;
serverBossBars.clear();
player.clearPlayerListHeaderAndFooterSilent();
player.getTabList().clearAllSilent();
player.tabList().clearAllSilent();
}
player.switchToConfigState();
@@ -513,7 +513,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
player.getPhase().onFirstJoin(player);
} else {
// 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
// entity IDs and send new dimension information.
@@ -551,10 +551,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
}
// 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(
GenericTitlePacket.constructTitlePacket(GenericTitlePacket.ActionType.RESET,
player.getProtocolVersion()));
player.protocolVersion()));
}
// Flush everything
@@ -574,7 +574,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
// improving compatibility with mods.
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
// additional respawn. On older versions of Minecraft this forces the client to perform
// garbage collection which adds additional latency.
@@ -616,7 +616,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
String commandLabel = command.substring(0, commandEndPosition);
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
// additional tab completion support.
outstandingTabComplete = packet;
@@ -658,7 +658,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
}
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
// additional tab completion support.
outstandingTabComplete = packet;
@@ -690,7 +690,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
server.getCommandManager().offerBrigadierSuggestions(player, command)
.thenAcceptAsync(offers -> {
boolean legacy =
player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0;
player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_13) < 0;
try {
for (Suggestion suggestion : offers.getList()) {
String offer = suggestion.getText();
@@ -709,7 +709,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
player.getConnection().write(response);
} catch (Exception e) {
logger.error("Unable to provide tab list completions for {} for command '{}'",
player.getUsername(), command,
player.username(), command,
e);
}
}, player.getConnection().eventLoop()).exceptionally((ex) -> {
@@ -729,7 +729,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler {
server.getEventManager().fire(new TabCompleteEvent(player, request.getCommand(), offers))
.thenAcceptAsync(e -> {
response.getOffers().clear();
for (String s : e.getSuggestions()) {
for (String s : e.suggestions()) {
response.getOffers().add(new Offer(s));
}
player.getConnection().write(response);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -61,13 +61,13 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
}
@Override
public InetSocketAddress getRemoteAddress() {
return delegate.getRemoteAddress();
public InetSocketAddress remoteAddress() {
return delegate.remoteAddress();
}
@Override
public Optional<InetSocketAddress> getVirtualHost() {
return delegate.getVirtualHost();
public Optional<InetSocketAddress> virtualHost() {
return delegate.virtualHost();
}
@Override
@@ -76,8 +76,8 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
}
@Override
public ProtocolVersion getProtocolVersion() {
return delegate.getProtocolVersion();
public ProtocolVersion protocolVersion() {
return delegate.protocolVersion();
}
@Override
@@ -92,7 +92,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
if (consumer == null) {
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 "
+ "Minecraft 1.13 and above");
}
@@ -100,7 +100,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
final int id = SEQUENCE_UPDATER.incrementAndGet(this);
this.outstandingResponses.put(id, consumer);
final LoginPluginMessage message = new LoginPluginMessage(id, identifier.getId(),
final LoginPluginMessage message = new LoginPluginMessage(id, identifier.id(),
Unpooled.wrappedBuffer(contents));
if (!this.loginEventFired) {
this.loginMessagesToSend.add(message);
@@ -163,7 +163,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi
}
@Override
public IdentifiedKey getIdentifiedKey() {
public IdentifiedKey identifiedKey() {
return playerKey;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -94,7 +94,7 @@ public final class ConnectionManager {
this.resolver = new SeparatePoolInetNameResolver(GlobalEventExecutor.INSTANCE);
this.httpClient = asyncHttpClient(config()
.setEventLoopGroup(this.workerGroup)
.setUserAgent(server.getVersion().getName() + "/" + server.getVersion().getVersion())
.setUserAgent(server.getVersion().name() + "/" + server.getVersion().version())
.addRequestFilter(new RequestFilter() {
@Override
public <T> FilterContext<T> filter(FilterContext<T> ctx) {

View File

@@ -95,7 +95,7 @@ public class GameSpyQueryHandler extends SimpleChannelInboundHandler<DatagramPac
.maxPlayers(server.getConfiguration().getShowMaxPlayers())
.proxyPort(((InetSocketAddress) server.getConfiguration().getBind()).getPort())
.proxyHost(((InetSocketAddress) server.getConfiguration().getBind()).getHostString())
.players(server.getAllPlayers().stream().map(Player::getUsername)
.players(server.getAllPlayers().stream().map(Player::username)
.collect(Collectors.toList()))
.proxyVersion("Velocity")
.plugins(
@@ -164,22 +164,22 @@ public class GameSpyQueryHandler extends SimpleChannelInboundHandler<DatagramPac
// Start writing the response
ResponseWriter responseWriter = new ResponseWriter(queryResponse, isBasic);
responseWriter.write("hostname", event.getResponse().getHostname());
responseWriter.write("hostname", event.response().hostname());
responseWriter.write("gametype", "SMP");
responseWriter.write("game_id", "MINECRAFT");
responseWriter.write("version", event.getResponse().getGameVersion());
responseWriter.writePlugins(event.getResponse().getProxyVersion(),
event.getResponse().getPlugins());
responseWriter.write("version", event.response().gameVersion());
responseWriter.writePlugins(event.response().proxyVersion(),
event.response().plugins());
responseWriter.write("map", event.getResponse().getMap());
responseWriter.write("numplayers", event.getResponse().getCurrentPlayers());
responseWriter.write("maxplayers", event.getResponse().getMaxPlayers());
responseWriter.write("hostport", event.getResponse().getProxyPort());
responseWriter.write("hostip", event.getResponse().getProxyHost());
responseWriter.write("map", event.response().map());
responseWriter.write("numplayers", event.response().currentPlayers());
responseWriter.write("maxplayers", event.response().maxPlayers());
responseWriter.write("hostport", event.response().proxyPort());
responseWriter.write("hostip", event.response().proxyHost());
if (!responseWriter.isBasic) {
responseWriter.writePlayers(event.getResponse().getPlayers());
responseWriter.writePlayers(event.response().players());
}
// Send the response
@@ -205,10 +205,10 @@ public class GameSpyQueryHandler extends SimpleChannelInboundHandler<DatagramPac
private List<QueryResponse.PluginInformation> getRealPluginInformation() {
List<QueryResponse.PluginInformation> result = new ArrayList<>();
for (PluginContainer plugin : server.getPluginManager().getPlugins()) {
PluginDescription description = plugin.getDescription();
result.add(QueryResponse.PluginInformation.of(description.getName()
.orElse(description.getId()), description.getVersion().orElse(null)));
for (PluginContainer plugin : server.getPluginManager().plugins()) {
PluginDescription description = plugin.description();
result.add(QueryResponse.PluginInformation.of(description.name()
.orElse(description.id()), description.version().orElse(null)));
}
return result;
}

View File

@@ -462,9 +462,9 @@ public enum ProtocolUtils {
public static void writeProperties(ByteBuf buf, List<GameProfile.Property> properties) {
writeVarInt(buf, properties.size());
for (GameProfile.Property property : properties) {
writeString(buf, property.getName());
writeString(buf, property.getValue());
String signature = property.getSignature();
writeString(buf, property.name());
writeString(buf, property.value());
String signature = property.signature();
if (signature != null && !signature.isEmpty()) {
buf.writeBoolean(true);
writeString(buf, signature);
@@ -650,9 +650,9 @@ public enum ProtocolUtils {
* @param playerKey the key to write
*/
public static void writePlayerKey(ByteBuf buf, IdentifiedKey playerKey) {
buf.writeLong(playerKey.getExpiryTemporal().toEpochMilli());
ProtocolUtils.writeByteArray(buf, playerKey.getSignedPublicKey().getEncoded());
ProtocolUtils.writeByteArray(buf, playerKey.getSignature());
buf.writeLong(playerKey.signatureExpiry().toEpochMilli());
ProtocolUtils.writeByteArray(buf, playerKey.publicKey().getEncoded());
ProtocolUtils.writeByteArray(buf, playerKey.signature());
}
/**

View File

@@ -47,7 +47,7 @@ public class LegacyDisconnect {
*/
public static LegacyDisconnect fromServerPing(ServerPing response,
LegacyMinecraftPingVersion version) {
Players players = response.getPlayers().orElse(FAKE_PLAYERS);
Players players = response.players().orElse(FAKE_PLAYERS);
switch (version) {
case MINECRAFT_1_3:
@@ -56,7 +56,7 @@ public class LegacyDisconnect {
// MOTD.
return new LegacyDisconnect(String.join(LEGACY_COLOR_CODE,
cleanSectionSymbol(getFirstLine(PlainTextComponentSerializer.plainText().serialize(
response.getDescriptionComponent()))),
response.description()))),
Integer.toString(players.getOnline()),
Integer.toString(players.getMax())));
case MINECRAFT_1_4:
@@ -64,10 +64,10 @@ public class LegacyDisconnect {
// Minecraft 1.4-1.6 provide support for more fields, and additionally support color codes.
return new LegacyDisconnect(String.join("\0",
LEGACY_COLOR_CODE + "1",
Integer.toString(response.getVersion().getProtocol()),
response.getVersion().getName(),
Integer.toString(response.version().getProtocol()),
response.version().getName(),
getFirstLine(LegacyComponentSerializer.legacySection().serialize(response
.getDescriptionComponent())),
.description())),
Integer.toString(players.getOnline()),
Integer.toString(players.getMax())
));

View File

@@ -207,12 +207,12 @@ public class LegacyPlayerListItem implements MinecraftPacket {
}
public static Item from(TabListEntry entry) {
return new Item(entry.getProfile().getId())
.setName(entry.getProfile().getName())
.setProperties(entry.getProfile().getProperties())
return new Item(entry.getProfile().uuid())
.setName(entry.getProfile().name())
.setProperties(entry.getProfile().properties())
.setLatency(entry.getLatency())
.setGameMode(entry.getGameMode())
.setPlayerKey(entry.getIdentifiedKey())
.setPlayerKey(entry.identifiedKey())
.setDisplayName(entry.getDisplayNameComponent().orElse(null));
}

View File

@@ -108,12 +108,12 @@ public class ResourcePackRequest implements MinecraftPacket {
public VelocityResourcePackInfo toServerPromptedPack() {
ResourcePackInfo.Builder builder =
new VelocityResourcePackInfo.BuilderImpl(Preconditions.checkNotNull(url)).setPrompt(prompt)
.setShouldForce(isRequired).setOrigin(ResourcePackInfo.Origin.DOWNSTREAM_SERVER);
new VelocityResourcePackInfo.BuilderImpl(Preconditions.checkNotNull(url)).prompt(prompt)
.required(isRequired).setOrigin(ResourcePackInfo.Origin.DOWNSTREAM_SERVER);
if (hash != null && !hash.isEmpty()) {
if (PLAUSIBLE_SHA1_HASH.matcher(hash).matches()) {
builder.setHash(ByteBufUtil.decodeHexDump(hash));
builder.hash(ByteBufUtil.decodeHexDump(hash));
}
}
return (VelocityResourcePackInfo) builder.build();

View File

@@ -89,12 +89,12 @@ public class ServerData implements MinecraftPacket {
buf.writeBoolean(hasFavicon);
if (hasFavicon) {
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_19_4) >= 0) {
String cutIconBase64 = favicon.getBase64Url().substring("data:image/png;base64,".length());
String cutIconBase64 = favicon.url().substring("data:image/png;base64,".length());
byte[] iconBytes = Base64.getDecoder()
.decode(cutIconBase64.getBytes(StandardCharsets.UTF_8));
ProtocolUtils.writeByteArray(buf, iconBytes);
} else {
ProtocolUtils.writeString(buf, favicon.getBase64Url());
ProtocolUtils.writeString(buf, favicon.url());
}
}

View File

@@ -132,9 +132,9 @@ public class ServerLogin implements MinecraftPacket {
}
if (version.compareTo(ProtocolVersion.MINECRAFT_1_19_1) >= 0) {
if (playerKey != null && playerKey.getSignatureHolder() != null) {
if (playerKey != null && playerKey.signatureHolder() != null) {
buf.writeBoolean(true);
ProtocolUtils.writeUuid(buf, playerKey.getSignatureHolder());
ProtocolUtils.writeUuid(buf, playerKey.signatureHolder());
} else if (this.holderUuid != null) {
buf.writeBoolean(true);
ProtocolUtils.writeUuid(buf, this.holderUuid);

View File

@@ -148,8 +148,8 @@ public class UpsertPlayerInfo implements MinecraftPacket {
ProtocolUtils.readProperties(buf)
);
}, (ignored, buf, info) -> { // write
ProtocolUtils.writeString(buf, info.profile.getName());
ProtocolUtils.writeProperties(buf, info.profile.getProperties());
ProtocolUtils.writeString(buf, info.profile.name());
ProtocolUtils.writeProperties(buf, info.profile.properties());
}),
INITIALIZE_CHAT((version, buf, info) -> { // read
if (buf.readBoolean()) {

View File

@@ -65,7 +65,7 @@ public interface CommandHandler<T extends MinecraftPacket> {
return pkt;
}).exceptionally(e -> {
logger.info(
"Exception occurred while running command for {}", player.getUsername(), e);
"Exception occurred while running command for {}", player.username(), e);
player.sendMessage(
Component.translatable("velocity.command.generic-error", NamedTextColor.RED));
return null;

View File

@@ -41,11 +41,11 @@ public class RemoteChatSession implements ChatSession {
this.identifiedKey = identifiedKey;
}
public IdentifiedKey getIdentifiedKey() {
public IdentifiedKey identifiedKey() {
return identifiedKey;
}
public @Nullable UUID getSessionId() {
public @Nullable UUID sessionId() {
return sessionId;
}

View File

@@ -52,7 +52,7 @@ public class KeyedChatHandler implements
public static void invalidCancel(Logger logger, ConnectedPlayer player) {
logger.fatal("A plugin tried to cancel a signed chat message."
+ " This is no longer possible in 1.19.1 and newer. "
+ "Disconnecting player " + player.getUsername());
+ "Disconnecting player " + player.username());
player.disconnect(Component.text("A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
}
@@ -60,7 +60,7 @@ public class KeyedChatHandler implements
public static void invalidChange(Logger logger, ConnectedPlayer player) {
logger.fatal("A plugin tried to change a signed chat message. "
+ "This is no longer possible in 1.19.1 and newer. "
+ "Disconnecting player " + player.getUsername());
+ "Disconnecting player " + player.username());
player.disconnect(Component.text("A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
}
@@ -73,7 +73,7 @@ public class KeyedChatHandler implements
CompletableFuture<PlayerChatEvent> future = eventManager.fire(toSend);
CompletableFuture<MinecraftPacket> chatFuture;
IdentifiedKey playerKey = this.player.getIdentifiedKey();
IdentifiedKey playerKey = this.player.identifiedKey();
if (playerKey != null && !packet.isUnsigned()) {
// 1.19->1.19.2 signed version
@@ -81,13 +81,13 @@ public class KeyedChatHandler implements
} else {
// 1.19->1.19.2 unsigned version
chatFuture = future.thenApply(pme -> {
PlayerChatEvent.ChatResult chatResult = pme.getResult();
if (!chatResult.isAllowed()) {
PlayerChatEvent.ChatResult chatResult = pme.result();
if (!chatResult.allowed()) {
return null;
}
return player.getChatBuilderFactory().builder()
.message(chatResult.getMessage().orElse(packet.getMessage()))
.message(chatResult.modifiedMessage().orElse(packet.getMessage()))
.setTimestamp(packet.getExpiry()).toServer();
});
}
@@ -101,26 +101,26 @@ public class KeyedChatHandler implements
}
private Function<PlayerChatEvent, MinecraftPacket> handleOldSignedChat(KeyedPlayerChat packet) {
IdentifiedKey playerKey = this.player.getIdentifiedKey();
IdentifiedKey playerKey = this.player.identifiedKey();
assert playerKey != null;
return pme -> {
PlayerChatEvent.ChatResult chatResult = pme.getResult();
if (!chatResult.isAllowed()) {
if (playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
PlayerChatEvent.ChatResult chatResult = pme.result();
if (!chatResult.allowed()) {
if (playerKey.revision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
// Bad, very bad.
invalidCancel(logger, player);
}
return null;
}
if (chatResult.getMessage().map(str -> !str.equals(packet.getMessage())).orElse(false)) {
if (playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
if (chatResult.modifiedMessage().map(str -> !str.equals(packet.getMessage())).orElse(false)) {
if (playerKey.revision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
// Bad, very bad.
invalidChange(logger, player);
} else {
logger.warn("A plugin changed a signed chat message. The server may not accept it.");
return player.getChatBuilderFactory().builder()
.message(chatResult.getMessage().get() /* always present at this point */)
.message(chatResult.modifiedMessage().get() /* always present at this point */)
.setTimestamp(packet.getExpiry())
.toServer();
}

View File

@@ -44,15 +44,15 @@ public class KeyedCommandHandler implements CommandHandler<KeyedPlayerCommand> {
@Override
public void handlePlayerCommandInternal(KeyedPlayerCommand packet) {
queueCommandResult(this.server, this.player, event -> {
CommandExecuteEvent.CommandResult result = event.getResult();
IdentifiedKey playerKey = player.getIdentifiedKey();
if (result == CommandExecuteEvent.CommandResult.denied()) {
CommandExecuteEvent.CommandResult result = event.result();
IdentifiedKey playerKey = player.identifiedKey();
if (result == CommandExecuteEvent.CommandResult.deny()) {
if (playerKey != null) {
if (!packet.isUnsigned()
&& playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
&& playerKey.revision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
logger.fatal("A plugin tried to deny a command with signable component(s). "
+ "This is not supported. "
+ "Disconnecting player " + player.getUsername() + ". Command packet: " + packet);
+ "Disconnecting player " + player.username() + ". Command packet: " + packet);
player.disconnect(Component.text(
"A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
@@ -72,10 +72,10 @@ public class KeyedCommandHandler implements CommandHandler<KeyedPlayerCommand> {
return CompletableFuture.completedFuture(packet);
} else {
if (!packet.isUnsigned() && playerKey != null
&& playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
&& playerKey.revision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
logger.fatal("A plugin tried to change a command with signed component(s). "
+ "This is not supported. "
+ "Disconnecting player " + player.getUsername() + ". Command packet: " + packet);
+ "Disconnecting player " + player.username() + ". Command packet: " + packet);
player.disconnect(Component.text(
"A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
@@ -92,10 +92,10 @@ public class KeyedCommandHandler implements CommandHandler<KeyedPlayerCommand> {
}
if (!packet.isUnsigned() && playerKey != null
&& playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
&& playerKey.revision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) {
logger.fatal("A plugin tried to change a command with signed component(s). "
+ "This is not supported. "
+ "Disconnecting player " + player.getUsername() + ". Command packet: " + packet);
+ "Disconnecting player " + player.username() + ". Command packet: " + packet);
player.disconnect(Component.text(
"A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));

View File

@@ -35,7 +35,7 @@ public class LegacyChatBuilder extends ChatBuilderV2 {
public MinecraftPacket toClient() {
// This is temporary
UUID identity = sender == null ? (senderIdentity == null ? Identity.nil().uuid()
: senderIdentity.uuid()) : sender.getUniqueId();
: senderIdentity.uuid()) : sender.uuid();
Component msg = component == null ? Component.text(message) : component;
return new LegacyChat(ProtocolUtils.getJsonChatSerializer(version).serialize(msg), type.getId(),

View File

@@ -46,12 +46,15 @@ public class LegacyChatHandler implements ChatHandler<LegacyChat> {
}
this.server.getEventManager().fire(new PlayerChatEvent(this.player, packet.getMessage()))
.whenComplete((chatEvent, throwable) -> {
if (!chatEvent.getResult().isAllowed()) {
if (!chatEvent.result().allowed()) {
return;
}
serverConnection.write(this.player.getChatBuilderFactory().builder()
.message(chatEvent.getResult().getMessage().orElse(packet.getMessage())).toServer());
serverConnection.write(
this.player.getChatBuilderFactory().builder()
.message(chatEvent.result().modifiedMessage().orElse(packet.getMessage()))
.toServer()
);
});
}
}

View File

@@ -43,8 +43,8 @@ public class LegacyCommandHandler implements CommandHandler<LegacyChat> {
public void handlePlayerCommandInternal(LegacyChat packet) {
String command = packet.getMessage().substring(1);
queueCommandResult(this.server, this.player, event -> {
CommandExecuteEvent.CommandResult result = event.getResult();
if (result == CommandExecuteEvent.CommandResult.denied()) {
CommandExecuteEvent.CommandResult result = event.result();
if (result == CommandExecuteEvent.CommandResult.deny()) {
return CompletableFuture.completedFuture(null);
}
String commandToRun = result.getCommand().orElse(command);

View File

@@ -54,15 +54,15 @@ public class SessionChatHandler implements ChatHandler<SessionPlayerChat> {
chatQueue.queuePacket(
eventManager.fire(toSend)
.thenApply(pme -> {
PlayerChatEvent.ChatResult chatResult = pme.getResult();
if (!chatResult.isAllowed()) {
PlayerChatEvent.ChatResult chatResult = pme.result();
if (!chatResult.allowed()) {
if (packet.isSigned()) {
invalidCancel(logger, player);
}
return null;
}
if (chatResult.getMessage().map(str -> !str.equals(packet.getMessage()))
if (chatResult.modifiedMessage().map(str -> !str.equals(packet.getMessage()))
.orElse(false)) {
if (packet.isSigned()) {
invalidChange(logger, player);

View File

@@ -44,19 +44,19 @@ public class SessionCommandHandler implements CommandHandler<SessionPlayerComman
@Override
public void handlePlayerCommandInternal(SessionPlayerCommand packet) {
queueCommandResult(this.server, this.player, event -> {
CommandExecuteEvent.CommandResult result = event.getResult();
if (result == CommandExecuteEvent.CommandResult.denied()) {
CommandExecuteEvent.CommandResult result = event.result();
if (result == CommandExecuteEvent.CommandResult.deny()) {
if (packet.isSigned()) {
logger.fatal("A plugin tried to deny a command with signable component(s). "
+ "This is not supported. "
+ "Disconnecting player " + player.getUsername() + ". Command packet: " + packet);
+ "Disconnecting player " + player.username() + ". Command packet: " + packet);
player.disconnect(Component.text(
"A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
}
// We seemingly can't actually do this if signed args exist, if not, we can probs
// keep stuff happy
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
return CompletableFuture.completedFuture(
new ChatAcknowledgement(packet.lastSeenMessages.getOffset()));
}
@@ -71,7 +71,7 @@ public class SessionCommandHandler implements CommandHandler<SessionPlayerComman
if (packet.isSigned()) {
logger.fatal("A plugin tried to change a command with signed component(s). "
+ "This is not supported. "
+ "Disconnecting player " + player.getUsername() + ". Command packet: " + packet);
+ "Disconnecting player " + player.username() + ". Command packet: " + packet);
player.disconnect(Component.text(
"A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
@@ -95,7 +95,7 @@ public class SessionCommandHandler implements CommandHandler<SessionPlayerComman
if (packet.isSigned()) {
logger.fatal("A plugin tried to change a command with signed component(s). "
+ "This is not supported. "
+ "Disconnecting player " + player.getUsername() + ". Command packet: " + packet);
+ "Disconnecting player " + player.username() + ". Command packet: " + packet);
player.disconnect(Component.text(
"A proxy plugin caused an illegal protocol state. "
+ "Contact your network administrator."));
@@ -110,7 +110,7 @@ public class SessionCommandHandler implements CommandHandler<SessionPlayerComman
.toServer();
}
}
if (player.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
if (player.protocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) >= 0) {
return new ChatAcknowledgement(packet.lastSeenMessages.getOffset());
}
return null;

View File

@@ -44,6 +44,6 @@ public final class FaviconSerializer implements JsonSerializer<Favicon>, JsonDes
@Override
public JsonElement serialize(Favicon src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getBase64Url());
return new JsonPrimitive(src.url());
}
}

View File

@@ -55,9 +55,9 @@ public final class GameProfileSerializer implements JsonSerializer<GameProfile>,
@Override
public JsonElement serialize(GameProfile src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
obj.add("id", new JsonPrimitive(src.getUndashedId()));
obj.add("name", new JsonPrimitive(src.getName()));
obj.add("properties", context.serialize(src.getProperties(), propertyList));
obj.add("id", new JsonPrimitive(src.undashedId()));
obj.add("name", new JsonPrimitive(src.name()));
obj.add("properties", context.serialize(src.properties(), propertyList));
return obj;
}
}

View File

@@ -136,7 +136,7 @@ public final class PluginMessageUtil {
checkArgument(isMcBrand(message), "message is not a brand plugin message");
String currentBrand = readBrandMessage(message.content());
String rewrittenBrand = String.format("%s (%s)", currentBrand, version.getName());
String rewrittenBrand = String.format("%s (%s)", currentBrand, version.name());
ByteBuf rewrittenBuf = Unpooled.buffer();
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {

View File

@@ -69,8 +69,8 @@ public class VelocityPluginManager implements PluginManager {
}
private void registerPlugin(PluginContainer plugin) {
pluginsById.put(plugin.getDescription().getId(), plugin);
Optional<?> instance = plugin.getInstance();
pluginsById.put(plugin.description().id(), plugin);
Optional<?> instance = plugin.instance();
instance.ifPresent(o -> pluginInstances.put(o, plugin));
}
@@ -113,10 +113,10 @@ public class VelocityPluginManager implements PluginManager {
pluginLoad:
for (PluginDescription candidate : sortedPlugins) {
// Verify dependencies
for (PluginDependency dependency : candidate.getDependencies()) {
if (!dependency.isOptional() && !loadedPluginsById.contains(dependency.getId())) {
logger.error("Can't load plugin {} due to missing dependency {}", candidate.getId(),
dependency.getId());
for (PluginDependency dependency : candidate.dependencies()) {
if (!dependency.optional() && !loadedPluginsById.contains(dependency.id())) {
logger.error("Can't load plugin {} due to missing dependency {}", candidate.id(),
dependency.id());
continue pluginLoad;
}
}
@@ -125,9 +125,9 @@ public class VelocityPluginManager implements PluginManager {
PluginDescription realPlugin = loader.createPluginFromCandidate(candidate);
VelocityPluginContainer container = new VelocityPluginContainer(realPlugin);
pluginContainers.put(container, loader.createModule(container));
loadedPluginsById.add(realPlugin.getId());
loadedPluginsById.add(realPlugin.id());
} catch (Throwable e) {
logger.error("Can't create module for plugin {}", candidate.getId(), e);
logger.error("Can't create module for plugin {}", candidate.id(), e);
}
}
@@ -141,7 +141,7 @@ public class VelocityPluginManager implements PluginManager {
bind(CommandManager.class).toInstance(server.getCommandManager());
for (PluginContainer container : pluginContainers.keySet()) {
bind(PluginContainer.class)
.annotatedWith(Names.named(container.getDescription().getId()))
.annotatedWith(Names.named(container.description().id()))
.toInstance(container);
}
}
@@ -149,17 +149,17 @@ public class VelocityPluginManager implements PluginManager {
for (Map.Entry<PluginContainer, Module> plugin : pluginContainers.entrySet()) {
PluginContainer container = plugin.getKey();
PluginDescription description = container.getDescription();
PluginDescription description = container.description();
try {
loader.createPlugin(container, plugin.getValue(), commonModule);
} catch (Throwable e) {
logger.error("Can't create plugin {}", description.getId(), e);
logger.error("Can't create plugin {}", description.id(), e);
continue;
}
logger.info("Loaded plugin {} {} by {}", description.getId(), description.getVersion()
.orElse("<UNKNOWN>"), Joiner.on(", ").join(description.getAuthors()));
logger.info("Loaded plugin {} {} by {}", description.id(), description.version()
.orElse("<UNKNOWN>"), Joiner.on(", ").join(description.authors()));
registerPlugin(container);
}
}
@@ -176,13 +176,13 @@ public class VelocityPluginManager implements PluginManager {
}
@Override
public Optional<PluginContainer> getPlugin(String id) {
public Optional<PluginContainer> plugin(String id) {
checkNotNull(id, "id");
return Optional.ofNullable(pluginsById.get(id));
}
@Override
public Collection<PluginContainer> getPlugins() {
public Collection<PluginContainer> plugins() {
return Collections.unmodifiableCollection(pluginsById.values());
}
@@ -197,7 +197,7 @@ public class VelocityPluginManager implements PluginManager {
checkNotNull(path, "path");
Optional<PluginContainer> optContainer = fromInstance(plugin);
checkArgument(optContainer.isPresent(), "plugin is not loaded");
Optional<?> optInstance = optContainer.get().getInstance();
Optional<?> optInstance = optContainer.get().instance();
checkArgument(optInstance.isPresent(), "plugin has no instance");
ClassLoader pluginClassloader = optInstance.get().getClass().getClassLoader();

View File

@@ -38,12 +38,12 @@ public class VelocityPluginContainer implements PluginContainer {
}
@Override
public PluginDescription getDescription() {
public PluginDescription description() {
return this.description;
}
@Override
public Optional<?> getInstance() {
public Optional<?> instance() {
return Optional.ofNullable(instance);
}
@@ -52,11 +52,11 @@ public class VelocityPluginContainer implements PluginContainer {
}
@Override
public ExecutorService getExecutorService() {
public ExecutorService executorService() {
if (this.service == null) {
synchronized (this) {
if (this.service == null) {
String name = this.description.getName().orElse(this.description.getId());
String name = this.description.name().orElse(this.description.id());
this.service = Executors.unconfigurableExecutorService(
Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setDaemon(true)

View File

@@ -66,47 +66,47 @@ public class VelocityPluginDescription implements PluginDescription {
this.description = Strings.emptyToNull(description);
this.url = Strings.emptyToNull(url);
this.authors = authors == null ? ImmutableList.of() : ImmutableList.copyOf(authors);
this.dependencies = Maps.uniqueIndex(dependencies, d -> d == null ? null : d.getId());
this.dependencies = Maps.uniqueIndex(dependencies, d -> d == null ? null : d.id());
this.source = source;
}
@Override
public String getId() {
public String id() {
return id;
}
@Override
public Optional<String> getName() {
public Optional<String> name() {
return Optional.ofNullable(name);
}
@Override
public Optional<String> getVersion() {
public Optional<String> version() {
return Optional.ofNullable(version);
}
@Override
public Optional<String> getDescription() {
public Optional<String> description() {
return Optional.ofNullable(description);
}
@Override
public Optional<String> getUrl() {
public Optional<String> url() {
return Optional.ofNullable(url);
}
@Override
public List<String> getAuthors() {
public List<String> authors() {
return authors;
}
@Override
public Collection<PluginDependency> getDependencies() {
public Collection<PluginDependency> dependencies() {
return dependencies.values();
}
@Override
public Optional<PluginDependency> getDependency(String id) {
public Optional<PluginDependency> dependency(String id) {
return Optional.ofNullable(dependencies.get(id));
}

View File

@@ -91,7 +91,7 @@ public class JavaPluginLoader implements PluginLoader {
@Override
public Module createModule(PluginContainer container) throws Exception {
PluginDescription description = container.getDescription();
PluginDescription description = container.description();
if (!(description instanceof JavaVelocityPluginDescription)) {
throw new IllegalArgumentException("Description provided isn't of the Java plugin loader");
}
@@ -111,7 +111,7 @@ public class JavaPluginLoader implements PluginLoader {
if (!(container instanceof VelocityPluginContainer)) {
throw new IllegalArgumentException("Container provided isn't of the Java plugin loader");
}
PluginDescription description = container.getDescription();
PluginDescription description = container.description();
if (!(description instanceof JavaVelocityPluginDescription)) {
throw new IllegalArgumentException("Description provided isn't of the Java plugin loader");
}
@@ -122,7 +122,7 @@ public class JavaPluginLoader implements PluginLoader {
if (instance == null) {
throw new IllegalStateException(
"Got nothing from injector for plugin " + description.getId());
"Got nothing from injector for plugin " + description.id());
}
((VelocityPluginContainer) container).setInstance(instance);
@@ -183,13 +183,13 @@ public class JavaPluginLoader implements PluginLoader {
JavaVelocityPluginDescriptionCandidate description,
Class mainClass) {
return new JavaVelocityPluginDescription(
description.getId(),
description.getName().orElse(null),
description.getVersion().orElse(null),
description.getDescription().orElse(null),
description.getUrl().orElse(null),
description.getAuthors(),
description.getDependencies(),
description.id(),
description.name().orElse(null),
description.version().orElse(null),
description.description().orElse(null),
description.url().orElse(null),
description.authors(),
description.dependencies(),
description.getSource().orElse(null),
mainClass
);

View File

@@ -49,13 +49,13 @@ class VelocityPluginModule implements Module {
public void configure(Binder binder) {
binder.bind(description.getMainClass()).in(Scopes.SINGLETON);
binder.bind(Logger.class).toInstance(LoggerFactory.getLogger(description.getId()));
binder.bind(ComponentLogger.class).toInstance(ComponentLogger.logger(description.getId()));
binder.bind(Logger.class).toInstance(LoggerFactory.getLogger(description.id()));
binder.bind(ComponentLogger.class).toInstance(ComponentLogger.logger(description.id()));
binder.bind(Path.class).annotatedWith(DataDirectory.class)
.toInstance(basePluginPath.resolve(description.getId()));
.toInstance(basePluginPath.resolve(description.id()));
binder.bind(PluginDescription.class).toInstance(description);
binder.bind(PluginContainer.class).toInstance(pluginContainer);
binder.bind(ExecutorService.class).toProvider(pluginContainer::getExecutorService);
binder.bind(ExecutorService.class).toProvider(pluginContainer::executorService);
}
}

View File

@@ -51,7 +51,7 @@ public class PluginDependencyUtils {
*/
public static List<PluginDescription> sortCandidates(List<PluginDescription> candidates) {
List<PluginDescription> sortedCandidates = new ArrayList<>(candidates);
sortedCandidates.sort(Comparator.comparing(PluginDescription::getId));
sortedCandidates.sort(Comparator.comparing(PluginDescription::id));
// Create a graph and populate it with plugin dependencies. Specifically, each graph has plugin
// nodes, and edges that represent the dependencies that plugin relies on. Non-existent plugins
@@ -61,13 +61,13 @@ public class PluginDependencyUtils {
.expectedNodeCount(sortedCandidates.size())
.build();
Map<String, PluginDescription> candidateMap = Maps.uniqueIndex(sortedCandidates,
PluginDescription::getId);
PluginDescription::id);
for (PluginDescription description : sortedCandidates) {
graph.addNode(description);
for (PluginDependency dependency : description.getDependencies()) {
PluginDescription in = candidateMap.get(dependency.getId());
for (PluginDependency dependency : description.dependencies()) {
PluginDescription in = candidateMap.get(dependency.id());
if (in != null) {
graph.putEdge(description, in);
@@ -102,7 +102,7 @@ public class PluginDependencyUtils {
// circular dependency, thus we do not have a directed acyclic graph and therefore no
// topological sort is possible.)
currentDependencyScanStack.addLast(current);
final String loop = currentDependencyScanStack.stream().map(PluginDescription::getId)
final String loop = currentDependencyScanStack.stream().map(PluginDescription::id)
.collect(Collectors.joining(" -> "));
throw new IllegalStateException("Circular dependency detected: " + loop);
}

View File

@@ -119,14 +119,14 @@ public class VelocityScheduler implements Scheduler {
task.cancel();
}
timerExecutionService.shutdown();
final List<PluginContainer> plugins = new ArrayList<>(this.pluginManager.getPlugins());
final List<PluginContainer> plugins = new ArrayList<>(this.pluginManager.plugins());
final Iterator<PluginContainer> pluginIterator = plugins.iterator();
while (pluginIterator.hasNext()) {
final PluginContainer container = pluginIterator.next();
if (container instanceof VelocityPluginContainer) {
final VelocityPluginContainer pluginContainer = (VelocityPluginContainer) container;
if (pluginContainer.hasExecutorService()) {
container.getExecutorService().shutdown();
container.executorService().shutdown();
} else {
pluginIterator.remove();
}
@@ -137,8 +137,8 @@ public class VelocityScheduler implements Scheduler {
boolean allShutdown = true;
for (final PluginContainer container : plugins) {
final String id = container.getDescription().getId();
final ExecutorService service = (container).getExecutorService();
final String id = container.description().id();
final ExecutorService service = (container).executorService();
try {
if (!service.awaitTermination(10, TimeUnit.SECONDS)) {
@@ -204,7 +204,7 @@ public class VelocityScheduler implements Scheduler {
@Override
public ScheduledTask schedule() {
VelocityTask task = new VelocityTask(container, runnable, consumer, delay, repeat);
tasksByPlugin.put(container.getInstance().get(), task);
tasksByPlugin.put(container.instance().get(), task);
task.schedule();
return task;
}
@@ -242,7 +242,7 @@ public class VelocityScheduler implements Scheduler {
@Override
public Object plugin() {
//noinspection OptionalGetWithoutIsPresent
return container.getInstance().get();
return container.instance().get();
}
@Override
@@ -278,7 +278,7 @@ public class VelocityScheduler implements Scheduler {
@Override
public void run() {
container.getExecutorService().execute(() -> {
container.executorService().execute(() -> {
currentTaskThread = Thread.currentThread();
try {
if (runnable != null) {
@@ -291,8 +291,8 @@ public class VelocityScheduler implements Scheduler {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
} else {
String friendlyPluginName = container.getDescription().getName()
.orElse(container.getDescription().getId());
String friendlyPluginName = container.description().name()
.orElse(container.description().id());
Object unit = consumer == null ? runnable : consumer;
Log.logger.error("Exception in task {} by plugin {}", unit, friendlyPluginName,
e);

View File

@@ -58,7 +58,7 @@ public class PingSessionHandler implements MinecraftSessionHandler {
Handshake handshake = new Handshake();
handshake.setNextStatus(StateRegistry.STATUS_ID);
SocketAddress address = server.getServerInfo().getAddress();
SocketAddress address = server.serverInfo().address();
if (address instanceof InetSocketAddress) {
InetSocketAddress socketAddr = (InetSocketAddress) address;
handshake.setServerAddress(socketAddr.getHostString());

View File

@@ -76,13 +76,13 @@ public class ServerMap {
*/
public RegisteredServer register(ServerInfo serverInfo) {
Preconditions.checkNotNull(serverInfo, "serverInfo");
String lowerName = serverInfo.getName().toLowerCase(Locale.US);
String lowerName = serverInfo.name().toLowerCase(Locale.US);
RegisteredServer rs = createRawRegisteredServer(serverInfo);
RegisteredServer existing = servers.putIfAbsent(lowerName, rs);
if (existing != null && !existing.getServerInfo().equals(serverInfo)) {
if (existing != null && !existing.serverInfo().equals(serverInfo)) {
throw new IllegalArgumentException(
"Server with name " + serverInfo.getName() + " already registered");
"Server with name " + serverInfo.name() + " already registered");
} else if (existing == null) {
return rs;
} else {
@@ -97,15 +97,15 @@ public class ServerMap {
*/
public void unregister(ServerInfo serverInfo) {
Preconditions.checkNotNull(serverInfo, "serverInfo");
String lowerName = serverInfo.getName().toLowerCase(Locale.US);
String lowerName = serverInfo.name().toLowerCase(Locale.US);
RegisteredServer rs = servers.get(lowerName);
if (rs == null) {
throw new IllegalArgumentException(
"Server with name " + serverInfo.getName() + " is not registered!");
"Server with name " + serverInfo.name() + " is not registered!");
}
Preconditions.checkArgument(rs.getServerInfo().equals(serverInfo),
"Trying to remove server %s with differing information", serverInfo.getName());
Preconditions.checkArgument(rs.serverInfo().equals(serverInfo),
"Trying to remove server %s with differing information", serverInfo.name());
Preconditions.checkState(servers.remove(lowerName, rs),
"Server with name %s replaced whilst unregistering", serverInfo.getName());
"Server with name %s replaced whilst unregistering", serverInfo.name());
}
}

View File

@@ -63,12 +63,12 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud
}
@Override
public ServerInfo getServerInfo() {
public ServerInfo serverInfo() {
return serverInfo;
}
@Override
public Collection<Player> getPlayersConnected() {
public Collection<Player> players() {
return ImmutableList.copyOf(players.values());
}
@@ -95,11 +95,11 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud
throw new IllegalStateException("No Velocity proxy instance available");
}
CompletableFuture<ServerPing> pingFuture = new CompletableFuture<>();
long timeoutMs = pingOptions.getTimeout() == 0
? server.getConfiguration().getReadTimeout() : pingOptions.getTimeout();
server.createBootstrap(loop, serverInfo.getAddress())
long timeoutMs = pingOptions.timeout() == 0
? server.getConfiguration().getReadTimeout() : pingOptions.timeout();
server.createBootstrap(loop, serverInfo.address())
.handler(new BackendChannelInitializer(timeoutMs))
.connect(serverInfo.getAddress())
.connect(serverInfo.address())
.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
Channel ch = future.channel();
@@ -107,7 +107,7 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud
ch.pipeline().addLast(HANDLER, conn);
conn.setActiveSessionHandler(StateRegistry.HANDSHAKE,
new PingSessionHandler(pingFuture, VelocityRegisteredServer.this, conn,
pingOptions.getProtocolVersion()));
pingOptions.protocolVersion()));
} else {
pingFuture.completeExceptionally(future.cause());
}
@@ -116,11 +116,11 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud
}
public void addPlayer(ConnectedPlayer player) {
players.put(player.getUniqueId(), player);
players.put(player.uuid(), player);
}
public void removePlayer(ConnectedPlayer player) {
players.remove(player.getUniqueId(), player);
players.remove(player.uuid(), player);
}
@Override
@@ -140,7 +140,7 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud
for (ConnectedPlayer player : players.values()) {
VelocityServerConnection serverConnection = player.getConnectedServer();
if (serverConnection != null && serverConnection.getConnection() != null
&& serverConnection.getServer() == this) {
&& serverConnection.server() == this) {
return serverConnection.sendPluginMessage(identifier, data);
}
}
@@ -156,6 +156,6 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud
@Override
public @NonNull Iterable<? extends Audience> audiences() {
return this.getPlayersConnected();
return this.players();
}
}

View File

@@ -77,7 +77,7 @@ public class KeyedVelocityTabList implements InternalTabList {
Preconditions.checkNotNull(entry, "entry");
Preconditions.checkArgument(entry.getTabList().equals(this),
"The provided entry was not created by this tab list");
Preconditions.checkArgument(!entries.containsKey(entry.getProfile().getId()),
Preconditions.checkArgument(!entries.containsKey(entry.getProfile().uuid()),
"this TabList already contains an entry with the same uuid");
Preconditions.checkArgument(entry instanceof KeyedVelocityTabListEntry,
"Not a Velocity tab list entry");
@@ -86,7 +86,7 @@ public class KeyedVelocityTabList implements InternalTabList {
connection.write(
new LegacyPlayerListItem(LegacyPlayerListItem.ADD_PLAYER,
Collections.singletonList(packetItem)));
entries.put(entry.getProfile().getId(), (KeyedVelocityTabListEntry) entry);
entries.put(entry.getProfile().uuid(), (KeyedVelocityTabListEntry) entry);
}
@Override
@@ -140,7 +140,7 @@ public class KeyedVelocityTabList implements InternalTabList {
}
@Override
public Collection<TabListEntry> getEntries() {
public Collection<TabListEntry> entries() {
return Collections.unmodifiableCollection(this.entries.values());
}
@@ -156,7 +156,7 @@ public class KeyedVelocityTabList implements InternalTabList {
int gameMode,
@Nullable ChatSession chatSession, boolean listed) {
return new KeyedVelocityTabListEntry(this, profile, displayName, latency, gameMode,
chatSession == null ? null : chatSession.getIdentifiedKey());
chatSession == null ? null : chatSession.identifiedKey());
}
@Override
@@ -222,19 +222,19 @@ public class KeyedVelocityTabList implements InternalTabList {
}
void updateEntry(int action, TabListEntry entry) {
if (entries.containsKey(entry.getProfile().getId())) {
if (entries.containsKey(entry.getProfile().uuid())) {
LegacyPlayerListItem.Item packetItem = LegacyPlayerListItem.Item.from(entry);
IdentifiedKey selectedKey = packetItem.getPlayerKey();
Optional<Player> existing = proxyServer.getPlayer(entry.getProfile().getId());
Optional<Player> existing = proxyServer.getPlayer(entry.getProfile().uuid());
if (existing.isPresent()) {
selectedKey = existing.get().getIdentifiedKey();
selectedKey = existing.get().identifiedKey();
}
if (selectedKey != null
&& selectedKey.getKeyRevision().getApplicableTo()
&& selectedKey.revision().applicableTo()
.contains(connection.getProtocolVersion())
&& Objects.equals(selectedKey.getSignatureHolder(), entry.getProfile().getId())) {
&& Objects.equals(selectedKey.signatureHolder(), entry.getProfile().uuid())) {
packetItem.setPlayerKey(selectedKey);
} else {
packetItem.setPlayerKey(null);

View File

@@ -114,7 +114,7 @@ public class KeyedVelocityTabListEntry implements TabListEntry {
}
@Override
public IdentifiedKey getIdentifiedKey() {
public IdentifiedKey identifiedKey() {
return playerKey;
}

View File

@@ -87,12 +87,12 @@ public class VelocityTabList implements InternalTabList {
}
EnumSet<UpsertPlayerInfo.Action> actions = EnumSet.noneOf(UpsertPlayerInfo.Action.class);
UpsertPlayerInfo.Entry playerInfoEntry = new UpsertPlayerInfo.Entry(entry.getProfile().getId());
UpsertPlayerInfo.Entry playerInfoEntry = new UpsertPlayerInfo.Entry(entry.getProfile().uuid());
Preconditions.checkNotNull(entry.getProfile(), "Profile cannot be null");
Preconditions.checkNotNull(entry.getProfile().getId(), "Profile ID cannot be null");
Preconditions.checkNotNull(entry.getProfile().uuid(), "Profile ID cannot be null");
TabListEntry previousEntry = this.entries.put(entry.getProfile().getId(), entry);
TabListEntry previousEntry = this.entries.put(entry.getProfile().uuid(), entry);
if (previousEntry != null) {
// we should merge entries here
@@ -121,7 +121,7 @@ public class VelocityTabList implements InternalTabList {
if (from != null) {
actions.add(UpsertPlayerInfo.Action.INITIALIZE_CHAT);
playerInfoEntry.setChatSession(
new RemoteChatSession(from.getSessionId(), from.getIdentifiedKey()));
new RemoteChatSession(from.sessionId(), from.identifiedKey()));
}
}
} else {
@@ -137,7 +137,7 @@ public class VelocityTabList implements InternalTabList {
actions.add(UpsertPlayerInfo.Action.INITIALIZE_CHAT);
ChatSession from = entry.getChatSession();
playerInfoEntry.setChatSession(
new RemoteChatSession(from.getSessionId(), from.getIdentifiedKey()));
new RemoteChatSession(from.sessionId(), from.identifiedKey()));
}
if (entry.getGameMode() != -1 && entry.getGameMode() != 256) {
actions.add(UpsertPlayerInfo.Action.UPDATE_GAME_MODE);
@@ -166,7 +166,7 @@ public class VelocityTabList implements InternalTabList {
}
@Override
public Collection<TabListEntry> getEntries() {
public Collection<TabListEntry> entries() {
return this.entries.values().stream().map(e -> (TabListEntry) e).collect(Collectors.toList());
}
@@ -199,8 +199,8 @@ public class VelocityTabList implements InternalTabList {
protected UpsertPlayerInfo.Entry createRawEntry(VelocityTabListEntry entry) {
Preconditions.checkNotNull(entry, "entry");
Preconditions.checkNotNull(entry.getProfile(), "Profile cannot be null");
Preconditions.checkNotNull(entry.getProfile().getId(), "Profile ID cannot be null");
return new UpsertPlayerInfo.Entry(entry.getProfile().getId());
Preconditions.checkNotNull(entry.getProfile().uuid(), "Profile ID cannot be null");
return new UpsertPlayerInfo.Entry(entry.getProfile().uuid());
}
protected void emitActionRaw(UpsertPlayerInfo.Action action, UpsertPlayerInfo.Entry entry) {

View File

@@ -34,7 +34,7 @@ public class VelocityTabListEntryLegacy extends KeyedVelocityTabListEntry {
@Override
public TabListEntry setDisplayName(@Nullable Component displayName) {
getTabList().removeEntry(getProfile().getId()); // We have to remove first if updating
getTabList().removeEntry(getProfile().uuid()); // We have to remove first if updating
return super.setDisplayName(displayName);
}
}

View File

@@ -55,13 +55,13 @@ public class VelocityTabListLegacy extends KeyedVelocityTabList {
@Override
public void addEntry(TabListEntry entry) {
super.addEntry(entry);
nameMapping.put(entry.getProfile().getName(), entry.getProfile().getId());
nameMapping.put(entry.getProfile().name(), entry.getProfile().uuid());
}
@Override
public Optional<TabListEntry> removeEntry(UUID uuid) {
Optional<TabListEntry> entry = super.removeEntry(uuid);
entry.map(TabListEntry::getProfile).map(GameProfile::getName).ifPresent(nameMapping::remove);
entry.map(TabListEntry::getProfile).map(GameProfile::name).ifPresent(nameMapping::remove);
return entry;
}
@@ -115,7 +115,7 @@ public class VelocityTabListLegacy extends KeyedVelocityTabList {
@Override
void updateEntry(int action, TabListEntry entry) {
if (entries.containsKey(entry.getProfile().getId())) {
if (entries.containsKey(entry.getProfile().uuid())) {
switch (action) {
case LegacyPlayerListItem.UPDATE_LATENCY:
case LegacyPlayerListItem.UPDATE_DISPLAY_NAME: // Add here because we removed beforehand

View File

@@ -57,36 +57,36 @@ public enum InformationUtils {
*/
public static JsonArray collectPluginInfo(ProxyServer proxy) {
List<PluginContainer> allPlugins = ImmutableList.copyOf(
proxy.getPluginManager().getPlugins());
proxy.getPluginManager().plugins());
JsonArray plugins = new JsonArray();
for (PluginContainer plugin : allPlugins) {
PluginDescription desc = plugin.getDescription();
PluginDescription desc = plugin.description();
JsonObject current = new JsonObject();
current.addProperty("id", desc.getId());
if (desc.getName().isPresent()) {
current.addProperty("name", desc.getName().get());
current.addProperty("id", desc.id());
if (desc.name().isPresent()) {
current.addProperty("name", desc.name().get());
}
if (desc.getVersion().isPresent()) {
current.addProperty("version", desc.getVersion().get());
if (desc.version().isPresent()) {
current.addProperty("version", desc.version().get());
}
if (!desc.getAuthors().isEmpty()) {
if (!desc.authors().isEmpty()) {
JsonArray authorsArray = new JsonArray();
for (String author : desc.getAuthors()) {
for (String author : desc.authors()) {
authorsArray.add(author);
}
current.add("authors", authorsArray);
}
if (desc.getDescription().isPresent()) {
current.addProperty("description", desc.getDescription().get());
if (desc.description().isPresent()) {
current.addProperty("description", desc.description().get());
}
if (desc.getUrl().isPresent()) {
current.addProperty("url", desc.getUrl().get());
if (desc.url().isPresent()) {
current.addProperty("url", desc.url().get());
}
if (!desc.getDependencies().isEmpty()) {
if (!desc.dependencies().isEmpty()) {
JsonArray dependencies = new JsonArray();
for (PluginDependency dependency : desc.getDependencies()) {
dependencies.add(dependency.getId());
for (PluginDependency dependency : desc.dependencies()) {
dependencies.add(dependency.id());
}
current.add("dependencies", dependencies);
}
@@ -196,8 +196,8 @@ public enum InformationUtils {
*/
public static JsonObject collectServerInfo(RegisteredServer server) {
JsonObject info = new JsonObject();
info.addProperty("currentPlayers", server.getPlayersConnected().size());
SocketAddress addr = server.getServerInfo().getAddress();
info.addProperty("currentPlayers", server.players().size());
SocketAddress addr = server.serverInfo().address();
if (addr instanceof InetSocketAddress) {
InetSocketAddress iaddr = (InetSocketAddress) addr;
if (iaddr.isUnresolved()) {

View File

@@ -46,10 +46,10 @@ public class VelocityChannelRegistrar implements ChannelRegistrar {
for (ChannelIdentifier identifier : identifiers) {
if (identifier instanceof MinecraftChannelIdentifier) {
identifierMap.put(identifier.getId(), identifier);
identifierMap.put(identifier.id(), identifier);
} else {
String rewritten = PluginMessageUtil.transformLegacyToModernChannel(identifier.getId());
identifierMap.put(identifier.getId(), identifier);
String rewritten = PluginMessageUtil.transformLegacyToModernChannel(identifier.id());
identifierMap.put(identifier.id(), identifier);
identifierMap.put(rewritten, identifier);
}
}
@@ -65,10 +65,10 @@ public class VelocityChannelRegistrar implements ChannelRegistrar {
for (ChannelIdentifier identifier : identifiers) {
if (identifier instanceof MinecraftChannelIdentifier) {
identifierMap.remove(identifier.getId());
identifierMap.remove(identifier.id());
} else {
String rewritten = PluginMessageUtil.transformLegacyToModernChannel(identifier.getId());
identifierMap.remove(identifier.getId());
String rewritten = PluginMessageUtil.transformLegacyToModernChannel(identifier.id());
identifierMap.remove(identifier.id());
identifierMap.remove(rewritten);
}
}
@@ -82,7 +82,7 @@ public class VelocityChannelRegistrar implements ChannelRegistrar {
public Collection<String> getLegacyChannelIds() {
Collection<String> ids = new HashSet<>();
for (ChannelIdentifier value : identifierMap.values()) {
ids.add(value.getId());
ids.add(value.id());
}
return ids;
}
@@ -96,9 +96,9 @@ public class VelocityChannelRegistrar implements ChannelRegistrar {
Collection<String> ids = new HashSet<>();
for (ChannelIdentifier value : identifierMap.values()) {
if (value instanceof MinecraftChannelIdentifier) {
ids.add(value.getId());
ids.add(value.id());
} else {
ids.add(PluginMessageUtil.transformLegacyToModernChannel(value.getId()));
ids.add(PluginMessageUtil.transformLegacyToModernChannel(value.id()));
}
}
return ids;

View File

@@ -129,7 +129,7 @@ public class AdventureBossBarManager implements BossBar.Listener {
}
for (ConnectedPlayer player : holder.subscribers) {
Component translated = player.translateMessage(newName);
BossBarPacket packet = holder.createTitleUpdate(translated, player.getProtocolVersion());
BossBarPacket packet = holder.createTitleUpdate(translated, player.protocolVersion());
player.getConnection().write(packet);
}
}
@@ -211,7 +211,7 @@ public class AdventureBossBarManager implements BossBar.Listener {
BossBarPacket packet = new BossBarPacket();
packet.setUuid(this.id);
packet.setAction(BossBarPacket.ADD);
packet.setName(ProtocolUtils.getJsonChatSerializer(player.getProtocolVersion())
packet.setName(ProtocolUtils.getJsonChatSerializer(player.protocolVersion())
.serialize(player.translateMessage(bar.name())));
packet.setColor(COLORS_TO_PROTOCOL.get(bar.color()));
packet.setOverlay(OVERLAY_TO_PROTOCOL.get(bar.overlay()));

View File

@@ -51,7 +51,7 @@ public class CommandGraphInjectorTests extends CommandTestSuite {
@Test
void testInjectInvocableCommand() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (SimpleCommand) invocation -> fail());
manager.getInjector().inject(dest, source);
@@ -64,7 +64,7 @@ public class CommandGraphInjectorTests extends CommandTestSuite {
void testFiltersImpermissibleAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -91,7 +91,7 @@ public class CommandGraphInjectorTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, (SimpleCommand) invocation -> fail());
@@ -109,7 +109,7 @@ public class CommandGraphInjectorTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new RawCommand() {

View File

@@ -42,17 +42,17 @@ public class CommandManagerTests extends CommandTestSuite {
@Test
void testRegisterWithMeta() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, DummyCommand.INSTANCE);
assertTrue(manager.hasCommand("hello"));
assertRegisteredAliases("hello");
assertEquals(meta, manager.getCommandMeta("hello"));
assertEquals(meta, manager.commandMeta("hello"));
}
@Test
void testRegisterWithMetaContainingMultipleAliases() {
final var meta = manager.metaBuilder("foo")
final var meta = manager.buildMeta("foo")
.aliases("bar")
.aliases("baz", "qux")
.build();
@@ -63,15 +63,15 @@ public class CommandManagerTests extends CommandTestSuite {
assertTrue(manager.hasCommand("baz"));
assertTrue(manager.hasCommand("qux"));
assertRegisteredAliases("foo", "bar", "baz", "qux");
assertEquals(meta, manager.getCommandMeta("foo"));
assertEquals(meta, manager.getCommandMeta("bar"));
assertEquals(meta, manager.getCommandMeta("baz"));
assertEquals(meta, manager.getCommandMeta("qux"));
assertEquals(meta, manager.commandMeta("foo"));
assertEquals(meta, manager.commandMeta("bar"));
assertEquals(meta, manager.commandMeta("baz"));
assertEquals(meta, manager.commandMeta("qux"));
}
@Test
void testRegisterAliasesAreCaseInsensitive() {
final var meta = manager.metaBuilder("Foo")
final var meta = manager.buildMeta("Foo")
.aliases("Bar")
.build();
manager.register(meta, DummyCommand.INSTANCE);
@@ -96,13 +96,13 @@ public class CommandManagerTests extends CommandTestSuite {
void testRegisterOverridesPreviousCommand() {
final var called = new AtomicBoolean();
final var oldMeta = manager.metaBuilder("foo").build();
final var oldMeta = manager.buildMeta("foo").build();
manager.register(oldMeta, DummyCommand.INSTANCE); // fails on execution
assertEquals(oldMeta, manager.getCommandMeta("foo"));
assertEquals(oldMeta, manager.commandMeta("foo"));
final var newMeta = manager.metaBuilder("foo").build();
final var newMeta = manager.buildMeta("foo").build();
manager.register(newMeta, (RawCommand) invocation -> called.set(true));
assertEquals(newMeta, manager.getCommandMeta("foo"));
assertEquals(newMeta, manager.commandMeta("foo"));
manager.executeAsync(MockCommandSource.INSTANCE, "foo").join();
assertTrue(called.get());
@@ -116,7 +116,7 @@ public class CommandManagerTests extends CommandTestSuite {
.build();
assertThrows(IllegalArgumentException.class, () -> {
manager.metaBuilder("hello").hint(hintNode);
manager.buildMeta("hello").hint(hintNode);
});
}
@@ -131,7 +131,7 @@ public class CommandManagerTests extends CommandTestSuite {
.build();
assertThrows(IllegalArgumentException.class, () -> {
manager.metaBuilder("hello").hint(hintNode);
manager.buildMeta("hello").hint(hintNode);
});
}
@@ -156,7 +156,7 @@ public class CommandManagerTests extends CommandTestSuite {
@Test
void testUnregisterSecondaryAlias() {
final var meta = manager.metaBuilder("foo")
final var meta = manager.buildMeta("foo")
.aliases("bar")
.build();
manager.register(meta, DummyCommand.INSTANCE);
@@ -164,13 +164,13 @@ public class CommandManagerTests extends CommandTestSuite {
assertFalse(manager.hasCommand("bar"));
assertTrue(manager.hasCommand("foo"));
assertEquals(meta, manager.getCommandMeta("foo"));
assertEquals(meta, manager.commandMeta("foo"));
assertRegisteredAliases("foo");
}
@Test
void testUnregisterAllAliases() {
final var meta = manager.metaBuilder("foo")
final var meta = manager.buildMeta("foo")
.aliases("bar")
.build();
manager.register(meta, DummyCommand.INSTANCE);
@@ -182,19 +182,19 @@ public class CommandManagerTests extends CommandTestSuite {
@Test
void testUnregisterAliasOverlap() {
final var meta1 = manager.metaBuilder("foo")
final var meta1 = manager.buildMeta("foo")
.aliases("bar")
.build();
manager.register(meta1, DummyCommand.INSTANCE);
final var meta2 = manager.metaBuilder("bar")
final var meta2 = manager.buildMeta("bar")
.build();
manager.register(meta2, DummyCommand.INSTANCE);
assertEquals(meta1, manager.getCommandMeta("foo"));
assertEquals(meta2, manager.getCommandMeta("bar"));
assertEquals(meta1, manager.commandMeta("foo"));
assertEquals(meta2, manager.commandMeta("bar"));
manager.unregister(meta1);
assertNull(manager.getCommandMeta("foo"));
assertEquals(meta2, manager.getCommandMeta("bar"));
assertNull(manager.commandMeta("foo"));
assertEquals(meta2, manager.commandMeta("bar"));
}
// Execution

View File

@@ -72,7 +72,7 @@ abstract class CommandTestSuite {
}
final void assertRegisteredAliases(final String... expected) {
final Collection<String> actual = manager.getAliases();
final Collection<String> actual = manager.aliases();
assertEquals(expected.length, actual.size());
final Collection<String> asList = Arrays.asList(expected);
assertTrue(asList.containsAll(actual));

View File

@@ -29,7 +29,7 @@ public class MockCommandSource implements CommandSource {
public static final CommandSource INSTANCE = new MockCommandSource();
@Override
public PermissionChecker getPermissionChecker() {
public PermissionChecker permissionChecker() {
return PermissionChecker.always(TriState.NOT_SET);
}
}

View File

@@ -45,7 +45,7 @@ public class RawCommandTests extends CommandTestSuite {
void testExecuteAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (RawCommand) invocation -> {
assertEquals(source, invocation.source());
assertEquals("hello", invocation.alias());
@@ -61,7 +61,7 @@ public class RawCommandTests extends CommandTestSuite {
void testExecuteIgnoresAliasCase() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (RawCommand) invocation -> {
assertEquals("hello", invocation.alias());
callCount.incrementAndGet();
@@ -75,7 +75,7 @@ public class RawCommandTests extends CommandTestSuite {
void testExecuteInputIsTrimmed() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (RawCommand) invocation -> {
assertEquals("hello", invocation.alias());
assertEquals("", invocation.arguments());
@@ -91,7 +91,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testExecuteAfterUnregisterForwards() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (RawCommand) invocation -> fail());
manager.unregister("hello");
@@ -102,7 +102,7 @@ public class RawCommandTests extends CommandTestSuite {
void testForwardsAndDoesNotExecuteImpermissibleAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -127,7 +127,7 @@ public class RawCommandTests extends CommandTestSuite {
void testExecutesWithArguments() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (RawCommand) invocation -> {
assertEquals("hello", invocation.alias());
assertEquals("dear world", invocation.arguments());
@@ -142,7 +142,7 @@ public class RawCommandTests extends CommandTestSuite {
void testHandlesAndDoesNotExecuteWithImpermissibleArgs() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("color").build();
final var meta = manager.buildMeta("color").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -166,7 +166,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestAliasIfImpermissible() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -189,7 +189,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestAliasAfterUnregister() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -208,7 +208,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsAfterAlias() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -228,7 +228,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsAfterAliasIgnoresAliasCase() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -247,7 +247,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsAfterPartialArguments() {
final var meta = manager.metaBuilder("numbers").build();
final var meta = manager.buildMeta("numbers").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -268,7 +268,7 @@ public class RawCommandTests extends CommandTestSuite {
void testDoesNotSuggestFirstArgumentIfImpermissibleAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -297,7 +297,7 @@ public class RawCommandTests extends CommandTestSuite {
void testDoesNotSuggestArgumentsAfterPartialImpermissibleArguments() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("foo").build();
final var meta = manager.buildMeta("foo").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -324,7 +324,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestIfFutureCompletesExceptionally() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -342,7 +342,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestIfSuggestAsyncThrows() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -361,7 +361,7 @@ public class RawCommandTests extends CommandTestSuite {
@Test
void testSuggestCompletesExceptionallyIfHasPermissionThrows() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -392,7 +392,7 @@ public class RawCommandTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new RawCommand() {
@@ -415,7 +415,7 @@ public class RawCommandTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new RawCommand() {
@@ -439,7 +439,7 @@ public class RawCommandTests extends CommandTestSuite {
.<CommandSource, String>argument("hint", word())
.suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException()))
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new RawCommand() {
@@ -465,7 +465,7 @@ public class RawCommandTests extends CommandTestSuite {
throw new RuntimeException();
})
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new RawCommand() {

View File

@@ -46,7 +46,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testExecutesAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (SimpleCommand) invocation -> {
assertEquals(source, invocation.source());
assertEquals("hello", invocation.alias());
@@ -62,7 +62,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testExecuteIgnoresAliasCase() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (SimpleCommand) invocation -> {
assertEquals("hello", invocation.alias());
callCount.incrementAndGet();
@@ -76,7 +76,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testExecuteInputIsTrimmed() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (SimpleCommand) invocation -> {
assertEquals("hello", invocation.alias());
assertArrayEquals(new String[0], invocation.arguments());
@@ -92,7 +92,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testExecuteAfterUnregisterForwards() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (SimpleCommand) invocation -> fail());
manager.unregister("hello");
@@ -103,7 +103,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testForwardsAndDoesNotExecuteImpermissibleAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -128,7 +128,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testExecutesWithArguments() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, (SimpleCommand) invocation -> {
assertEquals("hello", invocation.alias());
assertArrayEquals(new String[]{"dear", "world"}, invocation.arguments());
@@ -143,7 +143,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testHandlesAndDoesNotExecuteWithImpermissibleArgs() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("color").build();
final var meta = manager.buildMeta("color").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -167,7 +167,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestAliasIfImpermissible() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -190,7 +190,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestAliasAfterUnregister() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -209,7 +209,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsAfterAlias() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -229,7 +229,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsAfterAliasIgnoresAliasCase() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -248,7 +248,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsAfterPartialArguments() {
final var meta = manager.metaBuilder("numbers").build();
final var meta = manager.buildMeta("numbers").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -269,7 +269,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testDoesNotSuggestFirstArgumentIfImpermissibleAlias() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -298,7 +298,7 @@ public class SimpleCommandTests extends CommandTestSuite {
void testDoesNotSuggestArgumentsAfterPartialImpermissibleArguments() {
final var callCount = new AtomicInteger();
final var meta = manager.metaBuilder("foo").build();
final var meta = manager.buildMeta("foo").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -325,7 +325,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestIfFutureCompletesExceptionally() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -343,7 +343,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testDoesNotSuggestIfSuggestAsyncThrows() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -362,7 +362,7 @@ public class SimpleCommandTests extends CommandTestSuite {
@Test
void testSuggestCompletesExceptionallyIfHasPermissionThrows() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new SimpleCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -393,7 +393,7 @@ public class SimpleCommandTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new SimpleCommand() {
@@ -416,7 +416,7 @@ public class SimpleCommandTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new SimpleCommand() {
@@ -440,7 +440,7 @@ public class SimpleCommandTests extends CommandTestSuite {
.<CommandSource, String>argument("hint", word())
.suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException()))
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new SimpleCommand() {
@@ -466,7 +466,7 @@ public class SimpleCommandTests extends CommandTestSuite {
throw new RuntimeException();
})
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, new SimpleCommand() {

View File

@@ -38,9 +38,9 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testSuggestsAliasesForEmptyInput() {
manager.register(manager.metaBuilder("foo").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.metaBuilder("bar").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.metaBuilder("baz").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("foo").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("bar").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("baz").build(), NoSuggestionsCommand.INSTANCE);
assertSuggestions("", "bar", "baz", "foo"); // in alphabetical order
}
@@ -48,9 +48,9 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void willNotSuggestAliasesIfNotAnnouncingForPlayer() {
manager.setAnnounceProxyCommands(false);
manager.register(manager.metaBuilder("foo").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.metaBuilder("bar").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.metaBuilder("baz").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("foo").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("bar").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("baz").build(), NoSuggestionsCommand.INSTANCE);
assertPlayerSuggestions(""); // for a fake player
assertSuggestions("", "bar", "baz", "foo"); // for non-players
@@ -58,7 +58,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testDoesNotSuggestForLeadingWhitespace() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
assertSuggestions(" ");
@@ -66,8 +66,8 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testSuggestsAliasesForPartialAlias() {
manager.register(manager.metaBuilder("hello").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.metaBuilder("hey").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("hello").build(), NoSuggestionsCommand.INSTANCE);
manager.register(manager.buildMeta("hey").build(), NoSuggestionsCommand.INSTANCE);
assertSuggestions("hell", "hello");
assertSuggestions("He", "hello", "hey");
@@ -75,7 +75,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testDoesNotSuggestForFullAlias() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
assertSuggestions("hello");
@@ -84,7 +84,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testDoesNotSuggestForPartialIncorrectAlias() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
assertSuggestions("yo");
@@ -93,7 +93,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testDoesNotSuggestArgumentsForIncorrectAlias() {
final var meta = manager.metaBuilder("hello").build();
final var meta = manager.buildMeta("hello").build();
manager.register(meta, new RawCommand() {
@Override
public void execute(final Invocation invocation) {
@@ -115,7 +115,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testSuggestsAllAliases() {
final var meta = manager.metaBuilder("foo")
final var meta = manager.buildMeta("foo")
.aliases("bar", "baz")
.build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
@@ -125,7 +125,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
@Test
void testSuggestsArgumentsViaAlias() {
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.aliases("hi")
.build();
manager.register(meta, new RawCommand() {
@@ -150,7 +150,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
@@ -170,7 +170,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
.suggest("three")
.buildFuture())
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
@@ -184,7 +184,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
final var hint = LiteralArgumentBuilder
.<CommandSource>literal("bar")
.build();
final var meta = manager.metaBuilder("foo")
final var meta = manager.buildMeta("foo")
.hint(hint)
.build();
manager.register(meta, new RawCommand() {
@@ -213,7 +213,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
.requires(source1 -> fail())
.suggests((context, builder) -> builder.suggest("suggestion").buildFuture())
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
@@ -228,7 +228,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
.<CommandSource, String>argument("hint", word())
.suggests((context, builder) -> builder.suggest("suggestion").buildFuture())
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.setAnnounceProxyCommands(false);
@@ -245,7 +245,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
.<CommandSource, String>argument("hint", word())
.suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException()))
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);
@@ -261,7 +261,7 @@ public class SuggestionsProviderTests extends CommandTestSuite {
throw new RuntimeException();
})
.build();
final var meta = manager.metaBuilder("hello")
final var meta = manager.buildMeta("hello")
.hint(hint)
.build();
manager.register(meta, NoSuggestionsCommand.INSTANCE);

View File

@@ -37,12 +37,12 @@ public class MockPluginManager implements PluginManager {
}
@Override
public Optional<PluginContainer> getPlugin(final String id) {
public Optional<PluginContainer> plugin(final String id) {
return Optional.empty();
}
@Override
public Collection<PluginContainer> getPlugins() {
public Collection<PluginContainer> plugins() {
return ImmutableList.of();
}

View File

@@ -56,7 +56,7 @@ public class FakePluginManager implements PluginManager {
}
@Override
public @NonNull Optional<PluginContainer> getPlugin(@NonNull String id) {
public @NonNull Optional<PluginContainer> plugin(@NonNull String id) {
switch (id) {
case "a":
return Optional.of(containerA);
@@ -68,7 +68,7 @@ public class FakePluginManager implements PluginManager {
}
@Override
public @NonNull Collection<PluginContainer> getPlugins() {
public @NonNull Collection<PluginContainer> plugins() {
return ImmutableList.of(containerA, containerB);
}
@@ -97,17 +97,17 @@ public class FakePluginManager implements PluginManager {
}
@Override
public @NonNull PluginDescription getDescription() {
public @NonNull PluginDescription description() {
return () -> id;
}
@Override
public Optional<?> getInstance() {
public Optional<?> instance() {
return Optional.of(instance);
}
@Override
public ExecutorService getExecutorService() {
public ExecutorService executorService() {
return service;
}
}

View File

@@ -45,9 +45,9 @@ class VelocityChannelRegistrarTest {
// Two channels cover the modern channel (velocity:test) and the legacy-mapped channel
// (legacy:velocitytest). Make sure they're what we expect.
assertEquals(ImmutableSet.of(MODERN.getId(), SIMPLE_LEGACY_REMAPPED), registrar
assertEquals(ImmutableSet.of(MODERN.id(), SIMPLE_LEGACY_REMAPPED), registrar
.getModernChannelIds());
assertEquals(ImmutableSet.of(SIMPLE_LEGACY.getId(), MODERN.getId()), registrar
assertEquals(ImmutableSet.of(SIMPLE_LEGACY.id(), MODERN.id()), registrar
.getLegacyChannelIds());
}
@@ -57,8 +57,8 @@ class VelocityChannelRegistrarTest {
registrar.register(SPECIAL_REMAP_LEGACY, MODERN_SPECIAL_REMAP);
// This one, just one channel for the modern case.
assertEquals(ImmutableSet.of(MODERN_SPECIAL_REMAP.getId()), registrar.getModernChannelIds());
assertEquals(ImmutableSet.of(MODERN_SPECIAL_REMAP.getId(), SPECIAL_REMAP_LEGACY.getId()),
assertEquals(ImmutableSet.of(MODERN_SPECIAL_REMAP.id()), registrar.getModernChannelIds());
assertEquals(ImmutableSet.of(MODERN_SPECIAL_REMAP.id(), SPECIAL_REMAP_LEGACY.id()),
registrar.getLegacyChannelIds());
}
@@ -68,7 +68,7 @@ class VelocityChannelRegistrarTest {
registrar.register(MODERN, SIMPLE_LEGACY);
registrar.unregister(SIMPLE_LEGACY);
assertEquals(ImmutableSet.of(MODERN.getId()), registrar.getModernChannelIds());
assertEquals(ImmutableSet.of(MODERN.getId()), registrar.getLegacyChannelIds());
assertEquals(ImmutableSet.of(MODERN.id()), registrar.getModernChannelIds());
assertEquals(ImmutableSet.of(MODERN.id()), registrar.getLegacyChannelIds());
}
}