From d72d707b1c0dd6215a4984956faf4b2ec4bdbd97 Mon Sep 17 00:00:00 2001 From: Andrew Steinborn Date: Sun, 1 Jan 2023 17:53:37 -0500 Subject: [PATCH] Convert Velocity buildscripts to Kotlin DSL (#918) Spiritually indebted to #518 and @alexstaeding. There's a minor break - we're going up to 3.2.0-SNAPSHOT as the API now compiles against Java 11. But this is more academic in practice. --- api/build.gradle | 119 -------- api/build.gradle.kts | 80 ++++++ .../plugin/ap/PluginAnnotationProcessor.java | 3 + .../ap/SerializedPluginDescription.java | 6 + .../api/command/CommandManager.java | 1 + .../event/command/CommandExecuteEvent.java | 15 +- .../command/PlayerAvailableCommandsEvent.java | 1 + .../api/event/connection/DisconnectEvent.java | 3 + .../api/event/connection/PreLoginEvent.java | 1 + .../event/player/GameProfileRequestEvent.java | 1 + .../event/player/KickedFromServerEvent.java | 1 + .../api/event/player/PlayerChatEvent.java | 6 +- .../PlayerChooseInitialServerEvent.java | 4 +- .../player/PlayerResourcePackStatusEvent.java | 1 + .../event/player/ServerConnectedEvent.java | 1 + .../player/ServerLoginPluginMessageEvent.java | 4 + .../event/player/ServerPreConnectEvent.java | 7 + .../player/ServerResourcePackSendEvent.java | 2 +- .../api/event/player/TabCompleteEvent.java | 4 + .../api/plugin/InvalidPluginException.java | 3 + .../api/plugin/meta/PluginDependency.java | 1 + .../api/proxy/LoginPhaseConnection.java | 23 +- .../com/velocitypowered/api/proxy/Player.java | 12 +- .../api/proxy/crypto/IdentifiedKey.java | 4 + .../api/proxy/crypto/KeyIdentifiable.java | 9 +- .../api/proxy/crypto/KeySigned.java | 3 + .../api/proxy/crypto/SignedMessage.java | 3 + .../messages/MinecraftChannelIdentifier.java | 20 +- .../api/proxy/player/PlayerSettings.java | 6 + .../api/proxy/player/ResourcePackInfo.java | 16 +- .../api/proxy/player/SkinParts.java | 3 + .../api/proxy/player/TabListEntry.java | 4 +- .../api/proxy/server/QueryResponse.java | 13 + .../api/proxy/server/ServerPing.java | 17 ++ .../api/scheduler/TaskStatus.java | 3 + .../velocitypowered/api/util/GameProfile.java | 7 + .../com/velocitypowered/api/util/ModInfo.java | 12 + build.gradle | 59 ---- build.gradle.kts | 47 ++++ buildSrc/build.gradle.kts | 27 ++ .../script/SetManifestImplVersionPlugin.kt | 54 ++++ .../script/VelocityCheckstylePlugin.kt | 38 +++ .../script/VelocityPublishPlugin.kt | 72 +++++ config/checkstyle/checkstyle.xml | 124 +++++---- gradle.properties | 26 ++ gradle/checkstyle.gradle | 8 - gradle/publish.gradle | 13 - native/build.gradle | 39 --- native/build.gradle.kts | 18 ++ .../com/velocitypowered/natives/Native.java | 3 + .../natives/NativeSetupException.java | 3 + .../natives/compression/CompressorUtils.java | 1 + .../compression/JavaVelocityCompressor.java | 3 + .../LibdeflateVelocityCompressor.java | 3 + .../VelocityCompressorFactory.java | 3 + .../encryption/JavaVelocityCipher.java | 3 + .../encryption/NativeVelocityCipher.java | 3 + .../natives/encryption/VelocityCipher.java | 9 + .../encryption/VelocityCipherFactory.java | 3 + .../natives/util/BufferPreference.java | 3 + .../natives/util/MoreByteBufUtils.java | 3 + .../natives/util/NativeCodeLoader.java | 5 + .../natives/util/NativeConstraints.java | 3 + .../velocitypowered/natives/util/Natives.java | 3 + proxy/build.gradle | 162 ----------- proxy/build.gradle.kts | 159 +++++++++++ .../com/velocitypowered/proxy/Metrics.java | 3 + .../velocitypowered/proxy/ProxyOptions.java | 6 +- .../com/velocitypowered/proxy/Velocity.java | 5 + .../velocitypowered/proxy/VelocityServer.java | 24 +- .../proxy/command/CommandGraphInjector.java | 19 +- .../proxy/command/SuggestionsProvider.java | 81 +++--- .../proxy/command/VelocityCommandManager.java | 49 ++-- .../proxy/command/VelocityCommandMeta.java | 23 +- .../proxy/command/VelocityCommands.java | 54 ++-- .../brigadier/StringArrayArgumentType.java | 9 +- .../brigadier/VelocityArgumentBuilder.java | 16 +- .../VelocityArgumentCommandNode.java | 26 +- .../command/builtin/CommandMessages.java | 3 + .../proxy/command/builtin/GlistCommand.java | 33 ++- .../proxy/command/builtin/ServerCommand.java | 31 ++- .../command/builtin/ShutdownCommand.java | 37 ++- .../command/builtin/VelocityCommand.java | 18 +- .../invocation/CommandInvocationFactory.java | 21 +- .../invocation/RawCommandInvocation.java | 20 +- .../invocation/SimpleCommandInvocation.java | 21 +- .../registrar/AbstractCommandRegistrar.java | 4 +- .../command/registrar/CommandRegistrar.java | 12 +- .../registrar/InvocableCommandRegistrar.java | 64 ++--- .../registrar/RawCommandRegistrar.java | 2 +- .../registrar/SimpleCommandRegistrar.java | 2 +- .../proxy/config/PingPassthroughMode.java | 3 + .../proxy/config/PlayerInfoForwarding.java | 3 + .../proxy/config/VelocityConfiguration.java | 133 ++++++--- .../proxy/connection/ConnectionType.java | 8 +- .../proxy/connection/ConnectionTypes.java | 8 +- .../proxy/connection/MinecraftConnection.java | 15 +- .../MinecraftConnectionAssociation.java | 3 + .../connection/MinecraftSessionHandler.java | 3 + .../proxy/connection/VelocityConstants.java | 3 + .../backend/BackendConnectionPhase.java | 18 +- .../backend/BackendConnectionPhases.java | 13 +- .../backend/BackendPlaySessionHandler.java | 7 +- .../backend/BungeeCordMessageResponder.java | 13 +- .../backend/LoginSessionHandler.java | 17 +- .../backend/TransitionSessionHandler.java | 5 +- .../backend/VelocityServerConnection.java | 24 +- .../connection/client/AuthSessionHandler.java | 13 +- .../client/ClientConnectionPhase.java | 14 +- .../client/ClientConnectionPhases.java | 3 +- .../client/ClientPlaySessionHandler.java | 165 ++++++----- .../client/ClientSettingsWrapper.java | 3 + .../connection/client/ConnectedPlayer.java | 54 ++-- .../client/HandshakeSessionHandler.java | 5 + .../client/InitialConnectSessionHandler.java | 4 + .../client/InitialInboundConnection.java | 5 + .../client/InitialLoginSessionHandler.java | 38 ++- .../client/LoginInboundConnection.java | 4 + .../client/StatusSessionHandler.java | 5 +- .../forge/legacy/LegacyForgeConstants.java | 5 +- .../LegacyForgeHandshakeBackendPhase.java | 42 ++- .../LegacyForgeHandshakeClientPhase.java | 56 ++-- .../forge/legacy/LegacyForgeUtil.java | 2 +- .../player/VelocityResourcePackInfo.java | 22 +- .../proxy/connection/registry/ChatData.java | 109 -------- .../connection/registry/DimensionData.java | 89 +++--- .../connection/registry/DimensionInfo.java | 11 +- .../registry/DimensionRegistry.java | 23 +- .../connection/util/ConnectionMessages.java | 3 + .../util/ConnectionRequestResults.java | 11 +- .../connection/util/ConnectionTypeImpl.java | 4 +- .../util/ServerListPingHandler.java | 3 + .../util/VelocityInboundConnection.java | 4 + .../proxy/console/VelocityConsole.java | 17 +- .../proxy/crypto/EncryptionUtils.java | 39 +-- .../proxy/crypto/IdentifiedKeyImpl.java | 31 ++- .../proxy/crypto/SignaturePair.java | 10 +- .../proxy/crypto/SignedChatCommand.java | 10 +- .../proxy/event/UntargetedEventHandler.java | 12 + .../proxy/event/VelocityEventManager.java | 20 +- .../network/BackendChannelInitializer.java | 3 + .../BackendChannelInitializerHolder.java | 3 + .../proxy/network/ConnectionManager.java | 10 +- .../proxy/network/Connections.java | 3 + .../proxy/network/Endpoint.java | 1 + .../network/ServerChannelInitializer.java | 3 + .../ServerChannelInitializerHolder.java | 4 + .../proxy/network/TransportType.java | 21 +- .../netty/SeparatePoolInetNameResolver.java | 9 +- .../proxy/plugin/PluginClassLoader.java | 3 + .../proxy/plugin/VelocityPluginManager.java | 8 +- .../proxy/plugin/loader/PluginLoader.java | 15 +- .../loader/VelocityPluginContainer.java | 3 + .../loader/VelocityPluginDescription.java | 18 +- .../plugin/loader/java/JavaPluginLoader.java | 5 +- .../loader/java/VelocityPluginModule.java | 2 +- .../plugin/util/PluginDependencyUtils.java | 7 +- .../proxy/protocol/MinecraftPacket.java | 3 + .../proxy/protocol/ProtocolUtils.java | 66 +++-- .../proxy/protocol/StateRegistry.java | 29 +- .../protocol/netty/AutoReadHolderHandler.java | 4 +- ...yHandler.java => GameSpyQueryHandler.java} | 12 +- .../protocol/netty/LegacyPingDecoder.java | 3 + .../protocol/netty/LegacyPingEncoder.java | 3 + .../netty/MinecraftCipherDecoder.java | 3 + .../netty/MinecraftCipherEncoder.java | 3 + .../netty/MinecraftCompressDecoder.java | 5 +- .../MinecraftCompressorAndLengthEncoder.java | 3 + .../protocol/netty/MinecraftDecoder.java | 9 +- .../protocol/netty/MinecraftEncoder.java | 9 +- .../netty/MinecraftVarintFrameDecoder.java | 3 + .../netty/MinecraftVarintLengthEncoder.java | 3 + .../protocol/packet/AvailableCommands.java | 11 +- .../protocol/packet/EncryptionResponse.java | 11 +- .../protocol/packet/HeaderAndFooter.java | 2 +- .../proxy/protocol/packet/JoinGame.java | 2 +- .../protocol/packet/LegacyDisconnect.java | 4 +- .../protocol/packet/RemovePlayerInfo.java | 7 +- .../proxy/protocol/packet/Respawn.java | 6 +- .../proxy/protocol/packet/ServerData.java | 3 +- .../proxy/protocol/packet/ServerLogin.java | 3 +- .../protocol/packet/TabCompleteResponse.java | 1 + .../protocol/packet/UpsertPlayerInfo.java | 10 +- .../packet/brigadier/ArgumentIdentifier.java | 8 +- .../brigadier/ArgumentPropertyRegistry.java | 35 ++- .../brigadier/ArgumentPropertySerializer.java | 1 + .../ModArgumentPropertySerializer.java | 3 +- .../packet/brigadier/RegistryKeyArgument.java | 4 +- .../brigadier/RegistryKeyArgumentList.java | 4 + .../RegistryKeyArgumentSerializer.java | 4 +- .../protocol/packet/chat/ChatHandler.java | 1 + .../proxy/protocol/packet/chat/ChatQueue.java | 35 ++- .../protocol/packet/chat/ChatTimeKeeper.java | 1 + .../protocol/packet/chat/CommandHandler.java | 19 +- .../packet/chat/LastSeenMessages.java | 1 + .../packet/chat/PlayerChatCompletion.java | 6 +- .../packet/chat/RemoteChatSession.java | 1 + .../protocol/packet/chat/SystemChat.java | 15 +- .../chat/builder/ChatBuilderFactory.java | 1 + .../packet/chat/builder/ChatBuilderV2.java | 1 + .../packet/chat/keyed/KeyedChatBuilder.java | 1 + .../packet/chat/keyed/KeyedChatHandler.java | 10 +- .../chat/keyed/KeyedCommandHandler.java | 22 +- .../packet/chat/keyed/KeyedPlayerChat.java | 12 +- .../packet/chat/keyed/KeyedPlayerCommand.java | 12 +- .../packet/chat/legacy/LegacyChat.java | 6 +- .../packet/chat/legacy/LegacyChatBuilder.java | 4 +- .../packet/chat/legacy/LegacyChatHandler.java | 1 + .../chat/legacy/LegacyCommandHandler.java | 1 + .../chat/session/SessionChatBuilder.java | 1 + .../chat/session/SessionChatHandler.java | 4 +- .../chat/session/SessionCommandHandler.java | 19 +- .../chat/session/SessionPlayerChat.java | 7 +- .../chat/session/SessionPlayerCommand.java | 12 +- .../packet/title/GenericTitlePacket.java | 9 +- .../packet/title/LegacyTitlePacket.java | 2 +- .../protocol/util/FaviconSerializer.java | 4 + .../protocol/util/GameProfileSerializer.java | 6 +- .../protocol/util/NettyPreconditions.java | 24 +- .../protocol/util/PluginMessageUtil.java | 25 +- .../VelocityLegacyHoverEventSerializer.java | 4 +- .../proxy/scheduler/VelocityScheduler.java | 12 +- .../proxy/server/PingSessionHandler.java | 5 + .../proxy/server/ServerMap.java | 7 +- .../server/VelocityRegisteredServer.java | 8 +- .../proxy/tablist/InternalTabList.java | 4 + .../proxy/tablist/KeyedVelocityTabList.java | 45 ++- .../tablist/KeyedVelocityTabListEntry.java | 7 +- .../proxy/tablist/VelocityTabList.java | 35 ++- .../proxy/tablist/VelocityTabListEntry.java | 12 +- .../tablist/VelocityTabListEntryLegacy.java | 3 + .../proxy/tablist/VelocityTabListLegacy.java | 6 +- .../proxy/util/AddressUtil.java | 4 + .../proxy/util/CharacterUtil.java | 10 +- .../proxy/util/ClosestLocaleMatcher.java | 4 + .../proxy/util/DurationUtils.java | 1 + .../proxy/util/InformationUtils.java | 54 ++-- ...ileSystemUtils.java => ResourceUtils.java} | 17 +- .../proxy/util/VelocityChannelRegistrar.java | 4 + .../util/bossbar/AdventureBossBarManager.java | 8 +- .../proxy/util/collect/CappedSet.java | 3 +- .../proxy/util/collect/Enum2IntMap.java | 13 +- .../util/collect/IdentityHashStrategy.java | 5 + .../proxy/util/concurrent/Once.java | 9 +- .../VelocityNettyThreadFactory.java | 3 + .../util/except/QuietDecoderException.java | 4 +- .../util/except/QuietRuntimeException.java | 4 +- .../proxy/util/ratelimit/Ratelimiter.java | 1 + .../proxy/util/ratelimit/Ratelimiters.java | 4 + .../proxy/l10n/messages.properties | 9 - .../proxy/l10n/messages_ar_SA.properties | 8 - .../proxy/l10n/messages_bg_BG.properties | 8 - .../proxy/l10n/messages_cs_CZ.properties | 8 - .../proxy/l10n/messages_da_DK.properties | 8 - .../proxy/l10n/messages_de_DE.properties | 8 - .../proxy/l10n/messages_es_ES.properties | 8 - .../proxy/l10n/messages_et_EE.properties | 8 - .../proxy/l10n/messages_fi_FI.properties | 8 - .../proxy/l10n/messages_fr_FR.properties | 8 - .../proxy/l10n/messages_he_IL.properties | 8 - .../proxy/l10n/messages_hu_HU.properties | 8 - .../proxy/l10n/messages_it_IT.properties | 8 - .../proxy/l10n/messages_ja_JP.properties | 8 - .../proxy/l10n/messages_ko_KR.properties | 8 - .../proxy/l10n/messages_nb_NO.properties | 8 - .../proxy/l10n/messages_nl_NL.properties | 8 - .../proxy/l10n/messages_nn_NO.properties | 8 - .../proxy/l10n/messages_pl_PL.properties | 8 - .../proxy/l10n/messages_pt_BR.properties | 8 - .../proxy/l10n/messages_ru_RU.properties | 8 - .../proxy/l10n/messages_sk_SK.properties | 8 - .../proxy/l10n/messages_sq_AL.properties | 8 - .../proxy/l10n/messages_sr_CS.properties | 8 - .../proxy/l10n/messages_sv_SE.properties | 8 - .../proxy/l10n/messages_tl_PH.properties | 8 - .../proxy/l10n/messages_tr_TR.properties | 8 - .../proxy/l10n/messages_zh_CN.properties | 8 - .../proxy/l10n/messages_zh_HK.properties | 8 - .../src/main/resources/default-velocity.toml | 8 +- proxy/src/main/resources/log4j2.xml | 3 +- .../proxy/command/BrigadierCommandTests.java | 261 +++++++++--------- .../command/CommandGraphInjectorTests.java | 109 ++++---- .../proxy/command/CommandManagerTests.java | 40 +-- .../proxy/command/MockCommandSource.java | 3 + .../proxy/command/RawCommandTests.java | 45 +-- .../proxy/command/SimpleCommandTests.java | 57 ++-- .../command/SuggestionsProviderTests.java | 81 +++--- .../StringArrayArgumentTypeTests.java | 23 +- .../VelocityArgumentCommandNodeTests.java | 29 +- .../proxy/event/EventTaskTest.java | 15 +- .../proxy/event/EventTest.java | 97 +++---- .../proxy/event/RegistrationTest.java | 34 ++- .../proxy/plugin/MockPluginManager.java | 3 + .../proxy/protocol/PacketRegistryTest.java | 2 +- .../proxy/protocol/ProtocolUtilsTest.java | 3 + .../scheduler/VelocitySchedulerTest.java | 13 +- .../proxy/testutil/FakePluginManager.java | 3 + .../proxy/util/concurrent/OnceTest.java | 4 + settings.gradle | 9 - settings.gradle.kts | 9 + 300 files changed, 2880 insertions(+), 2169 deletions(-) delete mode 100644 api/build.gradle create mode 100644 api/build.gradle.kts delete mode 100644 build.gradle create mode 100644 build.gradle.kts create mode 100644 buildSrc/build.gradle.kts create mode 100644 buildSrc/src/main/kotlin/com/velocitypowered/script/SetManifestImplVersionPlugin.kt create mode 100644 buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityCheckstylePlugin.kt create mode 100644 buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityPublishPlugin.kt create mode 100644 gradle.properties delete mode 100644 gradle/checkstyle.gradle delete mode 100644 gradle/publish.gradle delete mode 100644 native/build.gradle create mode 100644 native/build.gradle.kts delete mode 100644 proxy/build.gradle create mode 100644 proxy/build.gradle.kts delete mode 100644 proxy/src/main/java/com/velocitypowered/proxy/connection/registry/ChatData.java rename proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/{GS4QueryHandler.java => GameSpyQueryHandler.java} (97%) rename proxy/src/main/java/com/velocitypowered/proxy/util/{FileSystemUtils.java => ResourceUtils.java} (87%) delete mode 100644 settings.gradle create mode 100644 settings.gradle.kts diff --git a/api/build.gradle b/api/build.gradle deleted file mode 100644 index 028bfe3c9..000000000 --- a/api/build.gradle +++ /dev/null @@ -1,119 +0,0 @@ -plugins { - id 'java-library' - id 'maven-publish' - id 'checkstyle' -} - -apply plugin: 'org.cadixdev.licenser' -apply from: '../gradle/checkstyle.gradle' -apply from: '../gradle/publish.gradle' -apply plugin: 'com.github.johnrengelman.shadow' - -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 -} - -license { - header = project.file('HEADER.txt') -} - -sourceSets { - ap { - compileClasspath += main.compileClasspath + main.output - } -} - -dependencies { - api 'com.google.code.gson:gson:2.9.0' - api "com.google.guava:guava:${guavaVersion}" - - // DEPRECATED: Will be removed in Velocity Polymer - api 'com.moandjiezana.toml:toml4j:0.7.2' - - api(platform("net.kyori:adventure-bom:${adventureVersion}")) - api("net.kyori:adventure-api") - api("net.kyori:adventure-text-serializer-gson") - api("net.kyori:adventure-text-serializer-legacy") - api("net.kyori:adventure-text-serializer-plain") - api("net.kyori:adventure-text-minimessage") - - api "org.slf4j:slf4j-api:${slf4jVersion}" - api 'com.google.inject:guice:5.0.1' - api "org.checkerframework:checker-qual:${checkerFrameworkVersion}" - api 'com.velocitypowered:velocity-brigadier:1.0.0-SNAPSHOT' - - api "org.spongepowered:configurate-hocon:${configurateVersion}" - api "org.spongepowered:configurate-yaml:${configurateVersion}" - api "org.spongepowered:configurate-gson:${configurateVersion}" - - testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}" - testImplementation "org.junit.jupiter:junit-jupiter-engine:${junitVersion}" -} - -task javadocJar(type: Jar) { - classifier 'javadoc' - from javadoc -} - -task sourcesJar(type: Jar) { - classifier 'sources' - from sourceSets.main.allSource - from sourceSets.ap.output -} - -jar { - from sourceSets.ap.output - manifest { - attributes 'Automatic-Module-Name': 'com.velocitypowered.api' - } -} - -shadowJar { - from sourceSets.ap.output -} - -artifacts { - archives javadocJar - archives shadowJar - archives sourcesJar -} - -javadoc { - options.encoding = 'UTF-8' - options.charSet = 'UTF-8' - options.source = '8' - options.links( - 'https://www.slf4j.org/apidocs/', - 'https://guava.dev/releases/25.1-jre/api/docs/', - 'https://google.github.io/guice/api-docs/5.0.1/javadoc/', - 'https://docs.oracle.com/en/java/javase/11/docs/api//', - "https://jd.adventure.kyori.net/api/${adventureVersion}/" - ) - - // Disable the crazy super-strict doclint tool in Java 8 - options.addStringOption('Xdoclint:none', '-quiet') - - // Mark sources as Java 8 source compatible - options.source = '8' - - // Remove 'undefined' from seach paths when generating javadoc for a non-modular project (JDK-8215291) - if (JavaVersion.current() >= JavaVersion.VERSION_1_9 && JavaVersion.current() < JavaVersion.VERSION_12) { - options.addBooleanOption('-no-module-directories', true) - } -} - -test { - useJUnitPlatform() -} - -publishing { - publications { - mavenJava(MavenPublication) { - from components.java - - artifact sourcesJar - artifact javadocJar - } - } -} diff --git a/api/build.gradle.kts b/api/build.gradle.kts new file mode 100644 index 000000000..51f2ce905 --- /dev/null +++ b/api/build.gradle.kts @@ -0,0 +1,80 @@ +plugins { + `java-library` + `maven-publish` +} + +license { + header(project.file("HEADER.txt")) +} + +java { + withJavadocJar() + withSourcesJar() + + sourceSets["main"].java { + srcDir("src/ap/java") + } +} + +val gsonVersion: String by project.extra +val guiceVersion: String by project.extra +val guavaVersion: String by project.extra +val adventureVersion: String by project.extra +val slf4jVersion: String by project.extra +val checkerFrameworkVersion: String by project.extra +val configurateVersion: String by project.extra + +dependencies { + api("com.google.code.gson:gson:$gsonVersion") + api("com.google.guava:guava:$guavaVersion") + + // DEPRECATED: Will be removed in Velocity Polymer + api("com.moandjiezana.toml:toml4j:0.7.2") + + api(platform("net.kyori:adventure-bom:${adventureVersion}")) + api("net.kyori:adventure-api") + api("net.kyori:adventure-text-serializer-gson") + api("net.kyori:adventure-text-serializer-legacy") + api("net.kyori:adventure-text-serializer-plain") + api("net.kyori:adventure-text-minimessage") + + api("org.slf4j:slf4j-api:$slf4jVersion") + api("com.google.inject:guice:$guiceVersion") + api("org.checkerframework:checker-qual:${checkerFrameworkVersion}") + api("com.velocitypowered:velocity-brigadier:1.0.0-SNAPSHOT") + + api("org.spongepowered:configurate-hocon:${configurateVersion}") + api("org.spongepowered:configurate-yaml:${configurateVersion}") + api("org.spongepowered:configurate-gson:${configurateVersion}") +} + +tasks { + jar { + manifest { + attributes["Automatic-Module-Name"] = "com.velocitypowered.api" + } + } + withType { + exclude("com/velocitypowered/api/plugin/ap/**") + + val o = options as StandardJavadocDocletOptions + o.encoding = "UTF-8" + o.source = "8" + + o.links( + "https://www.slf4j.org/apidocs/", + "https://guava.dev/releases/$guavaVersion/api/docs/", + "https://google.github.io/guice/api-docs/$guiceVersion/javadoc/", + "https://docs.oracle.com/en/java/javase/11/docs/api/", + "https://jd.adventure.kyori.net/api/$adventureVersion/" + ) + + // Disable the crazy super-strict doclint tool in Java 8 + o.addStringOption("Xdoclint:none", "-quiet") + + // Remove "undefined" from search paths when generating javadoc for a non-modular project (JDK-8215291) + if (JavaVersion.current() >= JavaVersion.VERSION_1_9 && JavaVersion.current() < JavaVersion.VERSION_12) { + o.addBooleanOption("-no-module-directories", true) + } + } +} diff --git a/api/src/ap/java/com/velocitypowered/api/plugin/ap/PluginAnnotationProcessor.java b/api/src/ap/java/com/velocitypowered/api/plugin/ap/PluginAnnotationProcessor.java index 6bd48f4f0..07e55e100 100644 --- a/api/src/ap/java/com/velocitypowered/api/plugin/ap/PluginAnnotationProcessor.java +++ b/api/src/ap/java/com/velocitypowered/api/plugin/ap/PluginAnnotationProcessor.java @@ -27,6 +27,9 @@ import javax.tools.Diagnostic; import javax.tools.FileObject; import javax.tools.StandardLocation; +/** + * Annotation processor for Velocity. + */ @SupportedAnnotationTypes({"com.velocitypowered.api.plugin.Plugin"}) public class PluginAnnotationProcessor extends AbstractProcessor { diff --git a/api/src/ap/java/com/velocitypowered/api/plugin/ap/SerializedPluginDescription.java b/api/src/ap/java/com/velocitypowered/api/plugin/ap/SerializedPluginDescription.java index e785d9adb..27800b42e 100644 --- a/api/src/ap/java/com/velocitypowered/api/plugin/ap/SerializedPluginDescription.java +++ b/api/src/ap/java/com/velocitypowered/api/plugin/ap/SerializedPluginDescription.java @@ -19,6 +19,9 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Serialized version of {@link com.velocitypowered.api.plugin.PluginDescription}. + */ public final class SerializedPluginDescription { public static final Pattern ID_PATTERN = Pattern.compile("[a-z][a-z0-9-_]{0,63}"); @@ -130,6 +133,9 @@ public final class SerializedPluginDescription { + '}'; } + /** + * Represents a dependency. + */ public static final class Dependency { private final String id; diff --git a/api/src/main/java/com/velocitypowered/api/command/CommandManager.java b/api/src/main/java/com/velocitypowered/api/command/CommandManager.java index 021b6ca1e..7bb71bdbe 100644 --- a/api/src/main/java/com/velocitypowered/api/command/CommandManager.java +++ b/api/src/main/java/com/velocitypowered/api/command/CommandManager.java @@ -84,6 +84,7 @@ public interface CommandManager { /** * Retrieves the {@link CommandMeta} from the specified command alias, if registered. + * * @param alias the command alias to lookup * @return an {@link CommandMeta} of the alias */ diff --git a/api/src/main/java/com/velocitypowered/api/event/command/CommandExecuteEvent.java b/api/src/main/java/com/velocitypowered/api/event/command/CommandExecuteEvent.java index 29afc41ca..3446195be 100644 --- a/api/src/main/java/com/velocitypowered/api/event/command/CommandExecuteEvent.java +++ b/api/src/main/java/com/velocitypowered/api/event/command/CommandExecuteEvent.java @@ -29,6 +29,7 @@ public final class CommandExecuteEvent implements ResultedEvent { /** * Constructs a CommandExecuteEvent. + * * @param commandSource the source executing the command * @param command the command being executed without first slash */ @@ -43,7 +44,8 @@ public final class CommandExecuteEvent implements ResultedEvent { } /** - * Gets the original command being executed without first slash. + * Gets the original command being executed without the first slash. + * * @return the original command being executed */ public String getCommand() { @@ -108,6 +110,7 @@ public final class CommandExecuteEvent implements ResultedEvent { /** * Allows the command to be sent, without modification. + * * @return the allowed result */ public static CommandResult allowed() { @@ -116,6 +119,7 @@ public final class CommandExecuteEvent implements ResultedEvent { /** * Prevents the command from being executed. + * * @return the denied result */ public static CommandResult denied() { @@ -123,7 +127,9 @@ public final class CommandExecuteEvent implements ResultedEvent { } /** - * Prevents the command from being executed, but forward command to server. + * Forwards the command to server instead of executing it on the proxy. This is the + * default behavior when a command is not registered on Velocity. + * * @return the forward result */ public static CommandResult forwardToServer() { @@ -132,6 +138,7 @@ public final class CommandExecuteEvent implements ResultedEvent { /** * Prevents the command from being executed on proxy, but forward command to server. + * * @param newCommand the command without first slash to use instead * @return a result with a new command being forwarded to server */ @@ -141,7 +148,9 @@ public final class CommandExecuteEvent implements ResultedEvent { } /** - * Allows the command to be executed, but silently replaced old command with another. + * Allows the command to be executed, but silently replaces the command with a different + * command. + * * @param newCommand the command to use instead without first slash * @return a result with a new command */ diff --git a/api/src/main/java/com/velocitypowered/api/event/command/PlayerAvailableCommandsEvent.java b/api/src/main/java/com/velocitypowered/api/event/command/PlayerAvailableCommandsEvent.java index 64440f1ee..a2759ed76 100644 --- a/api/src/main/java/com/velocitypowered/api/event/command/PlayerAvailableCommandsEvent.java +++ b/api/src/main/java/com/velocitypowered/api/event/command/PlayerAvailableCommandsEvent.java @@ -29,6 +29,7 @@ public class PlayerAvailableCommandsEvent { /** * Constructs an available commands event. + * * @param player the targeted player * @param rootNode the Brigadier root node */ diff --git a/api/src/main/java/com/velocitypowered/api/event/connection/DisconnectEvent.java b/api/src/main/java/com/velocitypowered/api/event/connection/DisconnectEvent.java index cb89984a2..a1a7d02de 100644 --- a/api/src/main/java/com/velocitypowered/api/event/connection/DisconnectEvent.java +++ b/api/src/main/java/com/velocitypowered/api/event/connection/DisconnectEvent.java @@ -51,6 +51,9 @@ public final class DisconnectEvent { + '}'; } + /** + * The status of the connection when the player disconnected. + */ public enum LoginStatus { SUCCESSFUL_LOGIN, diff --git a/api/src/main/java/com/velocitypowered/api/event/connection/PreLoginEvent.java b/api/src/main/java/com/velocitypowered/api/event/connection/PreLoginEvent.java index 13b48fc65..448528dd0 100644 --- a/api/src/main/java/com/velocitypowered/api/event/connection/PreLoginEvent.java +++ b/api/src/main/java/com/velocitypowered/api/event/connection/PreLoginEvent.java @@ -37,6 +37,7 @@ public final class PreLoginEvent implements ResultedEvent getSuggestions() { diff --git a/api/src/main/java/com/velocitypowered/api/plugin/InvalidPluginException.java b/api/src/main/java/com/velocitypowered/api/plugin/InvalidPluginException.java index 46530ef73..c8a38beeb 100644 --- a/api/src/main/java/com/velocitypowered/api/plugin/InvalidPluginException.java +++ b/api/src/main/java/com/velocitypowered/api/plugin/InvalidPluginException.java @@ -7,6 +7,9 @@ package com.velocitypowered.api.plugin; +/** + * Thrown if a JAR in the plugin directory does not look valid. + */ public class InvalidPluginException extends Exception { public InvalidPluginException() { diff --git a/api/src/main/java/com/velocitypowered/api/plugin/meta/PluginDependency.java b/api/src/main/java/com/velocitypowered/api/plugin/meta/PluginDependency.java index 9d75eaa46..31ef60dd9 100644 --- a/api/src/main/java/com/velocitypowered/api/plugin/meta/PluginDependency.java +++ b/api/src/main/java/com/velocitypowered/api/plugin/meta/PluginDependency.java @@ -27,6 +27,7 @@ public final class PluginDependency { /** * Creates a new instance. + * * @param id the plugin ID * @param version an optional version * @param optional whether or not this dependency is optional diff --git a/api/src/main/java/com/velocitypowered/api/proxy/LoginPhaseConnection.java b/api/src/main/java/com/velocitypowered/api/proxy/LoginPhaseConnection.java index e0fb221e1..cef076898 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/LoginPhaseConnection.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/LoginPhaseConnection.java @@ -12,14 +12,33 @@ import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import org.checkerframework.checker.nullness.qual.Nullable; /** - * Allows the server to communicate with a client logging into the proxy using login plugin - * messages. + * Represents a connextion that is in the login phase. This is most useful in conjunction + * for login plugin messages. */ public interface LoginPhaseConnection extends InboundConnection, KeyIdentifiable { + + /** + * Sends a login plugin message to the client, and provides a consumer to react to the + * response to the client. The login process will not continue until there are no more + * login plugin messages that require responses. + * + * @param identifier the channel identifier to use + * @param contents the message to send + * @param consumer the consumer that will respond to the message + */ void sendLoginPluginMessage(ChannelIdentifier identifier, byte[] contents, MessageConsumer consumer); + /** + * Consumes the message. + */ interface MessageConsumer { + + /** + * Consumes the message and responds to it. + * + * @param responseBody the message from the client, if any + */ void onMessageResponse(byte @Nullable [] responseBody); } } diff --git a/api/src/main/java/com/velocitypowered/api/proxy/Player.java b/api/src/main/java/com/velocitypowered/api/proxy/Player.java index 60c4aace9..916d39281 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/Player.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/Player.java @@ -32,13 +32,17 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEventSource; import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.checker.nullness.qual.Nullable; import org.jetbrains.annotations.NotNull; /** * Represents a player who is connected to the proxy. */ -public interface Player extends CommandSource, Identified, InboundConnection, - ChannelMessageSource, ChannelMessageSink, HoverEventSource, Keyed, KeyIdentifiable { +public interface Player extends + /* Fundamental Velocity interfaces */ + CommandSource, InboundConnection, ChannelMessageSource, ChannelMessageSink, + /* Adventure-specific interfaces */ + Identified, HoverEventSource, Keyed, KeyIdentifiable { /** * Returns the player's current username. @@ -48,8 +52,8 @@ public interface Player extends CommandSource, Identified, InboundConnection, String getUsername(); /** - * Returns the locale the proxy will use to send messages translated via the Adventure global translator. - * By default, the value of {@link PlayerSettings#getLocale()} is used. + * Returns the locale the proxy will use to send messages translated via the Adventure global + * translator. By default, the value of {@link PlayerSettings#getLocale()} is used. * *

This can be {@code null} when the client has not yet connected to any server.

* diff --git a/api/src/main/java/com/velocitypowered/api/proxy/crypto/IdentifiedKey.java b/api/src/main/java/com/velocitypowered/api/proxy/crypto/IdentifiedKey.java index 665853ae3..0fc20a380 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/crypto/IdentifiedKey.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/crypto/IdentifiedKey.java @@ -30,6 +30,7 @@ public interface IdentifiedKey extends KeySigned { /** * Validates a signature against this public key. + * * @param signature the signature data * @param toVerify the signed data * @@ -53,6 +54,9 @@ public interface IdentifiedKey extends KeySigned { */ Revision getKeyRevision(); + /** + * The different versions of player keys, per Minecraft version. + */ enum Revision { GENERIC_V1(ImmutableSet.of(), ImmutableSet.of(ProtocolVersion.MINECRAFT_1_19)), LINKED_V2(ImmutableSet.of(), ImmutableSet.of(ProtocolVersion.MINECRAFT_1_19_1)); diff --git a/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeyIdentifiable.java b/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeyIdentifiable.java index eb0c019f5..bd62be905 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeyIdentifiable.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeyIdentifiable.java @@ -7,15 +7,18 @@ package com.velocitypowered.api.proxy.crypto; +import org.checkerframework.checker.nullness.qual.Nullable; + /** * Identifies a type with a public RSA signature. */ public interface KeyIdentifiable { /** - * Returns the timed identified key of the object context. - *

Only available in 1.19 and newer

+ * Returns the timed identified key of the object context. This is only available if the client + * is running Minecraft 1.19 or newer. + * * @return the key or null if not available */ - IdentifiedKey getIdentifiedKey(); + @Nullable IdentifiedKey getIdentifiedKey(); } diff --git a/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeySigned.java b/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeySigned.java index 4c6c5a30c..aa096acc3 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeySigned.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/crypto/KeySigned.java @@ -12,6 +12,9 @@ import java.security.PublicKey; import java.time.Instant; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents the signature of a signed object. + */ public interface KeySigned { /** diff --git a/api/src/main/java/com/velocitypowered/api/proxy/crypto/SignedMessage.java b/api/src/main/java/com/velocitypowered/api/proxy/crypto/SignedMessage.java index d8e42d7b2..afdaab730 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/crypto/SignedMessage.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/crypto/SignedMessage.java @@ -9,6 +9,9 @@ package com.velocitypowered.api.proxy.crypto; import java.util.UUID; +/** + * A signed message. + */ public interface SignedMessage extends KeySigned { /** diff --git a/api/src/main/java/com/velocitypowered/api/proxy/messages/MinecraftChannelIdentifier.java b/api/src/main/java/com/velocitypowered/api/proxy/messages/MinecraftChannelIdentifier.java index a3ab53324..8d4a500e2 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/messages/MinecraftChannelIdentifier.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/messages/MinecraftChannelIdentifier.java @@ -7,7 +7,8 @@ package com.velocitypowered.api.proxy.messages; -import com.google.common.base.Preconditions; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.common.base.Strings; import java.util.Objects; import java.util.regex.Pattern; @@ -49,13 +50,16 @@ public final class MinecraftChannelIdentifier implements ChannelIdentifier { * @return a new channel identifier */ public static MinecraftChannelIdentifier create(String namespace, String name) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(namespace), "namespace is null or empty"); - Preconditions.checkArgument(name != null, "namespace is null or empty"); - Preconditions.checkArgument(VALID_IDENTIFIER_REGEX.matcher(namespace).matches(), - "namespace is not valid, must match: %s got %s", VALID_IDENTIFIER_REGEX.toString(), namespace); - Preconditions - .checkArgument(VALID_IDENTIFIER_REGEX.matcher(name).matches(), - "name is not valid, must match: %s got %s", VALID_IDENTIFIER_REGEX.toString(), name); + checkArgument(!Strings.isNullOrEmpty(namespace), "namespace is null or empty"); + checkArgument(name != null, "namespace is null or empty"); + checkArgument(VALID_IDENTIFIER_REGEX.matcher(namespace).matches(), + "namespace is not valid, must match: %s got %s", + VALID_IDENTIFIER_REGEX.toString(), + namespace); + checkArgument(VALID_IDENTIFIER_REGEX.matcher(name).matches(), + "name is not valid, must match: %s got %s", + VALID_IDENTIFIER_REGEX.toString(), + name); return new MinecraftChannelIdentifier(namespace, name); } diff --git a/api/src/main/java/com/velocitypowered/api/proxy/player/PlayerSettings.java b/api/src/main/java/com/velocitypowered/api/proxy/player/PlayerSettings.java index 0f70e4aac..9d2638211 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/player/PlayerSettings.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/player/PlayerSettings.java @@ -67,12 +67,18 @@ public interface PlayerSettings { */ boolean isClientListingAllowed(); + /** + * The client's current chat display mode. + */ enum ChatMode { SHOWN, COMMANDS_ONLY, HIDDEN } + /** + * The player's selected dominant hand. + */ enum MainHand { LEFT, RIGHT diff --git a/api/src/main/java/com/velocitypowered/api/proxy/player/ResourcePackInfo.java b/api/src/main/java/com/velocitypowered/api/proxy/player/ResourcePackInfo.java index 4b9700a21..3bd69bf56 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/player/ResourcePackInfo.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/player/ResourcePackInfo.java @@ -10,6 +10,9 @@ package com.velocitypowered.api.proxy.player; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents the information for a resource pack to apply that can be sent to the client. + */ public interface ResourcePackInfo { /** @@ -75,12 +78,12 @@ public interface ResourcePackInfo { ResourcePackInfo.Builder asBuilder(); /** - * Returns a copy of this {@link ResourcePackInfo} instance as a builder with the new URL as the pack URL so that - * it can be modified. + * Returns a copy of this {@link ResourcePackInfo} instance as a builder, using the new URL. + *

* It is not guaranteed that - * {@code resourcePackInfo.asBuilder(resourcePackInfo.getUrl()).build().equals(resourcePackInfo)} is true. - * That is due to the transient {@link ResourcePackInfo#getOrigin()} and - * {@link ResourcePackInfo#getOriginalOrigin()} fields. + * {@code resourcePackInfo.asBuilder(resourcePackInfo.getUrl()).build().equals(resourcePackInfo)} + * is true, because the {@link ResourcePackInfo#getOrigin()} and + * {@link ResourcePackInfo#getOriginalOrigin()} fields are transient. * * @param newUrl The new URL to use in the updated builder. * @@ -88,6 +91,9 @@ public interface ResourcePackInfo { */ ResourcePackInfo.Builder asBuilder(String newUrl); + /** + * Builder for {@link ResourcePackInfo} instances. + */ interface Builder { /** diff --git a/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java b/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java index eb32c846f..a2fc2f8d2 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java @@ -10,6 +10,9 @@ package com.velocitypowered.api.proxy.player; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents what, if any, extended parts of the skin this player has. + */ public final class SkinParts { private final byte bitmask; diff --git a/api/src/main/java/com/velocitypowered/api/proxy/player/TabListEntry.java b/api/src/main/java/com/velocitypowered/api/proxy/player/TabListEntry.java index a3f3bd61a..d343989d3 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/player/TabListEntry.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/player/TabListEntry.java @@ -121,7 +121,7 @@ public interface TabListEntry extends KeyIdentifiable { TabListEntry setGameMode(int gameMode); /** - * Whether or not the entry is listed, when listed they will be visible to other players in the tab list. + * Returns whether or not this player will be visible to other players in the tab list. * * @return Whether this entry is listed; only changeable in 1.19.3 and above */ @@ -193,7 +193,7 @@ public interface TabListEntry extends KeyIdentifiable { /** * Sets the {@link IdentifiedKey} of the {@link TabListEntry}. - *

This is only intended and only works for players currently not connected to this proxy.

+ *

This only works for players currently not connected to this proxy.

*

For any player currently connected to this proxy this will be filled automatically.

*

Will ignore mismatching key revisions data.

* diff --git a/api/src/main/java/com/velocitypowered/api/proxy/server/QueryResponse.java b/api/src/main/java/com/velocitypowered/api/proxy/server/QueryResponse.java index 617356c46..c357d2191 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/server/QueryResponse.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/server/QueryResponse.java @@ -245,6 +245,7 @@ public final class QueryResponse { /** * Sets the hostname for the response. + * * @param hostname the hostname to set * @return this builder, for chaining */ @@ -255,6 +256,7 @@ public final class QueryResponse { /** * Sets the game version for the response. + * * @param gameVersion the game version to set * @return this builder, for chaining */ @@ -265,6 +267,7 @@ public final class QueryResponse { /** * Sets the map that will appear in the response. + * * @param map the map to set * @return this builder, for chaining */ @@ -275,6 +278,7 @@ public final class QueryResponse { /** * Sets the players that are currently claimed to be online. + * * @param currentPlayers a non-negative number representing all players online * @return this builder, for chaining */ @@ -286,6 +290,7 @@ public final class QueryResponse { /** * Sets the maximum number of players this server purportedly can hold. + * * @param maxPlayers a non-negative number representing the maximum number of builders * @return this builder, for chaining */ @@ -297,6 +302,7 @@ public final class QueryResponse { /** * Sets the host where this proxy is running. + * * @param proxyHost the host where the proxy is running * @return this instance, for chaining */ @@ -307,6 +313,7 @@ public final class QueryResponse { /** * Sets the port where this proxy is running. + * * @param proxyPort the port where the proxy is running * @return this instance, for chaining */ @@ -319,6 +326,7 @@ public final class QueryResponse { /** * Adds the specified players to the player list. + * * @param players the players to add * @return this builder, for chaining */ @@ -329,6 +337,7 @@ public final class QueryResponse { /** * Adds the specified players to the player list. + * * @param players the players to add * @return this builder, for chaining */ @@ -339,6 +348,7 @@ public final class QueryResponse { /** * Removes all players from the builder. This does not affect {@link #getCurrentPlayers()}. + * * @return this builder, for chaining */ public Builder clearPlayers() { @@ -348,6 +358,7 @@ public final class QueryResponse { /** * Sets the proxy version. + * * @param proxyVersion the proxy version to set * @return this builder, for chaining */ @@ -358,6 +369,7 @@ public final class QueryResponse { /** * Adds the specified plugins to the plugins list. + * * @param plugins the plugins to add * @return this builder, for chaining */ @@ -368,6 +380,7 @@ public final class QueryResponse { /** * Adds the specified plugins to the plugins list. + * * @param plugins the plugins to add * @return this builder, for chaining */ diff --git a/api/src/main/java/com/velocitypowered/api/proxy/server/ServerPing.java b/api/src/main/java/com/velocitypowered/api/proxy/server/ServerPing.java index cf44632ad..612d6215e 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/server/ServerPing.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/server/ServerPing.java @@ -191,6 +191,7 @@ public final class ServerPing { /** * Uses the modified {@code mods} list in the response. + * * @param mods the mods list to use * @return this build, for chaining */ @@ -240,6 +241,7 @@ public final class ServerPing { /** * Uses the information from this builder to create a new {@link ServerPing} instance. The * builder can be re-used after this event has been called. + * * @return a new {@link ServerPing} instance */ public ServerPing build() { @@ -303,6 +305,12 @@ public final class ServerPing { } } + /** + * Represents the version of the server sent to the client. A protocol version + * that does not match the client's protocol version will show up on the server + * list as an incompatible version, but the client will still permit the user + * to connect to the server anyway. + */ public static final class Version { private final int protocol; @@ -310,6 +318,7 @@ public final class ServerPing { /** * Creates a new instance. + * * @param protocol the protocol version as an integer * @param name a friendly name for the protocol version */ @@ -352,6 +361,10 @@ public final class ServerPing { } } + /** + * Represents what the players the server purports to have online, its maximum capacity, + * and a sample of players on the server. + */ public static final class Players { private final int online; @@ -360,6 +373,7 @@ public final class ServerPing { /** * Creates a new instance. + * * @param online the number of online players * @param max the maximum number of players * @param sample a sample of players on the server @@ -410,6 +424,9 @@ public final class ServerPing { } } + /** + * A player returned in the sample field of the server ping players field. + */ public static final class SamplePlayer { private final String name; diff --git a/api/src/main/java/com/velocitypowered/api/scheduler/TaskStatus.java b/api/src/main/java/com/velocitypowered/api/scheduler/TaskStatus.java index bd10e9b47..fd239adff 100644 --- a/api/src/main/java/com/velocitypowered/api/scheduler/TaskStatus.java +++ b/api/src/main/java/com/velocitypowered/api/scheduler/TaskStatus.java @@ -7,6 +7,9 @@ package com.velocitypowered.api.scheduler; +/** + * Enumerates all possible task statuses. + */ public enum TaskStatus { /** * The task is scheduled and is currently running. diff --git a/api/src/main/java/com/velocitypowered/api/util/GameProfile.java b/api/src/main/java/com/velocitypowered/api/util/GameProfile.java index 0f9f41d19..769e79478 100644 --- a/api/src/main/java/com/velocitypowered/api/util/GameProfile.java +++ b/api/src/main/java/com/velocitypowered/api/util/GameProfile.java @@ -24,6 +24,7 @@ public final class GameProfile { /** * Creates a new Mojang game profile. + * * @param id the UUID for the profile * @param name the profile's username * @param properties properties for the profile @@ -35,6 +36,7 @@ public final class GameProfile { /** * Creates a new Mojang game profile. + * * @param undashedId the undashed, Mojang-style UUID for the profile * @param name the profile's username * @param properties properties for the profile @@ -53,6 +55,7 @@ public final class GameProfile { /** * Returns the undashed, Mojang-style UUID. + * * @return the undashed UUID */ public String getUndashedId() { @@ -61,6 +64,7 @@ public final class GameProfile { /** * Returns the UUID associated with this game profile. + * * @return the UUID */ public UUID getId() { @@ -69,6 +73,7 @@ public final class GameProfile { /** * Returns the username associated with this profile. + * * @return the username */ public String getName() { @@ -77,6 +82,7 @@ public final class GameProfile { /** * Returns an immutable list of profile properties associated with this profile. + * * @return the properties associated with this profile */ public List getProperties() { @@ -183,6 +189,7 @@ public final class GameProfile { /** * Creates a profile property entry. + * * @param name the name of the property * @param value the value of the property * @param signature the Mojang signature for the property diff --git a/api/src/main/java/com/velocitypowered/api/util/ModInfo.java b/api/src/main/java/com/velocitypowered/api/util/ModInfo.java index 8a2dea74e..f30789d8a 100644 --- a/api/src/main/java/com/velocitypowered/api/util/ModInfo.java +++ b/api/src/main/java/com/velocitypowered/api/util/ModInfo.java @@ -13,6 +13,9 @@ import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Objects; +/** + * Represents the information for a Forge mod list. + */ public final class ModInfo { public static final ModInfo DEFAULT = new ModInfo("FML", ImmutableList.of()); @@ -20,6 +23,12 @@ public final class ModInfo { private final String type; private final List modList; + /** + * Constructs a new ModInfo instance. + * + * @param type the Forge server list version to use + * @param modList the mods to present to the client + */ public ModInfo(String type, List modList) { this.type = Preconditions.checkNotNull(type, "type"); this.modList = ImmutableList.copyOf(modList); @@ -58,6 +67,9 @@ public final class ModInfo { return Objects.hash(type, modList); } + /** + * Represents a mod to send to the client. + */ public static final class Mod { @SerializedName("modid") diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 090e1c100..000000000 --- a/build.gradle +++ /dev/null @@ -1,59 +0,0 @@ -plugins { - id 'java' - id 'com.github.johnrengelman.shadow' version '7.1.0' apply false - id 'org.cadixdev.licenser' version '0.6.1' apply false -} - -allprojects { - group 'com.velocitypowered' - version '3.1.2-SNAPSHOT' - - ext { - // dependency versions - adventureVersion = '4.12.0' - junitVersion = '5.9.0' - slf4jVersion = '1.7.30' - log4jVersion = '2.19.0' - nettyVersion = '4.1.86.Final' - guavaVersion = '25.1-jre' - checkerFrameworkVersion = '3.6.1' - configurateVersion = '3.7.3' - - getCurrentShortRevision = { - new ByteArrayOutputStream().withStream { os -> - exec { - executable = "git" - args = ["rev-parse", "HEAD"] - standardOutput = os - } - return os.toString().trim().substring(0, 8) - } - } - } - - java { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 - } - - repositories { - mavenLocal() - mavenCentral() - - // for kyoripowered dependencies - maven { - url 'https://oss.sonatype.org/content/groups/public/' - } - - // Velocity repo - maven { - url "https://nexus.velocitypowered.com/repository/maven-public/" - } - } - - test { - reports { - junitXml.required = true - } - } -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..fe73eb42e --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,47 @@ +import com.velocitypowered.script.VelocityCheckstylePlugin +import com.velocitypowered.script.VelocityPublishPlugin +import org.cadixdev.gradle.licenser.Licenser + +plugins { + `java-library` + id("org.cadixdev.licenser") version "0.6.1" +} + +val junitVersion: String by project.extra + +subprojects { + group = "com.velocitypowered" + version = "3.2.0-SNAPSHOT" + + apply() + apply() + + apply() + apply() + + java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(11)) + } + } + + repositories { + mavenCentral() + // kyoripowered + maven("https://oss.sonatype.org/content/groups/public/") + // velocity + maven("https://nexus.velocitypowered.com/repository/maven-public/") + } + dependencies { + testImplementation("org.junit.jupiter:junit-jupiter:$junitVersion") + } + + tasks { + test { + useJUnitPlatform() + reports { + junitXml.required.set(true) + } + } + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 000000000..e9d1a75ba --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,27 @@ +plugins { + `kotlin-dsl` + checkstyle + id("net.kyori.indra.publishing") version "2.0.6" +} + +repositories { + mavenCentral() + maven("https://plugins.gradle.org/m2") +} + +gradlePlugin { + plugins { + register("set-manifest-impl-version") { + id = "set-manifest-impl-version" + implementationClass = "com.velocitypowered.script.SetManifestImplVersionPlugin" + } + register("velocity-checkstyle") { + id = "velocity-checkstyle" + implementationClass = "com.velocitypowered.script.VelocityCheckstylePlugin" + } + register("velocity-publish") { + id = "velocity-publish" + implementationClass = "com.velocitypowered.script.VelocityPublishPlugin" + } + } +} diff --git a/buildSrc/src/main/kotlin/com/velocitypowered/script/SetManifestImplVersionPlugin.kt b/buildSrc/src/main/kotlin/com/velocitypowered/script/SetManifestImplVersionPlugin.kt new file mode 100644 index 000000000..9c089d1cf --- /dev/null +++ b/buildSrc/src/main/kotlin/com/velocitypowered/script/SetManifestImplVersionPlugin.kt @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2018 Velocity Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.velocitypowered.script + +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.jvm.tasks.Jar +import org.gradle.kotlin.dsl.withType +import java.io.ByteArrayOutputStream + +class SetManifestImplVersionPlugin : Plugin { + override fun apply(target: Project) = target.afterEvaluate { configure() } + private fun Project.configure() { + val currentShortRevision = ByteArrayOutputStream().use { + exec { + executable = "git" + args = listOf("rev-parse", "HEAD") + standardOutput = it + } + it.toString().trim().substring(0, 8) + } + tasks.withType { + manifest { + val buildNumber = System.getenv("BUILD_NUMBER") + var velocityHumanVersion: String + if (project.version.toString().endsWith("-SNAPSHOT")) { + if (buildNumber != null) { + velocityHumanVersion = "${project.version} (git-$currentShortRevision-b$buildNumber)" + } else { + velocityHumanVersion = "${project.version} (git-$currentShortRevision)" + } + } else { + velocityHumanVersion = archiveVersion.get() + } + attributes["Implementation-Version"] = velocityHumanVersion + } + } + } +} diff --git a/buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityCheckstylePlugin.kt b/buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityCheckstylePlugin.kt new file mode 100644 index 000000000..85142e9d0 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityCheckstylePlugin.kt @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2018 Velocity Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.velocitypowered.script + +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.plugins.quality.CheckstyleExtension +import org.gradle.api.plugins.quality.CheckstylePlugin +import org.gradle.kotlin.dsl.apply +import org.gradle.kotlin.dsl.configure + +class VelocityCheckstylePlugin : Plugin { + override fun apply(target: Project) = target.configure() + private fun Project.configure() { + apply() + extensions.configure { + configFile = project.rootProject.file("config/checkstyle/checkstyle.xml") + maxErrors = 0 + maxWarnings = 0 + toolVersion = "10.6.0" + } + } +} diff --git a/buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityPublishPlugin.kt b/buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityPublishPlugin.kt new file mode 100644 index 000000000..33a167694 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/velocitypowered/script/VelocityPublishPlugin.kt @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2018 Velocity Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.velocitypowered.script + +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.repositories.PasswordCredentials +import org.gradle.api.plugins.JavaBasePlugin +import org.gradle.api.plugins.JavaPluginExtension +import org.gradle.api.publish.PublishingExtension +import org.gradle.api.publish.maven.MavenPublication +import org.gradle.api.publish.maven.plugins.MavenPublishPlugin +import org.gradle.kotlin.dsl.apply +import org.gradle.kotlin.dsl.configure +import org.gradle.kotlin.dsl.create +import org.gradle.kotlin.dsl.get +import org.gradle.kotlin.dsl.getByType + +class VelocityPublishPlugin : Plugin { + override fun apply(target: Project) = target.afterEvaluate { + if (target.name != "velocity-proxy") { + configure() + } + } + private fun Project.configure() { + apply() + apply() + extensions.configure { + repositories { + maven { + credentials(PasswordCredentials::class.java) + + name = "paper" + val base = "https://papermc.io/repo/repository/maven-" + val releasesRepoUrl = "$base-releases/" + val snapshotsRepoUrl = "$base-snapshots/" + setUrl(if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl) + } + } + publications { + create("maven") { + from(components["java"]) + pom { + name.set("Velocity") + description.set("The modern, next-generation Minecraft server proxy") + url.set("https://www.velocitypowered.com") + scm { + url.set("https://github.com/PaperMC/Velocity") + connection.set("scm:git:https://github.com/PaperMC/Velocity.git") + developerConnection.set("scm:git:https://github.com/PaperMC/Velocity.git") + } + } + } + } + } + } +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 6be8c6f0a..fd81776dc 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -1,7 +1,7 @@ + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> - - + + + @@ -33,7 +32,7 @@ + default="checkstyle-suppressions.xml" /> @@ -45,7 +44,7 @@ - + @@ -54,9 +53,9 @@ + value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/> + value="Consider using special escape sequence instead of octal value or Unicode escaped value."/> @@ -71,15 +70,15 @@ + value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/> + value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/> @@ -105,13 +104,7 @@ - - - + @@ -120,7 +113,7 @@ + value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/> @@ -142,7 +135,7 @@ @@ -177,79 +170,79 @@ + value="Package name ''{0}'' must match pattern ''{1}''."/> + value="Type name ''{0}'' must match pattern ''{1}''."/> + value="Member name ''{0}'' must match pattern ''{1}''."/> + value="Parameter name ''{0}'' must match pattern ''{1}''."/> + value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/> + value="Catch parameter name ''{0}'' must match pattern ''{1}''."/> + value="Local variable name ''{0}'' must match pattern ''{1}''."/> + value="Pattern variable name ''{0}'' must match pattern ''{1}''."/> + value="Class type name ''{0}'' must match pattern ''{1}''."/> + value="Record component name ''{0}'' must match pattern ''{1}''."/> + value="Record type name ''{0}'' must match pattern ''{1}''."/> + value="Method type name ''{0}'' must match pattern ''{1}''."/> + value="Interface type name ''{0}'' must match pattern ''{1}''."/> + value="GenericWhitespace ''{0}'' is followed by whitespace."/> + value="GenericWhitespace ''{0}'' is preceded with whitespace."/> + value="GenericWhitespace ''{0}'' should followed by whitespace."/> + value="GenericWhitespace ''{0}'' is not preceded with whitespace."/> @@ -261,9 +254,9 @@ - + @@ -278,18 +271,18 @@ @@ -318,15 +311,14 @@ + value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/> - + + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/> @@ -335,7 +327,7 @@ - - + + value="Method name ''{0}'' must match pattern ''{1}''."/> @@ -365,8 +356,21 @@ + default="checkstyle-xpath-suppressions.xml" /> + + + + + + + + + + + + + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 000000000..00ebb2177 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,26 @@ +# API dependencies. +gsonVersion=2.9.0 +junitVersion=5.9.0 +slf4jVersion=1.7.30 +adventureVersion=4.12.0 +guavaVersion=25.1-jre +checkerFrameworkVersion=3.6.1 +configurateVersion=3.7.3 +guiceVersion=5.0.1 + +# Proxy dependencies. +log4jVersion=2.19.0 +nettyVersion=4.1.86.Final +flareVersion=2.0.1 +asyncHttpClientVersion=2.12.3 +bstatsVersion=2.2.1 +caffeineVersion=3.1.1 +lmbdaVersion=2.0.0 +nightConfigVersion=3.6.4 +completableFuturesVersion=0.3.5 +adventureFacetVersion=4.1.2 +fastutilVersion=8.5.8 +disruptorVersion=3.4.4 +jansiVersion=3.21.0 +terminalConsoleAppenderVersion=1.3.0 +joptSimpleVersion=5.0.4 \ No newline at end of file diff --git a/gradle/checkstyle.gradle b/gradle/checkstyle.gradle deleted file mode 100644 index 624ba3c50..000000000 --- a/gradle/checkstyle.gradle +++ /dev/null @@ -1,8 +0,0 @@ -checkstyle { - toolVersion '10.3.1' - configFile new File(project.rootDir, ['config', 'checkstyle', 'checkstyle.xml'].join(File.separator)) - - // The build should immediately fail if we have errors. - maxErrors = 0 - maxWarnings = 0 -} \ No newline at end of file diff --git a/gradle/publish.gradle b/gradle/publish.gradle deleted file mode 100644 index d84bc5ce6..000000000 --- a/gradle/publish.gradle +++ /dev/null @@ -1,13 +0,0 @@ -publishing { - repositories { - maven { - credentials(PasswordCredentials.class) - - name = 'paper' - def base = 'https://papermc.io/repo/repository/maven' - def releasesRepoUrl = "$base-releases/" - def snapshotsRepoUrl = "$base-snapshots/" - url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl - } - } -} diff --git a/native/build.gradle b/native/build.gradle deleted file mode 100644 index b58547459..000000000 --- a/native/build.gradle +++ /dev/null @@ -1,39 +0,0 @@ -plugins { - id 'java-library' - id 'checkstyle' - id 'maven-publish' -} - -apply plugin: 'org.cadixdev.licenser' -apply from: '../gradle/checkstyle.gradle' -apply from: '../gradle/publish.gradle' - -java { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 -} - -license { - header = project.rootProject.file('HEADER.txt') -} - -dependencies { - implementation "com.google.guava:guava:${guavaVersion}" - implementation "io.netty:netty-handler:${nettyVersion}" - implementation "org.checkerframework:checker-qual:${checkerFrameworkVersion}" - - testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}" - testImplementation "org.junit.jupiter:junit-jupiter-engine:${junitVersion}" -} - -test { - useJUnitPlatform() -} - -publishing { - publications { - mavenJava(MavenPublication) { - from components.java - } - } -} \ No newline at end of file diff --git a/native/build.gradle.kts b/native/build.gradle.kts new file mode 100644 index 000000000..ca5ed5e27 --- /dev/null +++ b/native/build.gradle.kts @@ -0,0 +1,18 @@ +plugins { + `java-library` + `maven-publish` +} + +license { + header(project.rootProject.file("HEADER.txt")) +} + +val guavaVersion: String by project.extra +val nettyVersion: String by project.extra +val checkerFrameworkVersion: String by project.extra + +dependencies { + implementation("com.google.guava:guava:${guavaVersion}") + implementation("io.netty:netty-handler:${nettyVersion}") + implementation("org.checkerframework:checker-qual:${checkerFrameworkVersion}") +} \ No newline at end of file diff --git a/native/src/main/java/com/velocitypowered/natives/Native.java b/native/src/main/java/com/velocitypowered/natives/Native.java index f1bf323dd..5acc53fe3 100644 --- a/native/src/main/java/com/velocitypowered/natives/Native.java +++ b/native/src/main/java/com/velocitypowered/natives/Native.java @@ -19,6 +19,9 @@ package com.velocitypowered.natives; import com.velocitypowered.natives.util.BufferPreference; +/** + * Generic interface for any Velocity native. + */ public interface Native { BufferPreference preferredBufferType(); } diff --git a/native/src/main/java/com/velocitypowered/natives/NativeSetupException.java b/native/src/main/java/com/velocitypowered/natives/NativeSetupException.java index 72ce89d02..074bf63a2 100644 --- a/native/src/main/java/com/velocitypowered/natives/NativeSetupException.java +++ b/native/src/main/java/com/velocitypowered/natives/NativeSetupException.java @@ -17,6 +17,9 @@ package com.velocitypowered.natives; +/** + * Thrown when we cannot set up a variant of a native library. + */ public class NativeSetupException extends RuntimeException { public NativeSetupException() { diff --git a/native/src/main/java/com/velocitypowered/natives/compression/CompressorUtils.java b/native/src/main/java/com/velocitypowered/natives/compression/CompressorUtils.java index fdde8d320..7d93c1001 100644 --- a/native/src/main/java/com/velocitypowered/natives/compression/CompressorUtils.java +++ b/native/src/main/java/com/velocitypowered/natives/compression/CompressorUtils.java @@ -28,6 +28,7 @@ class CompressorUtils { /** * Ensures that the buffer does not go over {@code max}. + * * @param buf the buffer for check * @param max the maximum size for the buffer * @throws DataFormatException if the buffer becomes too bug diff --git a/native/src/main/java/com/velocitypowered/natives/compression/JavaVelocityCompressor.java b/native/src/main/java/com/velocitypowered/natives/compression/JavaVelocityCompressor.java index 26c2f4e29..4b63bd93e 100644 --- a/native/src/main/java/com/velocitypowered/natives/compression/JavaVelocityCompressor.java +++ b/native/src/main/java/com/velocitypowered/natives/compression/JavaVelocityCompressor.java @@ -28,6 +28,9 @@ import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; +/** + * Implements deflate compression by wrapping {@link Deflater} and {@link Inflater}. + */ public class JavaVelocityCompressor implements VelocityCompressor { public static final VelocityCompressorFactory FACTORY = JavaVelocityCompressor::new; diff --git a/native/src/main/java/com/velocitypowered/natives/compression/LibdeflateVelocityCompressor.java b/native/src/main/java/com/velocitypowered/natives/compression/LibdeflateVelocityCompressor.java index 2976d627d..8af692ec2 100644 --- a/native/src/main/java/com/velocitypowered/natives/compression/LibdeflateVelocityCompressor.java +++ b/native/src/main/java/com/velocitypowered/natives/compression/LibdeflateVelocityCompressor.java @@ -22,6 +22,9 @@ import com.velocitypowered.natives.util.BufferPreference; import io.netty.buffer.ByteBuf; import java.util.zip.DataFormatException; +/** + * Implements deflate compression using the {@code libdeflate} native C library. + */ public class LibdeflateVelocityCompressor implements VelocityCompressor { public static final VelocityCompressorFactory FACTORY = LibdeflateVelocityCompressor::new; diff --git a/native/src/main/java/com/velocitypowered/natives/compression/VelocityCompressorFactory.java b/native/src/main/java/com/velocitypowered/natives/compression/VelocityCompressorFactory.java index dac8ed4a4..b296a975a 100644 --- a/native/src/main/java/com/velocitypowered/natives/compression/VelocityCompressorFactory.java +++ b/native/src/main/java/com/velocitypowered/natives/compression/VelocityCompressorFactory.java @@ -17,6 +17,9 @@ package com.velocitypowered.natives.compression; +/** + * Factory for {@link VelocityCompressor}. + */ public interface VelocityCompressorFactory { VelocityCompressor create(int level); diff --git a/native/src/main/java/com/velocitypowered/natives/encryption/JavaVelocityCipher.java b/native/src/main/java/com/velocitypowered/natives/encryption/JavaVelocityCipher.java index 220f39d8a..3fb14cb57 100644 --- a/native/src/main/java/com/velocitypowered/natives/encryption/JavaVelocityCipher.java +++ b/native/src/main/java/com/velocitypowered/natives/encryption/JavaVelocityCipher.java @@ -26,6 +26,9 @@ import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; +/** + * Implements AES-CFB8 encryption/decryption using {@link Cipher}. + */ public class JavaVelocityCipher implements VelocityCipher { public static final VelocityCipherFactory FACTORY = new VelocityCipherFactory() { diff --git a/native/src/main/java/com/velocitypowered/natives/encryption/NativeVelocityCipher.java b/native/src/main/java/com/velocitypowered/natives/encryption/NativeVelocityCipher.java index 26319e398..5cb7f02ab 100644 --- a/native/src/main/java/com/velocitypowered/natives/encryption/NativeVelocityCipher.java +++ b/native/src/main/java/com/velocitypowered/natives/encryption/NativeVelocityCipher.java @@ -23,6 +23,9 @@ import io.netty.buffer.ByteBuf; import java.security.GeneralSecurityException; import javax.crypto.SecretKey; +/** + * Implements AES-CFB8 encryption/decryption using a native library. + */ public class NativeVelocityCipher implements VelocityCipher { public static final VelocityCipherFactory FACTORY = new VelocityCipherFactory() { diff --git a/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipher.java b/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipher.java index c62a70b2b..66614ddc0 100644 --- a/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipher.java +++ b/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipher.java @@ -21,6 +21,15 @@ import com.velocitypowered.natives.Disposable; import com.velocitypowered.natives.Native; import io.netty.buffer.ByteBuf; +/** + * Implements an AES-CFB8 cipher that either encrypts or decrypts connection data. + */ public interface VelocityCipher extends Disposable, Native { + + /** + * Encrypts the given {@link ByteBuf} in-place. + * + * @param source the buffer to encrypt + */ void process(ByteBuf source); } diff --git a/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipherFactory.java b/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipherFactory.java index ec6b830ff..dfe4523a5 100644 --- a/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipherFactory.java +++ b/native/src/main/java/com/velocitypowered/natives/encryption/VelocityCipherFactory.java @@ -20,6 +20,9 @@ package com.velocitypowered.natives.encryption; import java.security.GeneralSecurityException; import javax.crypto.SecretKey; +/** + * A factory interface for {@link VelocityCipher}. + */ public interface VelocityCipherFactory { VelocityCipher forEncryption(SecretKey key) throws GeneralSecurityException; diff --git a/native/src/main/java/com/velocitypowered/natives/util/BufferPreference.java b/native/src/main/java/com/velocitypowered/natives/util/BufferPreference.java index c728bfb97..b21aa1373 100644 --- a/native/src/main/java/com/velocitypowered/natives/util/BufferPreference.java +++ b/native/src/main/java/com/velocitypowered/natives/util/BufferPreference.java @@ -17,6 +17,9 @@ package com.velocitypowered.natives.util; +/** + * Emumerates Netty buffer preferences and requirements for use with Netty. + */ public enum BufferPreference { /** * A heap buffer is required. diff --git a/native/src/main/java/com/velocitypowered/natives/util/MoreByteBufUtils.java b/native/src/main/java/com/velocitypowered/natives/util/MoreByteBufUtils.java index 20450221f..cbea295b0 100644 --- a/native/src/main/java/com/velocitypowered/natives/util/MoreByteBufUtils.java +++ b/native/src/main/java/com/velocitypowered/natives/util/MoreByteBufUtils.java @@ -21,6 +21,9 @@ import com.velocitypowered.natives.Native; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; +/** + * Additional utilities for {@link ByteBuf}. + */ public class MoreByteBufUtils { private MoreByteBufUtils() { throw new AssertionError(); diff --git a/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java b/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java index 58175e77f..2e6cec76e 100644 --- a/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java +++ b/native/src/main/java/com/velocitypowered/natives/util/NativeCodeLoader.java @@ -22,6 +22,11 @@ import java.util.function.BooleanSupplier; import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * A loader for native code. + * + * @param the interface of the instance to load + */ public final class NativeCodeLoader implements Supplier { private final Variant selected; diff --git a/native/src/main/java/com/velocitypowered/natives/util/NativeConstraints.java b/native/src/main/java/com/velocitypowered/natives/util/NativeConstraints.java index 68577a7b7..a5e0fa49a 100644 --- a/native/src/main/java/com/velocitypowered/natives/util/NativeConstraints.java +++ b/native/src/main/java/com/velocitypowered/natives/util/NativeConstraints.java @@ -21,6 +21,9 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.util.function.BooleanSupplier; +/** + * Statically-computed constraints for native code. + */ public class NativeConstraints { private static final boolean NATIVES_ENABLED = !Boolean.getBoolean("velocity.natives-disabled"); private static final boolean IS_AMD64; diff --git a/native/src/main/java/com/velocitypowered/natives/util/Natives.java b/native/src/main/java/com/velocitypowered/natives/util/Natives.java index d983bc10a..fac9a06fc 100644 --- a/native/src/main/java/com/velocitypowered/natives/util/Natives.java +++ b/native/src/main/java/com/velocitypowered/natives/util/Natives.java @@ -31,6 +31,9 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +/** + * Enumerates all supported natives for Velocity. + */ public class Natives { private Natives() { diff --git a/proxy/build.gradle b/proxy/build.gradle deleted file mode 100644 index 24e4db589..000000000 --- a/proxy/build.gradle +++ /dev/null @@ -1,162 +0,0 @@ -import com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer - -plugins { - id 'java' - id 'checkstyle' -} - -apply plugin: 'org.cadixdev.licenser' -apply from: '../gradle/checkstyle.gradle' -apply plugin: 'com.github.johnrengelman.shadow' - -license { - header = project.rootProject.file('HEADER.txt') -} - -jar { - manifest { - def buildNumber = System.getenv("BUILD_NUMBER") ?: "unknown" - def version - if (project.version.endsWith("-SNAPSHOT")) { - version = "${project.version} (git-${project.ext.getCurrentShortRevision()}-b${buildNumber})" - } else { - version = "${project.version}" - } - - attributes 'Main-Class': 'com.velocitypowered.proxy.Velocity' - attributes 'Implementation-Title': "Velocity" - attributes 'Implementation-Version': version - attributes 'Implementation-Vendor': "Velocity Contributors" - attributes 'Multi-Release': 'true' - } -} - -shadowJar { - transform(Log4j2PluginsCacheFileTransformer) -} - -tasks.withType(Checkstyle) { - exclude('**/com/velocitypowered/proxy/protocol/packet/*.java') -} - -dependencies { - // Note: we depend on the API twice, first the main sourceset, and then the annotation processor. - implementation project(':velocity-api') - implementation project(':velocity-api').sourceSets.ap.output - implementation project(':velocity-native') - - implementation "io.netty:netty-codec:${nettyVersion}" - implementation "io.netty:netty-codec-haproxy:${nettyVersion}" - implementation "io.netty:netty-codec-http:${nettyVersion}" - implementation "io.netty:netty-handler:${nettyVersion}" - implementation "io.netty:netty-transport-native-epoll:${nettyVersion}" - implementation "io.netty:netty-transport-native-epoll:${nettyVersion}:linux-x86_64" - implementation "io.netty:netty-transport-native-epoll:${nettyVersion}:linux-aarch_64" - - implementation "org.apache.logging.log4j:log4j-api:${log4jVersion}" - implementation "org.apache.logging.log4j:log4j-core:${log4jVersion}" - implementation "org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}" - implementation "org.apache.logging.log4j:log4j-iostreams:${log4jVersion}" - implementation "org.apache.logging.log4j:log4j-jul:${log4jVersion}" - - implementation 'net.sf.jopt-simple:jopt-simple:5.0.4' // command-line options - implementation 'net.minecrell:terminalconsoleappender:1.3.0' - runtimeOnly 'org.jline:jline-terminal-jansi:3.21.0' // Needed for JLine - runtimeOnly 'com.lmax:disruptor:3.4.4' // Async loggers - - implementation 'it.unimi.dsi:fastutil-core:8.5.8' - - implementation(platform("net.kyori:adventure-bom:${adventureVersion}")) - implementation("net.kyori:adventure-nbt") - implementation("net.kyori:adventure-platform-facet:4.1.2") - - implementation 'org.asynchttpclient:async-http-client:2.12.3' - - implementation 'com.spotify:completable-futures:0.3.5' - - implementation 'com.electronwill.night-config:toml:3.6.4' - - implementation 'org.bstats:bstats-base:2.2.1' - implementation 'org.lanternpowered:lmbda:2.0.0' - - implementation 'com.github.ben-manes.caffeine:caffeine:3.1.1' - - implementation 'space.vectrix.flare:flare:2.0.1' - implementation 'space.vectrix.flare:flare-fastutil:2.0.1' - - compileOnly 'com.github.spotbugs:spotbugs-annotations:4.4.0' - - testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}" - testImplementation "org.junit.jupiter:junit-jupiter-engine:${junitVersion}" - testImplementation "org.mockito:mockito-core:3.+" -} - -test { - useJUnitPlatform() -} - -shadowJar { - // Exclude all the collection types we don't intend to use - exclude 'it/unimi/dsi/fastutil/booleans/**' - exclude 'it/unimi/dsi/fastutil/bytes/**' - exclude 'it/unimi/dsi/fastutil/chars/**' - exclude 'it/unimi/dsi/fastutil/doubles/**' - exclude 'it/unimi/dsi/fastutil/floats/**' - exclude 'it/unimi/dsi/fastutil/longs/**' - exclude 'it/unimi/dsi/fastutil/shorts/**' - - // Exclude the fastutil IO utilities - we don't use them. - exclude 'it/unimi/dsi/fastutil/io/**' - - // Exclude most of the int types - Object2IntMap have a values() method that returns an - // IntCollection, and we need Int2ObjectMap - exclude 'it/unimi/dsi/fastutil/ints/*Int2Boolean*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Byte*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Char*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Double*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Float*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Int*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Long*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Short*' - exclude 'it/unimi/dsi/fastutil/ints/*Int2Reference*' - exclude 'it/unimi/dsi/fastutil/ints/IntAVL*' - exclude 'it/unimi/dsi/fastutil/ints/IntArray*' - exclude 'it/unimi/dsi/fastutil/ints/*IntBi*' - exclude 'it/unimi/dsi/fastutil/ints/Int*Pair' - exclude 'it/unimi/dsi/fastutil/ints/IntLinked*' - exclude 'it/unimi/dsi/fastutil/ints/IntList*' - exclude 'it/unimi/dsi/fastutil/ints/IntHeap*' - exclude 'it/unimi/dsi/fastutil/ints/IntOpen*' - exclude 'it/unimi/dsi/fastutil/ints/IntRB*' - exclude 'it/unimi/dsi/fastutil/ints/IntSorted*' - exclude 'it/unimi/dsi/fastutil/ints/*Priority*' - exclude 'it/unimi/dsi/fastutil/ints/*BigList*' - - // Try to exclude everything BUT Object2Int{LinkedOpen,Open,CustomOpen}HashMap - exclude 'it/unimi/dsi/fastutil/objects/*ObjectArray*' - exclude 'it/unimi/dsi/fastutil/objects/*ObjectAVL*' - exclude 'it/unimi/dsi/fastutil/objects/*Object*Big*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Boolean*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Byte*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Char*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Double*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Float*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2IntArray*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2IntAVL*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2IntRB*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Long*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Object*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Reference*' - exclude 'it/unimi/dsi/fastutil/objects/*Object2Short*' - exclude 'it/unimi/dsi/fastutil/objects/*ObjectRB*' - exclude 'it/unimi/dsi/fastutil/objects/*Reference*' - - // Exclude Checker Framework annotations - exclude 'org/checkerframework/checker/**' - - relocate 'org.bstats', 'com.velocitypowered.proxy.bstats' -} - -artifacts { - archives shadowJar -} diff --git a/proxy/build.gradle.kts b/proxy/build.gradle.kts new file mode 100644 index 000000000..d46b9b86d --- /dev/null +++ b/proxy/build.gradle.kts @@ -0,0 +1,159 @@ +import com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer + +plugins { + application + `set-manifest-impl-version` + id("com.github.johnrengelman.shadow") version "7.1.0" +} + +license { + header(project.rootProject.file("HEADER.txt")) +} + +application { + mainClass.set("com.velocitypowered.proxy.Velocity") +} + +tasks { + withType { + exclude("**/com/velocitypowered/proxy/protocol/packet/**") + } + + jar { + manifest { + attributes["Implementation-Title"] = "Velocity" + attributes["Implementation-Vendor"] = "Velocity Contributors" + attributes["Multi-Release"] = "true" + } + } + + shadowJar { + transform(Log4j2PluginsCacheFileTransformer::class.java) + + // Exclude all the collection types we don"t intend to use + exclude("it/unimi/dsi/fastutil/booleans/**") + exclude("it/unimi/dsi/fastutil/bytes/**") + exclude("it/unimi/dsi/fastutil/chars/**") + exclude("it/unimi/dsi/fastutil/doubles/**") + exclude("it/unimi/dsi/fastutil/floats/**") + exclude("it/unimi/dsi/fastutil/longs/**") + exclude("it/unimi/dsi/fastutil/shorts/**") + + // Exclude the fastutil IO utilities - we don"t use them. + exclude("it/unimi/dsi/fastutil/io/**") + + // Exclude most of the int types - Object2IntMap have a values() method that returns an + // IntCollection, and we need Int2ObjectMap + exclude("it/unimi/dsi/fastutil/ints/*Int2Boolean*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Byte*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Char*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Double*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Float*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Int*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Long*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Short*") + exclude("it/unimi/dsi/fastutil/ints/*Int2Reference*") + exclude("it/unimi/dsi/fastutil/ints/IntAVL*") + exclude("it/unimi/dsi/fastutil/ints/IntArray*") + exclude("it/unimi/dsi/fastutil/ints/*IntBi*") + exclude("it/unimi/dsi/fastutil/ints/Int*Pair") + exclude("it/unimi/dsi/fastutil/ints/IntLinked*") + exclude("it/unimi/dsi/fastutil/ints/IntList*") + exclude("it/unimi/dsi/fastutil/ints/IntHeap*") + exclude("it/unimi/dsi/fastutil/ints/IntOpen*") + exclude("it/unimi/dsi/fastutil/ints/IntRB*") + exclude("it/unimi/dsi/fastutil/ints/IntSorted*") + exclude("it/unimi/dsi/fastutil/ints/*Priority*") + exclude("it/unimi/dsi/fastutil/ints/*BigList*") + + // Try to exclude everything BUT Object2Int{LinkedOpen,Open,CustomOpen}HashMap + exclude("it/unimi/dsi/fastutil/objects/*ObjectArray*") + exclude("it/unimi/dsi/fastutil/objects/*ObjectAVL*") + exclude("it/unimi/dsi/fastutil/objects/*Object*Big*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Boolean*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Byte*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Char*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Double*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Float*") + exclude("it/unimi/dsi/fastutil/objects/*Object2IntArray*") + exclude("it/unimi/dsi/fastutil/objects/*Object2IntAVL*") + exclude("it/unimi/dsi/fastutil/objects/*Object2IntRB*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Long*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Object*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Reference*") + exclude("it/unimi/dsi/fastutil/objects/*Object2Short*") + exclude("it/unimi/dsi/fastutil/objects/*ObjectRB*") + exclude("it/unimi/dsi/fastutil/objects/*Reference*") + + // Exclude Checker Framework annotations + exclude("org/checkerframework/checker/**") + + relocate("org.bstats", "com.velocitypowered.proxy.bstats") + } +} + +val adventureVersion: String by project.extra +val adventureFacetVersion: String by project.extra +val asyncHttpClientVersion: String by project.extra +val bstatsVersion: String by project.extra +val caffeineVersion: String by project.extra +val completableFuturesVersion: String by project.extra +val disruptorVersion: String by project.extra +val fastutilVersion: String by project.extra +val flareVersion: String by project.extra +val jansiVersion: String by project.extra +val joptSimpleVersion: String by project.extra +val lmbdaVersion: String by project.extra +val log4jVersion: String by project.extra +val nettyVersion: String by project.extra +val nightConfigVersion: String by project.extra +val semver4jVersion: String by project.extra +val terminalConsoleAppenderVersion: String by project.extra + +dependencies { + implementation(project(":velocity-api")) + implementation(project(":velocity-native")) + + implementation("io.netty:netty-codec:${nettyVersion}") + implementation("io.netty:netty-codec-haproxy:${nettyVersion}") + implementation("io.netty:netty-codec-http:${nettyVersion}") + implementation("io.netty:netty-handler:${nettyVersion}") + implementation("io.netty:netty-transport-native-epoll:${nettyVersion}") + implementation("io.netty:netty-transport-native-epoll:${nettyVersion}:linux-x86_64") + implementation("io.netty:netty-transport-native-epoll:${nettyVersion}:linux-aarch_64") + + implementation("org.apache.logging.log4j:log4j-api:${log4jVersion}") + implementation("org.apache.logging.log4j:log4j-core:${log4jVersion}") + implementation("org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}") + implementation("org.apache.logging.log4j:log4j-iostreams:${log4jVersion}") + implementation("org.apache.logging.log4j:log4j-jul:${log4jVersion}") + + implementation("net.sf.jopt-simple:jopt-simple:$joptSimpleVersion") // command-line options + implementation("net.minecrell:terminalconsoleappender:$terminalConsoleAppenderVersion") + runtimeOnly("org.jline:jline-terminal-jansi:$jansiVersion") // Needed for JLine + runtimeOnly("com.lmax:disruptor:$disruptorVersion") // Async loggers + + implementation("it.unimi.dsi:fastutil-core:$fastutilVersion") + + implementation(platform("net.kyori:adventure-bom:$adventureVersion")) + implementation("net.kyori:adventure-nbt") + implementation("net.kyori:adventure-platform-facet:$adventureFacetVersion") + + implementation("org.asynchttpclient:async-http-client:$asyncHttpClientVersion") + + implementation("com.spotify:completable-futures:$completableFuturesVersion") + + implementation("com.electronwill.night-config:toml:$nightConfigVersion") + + implementation("org.bstats:bstats-base:$bstatsVersion") + implementation("org.lanternpowered:lmbda:$lmbdaVersion") + + implementation("com.github.ben-manes.caffeine:caffeine:$caffeineVersion") + + implementation("space.vectrix.flare:flare:$flareVersion") + implementation("space.vectrix.flare:flare-fastutil:$flareVersion") + + compileOnly("com.github.spotbugs:spotbugs-annotations:4.4.0") + + testImplementation("org.mockito:mockito-core:3.+") +} diff --git a/proxy/src/main/java/com/velocitypowered/proxy/Metrics.java b/proxy/src/main/java/com/velocitypowered/proxy/Metrics.java index 97da171b4..ab6fd25da 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/Metrics.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/Metrics.java @@ -35,6 +35,9 @@ import org.bstats.charts.SingleLineChart; import org.bstats.config.MetricsConfig; import org.bstats.json.JsonObjectBuilder; +/** + * Initializes bStats. + */ public class Metrics { private MetricsBase metricsBase; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/ProxyOptions.java b/proxy/src/main/java/com/velocitypowered/proxy/ProxyOptions.java index c80b471a5..e409e01a9 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/ProxyOptions.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/ProxyOptions.java @@ -26,7 +26,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Holds parsed command line options. + */ public final class ProxyOptions { + private static final Logger logger = LogManager.getLogger(ProxyOptions.class); private final boolean help; private final @Nullable Integer port; @@ -37,7 +41,7 @@ public final class ProxyOptions { final OptionSpec help = parser.acceptsAll(Arrays.asList("h", "help"), "Print help") .forHelp(); final OptionSpec port = parser.acceptsAll(Arrays.asList("p", "port"), - "Specify the bind port to be used. The configuration bind port will be ignored.") + "Specify the bind port to be used. The configuration bind port will be ignored.") .withRequiredArg().ofType(Integer.class); final OptionSet set = parser.parse(args); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java b/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java index 25b3a7c47..9486a839a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/Velocity.java @@ -23,6 +23,10 @@ import java.text.DecimalFormat; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * The main class. Responsible for parsing command line arguments and then launching the + * proxy. + */ public class Velocity { private static final Logger logger; @@ -50,6 +54,7 @@ public class Velocity { /** * Main method that the JVM will call when {@code java -jar velocity.jar} is executed. + * * @param args the arguments to the proxy */ public static void main(String... args) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java b/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java index ac99d7cd1..e3b077d07 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java @@ -57,7 +57,7 @@ import com.velocitypowered.proxy.scheduler.VelocityScheduler; import com.velocitypowered.proxy.server.ServerMap; import com.velocitypowered.proxy.util.AddressUtil; import com.velocitypowered.proxy.util.ClosestLocaleMatcher; -import com.velocitypowered.proxy.util.FileSystemUtils; +import com.velocitypowered.proxy.util.ResourceUtils; import com.velocitypowered.proxy.util.VelocityChannelRegistrar; import com.velocitypowered.proxy.util.bossbar.AdventureBossBarManager; import com.velocitypowered.proxy.util.ratelimit.Ratelimiter; @@ -105,6 +105,9 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Implementation of {@link ProxyServer}. + */ public class VelocityServer implements ProxyServer, ForwardingAudience { private static final Logger logger = LogManager.getLogger(VelocityServer.class); @@ -250,7 +253,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { .create(Key.key("velocity", "translations")); translationRegistry.defaultLocale(Locale.US); try { - FileSystemUtils.visitResources(VelocityServer.class, path -> { + ResourceUtils.visitResources(VelocityServer.class, path -> { logger.info("Loading localizations..."); final Path langPath = Path.of("lang"); @@ -275,7 +278,6 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { }); } - Files.walk(langPath).forEach(file -> { if (!Files.isRegularFile(file)) { return; @@ -468,10 +470,10 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { } /** - * Shuts down the proxy, kicking players with the specified {@param reason}. + * Shuts down the proxy, kicking players with the specified reason. * * @param explicitExit whether the user explicitly shut down the proxy - * @param reason message to kick online players with + * @param reason message to kick online players with */ public void shutdown(boolean explicitExit, Component reason) { if (eventManager == null || pluginManager == null || cm == null || scheduler == null) { @@ -502,8 +504,8 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { // makes sure that all the disconnect events are being fired CompletableFuture playersTeardownFuture = CompletableFuture.allOf(players.stream() - .map(ConnectedPlayer::getTeardownFuture) - .toArray((IntFunction[]>) CompletableFuture[]::new)); + .map(ConnectedPlayer::getTeardownFuture) + .toArray((IntFunction[]>) CompletableFuture[]::new)); playersTeardownFuture.get(10, TimeUnit.SECONDS); } catch (TimeoutException e) { @@ -580,6 +582,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { /** * Checks if the {@code connection} can be registered with the proxy. + * * @param connection the connection to check * @return {@code true} if we can register the connection, {@code false} if not */ @@ -591,9 +594,10 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { return !(connectionsByName.containsKey(lowerName) || connectionsByUuid.containsKey(connection.getUniqueId())); } - + /** * Attempts to register the {@code connection} with the proxy. + * * @param connection the connection to register * @return {@code true} if we registered the connection, {@code false} if not */ @@ -650,7 +654,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { return getAllPlayers().stream().filter(p -> p.getUsername() .regionMatches(true, 0, partialName, 0, partialName.length())) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } @Override @@ -659,7 +663,7 @@ public class VelocityServer implements ProxyServer, ForwardingAudience { return getAllServers().stream().filter(s -> s.getServerInfo().getName() .regionMatches(true, 0, partialName, 0, partialName.length())) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/CommandGraphInjector.java b/proxy/src/main/java/com/velocitypowered/proxy/command/CommandGraphInjector.java index 0d692891a..d6bdce149 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/CommandGraphInjector.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/CommandGraphInjector.java @@ -32,9 +32,8 @@ import org.checkerframework.checker.lock.qual.GuardedBy; import org.checkerframework.checker.nullness.qual.Nullable; /** - * Copies the nodes of a {@link RootCommandNode} to a possibly non-empty - * destination {@link RootCommandNode}, respecting the requirements satisfied - * by a given command source. + * Copies the nodes of a {@link RootCommandNode} to a possibly non-empty destination + * {@link RootCommandNode}, respecting the requirements satisfied by a given command source. * * @param the type of the source to inject the nodes for */ @@ -55,13 +54,13 @@ public final class CommandGraphInjector { // the root node we are copying nodes from to the destination node. /** - * Adds the node from the root node of this injector to the given root node, - * respecting the requirements satisfied by the given source. + * Adds the node from the root node of this injector to the given root node, respecting the + * requirements satisfied by the given source. * *

Prior to adding a literal with the same name as one previously contained * in the destination node, the old node is removed from the destination node. * - * @param dest the root node to add the permissible nodes to + * @param dest the root node to add the permissible nodes to * @param source the command source to inject the nodes for */ public void inject(final RootCommandNode dest, final S source) { @@ -69,7 +68,7 @@ public final class CommandGraphInjector { try { final RootCommandNode origin = this.dispatcher.getRoot(); final CommandContextBuilder rootContext = - new CommandContextBuilder<>(this.dispatcher, source, origin, 0); + new CommandContextBuilder<>(this.dispatcher, source, origin, 0); // Filter alias nodes for (final CommandNode node : origin.getChildren()) { @@ -78,7 +77,7 @@ public final class CommandGraphInjector { } final CommandContextBuilder context = rootContext.copy() - .withNode(node, ALIAS_RANGE); + .withNode(node, ALIAS_RANGE); if (!node.canUse(context, ALIAS_READER)) { continue; } @@ -86,7 +85,7 @@ public final class CommandGraphInjector { final LiteralCommandNode asLiteral = (LiteralCommandNode) node; final LiteralCommandNode copy = asLiteral.createBuilder().build(); final VelocityArgumentCommandNode argsNode = - VelocityCommands.getArgumentsNode(asLiteral); + VelocityCommands.getArgumentsNode(asLiteral); if (argsNode == null) { // This literal is associated to a BrigadierCommand, filter normally. this.copyChildren(node, copy, source); @@ -126,7 +125,7 @@ public final class CommandGraphInjector { } private void copyChildren(final CommandNode parent, final CommandNode dest, - final S source) { + final S source) { for (final CommandNode child : parent.getChildren()) { final CommandNode filtered = this.filterNode(child, source); if (filtered != null) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java b/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java index 0639e7cb0..9db3cfe03 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java @@ -50,8 +50,8 @@ import org.checkerframework.checker.lock.qual.GuardedBy; * Provides suggestions for a given command input. * *

Similar to {@link CommandDispatcher#getCompletionSuggestions(ParseResults)}, except it - * avoids fully parsing the given input and performs exactly one requirement predicate check - * per considered node. + * avoids fully parsing the given input and performs exactly one requirement predicate check per + * considered node. * * @param the type of the command source */ @@ -74,31 +74,31 @@ final class SuggestionsProvider { /** * Provides suggestions for the given input and source. * - * @param input the partial input + * @param input the partial input * @param source the command source invoking the command * @return a future that completes with the suggestions */ public CompletableFuture provideSuggestions(final String input, final S source) { final CommandContextBuilder context = new CommandContextBuilder<>( - this.dispatcher, source, this.dispatcher.getRoot(), 0); + this.dispatcher, source, this.dispatcher.getRoot(), 0); return this.provideSuggestions(new StringReader(input), context); } /** * Provides suggestions for the given input and context. * - * @param reader the input reader + * @param reader the input reader * @param context an empty context * @return a future that completes with the suggestions */ private CompletableFuture provideSuggestions( - final StringReader reader, final CommandContextBuilder context) { + final StringReader reader, final CommandContextBuilder context) { lock.lock(); try { final StringRange aliasRange = this.consumeAlias(reader); final String alias = aliasRange.get(reader).toLowerCase(Locale.ENGLISH); final LiteralCommandNode literal = - (LiteralCommandNode) context.getRootNode().getChild(alias); + (LiteralCommandNode) context.getRootNode().getChild(alias); final boolean hasArguments = reader.canRead(); if (hasArguments) { @@ -119,9 +119,9 @@ final class SuggestionsProvider { private StringRange consumeAlias(final StringReader reader) { final int firstSep = reader.getString().indexOf( - CommandDispatcher.ARGUMENT_SEPARATOR_CHAR, reader.getCursor()); + CommandDispatcher.ARGUMENT_SEPARATOR_CHAR, reader.getCursor()); final StringRange range = StringRange.between( - reader.getCursor(), firstSep == -1 ? reader.getTotalLength() : firstSep); + reader.getCursor(), firstSep == -1 ? reader.getTotalLength() : firstSep); reader.setCursor(range.getEnd()); return range; } @@ -130,7 +130,7 @@ final class SuggestionsProvider { * Returns whether a literal node with the given lowercase name should be considered for * suggestions given the specified input. * - * @param name the lowercase literal name + * @param name the lowercase literal name * @param input the partial input * @return true if the literal should be considered; false otherwise */ @@ -141,12 +141,12 @@ final class SuggestionsProvider { /** * Returns alias suggestions for the given input. * - * @param reader the input reader + * @param reader the input reader * @param contextSoFar an empty context * @return a future that completes with the suggestions */ private CompletableFuture provideAliasSuggestions( - final StringReader reader, final CommandContextBuilder contextSoFar) { + final StringReader reader, final CommandContextBuilder contextSoFar) { final S source = contextSoFar.getSource(); // Lowercase the alias here so all comparisons can be case-sensitive (cheaper) // TODO Is this actually faster? It may incur an allocation @@ -166,7 +166,7 @@ final class SuggestionsProvider { if (shouldConsider(alias, input) && node.canUse(source)) { final CommandContextBuilder context = contextSoFar.copy() - .withNode(node, ALIAS_SUGGESTION_RANGE); + .withNode(node, ALIAS_SUGGESTION_RANGE); if (node.canUse(context, reader)) { // LiteralCommandNode#listSuggestions is case insensitive final SuggestionsBuilder builder = new SuggestionsBuilder(input, 0); @@ -179,19 +179,19 @@ final class SuggestionsProvider { } /** - * Merges the suggestions provided by the {@link Command} associated to the given - * alias node and the hints given during registration for the given input. + * Merges the suggestions provided by the {@link Command} associated to the given alias node and + * the hints given during registration for the given input. * *

The context is not mutated by this method. The reader's cursor may be modified. * - * @param alias the alias node - * @param reader the input reader + * @param alias the alias node + * @param reader the input reader * @param contextSoFar the context, containing {@code alias} * @return a future that completes with the suggestions */ private CompletableFuture provideArgumentsSuggestions( - final LiteralCommandNode alias, final StringReader reader, - final CommandContextBuilder contextSoFar) { + final LiteralCommandNode alias, final StringReader reader, + final CommandContextBuilder contextSoFar) { final S source = contextSoFar.getSource(); final String fullInput = reader.getString(); final VelocityArgumentCommandNode argsNode = VelocityCommands.getArgumentsNode(alias); @@ -227,7 +227,7 @@ final class SuggestionsProvider { // Ask the command for suggestions via the arguments node reader.setCursor(start); final CompletableFuture cmdSuggestions = - this.getArgumentsNodeSuggestions(argsNode, reader, context); + this.getArgumentsNodeSuggestions(argsNode, reader, context); final boolean hasHints = alias.getChildren().size() > 1; if (!hasHints) { return this.merge(fullInput, cmdSuggestions); @@ -236,24 +236,24 @@ final class SuggestionsProvider { // Parse the hint nodes to get remaining suggestions reader.setCursor(start); final CompletableFuture hintSuggestions = - this.getHintSuggestions(alias, reader, contextSoFar); + this.getHintSuggestions(alias, reader, contextSoFar); return this.merge(fullInput, cmdSuggestions, hintSuggestions); } /** - * Returns the suggestions provided by the {@link Command} associated to - * the specified arguments node for the given input. + * Returns the suggestions provided by the {@link Command} associated to the specified arguments + * node for the given input. * *

The reader and context are not mutated by this method. * - * @param node the arguments node of the command - * @param reader the input reader + * @param node the arguments node of the command + * @param reader the input reader * @param context the context, containing an alias node and {@code node} * @return a future that completes with the suggestions */ private CompletableFuture getArgumentsNodeSuggestions( - final VelocityArgumentCommandNode node, final StringReader reader, - final CommandContextBuilder context) { + final VelocityArgumentCommandNode node, final StringReader reader, + final CommandContextBuilder context) { final int start = reader.getCursor(); final String fullInput = reader.getString(); final CommandContext built = context.build(fullInput); @@ -271,14 +271,14 @@ final class SuggestionsProvider { * *

The reader and context are not mutated by this method. * - * @param alias the alias node - * @param reader the input reader + * @param alias the alias node + * @param reader the input reader * @param context the context, containing {@code alias} * @return a future that completes with the suggestions */ private CompletableFuture getHintSuggestions( - final LiteralCommandNode alias, final StringReader reader, - final CommandContextBuilder context) { + final LiteralCommandNode alias, final StringReader reader, + final CommandContextBuilder context) { final ParseResults parse = this.parseHints(alias, reader, context); try { return this.dispatcher.getCompletionSuggestions(parse); @@ -290,20 +290,20 @@ final class SuggestionsProvider { } /** - * Parses the hint nodes under the given node, which is either an alias node of - * a {@link Command} or another hint node. + * Parses the hint nodes under the given node, which is either an alias node of a {@link Command} + * or another hint node. * *

The reader and context are not mutated by this method. * - * @param node the node to parse + * @param node the node to parse * @param originalReader the input reader - * @param contextSoFar the context, containing the alias node of the command + * @param contextSoFar the context, containing the alias node of the command * @return the parse results containing the parsed hint nodes * @see VelocityCommandMeta#copyHints(CommandMeta) for the conditions under which the returned * hints can be suggested to a {@link CommandSource}. */ private ParseResults parseHints(final CommandNode node, final StringReader originalReader, - final CommandContextBuilder contextSoFar) { + final CommandContextBuilder contextSoFar) { // This is a stripped-down version of CommandDispatcher#parseNodes that doesn't // check the requirements are satisfied and ignores redirects, neither of which // are used by hint nodes. Parsing errors are ignored. @@ -350,17 +350,16 @@ final class SuggestionsProvider { } /** - * Returns a future that is completed with the result of merging the {@link Suggestions} - * the given futures complete with. The results of the futures that complete exceptionally - * are ignored. + * Returns a future that is completed with the result of merging the {@link Suggestions} the given + * futures complete with. The results of the futures that complete exceptionally are ignored. * * @param fullInput the command input - * @param futures the futures that complete with the suggestions + * @param futures the futures that complete with the suggestions * @return the future that completes with the merged suggestions */ @SafeVarargs private CompletableFuture merge( - final String fullInput, final CompletableFuture... futures) { + final String fullInput, final CompletableFuture... futures) { // https://github.com/Mojang/brigadier/pull/81 return CompletableFuture.allOf(futures).handle((unused, throwable) -> { final List suggestions = new ArrayList<>(futures.length); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java index 7baa22fe7..f3b463e2d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java @@ -54,6 +54,9 @@ import org.checkerframework.checker.lock.qual.GuardedBy; import org.checkerframework.checker.nullness.qual.Nullable; import org.jetbrains.annotations.VisibleForTesting; +/** + * Impelements Velocity's command handler. + */ public class VelocityCommandManager implements CommandManager { private final @GuardedBy("lock") CommandDispatcher dispatcher; @@ -76,9 +79,9 @@ public class VelocityCommandManager implements CommandManager { this.eventManager = Preconditions.checkNotNull(eventManager); final RootCommandNode root = this.dispatcher.getRoot(); this.registrars = ImmutableList.of( - new BrigadierCommandRegistrar(root, this.lock.writeLock()), - new SimpleCommandRegistrar(root, this.lock.writeLock()), - new RawCommandRegistrar(root, this.lock.writeLock())); + new BrigadierCommandRegistrar(root, this.lock.writeLock()), + new SimpleCommandRegistrar(root, this.lock.writeLock()), + new RawCommandRegistrar(root, this.lock.writeLock())); this.suggestionsProvider = new SuggestionsProvider<>(this.dispatcher, this.lock.readLock()); this.injector = new CommandGraphInjector<>(this.dispatcher, this.lock.readLock()); this.commandMetas = new ConcurrentHashMap<>(); @@ -118,24 +121,24 @@ public class VelocityCommandManager implements CommandManager { } } throw new IllegalArgumentException( - command + " does not implement a registrable Command subinterface"); + command + " does not implement a registrable Command subinterface"); } /** * Attempts to register the given command if it implements the - * {@linkplain CommandRegistrar#registrableSuperInterface() registrable superinterface} - * of the given registrar. + * {@linkplain CommandRegistrar#registrableSuperInterface() registrable superinterface} of the + * given registrar. * * @param registrar the registrar to register the command - * @param command the command to register - * @param meta the command metadata - * @param the type of the command - * @return true if the command implements the registrable superinterface of the registrar; - * false otherwise. + * @param command the command to register + * @param meta the command metadata + * @param the type of the command + * @return true if the command implements the registrable superinterface of the registrar; false + * otherwise. * @throws IllegalArgumentException if the registrar cannot register the command */ private boolean tryRegister(final CommandRegistrar registrar, - final Command command, final CommandMeta meta) { + final Command command, final CommandMeta meta) { final Class superInterface = registrar.registrableSuperInterface(); if (!superInterface.isInstance(command)) { return false; @@ -188,7 +191,7 @@ public class VelocityCommandManager implements CommandManager { /** * Fires a {@link CommandExecuteEvent}. * - * @param source the source to execute the command for + * @param source the source to execute the command for * @param cmdLine the command to execute * @return the {@link CompletableFuture} of the event */ @@ -251,10 +254,9 @@ public class VelocityCommandManager implements CommandManager { /** * Returns suggestions to fill in the given command. * - * @param source the source to execute the command for + * @param source the source to execute the command for * @param cmdLine the partially completed command - * @return a {@link CompletableFuture} eventually completed with a {@link List}, - * possibly empty + * @return a {@link CompletableFuture} eventually completed with a {@link List}, possibly empty */ public CompletableFuture> offerSuggestions(final CommandSource source, final String cmdLine) { @@ -265,10 +267,10 @@ public class VelocityCommandManager implements CommandManager { /** * Returns suggestions to fill in the given command. * - * @param source the source to execute the command for + * @param source the source to execute the command for * @param cmdLine the partially completed command - * @return a {@link CompletableFuture} eventually completed with {@link Suggestions}, - * possibly empty + * @return a {@link CompletableFuture} eventually completed with {@link Suggestions}, possibly + * empty */ public CompletableFuture offerBrigadierSuggestions( final CommandSource source, final String cmdLine) { @@ -281,14 +283,15 @@ public class VelocityCommandManager implements CommandManager { } catch (final Throwable e) { // Again, plugins are naughty return CompletableFuture.failedFuture( - new RuntimeException("Unable to provide suggestions for " + cmdLine + " for " + source, e)); + new RuntimeException("Unable to provide suggestions for " + cmdLine + " for " + source, + e)); } } /** * Parses the given command input. * - * @param input the normalized command input, without the leading slash ('/') + * @param input the normalized command input, without the leading slash ('/') * @param source the command source to parse the command for * @return the parse results */ @@ -307,8 +310,8 @@ public class VelocityCommandManager implements CommandManager { try { // A RootCommandNode may only contain LiteralCommandNode children instances return dispatcher.getRoot().getChildren().stream() - .map(CommandNode::getName) - .collect(ImmutableList.toImmutableList()); + .map(CommandNode::getName) + .collect(ImmutableList.toImmutableList()); } finally { lock.readLock().unlock(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandMeta.java b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandMeta.java index b9cb4ee14..4b4efe6d1 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandMeta.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandMeta.java @@ -33,6 +33,9 @@ import java.util.stream.Stream; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Handles building commands for plugins to register. + */ public final class VelocityCommandMeta implements CommandMeta { static final class Builder implements CommandMeta.Builder { @@ -44,7 +47,7 @@ public final class VelocityCommandMeta implements CommandMeta { public Builder(final String alias) { Preconditions.checkNotNull(alias, "alias"); this.aliases = ImmutableSet.builder() - .add(alias.toLowerCase(Locale.ENGLISH)); + .add(alias.toLowerCase(Locale.ENGLISH)); this.hints = ImmutableList.builder(); this.plugin = null; } @@ -87,12 +90,12 @@ public final class VelocityCommandMeta implements CommandMeta { } /** - * Creates a node to use for hinting the arguments of a {@link Command}. Hint nodes are - * sent to 1.13+ clients and the proxy uses them for providing suggestions. + * Creates a node to use for hinting the arguments of a {@link Command}. Hint nodes are sent to + * 1.13+ clients and the proxy uses them for providing suggestions. * *

A hint node is used to provide suggestions if and only if the requirements of - * the corresponding {@link CommandNode} are satisfied. The requirement predicate - * of the returned node always returns {@code false}. + * the corresponding {@link CommandNode} are satisfied. The requirement predicate of the returned + * node always returns {@code false}. * * @param hint the node containing hinting metadata * @return the hinting command node @@ -101,8 +104,8 @@ public final class VelocityCommandMeta implements CommandMeta { // We need to perform a deep copy of the hint to prevent the user // from modifying the nodes and adding a Command or a redirect. final ArgumentBuilder builder = hint.createBuilder() - // Requirement checking is performed by SuggestionProvider - .requires(source -> false); + // Requirement checking is performed by SuggestionProvider + .requires(source -> false); for (final CommandNode child : hint.getChildren()) { builder.then(copyForHinting(child)); } @@ -125,9 +128,9 @@ public final class VelocityCommandMeta implements CommandMeta { private final Object plugin; private VelocityCommandMeta( - final Set aliases, - final List> hints, - final @Nullable Object plugin + final Set aliases, + final List> hints, + final @Nullable Object plugin ) { this.aliases = aliases; this.hints = hints; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java index 262812f22..70c668c1f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java @@ -38,10 +38,9 @@ import java.util.Map; import org.checkerframework.checker.nullness.qual.Nullable; /** - * Provides utility methods common to most {@link Command} implementations. - * In particular, {@link InvocableCommand} implementations use the same logic for - * creating and parsing the alias and arguments command nodes, which is contained - * in this class. + * Provides utility methods common to most {@link Command} implementations. In particular, + * {@link InvocableCommand} implementations use the same logic for creating and parsing the alias + * and arguments command nodes, which is contained in this class. */ public final class VelocityCommands { @@ -51,7 +50,7 @@ public final class VelocityCommands { * Normalizes the given command input. * * @param input the raw command input, without the leading slash ('/') - * @param trim whether to remove leading and trailing whitespace from the input + * @param trim whether to remove leading and trailing whitespace from the input * @return the normalized command input */ static String normalizeInput(final String input, final boolean trim) { @@ -60,7 +59,7 @@ public final class VelocityCommands { if (firstSep != -1) { // Aliases are case-insensitive, arguments are not return command.substring(0, firstSep).toLowerCase(Locale.ENGLISH) - + command.substring(firstSep); + + command.substring(firstSep); } else { return command.toLowerCase(Locale.ENGLISH); } @@ -85,18 +84,19 @@ public final class VelocityCommands { public static final String ARGS_NODE_NAME = "arguments"; /** - * Returns the parsed arguments that come after the command alias, or {@code fallback} if - * no arguments were provided. + * Returns the parsed arguments that come after the command alias, or {@code fallback} if no + * arguments were provided. * * @param arguments the map of parsed arguments, as returned by - * {@link CommandContext#getArguments()} or {@link CommandContextBuilder#getArguments()} - * @param type the type class of the arguments - * @param fallback the value to return if no arguments were provided - * @param the type of the arguments + * {@link CommandContext#getArguments()} or + * {@link CommandContextBuilder#getArguments()} + * @param type the type class of the arguments + * @param fallback the value to return if no arguments were provided + * @param the type of the arguments * @return the command arguments */ public static V readArguments(final Map> arguments, - final Class type, final V fallback) { + final Class type, final V fallback) { final ParsedArgument argument = arguments.get(ARGS_NODE_NAME); if (argument == null) { return fallback; // either no arguments were given or this isn't an InvocableCommand @@ -106,15 +106,15 @@ public final class VelocityCommands { return type.cast(result); } catch (final ClassCastException e) { throw new IllegalArgumentException("Parsed argument is of type " + result.getClass() - + ", expected " + type, e); + + ", expected " + type, e); } } // Alias nodes /** - * Returns whether a literal node with the given name can be added to - * the {@link RootCommandNode} associated to a {@link CommandManager}. + * Returns whether a literal node with the given name can be added to the {@link RootCommandNode} + * associated to a {@link CommandManager}. * *

This is an internal method and should not be used in user-facing * methods. Instead, they should lowercase the given aliases themselves. @@ -130,11 +130,11 @@ public final class VelocityCommands { * Creates a copy of the given literal with the specified name. * * @param original the literal node to copy - * @param newName the name of the returned literal node + * @param newName the name of the returned literal node * @return a copy of the literal with the given name */ public static LiteralCommandNode shallowCopy( - final LiteralCommandNode original, final String newName) { + final LiteralCommandNode original, final String newName) { // Brigadier resolves the redirect of a node if further input can be parsed. // Let be a literal node having a redirect to a literal. Then, // the context returned by CommandDispatcher#parseNodes when given the input @@ -145,11 +145,11 @@ public final class VelocityCommands { Preconditions.checkNotNull(original, "original"); Preconditions.checkNotNull(newName, "secondaryAlias"); final LiteralArgumentBuilder builder = LiteralArgumentBuilder - .literal(newName) - .requires(original.getRequirement()) - .requiresWithContext(original.getContextRequirement()) - .forward(original.getRedirect(), original.getRedirectModifier(), original.isFork()) - .executes(original.getCommand()); + .literal(newName) + .requires(original.getRequirement()) + .requiresWithContext(original.getContextRequirement()) + .forward(original.getRedirect(), original.getRedirectModifier(), original.isFork()) + .executes(original.getCommand()); for (final CommandNode child : original.getChildren()) { builder.then(child); } @@ -159,15 +159,15 @@ public final class VelocityCommands { // Arguments node /** - * Returns the arguments node for the command represented by the given alias node, - * if present; otherwise returns {@code null}. + * Returns the arguments node for the command represented by the given alias node, if present; + * otherwise returns {@code null}. * * @param alias the alias node - * @param the type of the command source + * @param the type of the command source * @return the arguments node, or null if not present */ static @Nullable VelocityArgumentCommandNode getArgumentsNode( - final LiteralCommandNode alias) { + final LiteralCommandNode alias) { final CommandNode node = alias.getChild(ARGS_NODE_NAME); if (node instanceof VelocityArgumentCommandNode) { return (VelocityArgumentCommandNode) node; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentType.java b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentType.java index eefeec46e..3e3028b67 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentType.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentType.java @@ -27,8 +27,8 @@ import java.util.Collection; import java.util.List; /** - * An argument type that parses the remaining contents of a {@link StringReader}, - * splitting the input into words and placing the results in a string array. + * An argument type that parses the remaining contents of a {@link StringReader}, splitting the + * input into words and placing the results in a string array. */ public final class StringArrayArgumentType implements ArgumentType { @@ -36,10 +36,11 @@ public final class StringArrayArgumentType implements ArgumentType { public static final String[] EMPTY = new String[0]; private static final Splitter WORD_SPLITTER = - Splitter.on(CommandDispatcher.ARGUMENT_SEPARATOR_CHAR); + Splitter.on(CommandDispatcher.ARGUMENT_SEPARATOR_CHAR); private static final List EXAMPLES = Arrays.asList("word", "some words"); - private StringArrayArgumentType() {} + private StringArrayArgumentType() { + } @Override public String[] parse(final StringReader reader) throws CommandSyntaxException { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentBuilder.java b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentBuilder.java index 62e8c8b93..e63426ab6 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentBuilder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentBuilder.java @@ -31,20 +31,20 @@ import org.checkerframework.checker.nullness.qual.Nullable; * @param the type of the argument to parse */ public final class VelocityArgumentBuilder - extends ArgumentBuilder> { + extends ArgumentBuilder> { /** - * Creates a builder for creating {@link VelocityArgumentCommandNode}s with - * the given name and type. + * Creates a builder for creating {@link VelocityArgumentCommandNode}s with the given name and + * type. * * @param name the name of the node * @param type the type of the argument to parse - * @param the type of the command source - * @param the type of the argument to parse + * @param the type of the command source + * @param the type of the argument to parse * @return a builder */ public static VelocityArgumentBuilder velocityArgument(final String name, - final ArgumentType type) { + final ArgumentType type) { Preconditions.checkNotNull(name, "name"); Preconditions.checkNotNull(type, "type"); return new VelocityArgumentBuilder<>(name, type); @@ -82,7 +82,7 @@ public final class VelocityArgumentBuilder @Override public VelocityArgumentCommandNode build() { return new VelocityArgumentCommandNode<>(this.name, this.type, getCommand(), getRequirement(), - getContextRequirement(), getRedirect(), getRedirectModifier(), isFork(), - this.suggestionsProvider); + getContextRequirement(), getRedirect(), getRedirectModifier(), isFork(), + this.suggestionsProvider); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java index d0bb4f6ec..55e9d6c5a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java @@ -40,9 +40,9 @@ import java.util.function.BiPredicate; import java.util.function.Predicate; /** - * An argument node that uses the given (possibly custom) {@link ArgumentType} - * for parsing, while maintaining compatibility with the vanilla client. - * The argument type must be greedy and accept any input. + * An argument node that uses the given (possibly custom) {@link ArgumentType} for parsing, while + * maintaining compatibility with the vanilla client. The argument type must be greedy and accept + * any input. * * @param the type of the command source * @param the type of the argument to parse @@ -52,25 +52,25 @@ public class VelocityArgumentCommandNode extends ArgumentCommandNode type; VelocityArgumentCommandNode( - final String name, final ArgumentType type, final Command command, - final Predicate requirement, - final BiPredicate, ImmutableStringReader> contextRequirement, - final CommandNode redirect, final RedirectModifier modifier, final boolean forks, - final SuggestionProvider customSuggestions) { + final String name, final ArgumentType type, final Command command, + final Predicate requirement, + final BiPredicate, ImmutableStringReader> contextRequirement, + final CommandNode redirect, final RedirectModifier modifier, final boolean forks, + final SuggestionProvider customSuggestions) { super(name, StringArgumentType.greedyString(), command, requirement, contextRequirement, - redirect, modifier, forks, customSuggestions); + redirect, modifier, forks, customSuggestions); this.type = Preconditions.checkNotNull(type, "type"); } @Override public void parse(final StringReader reader, final CommandContextBuilder contextBuilder) - throws CommandSyntaxException { + throws CommandSyntaxException { // Same as super, except we use the rich ArgumentType final int start = reader.getCursor(); final T result = this.type.parse(reader); if (reader.canRead()) { throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherParseException() - .createWithContext(reader, "Expected greedy ArgumentType to parse all input"); + .createWithContext(reader, "Expected greedy ArgumentType to parse all input"); } final ParsedArgument parsed = new ParsedArgument<>(start, reader.getCursor(), result); @@ -80,8 +80,8 @@ public class VelocityArgumentCommandNode extends ArgumentCommandNode listSuggestions( - final CommandContext context, final SuggestionsBuilder builder) - throws CommandSyntaxException { + final CommandContext context, final SuggestionsBuilder builder) + throws CommandSyntaxException { if (getCustomSuggestions() == null) { return Suggestions.empty(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/CommandMessages.java b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/CommandMessages.java index b4a5a2130..8748768ae 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/CommandMessages.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/CommandMessages.java @@ -21,6 +21,9 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.format.NamedTextColor; +/** + * Basic, common command messages. + */ public class CommandMessages { public static final TranslatableComponent PLAYERS_ONLY = Component.translatable( diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/GlistCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/GlistCommand.java index 64e4c8714..4234479f5 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/GlistCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/GlistCommand.java @@ -40,6 +40,9 @@ import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.format.NamedTextColor; +/** + * Implements the Velocity default {@code /glist} command. + */ public class GlistCommand { private static final String SERVER_ARG = "server"; @@ -55,22 +58,22 @@ public class GlistCommand { */ public void register() { LiteralCommandNode totalNode = LiteralArgumentBuilder - .literal("glist") - .requires(source -> - source.getPermissionValue("velocity.command.glist") == Tristate.TRUE) - .executes(this::totalCount) - .build(); + .literal("glist") + .requires(source -> + source.getPermissionValue("velocity.command.glist") == Tristate.TRUE) + .executes(this::totalCount) + .build(); ArgumentCommandNode serverNode = RequiredArgumentBuilder - .argument(SERVER_ARG, StringArgumentType.string()) - .suggests((context, builder) -> { - for (RegisteredServer server : server.getAllServers()) { - builder.suggest(server.getServerInfo().getName()); - } - builder.suggest("all"); - return builder.buildFuture(); - }) - .executes(this::serverCount) - .build(); + .argument(SERVER_ARG, StringArgumentType.string()) + .suggests((context, builder) -> { + for (RegisteredServer server : server.getAllServers()) { + builder.suggest(server.getServerInfo().getName()); + } + builder.suggest("all"); + return builder.buildFuture(); + }) + .executes(this::serverCount) + .build(); totalNode.addChild(serverNode); server.getCommandManager().register(new BrigadierCommand(totalNode)); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ServerCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ServerCommand.java index 0514c5213..541e00b79 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ServerCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ServerCommand.java @@ -39,6 +39,9 @@ import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; +/** + * Implements Velocity's {@code /server} command. + */ public class ServerCommand implements SimpleCommand { public static final int MAX_SERVERS_TO_LIST = 50; @@ -54,7 +57,7 @@ public class ServerCommand implements SimpleCommand { final String[] args = invocation.arguments(); if (!(source instanceof Player)) { - source.sendMessage(Identity.nil(), CommandMessages.PLAYERS_ONLY); + source.sendMessage(CommandMessages.PLAYERS_ONLY); return; } @@ -63,9 +66,8 @@ public class ServerCommand implements SimpleCommand { // Trying to connect to a server. String serverName = args[0]; Optional toConnect = server.getServer(serverName); - if (!toConnect.isPresent()) { - player.sendMessage(Identity.nil(), CommandMessages.SERVER_DOES_NOT_EXIST - .args(Component.text(serverName))); + if (toConnect.isEmpty()) { + player.sendMessage(CommandMessages.SERVER_DOES_NOT_EXIST.args(Component.text(serverName))); return; } @@ -78,14 +80,14 @@ public class ServerCommand implements SimpleCommand { private void outputServerInformation(Player executor) { String currentServer = executor.getCurrentServer().map(ServerConnection::getServerInfo) .map(ServerInfo::getName).orElse(""); - executor.sendMessage(Identity.nil(), Component.translatable( + executor.sendMessage(Component.translatable( "velocity.command.server-current-server", NamedTextColor.YELLOW, Component.text(currentServer))); List servers = BuiltinCommandUtil.sortedServerList(server); if (servers.size() > MAX_SERVERS_TO_LIST) { - executor.sendMessage(Identity.nil(), Component.translatable( + executor.sendMessage(Component.translatable( "velocity.command.server-too-many", NamedTextColor.RED)); return; } @@ -103,7 +105,7 @@ public class ServerCommand implements SimpleCommand { } } - executor.sendMessage(Identity.nil(), serverListBuilder.build()); + executor.sendMessage(serverListBuilder.build()); } private TextComponent formatServerComponent(String currentPlayerServer, RegisteredServer server) { @@ -113,9 +115,11 @@ public class ServerCommand implements SimpleCommand { int connectedPlayers = server.getPlayersConnected().size(); TranslatableComponent playersTextComponent; if (connectedPlayers == 1) { - playersTextComponent = Component.translatable("velocity.command.server-tooltip-player-online"); + playersTextComponent = Component.translatable( + "velocity.command.server-tooltip-player-online"); } else { - playersTextComponent = Component.translatable("velocity.command.server-tooltip-players-online"); + playersTextComponent = Component.translatable( + "velocity.command.server-tooltip-players-online"); } playersTextComponent = playersTextComponent.args(Component.text(connectedPlayers)); if (serverInfo.getName().equals(currentPlayerServer)) { @@ -130,9 +134,10 @@ public class ServerCommand implements SimpleCommand { serverTextComponent = serverTextComponent.color(NamedTextColor.GRAY) .clickEvent(ClickEvent.runCommand("/server " + serverInfo.getName())) .hoverEvent( - showText(Component.translatable("velocity.command.server-tooltip-offer-connect-server") - .append(Component.newline()) - .append(playersTextComponent)) + showText( + Component.translatable("velocity.command.server-tooltip-offer-connect-server") + .append(Component.newline()) + .append(playersTextComponent)) ); } return serverTextComponent; @@ -142,7 +147,7 @@ public class ServerCommand implements SimpleCommand { public List suggest(final SimpleCommand.Invocation invocation) { final String[] currentArgs = invocation.arguments(); Stream possibilities = server.getAllServers().stream() - .map(rs -> rs.getServerInfo().getName()); + .map(rs -> rs.getServerInfo().getName()); if (currentArgs.length == 0) { return possibilities.collect(Collectors.toList()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ShutdownCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ShutdownCommand.java index c2d80efd6..3084fad9c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ShutdownCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/ShutdownCommand.java @@ -27,31 +27,38 @@ import com.velocitypowered.proxy.VelocityServer; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -public final class ShutdownCommand { - private ShutdownCommand() {} +/** + * Shuts down the proxy. + */ +public final class ShutdownCommand { + + private ShutdownCommand() { + } /** * Creates a Velocity Shutdown Command. + * * @param server the proxy instance * @return the Shutdown Command */ public static BrigadierCommand command(final VelocityServer server) { return new BrigadierCommand(LiteralArgumentBuilder.literal("shutdown") - .requires(source -> source == server.getConsoleCommandSource()) - .executes(context -> { - server.shutdown(true); - return Command.SINGLE_SUCCESS; - }) - .then(RequiredArgumentBuilder.argument("reason", StringArgumentType.greedyString()) + .requires(source -> source == server.getConsoleCommandSource()) .executes(context -> { - String reason = context.getArgument("reason", String.class); - server.shutdown(true, MiniMessage.miniMessage().deserialize( - MiniMessage.miniMessage().serialize( - LegacyComponentSerializer.legacy('&').deserialize(reason) - ) - )); + server.shutdown(true); return Command.SINGLE_SUCCESS; }) - ).build()); + .then(RequiredArgumentBuilder.argument("reason", + StringArgumentType.greedyString()) + .executes(context -> { + String reason = context.getArgument("reason", String.class); + server.shutdown(true, MiniMessage.miniMessage().deserialize( + MiniMessage.miniMessage().serialize( + LegacyComponentSerializer.legacy('&').deserialize(reason) + ) + )); + return Command.SINGLE_SUCCESS; + }) + ).build()); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java index 7ffc6fe8c..17a377710 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java @@ -60,6 +60,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; +/** + * Implements the {@code /velocity} command and friends. + */ public class VelocityCommand implements SimpleCommand { private interface SubCommand { @@ -125,9 +128,9 @@ public class VelocityCommand implements SimpleCommand { if (currentArgs.length == 0) { return commands.entrySet().stream() - .filter(e -> e.getValue().hasPermission(source, new String[0])) - .map(Map.Entry::getKey) - .collect(ImmutableList.toImmutableList()); + .filter(e -> e.getValue().hasPermission(source, new String[0])) + .map(Map.Entry::getKey) + .collect(ImmutableList.toImmutableList()); } if (currentArgs.length == 1) { @@ -353,11 +356,11 @@ public class VelocityCommand implements SimpleCommand { JsonObject servers = new JsonObject(); for (RegisteredServer iter : allServers) { servers.add(iter.getServerInfo().getName(), - InformationUtils.collectServerInfo(iter)); + InformationUtils.collectServerInfo(iter)); } JsonArray connectOrder = new JsonArray(); List attemptedConnectionOrder = ImmutableList.copyOf( - server.getConfiguration().getAttemptConnectionOrder()); + server.getConfiguration().getAttemptConnectionOrder()); for (String s : attemptedConnectionOrder) { connectOrder.add(s); } @@ -366,7 +369,7 @@ public class VelocityCommand implements SimpleCommand { proxyConfig.add("servers", servers); proxyConfig.add("connectOrder", connectOrder); proxyConfig.add("forcedHosts", - InformationUtils.collectForcedHosts(server.getConfiguration())); + InformationUtils.collectForcedHosts(server.getConfiguration())); JsonObject dump = new JsonObject(); dump.add("versionInfo", InformationUtils.collectProxyInfo(server.getVersion())); @@ -383,7 +386,8 @@ public class VelocityCommand implements SimpleCommand { source.sendMessage(Component.text( "An anonymised report containing useful information about " - + "this proxy has been saved at " + dumpPath.toAbsolutePath(), NamedTextColor.GREEN)); + + "this proxy has been saved at " + dumpPath.toAbsolutePath(), + NamedTextColor.GREEN)); } catch (IOException e) { logger.error("Failed to complete dump command, " + "the executor was interrupted: " + e.getMessage()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/CommandInvocationFactory.java b/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/CommandInvocationFactory.java index c462a01ce..e66b1507d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/CommandInvocationFactory.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/CommandInvocationFactory.java @@ -27,14 +27,12 @@ import java.util.List; import java.util.Map; /** - * Creates command invocation objects from a command context builder or - * a command context. + * Creates command invocation objects from a command context builder or a command context. * *

Let {@code builder} be a command context builder, and {@code context} - * a context returned by calling {@link CommandContextBuilder#build(String)} on - * {@code builder}. The invocations returned by {@link #create(CommandContext)} - * when given {@code context}, and {@link #create(CommandContextBuilder)} when - * given {@code builder} are equal. + * a context returned by calling {@link CommandContextBuilder#build(String)} on {@code builder}. The + * invocations returned by {@link #create(CommandContext)} when given {@code context}, and + * {@link #create(CommandContextBuilder)} when given {@code builder} are equal. * * @param the type of the built invocation */ @@ -63,16 +61,17 @@ public interface CommandInvocationFactory> { /** * Creates an invocation from the given parsed nodes and arguments. * - * @param source the command source - * @param nodes the list of parsed nodes, as returned by {@link CommandContext#getNodes()} and - * {@link CommandContextBuilder#getNodes()} + * @param source the command source + * @param nodes the list of parsed nodes, as returned by {@link CommandContext#getNodes()} and + * {@link CommandContextBuilder#getNodes()} * @param arguments the list of parsed arguments, as returned by - * {@link CommandContext#getArguments()} and {@link CommandContextBuilder#getArguments()} + * {@link CommandContext#getArguments()} and + * {@link CommandContextBuilder#getArguments()} * @return the built invocation context */ // This provides an abstraction over methods common to CommandContext and CommandContextBuilder. // Annoyingly, they mostly have the same getters but one is (correctly) not a subclass of // the other. Subclasses may override the methods above to obtain class-specific data. I create(final CommandSource source, final List> nodes, - final Map> arguments); + final Map> arguments); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/RawCommandInvocation.java b/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/RawCommandInvocation.java index 2579a2e65..78d7aba5e 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/RawCommandInvocation.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/invocation/RawCommandInvocation.java @@ -22,12 +22,16 @@ import com.mojang.brigadier.context.ParsedArgument; import com.mojang.brigadier.context.ParsedCommandNode; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.RawCommand; +import com.velocitypowered.api.command.SimpleCommand; import com.velocitypowered.proxy.command.VelocityCommands; import java.util.List; import java.util.Map; +/** + * Implements {@link RawCommand.Invocation}. + */ public final class RawCommandInvocation extends AbstractCommandInvocation - implements RawCommand.Invocation { + implements RawCommand.Invocation { public static final Factory FACTORY = new Factory(); @@ -35,8 +39,8 @@ public final class RawCommandInvocation extends AbstractCommandInvocation> nodes, - final Map> arguments) { + final CommandSource source, final List> nodes, + final Map> arguments) { final String alias = VelocityCommands.readAlias(nodes); final String args = VelocityCommands.readArguments(arguments, String.class, ""); return new RawCommandInvocation(source, alias, args); @@ -46,7 +50,7 @@ public final class RawCommandInvocation extends AbstractCommandInvocation - implements SimpleCommand.Invocation { + implements SimpleCommand.Invocation { public static final Factory FACTORY = new Factory(); @@ -37,11 +40,11 @@ public final class SimpleCommandInvocation extends AbstractCommandInvocation> nodes, - final Map> arguments) { + final CommandSource source, final List> nodes, + final Map> arguments) { final String alias = VelocityCommands.readAlias(nodes); final String[] args = VelocityCommands.readArguments( - arguments, String[].class, StringArrayArgumentType.EMPTY); + arguments, String[].class, StringArrayArgumentType.EMPTY); return new SimpleCommandInvocation(source, alias, args); } } @@ -49,7 +52,7 @@ public final class SimpleCommandInvocation extends AbstractCommandInvocation implements CommandReg } protected void register(final LiteralCommandNode node, - final String secondaryAlias) { + final String secondaryAlias) { final LiteralCommandNode copy = - VelocityCommands.shallowCopy(node, secondaryAlias); + VelocityCommands.shallowCopy(node, secondaryAlias); this.register(copy); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/CommandRegistrar.java b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/CommandRegistrar.java index 5b53aee83..11e0fc2f2 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/CommandRegistrar.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/CommandRegistrar.java @@ -23,8 +23,8 @@ import com.velocitypowered.api.command.Command; import com.velocitypowered.api.command.CommandMeta; /** - * Creates and registers the {@link LiteralCommandNode} representations of - * a given {@link Command} in a {@link RootCommandNode}. + * Creates and registers the {@link LiteralCommandNode} representations of a given {@link Command} + * in a {@link RootCommandNode}. * * @param the type of the command to register */ @@ -33,16 +33,16 @@ public interface CommandRegistrar { /** * Registers the given command. * - * @param meta the command metadata, including the case-insensitive aliases + * @param meta the command metadata, including the case-insensitive aliases * @param command the command to register * @throws IllegalArgumentException if the given command cannot be registered */ void register(final CommandMeta meta, final T command); /** - * Returns the superclass or superinterface of all {@link Command} classes - * compatible with this registrar. Note that {@link #register(CommandMeta, Command)} - * may impose additional restrictions on individual {@link Command} instances. + * Returns the superclass or superinterface of all {@link Command} classes compatible with this + * registrar. Note that {@link #register(CommandMeta, Command)} may impose additional restrictions + * on individual {@link Command} instances. * * @return the superclass of all the classes compatible with this registrar */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/InvocableCommandRegistrar.java b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/InvocableCommandRegistrar.java index e6ff7129c..91c5f16e4 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/InvocableCommandRegistrar.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/InvocableCommandRegistrar.java @@ -42,14 +42,14 @@ import java.util.function.Predicate; * {@link InvocableCommand} in a root node. */ abstract class InvocableCommandRegistrar, - I extends CommandInvocation, A> extends AbstractCommandRegistrar { + I extends CommandInvocation, A> extends AbstractCommandRegistrar { private final CommandInvocationFactory invocationFactory; private final ArgumentType argumentsType; protected InvocableCommandRegistrar(final RootCommandNode root, final Lock lock, - final CommandInvocationFactory invocationFactory, - final ArgumentType argumentsType) { + final CommandInvocationFactory invocationFactory, + final ArgumentType argumentsType) { super(root, lock); this.invocationFactory = Preconditions.checkNotNull(invocationFactory, "invocationFactory"); this.argumentsType = Preconditions.checkNotNull(argumentsType, "argumentsType"); @@ -61,7 +61,7 @@ abstract class InvocableCommandRegistrar, final String primaryAlias = aliases.next(); final LiteralCommandNode literal = - this.createLiteral(command, meta, primaryAlias); + this.createLiteral(command, meta, primaryAlias); this.register(literal); while (aliases.hasNext()) { @@ -71,7 +71,7 @@ abstract class InvocableCommandRegistrar, } private LiteralCommandNode createLiteral(final T command, final CommandMeta meta, - final String alias) { + final String alias) { final Predicate> requirement = context -> { final I invocation = invocationFactory.create(context); return command.hasPermission(invocation); @@ -83,35 +83,35 @@ abstract class InvocableCommandRegistrar, }; final LiteralCommandNode literal = LiteralArgumentBuilder - .literal(alias) - .requiresWithContext((context, reader) -> { - if (reader.canRead()) { - // InvocableCommands do not follow a tree-like permissions checking structure. - // Thus, a CommandSource may be able to execute a command with arguments while - // not being able to execute the argument-less variant. - // Only check for permissions once parsing is complete. - return true; - } - return requirement.test(context); - }) - .executes(callback) - .build(); + .literal(alias) + .requiresWithContext((context, reader) -> { + if (reader.canRead()) { + // InvocableCommands do not follow a tree-like permissions checking structure. + // Thus, a CommandSource may be able to execute a command with arguments while + // not being able to execute the argument-less variant. + // Only check for permissions once parsing is complete. + return true; + } + return requirement.test(context); + }) + .executes(callback) + .build(); final ArgumentCommandNode arguments = VelocityArgumentBuilder - .velocityArgument(VelocityCommands.ARGS_NODE_NAME, argumentsType) - .requiresWithContext((context, reader) -> requirement.test(context)) - .executes(callback) - .suggests((context, builder) -> { - final I invocation = invocationFactory.create(context); - return command.suggestAsync(invocation).thenApply(suggestions -> { - for (String value : suggestions) { - Preconditions.checkNotNull(value, "suggestion"); - builder.suggest(value); - } - return builder.build(); - }); - }) - .build(); + .velocityArgument(VelocityCommands.ARGS_NODE_NAME, argumentsType) + .requiresWithContext((context, reader) -> requirement.test(context)) + .executes(callback) + .suggests((context, builder) -> { + final I invocation = invocationFactory.create(context); + return command.suggestAsync(invocation).thenApply(suggestions -> { + for (String value : suggestions) { + Preconditions.checkNotNull(value, "suggestion"); + builder.suggest(value); + } + return builder.build(); + }); + }) + .build(); literal.addChild(arguments); // Add hinting nodes diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/RawCommandRegistrar.java b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/RawCommandRegistrar.java index 2c1e8f109..4101dc519 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/RawCommandRegistrar.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/RawCommandRegistrar.java @@ -28,7 +28,7 @@ import java.util.concurrent.locks.Lock; * Registers {@link RawCommand}s in a root node. */ public final class RawCommandRegistrar - extends InvocableCommandRegistrar { + extends InvocableCommandRegistrar { public RawCommandRegistrar(final RootCommandNode root, final Lock lock) { super(root, lock, RawCommandInvocation.FACTORY, StringArgumentType.greedyString()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/SimpleCommandRegistrar.java b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/SimpleCommandRegistrar.java index bfd4ef430..8fb749ed3 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/SimpleCommandRegistrar.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/registrar/SimpleCommandRegistrar.java @@ -28,7 +28,7 @@ import java.util.concurrent.locks.Lock; * Registers {@link SimpleCommand}s in a root node. */ public final class SimpleCommandRegistrar - extends InvocableCommandRegistrar { + extends InvocableCommandRegistrar { public SimpleCommandRegistrar(final RootCommandNode root, final Lock lock) { super(root, lock, SimpleCommandInvocation.FACTORY, StringArrayArgumentType.INSTANCE); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/config/PingPassthroughMode.java b/proxy/src/main/java/com/velocitypowered/proxy/config/PingPassthroughMode.java index 1c28a4c27..45ae3bcac 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/config/PingPassthroughMode.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/config/PingPassthroughMode.java @@ -17,6 +17,9 @@ package com.velocitypowered.proxy.config; +/** + * Supported passthrough modes for ping passthrough. + */ public enum PingPassthroughMode { DISABLED, MODS, diff --git a/proxy/src/main/java/com/velocitypowered/proxy/config/PlayerInfoForwarding.java b/proxy/src/main/java/com/velocitypowered/proxy/config/PlayerInfoForwarding.java index 6adb06552..9b472f5f9 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/config/PlayerInfoForwarding.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/config/PlayerInfoForwarding.java @@ -17,6 +17,9 @@ package com.velocitypowered.proxy.config; +/** + * Supported player info forwarding methods. + */ public enum PlayerInfoForwarding { NONE, LEGACY, diff --git a/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java b/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java index c84aa8007..e7af63225 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java @@ -52,29 +52,45 @@ import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Velocity's configuration. + */ public class VelocityConfiguration implements ProxyConfig { private static final Logger logger = LogManager.getLogger(VelocityConfiguration.class); - @Expose private String bind = "0.0.0.0:25577"; - @Expose private String motd = "&3A Velocity Server"; - @Expose private int showMaxPlayers = 500; - @Expose private boolean onlineMode = true; - @Expose private boolean preventClientProxyConnections = false; - @Expose private PlayerInfoForwarding playerInfoForwardingMode = PlayerInfoForwarding.NONE; + @Expose + private String bind = "0.0.0.0:25577"; + @Expose + private String motd = "&3A Velocity Server"; + @Expose + private int showMaxPlayers = 500; + @Expose + private boolean onlineMode = true; + @Expose + private boolean preventClientProxyConnections = false; + @Expose + private PlayerInfoForwarding playerInfoForwardingMode = PlayerInfoForwarding.NONE; private byte[] forwardingSecret = generateRandomString(12).getBytes(StandardCharsets.UTF_8); - @Expose private boolean announceForge = false; - @Expose private boolean onlineModeKickExistingPlayers = false; - @Expose private PingPassthroughMode pingPassthrough = PingPassthroughMode.DISABLED; + @Expose + private boolean announceForge = false; + @Expose + private boolean onlineModeKickExistingPlayers = false; + @Expose + private PingPassthroughMode pingPassthrough = PingPassthroughMode.DISABLED; private final Servers servers; private final ForcedHosts forcedHosts; - @Expose private final Advanced advanced; - @Expose private final Query query; + @Expose + private final Advanced advanced; + @Expose + private final Query query; private final Metrics metrics; - @Expose private boolean enablePlayerAddressLogging = true; + @Expose + private boolean enablePlayerAddressLogging = true; private net.kyori.adventure.text.@MonotonicNonNull Component motdAsComponent; private @Nullable Favicon favicon; - @Expose private boolean forceKeyAuthentication = true; // Added in 1.19 + @Expose + private boolean forceKeyAuthentication = true; // Added in 1.19 private VelocityConfiguration(Servers servers, ForcedHosts forcedHosts, Advanced advanced, Query query, Metrics metrics) { @@ -112,6 +128,7 @@ public class VelocityConfiguration implements ProxyConfig { /** * Attempts to validate the configuration. + * * @return {@code true} if the configuration is sound, {@code false} if not */ public boolean validate() { @@ -408,6 +425,7 @@ public class VelocityConfiguration implements ProxyConfig { /** * Reads the Velocity configuration from {@code path}. + * * @param path the path to read from * @return the deserialized Velocity configuration * @throws IOException if we could not read from the {@code path}. @@ -455,23 +473,25 @@ public class VelocityConfiguration implements ProxyConfig { configVersion = 1.0; } - // Whether or not this config version is older than 2.0 which uses the deprecated "forwarding-secret" parameter + // Whether or not this config version is older than 2.0 which uses the deprecated + // "forwarding-secret" parameter boolean legacyConfig = configVersion < 2.0; String forwardingSecretString; byte[] forwardingSecret; // Handle the previous (version 1.0) config - // There is duplicate/old code here in effort to make the future commit which abandons legacy config handling - // easier to implement. All that would be required is removing the if statement here and keeping the contents - // of the else block (with slight tidying). + // There is duplicate/old code here in effort to make the future commit which abandons legacy + // config handling easier to implement. All that would be required is removing the if statement + // here and keeping the contents of the else block (with slight tidying). if (legacyConfig) { - logger.warn("You are currently using a deprecated configuration version. The \"forwarding-secret\"" - + " parameter has been recognized as a security concern and has been removed in config version 2.0." - + " It's recommended you rename your current \"velocity.toml\" to something else to allow Velocity" - + " to generate a config file of the new version. You may then configure that file as you normally would." - + " The only differences are the config-version and \"forwarding-secret\" has been replaced" - + " by \"forwarding-secret-file\"."); + logger.warn( + "You are currently using a deprecated configuration version. The \"forwarding-secret\"" + + " parameter is a security hazard and was removed in config version 2.0." + + " You should rename your current \"velocity.toml\" to something else to allow" + + " Velocity to generate a config file for the new version. You may then configure " + + " that file as you normally would. The only differences are the config-version " + + "and \"forwarding-secret\" has been replaced by \"forwarding-secret-file\"."); // Default legacy handling forwardingSecretString = System.getenv() @@ -493,7 +513,8 @@ public class VelocityConfiguration implements ProxyConfig { if (Files.isRegularFile(secretPath)) { forwardingSecretString = String.join("", Files.readAllLines(secretPath)); } else { - throw new RuntimeException("The file " + forwardSecretFile + " is not a valid file or it is a directory."); + throw new RuntimeException( + "The file " + forwardSecretFile + " is not a valid file or it is a directory."); } } else { throw new RuntimeException("The forwarding-secret-file does not exist."); @@ -505,7 +526,7 @@ public class VelocityConfiguration implements ProxyConfig { if (configVersion == 1.0 || configVersion == 2.0) { config.set("force-key-authentication", config.getOrElse("force-key-authentication", true)); config.setComment("force-key-authentication", - "Should the proxy enforce the new public key security standard? By default, this is on."); + "Should the proxy enforce the new public key security standard? By default, this is on."); config.set("config-version", configVersion == 2.0 ? "2.5" : "1.5"); mustResave = true; } @@ -632,12 +653,11 @@ public class VelocityConfiguration implements ProxyConfig { } /** - * TOML requires keys to match a regex of {@code [A-Za-z0-9_-]} unless it is wrapped in - * quotes; however, the TOML parser returns the key with the quotes so we need to clean the - * server name before we pass it onto server registration to keep proper server name behavior. + * TOML requires keys to match a regex of {@code [A-Za-z0-9_-]} unless it is wrapped in quotes; + * however, the TOML parser returns the key with the quotes so we need to clean the server name + * before we pass it onto server registration to keep proper server name behavior. * * @param name the server name to clean - * * @return the cleaned server name */ private String cleanServerName(String name) { @@ -705,19 +725,32 @@ public class VelocityConfiguration implements ProxyConfig { private static class Advanced { - @Expose private int compressionThreshold = 256; - @Expose private int compressionLevel = -1; - @Expose private int loginRatelimit = 3000; - @Expose private int connectionTimeout = 5000; - @Expose private int readTimeout = 30000; - @Expose private boolean proxyProtocol = false; - @Expose private boolean tcpFastOpen = false; - @Expose private boolean bungeePluginMessageChannel = true; - @Expose private boolean showPingRequests = false; - @Expose private boolean failoverOnUnexpectedServerDisconnect = true; - @Expose private boolean announceProxyCommands = true; - @Expose private boolean logCommandExecutions = false; - @Expose private boolean logPlayerConnections = true; + @Expose + private int compressionThreshold = 256; + @Expose + private int compressionLevel = -1; + @Expose + private int loginRatelimit = 3000; + @Expose + private int connectionTimeout = 5000; + @Expose + private int readTimeout = 30000; + @Expose + private boolean proxyProtocol = false; + @Expose + private boolean tcpFastOpen = false; + @Expose + private boolean bungeePluginMessageChannel = true; + @Expose + private boolean showPingRequests = false; + @Expose + private boolean failoverOnUnexpectedServerDisconnect = true; + @Expose + private boolean announceProxyCommands = true; + @Expose + private boolean logCommandExecutions = false; + @Expose + private boolean logPlayerConnections = true; private Advanced() { } @@ -819,10 +852,14 @@ public class VelocityConfiguration implements ProxyConfig { private static class Query { - @Expose private boolean queryEnabled = false; - @Expose private int queryPort = 25577; - @Expose private String queryMap = "Velocity"; - @Expose private boolean showPlugins = false; + @Expose + private boolean queryEnabled = false; + @Expose + private int queryPort = 25577; + @Expose + private String queryMap = "Velocity"; + @Expose + private boolean showPlugins = false; private Query() { } @@ -870,7 +907,11 @@ public class VelocityConfiguration implements ProxyConfig { } } + /** + * Configuration for metrics. + */ public static class Metrics { + private boolean enabled = true; private Metrics(CommentedConfig toml) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionType.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionType.java index 4820ce688..ec6c99313 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionType.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionType.java @@ -42,13 +42,13 @@ public interface ConnectionType { BackendConnectionPhase getInitialBackendPhase(); /** - * Adds properties to the {@link GameProfile} if required. If any properties - * are added, the returned {@link GameProfile} will be a copy. + * Adds properties to the {@link GameProfile} if required. If any properties are added, the + * returned {@link GameProfile} will be a copy. * - * @param original The original {@link GameProfile} + * @param original The original {@link GameProfile} * @param forwardingType The Velocity {@link PlayerInfoForwarding} * @return The {@link GameProfile} with the properties added in. */ GameProfile addGameProfileTokensIfRequired(GameProfile original, - PlayerInfoForwarding forwardingType); + PlayerInfoForwarding forwardingType); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionTypes.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionTypes.java index 6f5ece082..11cb6f476 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionTypes.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/ConnectionTypes.java @@ -29,9 +29,8 @@ import com.velocitypowered.proxy.connection.util.ConnectionTypeImpl; public final class ConnectionTypes { /** - * Indicates that the connection has yet to reach the - * point where we have a definitive answer as to what - * type of connection we have. + * Indicates that the connection has yet to reach the point where we have a definitive answer as + * to what type of connection we have. */ public static final ConnectionType UNDETERMINED = new ConnectionTypeImpl(ClientConnectionPhases.VANILLA, BackendConnectionPhases.UNKNOWN); @@ -46,8 +45,7 @@ public final class ConnectionTypes { LegacyForgeHandshakeClientPhase.NOT_STARTED, BackendConnectionPhases.UNKNOWN); /** - * Indicates that the connection is a 1.8-1.12 Forge - * connection. + * Indicates that the connection is a 1.8-1.12 Forge connection. */ public static final ConnectionType LEGACY_FORGE = new LegacyForgeConnectionType(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java index 7d08a3037..a560d77f2 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java @@ -87,8 +87,9 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Initializes a new {@link MinecraftConnection} instance. + * * @param channel the channel on the connection - * @param server the Velocity instance + * @param server the Velocity instance */ public MinecraftConnection(Channel channel, VelocityServer server) { this.channel = channel; @@ -211,6 +212,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Writes and immediately flushes a message to the connection. + * * @param msg the message to write */ public void write(Object msg) { @@ -223,6 +225,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Writes, but does not flush, a message to the connection. + * * @param msg the message to write */ public void delayedWrite(Object msg) { @@ -244,6 +247,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Closes the connection after writing the {@code msg}. + * * @param msg the message to write */ public void closeWith(Object msg) { @@ -273,6 +277,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Immediately closes the connection. + * * @param markKnown whether the disconnection is known */ public void close(boolean markKnown) { @@ -319,6 +324,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Determines whether or not the channel should continue reading data automaticaly. + * * @param autoReading whether or not we should read data automatically */ public void setAutoReading(boolean autoReading) { @@ -337,6 +343,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Changes the state of the Minecraft connection. + * * @param state the new state */ public void setState(StateRegistry state) { @@ -353,6 +360,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Sets the new protocol version for the connection. + * * @param protocolVersion the protocol version to use */ public void setProtocolVersion(ProtocolVersion protocolVersion) { @@ -380,6 +388,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Sets the session handler for this connection. + * * @param sessionHandler the handler to use */ public void setSessionHandler(MinecraftSessionHandler sessionHandler) { @@ -399,6 +408,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Sets the compression threshold on the connection. You are responsible for sending * {@link com.velocitypowered.proxy.protocol.packet.SetCompression} beforehand. + * * @param threshold the compression threshold to use */ public void setCompressionThreshold(int threshold) { @@ -440,6 +450,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Enables encryption on the connection. + * * @param secret the secret key negotiated between the client and the server * @throws GeneralSecurityException if encryption can't be enabled */ @@ -471,6 +482,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Gets the detected {@link ConnectionType}. + * * @return The {@link ConnectionType} */ public ConnectionType getType() { @@ -479,6 +491,7 @@ public class MinecraftConnection extends ChannelInboundHandlerAdapter { /** * Sets the detected {@link ConnectionType}. + * * @param connectionType The {@link ConnectionType} */ public void setType(ConnectionType connectionType) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnectionAssociation.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnectionAssociation.java index 0bee34efc..363916b11 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnectionAssociation.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnectionAssociation.java @@ -17,6 +17,9 @@ package com.velocitypowered.proxy.connection; +/** + * Marker interface for something that can be associated with a {@link MinecraftConnection}. + */ public interface MinecraftConnectionAssociation { } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftSessionHandler.java index e7205edb0..83207f84b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftSessionHandler.java @@ -63,6 +63,9 @@ import com.velocitypowered.proxy.protocol.packet.title.TitleTextPacket; import com.velocitypowered.proxy.protocol.packet.title.TitleTimesPacket; import io.netty.buffer.ByteBuf; +/** + * Interface for dispatching received Minecraft packets. + */ public interface MinecraftSessionHandler { default boolean beforeHandle() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/VelocityConstants.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/VelocityConstants.java index e95996b0b..873f3642d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/VelocityConstants.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/VelocityConstants.java @@ -17,6 +17,9 @@ package com.velocitypowered.proxy.connection; +/** + * Various useful constants. + */ public class VelocityConstants { private VelocityConstants() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhase.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhase.java index 24a808b0f..bc3c01950 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhase.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhase.java @@ -30,20 +30,22 @@ import com.velocitypowered.proxy.protocol.packet.PluginMessage; public interface BackendConnectionPhase { /** - * Handle a plugin message in the context of - * this phase. + * Handle a plugin message in the context of this phase. * + * @param server the server connection + * @param player the player * @param message The message to handle * @return true if handled, false otherwise. */ default boolean handle(VelocityServerConnection server, - ConnectedPlayer player, - PluginMessage message) { + ConnectedPlayer player, + PluginMessage message) { return false; } /** * Indicates whether the connection is considered complete. + * * @return true if so */ default boolean consideredComplete() { @@ -51,13 +53,13 @@ public interface BackendConnectionPhase { } /** - * Fired when the provided server connection is about to be terminated - * because the provided player is connecting to a new server. + * Fired when the provided server connection is about to be terminated because the provided player + * is connecting to a new server. * * @param serverConnection The server the player is disconnecting from - * @param player The player + * @param player The player */ default void onDepartForNewServer(VelocityServerConnection serverConnection, - ConnectedPlayer player) { + ConnectedPlayer player) { } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhases.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhases.java index 3fb42348b..13fc35630 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhases.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendConnectionPhases.java @@ -32,7 +32,8 @@ public final class BackendConnectionPhases { /** * The backend connection is vanilla. */ - public static final BackendConnectionPhase VANILLA = new BackendConnectionPhase() {}; + public static final BackendConnectionPhase VANILLA = new BackendConnectionPhase() { + }; /** * The backend connection is unknown at this time. @@ -45,8 +46,8 @@ public final class BackendConnectionPhases { @Override public boolean handle(VelocityServerConnection serverConn, - ConnectedPlayer player, - PluginMessage message) { + ConnectedPlayer player, + PluginMessage message) { // The connection may be legacy forge. If so, the Forge handler will deal with this // for us. Otherwise, we have nothing to do. return LegacyForgeHandshakeBackendPhase.NOT_STARTED.handle(serverConn, player, message); @@ -54,9 +55,9 @@ public final class BackendConnectionPhases { }; /** - * A special backend phase used to indicate that this connection is about to become - * obsolete (transfer to a new server, for instance) and that Forge messages ought to be - * forwarded on to an in-flight connection instead. + * A special backend phase used to indicate that this connection is about to become obsolete + * (transfer to a new server, for instance) and that Forge messages ought to be forwarded on to an + * in-flight connection instead. */ public static final BackendConnectionPhase IN_TRANSITION = new BackendConnectionPhase() { @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java index 0be9ab121..dd98b931c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java @@ -61,7 +61,11 @@ import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Handles a connected player. + */ public class BackendPlaySessionHandler implements MinecraftSessionHandler { + private static final Pattern PLAUSIBLE_SHA1_HASH = Pattern.compile("^[a-z0-9]{40}$"); private static final Logger logger = LogManager.getLogger(BackendPlaySessionHandler.class); private static final boolean BACKPRESSURE_LOG = Boolean @@ -286,7 +290,8 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler { public boolean handle(ServerData packet) { server.getServerListPingHandler().getInitialPing(this.serverConn.getPlayer()) .thenComposeAsync( - ping -> server.getEventManager().fire(new ProxyPingEvent(this.serverConn.getPlayer(), ping)), + ping -> server.getEventManager() + .fire(new ProxyPingEvent(this.serverConn.getPlayer(), ping)), playerConnection.eventLoop() ) .thenAcceptAsync(pingEvent -> diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java index 12ff5bdc7..131fa73ca 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java @@ -44,9 +44,16 @@ import net.kyori.adventure.text.serializer.ComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -@SuppressFBWarnings(value = "OS_OPEN_STREAM", justification = "Most methods in this class open " - + "instances of ByteBufDataOutput backed by heap-allocated ByteBufs. Closing them does " - + "nothing.") +/** + * Handles messages coming from servers trying to communicate with the BungeeCord plugin + * messaging channel interface. + */ +@SuppressFBWarnings( + value = "OS_OPEN_STREAM", + justification = "Most methods in this class open " + + "instances of ByteBufDataOutput backed by heap-allocated ByteBufs. Closing them does " + + "nothing." +) public class BungeeCordMessageResponder { private static final MinecraftChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java index c23640cb1..70213e720 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java @@ -52,7 +52,11 @@ import net.kyori.adventure.text.Component; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Handles a player trying to log into the proxy. + */ public class LoginSessionHandler implements MinecraftSessionHandler { + private static final Logger logger = LogManager.getLogger(LoginSessionHandler.class); private static final Component MODERN_IP_FORWARDING_FAILURE = Component @@ -88,7 +92,8 @@ public class LoginSessionHandler implements MinecraftSessionHandler { requestedForwardingVersion = packet.content().readByte(); } ByteBuf forwardingData = createForwardingData(configuration.getForwardingSecret(), - serverConn.getPlayerRemoteAddressAsString(), serverConn.getPlayer(), requestedForwardingVersion); + serverConn.getPlayerRemoteAddressAsString(), serverConn.getPlayer(), + requestedForwardingVersion); LoginPluginResponse response = new LoginPluginResponse(packet.getId(), true, forwardingData); mc.write(response); @@ -104,7 +109,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { final MinecraftChannelIdentifier identifier = MinecraftChannelIdentifier .from(packet.getChannel()); this.server.getEventManager().fire(new ServerLoginPluginMessageEvent(serverConn, identifier, - contents, packet.getId())) + contents, packet.getId())) .thenAcceptAsync(event -> { if (event.getResult().isAllowed()) { mc.write(new LoginPluginResponse(packet.getId(), true, Unpooled @@ -178,7 +183,8 @@ public class LoginSessionHandler implements MinecraftSessionHandler { 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) { - return requested >= VelocityConstants.MODERN_LAZY_SESSION ? VelocityConstants.MODERN_LAZY_SESSION + return requested >= VelocityConstants.MODERN_LAZY_SESSION + ? VelocityConstants.MODERN_LAZY_SESSION : VelocityConstants.MODERN_FORWARDING_DEFAULT; } if (player.getIdentifiedKey() != null) { @@ -189,7 +195,8 @@ public class LoginSessionHandler implements MinecraftSessionHandler { // Since V2 is not backwards compatible we have to throw the key if v2 and requested is v1 case LINKED_V2: return requested >= VelocityConstants.MODERN_FORWARDING_WITH_KEY_V2 - ? VelocityConstants.MODERN_FORWARDING_WITH_KEY_V2 : VelocityConstants.MODERN_FORWARDING_DEFAULT; + ? VelocityConstants.MODERN_FORWARDING_WITH_KEY_V2 + : VelocityConstants.MODERN_FORWARDING_DEFAULT; default: return VelocityConstants.MODERN_FORWARDING_DEFAULT; } @@ -201,7 +208,7 @@ public class LoginSessionHandler implements MinecraftSessionHandler { } private static ByteBuf createForwardingData(byte[] hmacSecret, String address, - ConnectedPlayer player, int requestedVersion) { + ConnectedPlayer player, int requestedVersion) { ByteBuf forwarded = Unpooled.buffer(2048); try { int actualVersion = findForwardingVersion(requestedVersion, player); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java index ab0948694..0856ec84f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java @@ -56,8 +56,9 @@ public class TransitionSessionHandler implements MinecraftSessionHandler { /** * Creates the new transition handler. - * @param server the Velocity server instance - * @param serverConn the server connection + * + * @param server the Velocity server instance + * @param serverConn the server connection * @param resultFuture the result future */ TransitionSessionHandler(VelocityServer server, diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java index fde61127f..a7663f2aa 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java @@ -56,6 +56,9 @@ import java.util.function.UnaryOperator; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Handles a connection from the proxy to some backend server. + */ public class VelocityServerConnection implements MinecraftConnectionAssociation, ServerConnection { private final VelocityRegisteredServer registeredServer; @@ -71,10 +74,11 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, /** * Initializes a new server connection. + * * @param registeredServer the server to connect to - * @param previousServer the server the player is coming from - * @param proxyPlayer the player connecting to the server - * @param server the Velocity proxy instance + * @param previousServer the server the player is coming from + * @param proxyPlayer the player connecting to the server + * @param server the Velocity proxy instance */ public VelocityServerConnection(VelocityRegisteredServer registeredServer, @Nullable VelocityRegisteredServer previousServer, @@ -87,6 +91,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, /** * Connects to the server. + * * @return a {@link com.velocitypowered.api.proxy.ConnectionRequestBuilder.Result} representing * whether or not the connect succeeded */ @@ -205,6 +210,7 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, /** * Ensures the connection is still active and throws an exception if it is not. + * * @return the active connection * @throws IllegalStateException if the connection is inactive */ @@ -259,8 +265,9 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, /** * Sends a plugin message to the server through this connection. + * * @param identifier the channel ID to use - * @param data the data + * @param data the data * @return whether or not the message was sent */ public boolean sendPluginMessage(ChannelIdentifier identifier, ByteBuf data) { @@ -310,9 +317,8 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, } /** - * Gets the current "phase" of the connection, mostly used for tracking - * modded negotiation for legacy forge servers and provides methods - * for performing phase specific actions. + * Gets the current "phase" of the connection, mostly used for tracking modded negotiation for + * legacy forge servers and provides methods for performing phase specific actions. * * @return The {@link BackendConnectionPhase} */ @@ -330,8 +336,8 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, } /** - * Gets whether the {@link com.velocitypowered.proxy.protocol.packet.JoinGame} - * packet has been sent by this server. + * Gets whether the {@link com.velocitypowered.proxy.protocol.packet.JoinGame} packet has been + * sent by this server. * * @return Whether the join has been completed. */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/AuthSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/AuthSessionHandler.java index 322ef8106..fae7ee475 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/AuthSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/AuthSessionHandler.java @@ -51,6 +51,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +/** + * A session handler that is activated to complete the login phase. + */ public class AuthSessionHandler implements MinecraftSessionHandler { private static final Logger logger = LogManager.getLogger(AuthSessionHandler.class); @@ -63,7 +66,7 @@ public class AuthSessionHandler implements MinecraftSessionHandler { private final boolean onlineMode; AuthSessionHandler(VelocityServer server, LoginInboundConnection inbound, - GameProfile profile, boolean onlineMode) { + GameProfile profile, boolean onlineMode) { this.server = Preconditions.checkNotNull(server, "server"); this.inbound = Preconditions.checkNotNull(inbound, "inbound"); this.profile = Preconditions.checkNotNull(profile, "profile"); @@ -88,7 +91,8 @@ 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()); + mcConnection, inbound.getVirtualHost().orElse(null), onlineMode, + inbound.getIdentifiedKey()); this.connectedPlayer = player; if (!server.canRegisterConnection(player)) { player.disconnect0(Component.translatable("velocity.error.already-connected-proxy", @@ -143,7 +147,8 @@ public class AuthSessionHandler implements MinecraftSessionHandler { // Failsafe if (!unlinkedKey.internalAddHolder(player.getUniqueId())) { if (onlineMode) { - inbound.disconnect(Component.translatable("multiplayer.disconnect.invalid_public_key")); + inbound.disconnect( + Component.translatable("multiplayer.disconnect.invalid_public_key")); return; } else { logger.warn("Key for player " + player.getUsername() + " could not be verified!"); @@ -155,7 +160,7 @@ public class AuthSessionHandler implements MinecraftSessionHandler { } else { if (!Objects.equals(playerKey.getSignatureHolder(), playerUniqueId)) { logger.warn("UUID for Player " + player.getUsername() + " mismatches! " - + "Chat/Commands signatures will not work correctly for this player!"); + + "Chat/Commands signatures will not work correctly for this player!"); } } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhase.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhase.java index b0ee83b34..425d185b9 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhase.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhase.java @@ -30,12 +30,11 @@ import com.velocitypowered.proxy.protocol.packet.PluginMessage; public interface ClientConnectionPhase { /** - * Handle a plugin message in the context of - * this phase. + * Handle a plugin message in the context of this phase. * - * @param player The player + * @param player The player * @param message The message to handle - * @param server The backend connection to use + * @param server The backend connection to use * @return true if handled, false otherwise. */ default boolean handle(ConnectedPlayer player, @@ -45,8 +44,7 @@ public interface ClientConnectionPhase { } /** - * Instruct Velocity to reset the connection phase - * back to its default for the connection type. + * Instruct Velocity to reset the connection phase back to its default for the connection type. * * @param player The player */ @@ -54,8 +52,7 @@ public interface ClientConnectionPhase { } /** - * Perform actions just as the player joins the - * server. + * Perform actions just as the player joins the server. * * @param player The player */ @@ -64,6 +61,7 @@ public interface ClientConnectionPhase { /** * Indicates whether the connection is considered complete. + * * @return true if so */ default boolean consideredComplete() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhases.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhases.java index 934dae0ad..7c4147900 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhases.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientConnectionPhases.java @@ -28,7 +28,8 @@ public final class ClientConnectionPhases { /** * The client is connecting with a vanilla client (as far as we can tell). */ - public static final ClientConnectionPhase VANILLA = new ClientConnectionPhase() {}; + public static final ClientConnectionPhase VANILLA = new ClientConnectionPhase() { + }; private ClientConnectionPhases() { throw new AssertionError(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java index 2b01a3e27..8a1be9530 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java @@ -141,7 +141,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean validateChat(String message) { if (CharacterUtil.containsIllegalCharacters(message)) { - player.disconnect(Component.translatable("velocity.error.illegal-chat-characters", NamedTextColor.RED)); + player.disconnect( + Component.translatable("velocity.error.illegal-chat-characters", NamedTextColor.RED)); return false; } return true; @@ -149,7 +150,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { @Override public void activated() { - Collection channels = server.getChannelRegistrar().getChannelsForProtocol(player.getProtocolVersion()); + Collection channels = server.getChannelRegistrar() + .getChannelsForProtocol(player.getProtocolVersion()); if (!channels.isEmpty()) { PluginMessage register = constructChannelsPacket(player.getProtocolVersion(), channels); player.getConnection().write(register); @@ -280,7 +282,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { if (serverConn != null && backendConn != null) { if (backendConn.getState() != StateRegistry.PLAY) { logger.warn( - "A plugin message was received while the backend server was not " + "ready. Channel: {}. Packet discarded.", + "A plugin message was received while the backend server was not " + + "ready. Channel: {}. Packet discarded.", packet.getChannel()); } else if (PluginMessageUtil.isRegister(packet)) { List channels = PluginMessageUtil.getChannels(packet); @@ -294,7 +297,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { } } server.getEventManager() - .fireAndForget(new PlayerChannelRegisterEvent(player, ImmutableList.copyOf(channelIdentifiers))); + .fireAndForget( + new PlayerChannelRegisterEvent(player, ImmutableList.copyOf(channelIdentifiers))); backendConn.write(packet.retain()); } else if (PluginMessageUtil.isUnregister(packet)) { player.getKnownChannels().removeAll(PluginMessageUtil.getChannels(packet)); @@ -304,7 +308,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { server.getEventManager().fireAndForget(new PlayerClientBrandEvent(player, brand)); player.setClientBrand(brand); backendConn.write( - PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(), player.getProtocolVersion())); + PluginMessageUtil.rewriteMinecraftBrand(packet, server.getVersion(), + player.getProtocolVersion())); } else if (BungeeCordMessageResponder.isBungeeCordMessage(packet)) { return true; } else { @@ -321,7 +326,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { ChannelIdentifier id = server.getChannelRegistrar().getFromId(packet.getChannel()); if (id == null) { // We don't have any plugins listening on this channel, process the packet now. - if (!player.getPhase().consideredComplete() || !serverConn.getPhase().consideredComplete()) { + if (!player.getPhase().consideredComplete() || !serverConn.getPhase() + .consideredComplete()) { // The client is trying to send messages too early. This is primarily caused by mods, // but further aggravated by Velocity. To work around these issues, we will queue any // non-FML handshake messages to be sent once the FML handshake has completed or the @@ -339,8 +345,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { PluginMessageEvent event = new PluginMessageEvent(player, serverConn, id, copy); server.getEventManager().fire(event).thenAcceptAsync(pme -> { if (pme.getResult().isAllowed()) { - PluginMessage message = new PluginMessage(packet.getChannel(), Unpooled.wrappedBuffer(copy)); - if (!player.getPhase().consideredComplete() || !serverConn.getPhase().consideredComplete()) { + PluginMessage message = new PluginMessage(packet.getChannel(), + Unpooled.wrappedBuffer(copy)); + if (!player.getPhase().consideredComplete() || !serverConn.getPhase() + .consideredComplete()) { // We're still processing the connection (see above), enqueue the packet for now. loginPluginMessages.add(message.retain()); } else { @@ -402,7 +410,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { @Override public void exception(Throwable throwable) { - player.disconnect(Component.translatable("velocity.error.player-connection-error", NamedTextColor.RED)); + player.disconnect( + Component.translatable("velocity.error.player-connection-error", NamedTextColor.RED)); } @Override @@ -483,7 +492,8 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { // Clear any title from the previous server. if (player.getProtocolVersion().compareTo(MINECRAFT_1_8) >= 0) { player.getConnection().delayedWrite( - GenericTitlePacket.constructTitlePacket(GenericTitlePacket.ActionType.RESET, player.getProtocolVersion())); + GenericTitlePacket.constructTitlePacket(GenericTitlePacket.ActionType.RESET, + player.getProtocolVersion())); } // Flush everything @@ -553,33 +563,36 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { return false; } - server.getCommandManager().offerBrigadierSuggestions(player, command).thenAcceptAsync(suggestions -> { - if (suggestions.isEmpty()) { - return; - } + server.getCommandManager().offerBrigadierSuggestions(player, command) + .thenAcceptAsync(suggestions -> { + if (suggestions.isEmpty()) { + return; + } - List offers = new ArrayList<>(); - for (Suggestion suggestion : suggestions.getList()) { - String offer = suggestion.getText(); - Component tooltip = null; - if (suggestion.getTooltip() != null && suggestion.getTooltip() instanceof VelocityBrigadierMessage) { - tooltip = ((VelocityBrigadierMessage) suggestion.getTooltip()).asComponent(); - } - offers.add(new Offer(offer, tooltip)); - } - int startPos = packet.getCommand().lastIndexOf(' ') + 1; - if (startPos > 0) { - TabCompleteResponse resp = new TabCompleteResponse(); - resp.setTransactionId(packet.getTransactionId()); - resp.setStart(startPos); - resp.setLength(packet.getCommand().length() - startPos); - resp.getOffers().addAll(offers); - player.getConnection().write(resp); - } - }, player.getConnection().eventLoop()).exceptionally((ex) -> { - logger.error("Exception while handling command tab completion for player {} executing {}", player, command, ex); - return null; - }); + List offers = new ArrayList<>(); + for (Suggestion suggestion : suggestions.getList()) { + String offer = suggestion.getText(); + Component tooltip = null; + if (suggestion.getTooltip() != null + && suggestion.getTooltip() instanceof VelocityBrigadierMessage) { + tooltip = ((VelocityBrigadierMessage) suggestion.getTooltip()).asComponent(); + } + offers.add(new Offer(offer, tooltip)); + } + int startPos = packet.getCommand().lastIndexOf(' ') + 1; + if (startPos > 0) { + TabCompleteResponse resp = new TabCompleteResponse(); + resp.setTransactionId(packet.getTransactionId()); + resp.setStart(startPos); + resp.setLength(packet.getCommand().length() - startPos); + resp.getOffers().addAll(offers); + player.getConnection().write(resp); + } + }, player.getConnection().eventLoop()).exceptionally((ex) -> { + logger.error("Exception while handling command tab completion for player {} executing {}", + player, command, ex); + return null; + }); return true; // Sorry, handler; we're just gonna have to lie to you here. } @@ -613,32 +626,37 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { private void finishCommandTabComplete(TabCompleteRequest request, TabCompleteResponse response) { String command = request.getCommand().substring(1); - server.getCommandManager().offerBrigadierSuggestions(player, command).thenAcceptAsync(offers -> { - boolean legacy = player.getProtocolVersion().compareTo(MINECRAFT_1_13) < 0; - try { - for (Suggestion suggestion : offers.getList()) { - String offer = suggestion.getText(); - offer = legacy && !offer.startsWith("/") ? "/" + offer : offer; - if (legacy && offer.startsWith(command)) { - offer = offer.substring(command.length()); + server.getCommandManager().offerBrigadierSuggestions(player, command) + .thenAcceptAsync(offers -> { + boolean legacy = player.getProtocolVersion().compareTo(MINECRAFT_1_13) < 0; + try { + for (Suggestion suggestion : offers.getList()) { + String offer = suggestion.getText(); + offer = legacy && !offer.startsWith("/") ? "/" + offer : offer; + if (legacy && offer.startsWith(command)) { + offer = offer.substring(command.length()); + } + Component tooltip = null; + if (suggestion.getTooltip() != null + && suggestion.getTooltip() instanceof VelocityBrigadierMessage) { + tooltip = ((VelocityBrigadierMessage) suggestion.getTooltip()).asComponent(); + } + response.getOffers().add(new Offer(offer, tooltip)); + } + response.getOffers().sort(null); + player.getConnection().write(response); + } catch (Exception e) { + logger.error("Unable to provide tab list completions for {} for command '{}'", + player.getUsername(), command, + e); } - Component tooltip = null; - if (suggestion.getTooltip() != null && suggestion.getTooltip() instanceof VelocityBrigadierMessage) { - tooltip = ((VelocityBrigadierMessage) suggestion.getTooltip()).asComponent(); - } - response.getOffers().add(new Offer(offer, tooltip)); - } - response.getOffers().sort(null); - player.getConnection().write(response); - } catch (Exception e) { - logger.error("Unable to provide tab list completions for {} for command '{}'", player.getUsername(), command, - e); - } - }, player.getConnection().eventLoop()).exceptionally((ex) -> { - logger.error("Exception while finishing command tab completion, with request {} and response {}", request, - response, ex); - return null; - }); + }, player.getConnection().eventLoop()).exceptionally((ex) -> { + logger.error( + "Exception while finishing command tab completion, with request {} and response {}", + request, + response, ex); + return null; + }); } private void finishRegularTabComplete(TabCompleteRequest request, TabCompleteResponse response) { @@ -646,17 +664,20 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { for (Offer offer : response.getOffers()) { offers.add(offer.getText()); } - server.getEventManager().fire(new TabCompleteEvent(player, request.getCommand(), offers)).thenAcceptAsync(e -> { - response.getOffers().clear(); - for (String s : e.getSuggestions()) { - response.getOffers().add(new Offer(s)); - } - player.getConnection().write(response); - }, player.getConnection().eventLoop()).exceptionally((ex) -> { - logger.error("Exception while finishing regular tab completion, with request {} and response{}", request, - response, ex); - return null; - }); + server.getEventManager().fire(new TabCompleteEvent(player, request.getCommand(), offers)) + .thenAcceptAsync(e -> { + response.getOffers().clear(); + for (String s : e.getSuggestions()) { + response.getOffers().add(new Offer(s)); + } + player.getConnection().write(response); + }, player.getConnection().eventLoop()).exceptionally((ex) -> { + logger.error( + "Exception while finishing regular tab completion, with request {} and response{}", + request, + response, ex); + return null; + }); } /** diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java index 36f906b5b..646acb32a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java @@ -24,6 +24,9 @@ import java.util.Locale; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Wraps the settings received in the Client Settings packet. + */ public class ClientSettingsWrapper implements PlayerSettings { static final PlayerSettings DEFAULT = new ClientSettingsWrapper( diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java index 9570b6513..a9ad6c911 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java @@ -117,16 +117,20 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.jetbrains.annotations.NotNull; +/** + * Represents a player that is connected to the proxy. + */ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, KeyIdentifiable, VelocityInboundConnection { private static final int MAX_PLUGIN_CHANNELS = 1024; - private static final PlainTextComponentSerializer PASS_THRU_TRANSLATE = PlainTextComponentSerializer.builder() - .flattener(ComponentFlattener.basic().toBuilder() - .mapper(KeybindComponent.class, c -> "") - .mapper(TranslatableComponent.class, TranslatableComponent::key) - .build()) - .build(); + private static final PlainTextComponentSerializer PASS_THRU_TRANSLATE = + PlainTextComponentSerializer.builder() + .flattener(ComponentFlattener.basic().toBuilder() + .mapper(KeybindComponent.class, c -> "") + .mapper(TranslatableComponent.class, TranslatableComponent::key) + .build()) + .build(); static final PermissionProvider DEFAULT_PERMISSIONS = s -> PermissionFunction.ALWAYS_UNDEFINED; private static final Logger logger = LogManager.getLogger(ConnectedPlayer.class); @@ -173,7 +177,8 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, private final ChatBuilderFactory chatBuilderFactory; ConnectedPlayer(VelocityServer server, GameProfile profile, MinecraftConnection connection, - @Nullable InetSocketAddress virtualHost, boolean onlineMode, @Nullable IdentifiedKey playerKey) { + @Nullable InetSocketAddress virtualHost, boolean onlineMode, + @Nullable IdentifiedKey playerKey) { this.server = server; this.profile = profile; this.connection = connection; @@ -344,7 +349,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, @Override public void sendMessage(@NonNull Identity identity, @NonNull Component message, - @NonNull MessageType type) { + @NonNull MessageType type) { Preconditions.checkNotNull(message, "message"); Preconditions.checkNotNull(type, "type"); @@ -516,7 +521,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } private ConnectionRequestBuilder createConnectionRequest(RegisteredServer server, - @Nullable VelocityServerConnection previousConnection) { + @Nullable VelocityServerConnection previousConnection) { return new ConnectionRequestBuilderImpl(server, previousConnection); } @@ -585,7 +590,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, * @param safe whether or not we can safely reconnect to a new server */ public void handleConnectionException(RegisteredServer server, Throwable throwable, - boolean safe) { + boolean safe) { if (!isActive()) { // If the connection is no longer active, it makes no sense to try and recover it. return; @@ -624,7 +629,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, * @param safe whether or not we can safely reconnect to a new server */ public void handleConnectionException(RegisteredServer server, Disconnect disconnect, - boolean safe) { + boolean safe) { if (!isActive()) { // If the connection is no longer active, it makes no sense to try and recover it. return; @@ -650,7 +655,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } private void handleConnectionException(RegisteredServer rs, - @Nullable Component kickReason, Component friendlyReason, boolean safe) { + @Nullable Component kickReason, Component friendlyReason, boolean safe) { if (!isActive()) { // If the connection is no longer active, it makes no sense to try and recover it. return; @@ -683,7 +688,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } private void handleKickEvent(KickedFromServerEvent originalEvent, Component friendlyReason, - boolean kickedFromCurrent) { + boolean kickedFromCurrent) { server.getEventManager().fire(originalEvent) .thenAcceptAsync(event -> { // There can't be any connection in flight now. @@ -890,8 +895,10 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, @Override public String toString() { - boolean isPlayerAddressLoggingEnabled = server.getConfiguration().isPlayerAddressLoggingEnabled(); - String playerIp = isPlayerAddressLoggingEnabled ? getRemoteAddress().toString() : ""; + boolean isPlayerAddressLoggingEnabled = server.getConfiguration() + .isPlayerAddressLoggingEnabled(); + String playerIp = + isPlayerAddressLoggingEnabled ? getRemoteAddress().toString() : ""; return "[connected player] " + profile.getName() + " (" + playerIp + ")"; } @@ -956,8 +963,8 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } /** - * Queues a resource-pack for sending to the player and sends it - * immediately if the queue is empty. + * Queues a resource-pack for sending to the player and sends it immediately if the queue is + * empty. */ public void queueResourcePack(ResourcePackInfo info) { outstandingResourcePacks.add(info); @@ -1061,9 +1068,8 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } /** - * Sends a {@link KeepAlive} packet to the player with a random ID. - * The response will be ignored by Velocity as it will not match the - * ID last sent by the server. + * Sends a {@link KeepAlive} packet to the player with a random ID. The response will be ignored + * by Velocity as it will not match the ID last sent by the server. */ public void sendKeepAlive() { if (connection.getState() == StateRegistry.PLAY) { @@ -1074,9 +1080,8 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } /** - * Gets the current "phase" of the connection, mostly used for tracking - * modded negotiation for legacy forge servers and provides methods - * for performing phase specific actions. + * Gets the current "phase" of the connection, mostly used for tracking modded negotiation for + * legacy forge servers and provides methods for performing phase specific actions. * * @return The {@link ClientConnectionPhase} */ @@ -1108,6 +1113,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, } private class IdentityImpl implements Identity { + @Override public @NonNull UUID uuid() { return ConnectedPlayer.this.getUniqueId(); @@ -1120,7 +1126,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player, private final @Nullable VelocityRegisteredServer previousServer; ConnectionRequestBuilderImpl(RegisteredServer toConnect, - @Nullable VelocityServerConnection previousConnection) { + @Nullable VelocityServerConnection previousConnection) { this.toConnect = Preconditions.checkNotNull(toConnect, "info"); this.previousServer = previousConnection == null ? null : previousConnection.getServer(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java index 0d578a4f1..9405bf0dd 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java @@ -46,6 +46,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * The initial handler used when a connection is established to the proxy. This will either + * transition to {@link StatusSessionHandler} or {@link InitialLoginSessionHandler} as soon + * as the handshake packet is received. + */ public class HandshakeSessionHandler implements MinecraftSessionHandler { private static final Logger LOGGER = LogManager.getLogger(HandshakeSessionHandler.class); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialConnectSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialConnectSessionHandler.java index 8dcc5c041..e208701c8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialConnectSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialConnectSessionHandler.java @@ -23,6 +23,10 @@ import com.velocitypowered.proxy.connection.backend.VelocityServerConnection; import com.velocitypowered.proxy.protocol.packet.PluginMessage; import com.velocitypowered.proxy.protocol.util.PluginMessageUtil; +/** + * Handles the play state between exiting the login phase and establishing the first connection + * to a backend server. + */ public class InitialConnectSessionHandler implements MinecraftSessionHandler { private final ConnectedPlayer player; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialInboundConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialInboundConnection.java index d350c4841..32d89d528 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialInboundConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialInboundConnection.java @@ -34,6 +34,9 @@ import net.kyori.adventure.translation.GlobalTranslator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Implements {@link InboundConnection} for a newly-established connection. + */ public final class InitialInboundConnection implements VelocityInboundConnection, MinecraftConnectionAssociation { @@ -82,6 +85,7 @@ public final class InitialInboundConnection implements VelocityInboundConnection /** * Disconnects the connection from the server. + * * @param reason the reason for disconnecting */ public void disconnect(Component reason) { @@ -96,6 +100,7 @@ public final class InitialInboundConnection implements VelocityInboundConnection /** * Disconnects the connection from the server silently. + * * @param reason the reason for disconnecting */ public void disconnectQuietly(Component reason) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java index c070d6621..36f8ef4a7 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java @@ -56,11 +56,15 @@ import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.Response; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +/** + * Handles authenticating the player to Mojang's servers. + */ public class InitialLoginSessionHandler implements MinecraftSessionHandler { private static final Logger logger = LogManager.getLogger(InitialLoginSessionHandler.class); private static final String MOJANG_HASJOINED_URL = - System.getProperty("mojang.sessionserver", "https://sessionserver.mojang.com/session/minecraft/hasJoined") + System.getProperty("mojang.sessionserver", + "https://sessionserver.mojang.com/session/minecraft/hasJoined") .concat("?username=%s&serverId=%s"); private final VelocityServer server; @@ -72,12 +76,13 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { private boolean forceKeyAuthentication; InitialLoginSessionHandler(VelocityServer server, MinecraftConnection mcConnection, - LoginInboundConnection inbound) { + LoginInboundConnection inbound) { this.server = Preconditions.checkNotNull(server, "server"); this.mcConnection = Preconditions.checkNotNull(mcConnection, "mcConnection"); this.inbound = Preconditions.checkNotNull(inbound, "inbound"); this.forceKeyAuthentication = System.getProperties().containsKey("auth.forceSecureProfiles") - ? Boolean.getBoolean("auth.forceSecureProfiles") : server.getConfiguration().isForceKeyAuthentication(); + ? Boolean.getBoolean("auth.forceSecureProfiles") + : server.getConfiguration().isForceKeyAuthentication(); } @Override @@ -87,13 +92,14 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { IdentifiedKey playerKey = packet.getPlayerKey(); if (playerKey != null) { if (playerKey.hasExpired()) { - inbound.disconnect(Component.translatable("multiplayer.disconnect.invalid_public_key_signature")); + inbound.disconnect( + Component.translatable("multiplayer.disconnect.invalid_public_key_signature")); return true; } boolean isKeyValid; if (playerKey.getKeyRevision() == IdentifiedKey.Revision.LINKED_V2 - && playerKey instanceof IdentifiedKeyImpl) { + && playerKey instanceof IdentifiedKeyImpl) { IdentifiedKeyImpl keyImpl = (IdentifiedKeyImpl) playerKey; isKeyValid = keyImpl.internalAddHolder(packet.getHolderUuid()); } else { @@ -105,8 +111,8 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { return true; } } else if (mcConnection.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0 - && forceKeyAuthentication - && mcConnection.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) < 0) { + && forceKeyAuthentication + && mcConnection.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_19_3) < 0) { inbound.disconnect(Component.translatable("multiplayer.disconnect.missing_public_key")); return true; } @@ -145,7 +151,7 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { this.currentState = LoginState.ENCRYPTION_REQUEST_SENT; } else { mcConnection.setSessionHandler(new AuthSessionHandler( - server, inbound, GameProfile.forOfflinePlayer(login.getUsername()), false + server, inbound, GameProfile.forOfflinePlayer(login.getUsername()), false )); } }); @@ -182,7 +188,8 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { KeyPair serverKeyPair = server.getServerKeyPair(); if (inbound.getIdentifiedKey() != null) { IdentifiedKey playerKey = inbound.getIdentifiedKey(); - if (!playerKey.verifyDataSignature(packet.getVerifyToken(), verify, Longs.toByteArray(packet.getSalt()))) { + if (!playerKey.verifyDataSignature(packet.getVerifyToken(), verify, + Longs.toByteArray(packet.getSalt()))) { throw new IllegalStateException("Invalid client public signature."); } } else { @@ -226,14 +233,16 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { try { Response profileResponse = hasJoinedResponse.get(); if (profileResponse.getStatusCode() == 200) { - final GameProfile profile = GENERAL_GSON.fromJson(profileResponse.getResponseBody(), GameProfile.class); + 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) { + && inbound.getIdentifiedKey().getKeyRevision() == IdentifiedKey.Revision.LINKED_V2 + && inbound.getIdentifiedKey() instanceof IdentifiedKeyImpl) { IdentifiedKeyImpl key = (IdentifiedKeyImpl) inbound.getIdentifiedKey(); if (!key.internalAddHolder(profile.getId())) { - inbound.disconnect(Component.translatable("multiplayer.disconnect.invalid_public_key")); + inbound.disconnect( + Component.translatable("multiplayer.disconnect.invalid_public_key")); } } // All went well, initialize the session. @@ -289,7 +298,8 @@ public class InitialLoginSessionHandler implements MinecraftSessionHandler { private void assertState(LoginState expectedState) { if (this.currentState != expectedState) { if (MinecraftDecoder.DEBUG) { - logger.error("{} Received an unexpected packet requiring state {}, but we are in {}", inbound, + logger.error("{} Received an unexpected packet requiring state {}, but we are in {}", + inbound, expectedState, this.currentState); } mcConnection.close(true); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginInboundConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginInboundConnection.java index 955e28029..1eb066f7a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginInboundConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/LoginInboundConnection.java @@ -37,6 +37,9 @@ import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import space.vectrix.flare.fastutil.Int2ObjectSyncMap; +/** + * Handles the actual login stage of a player logging in. + */ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifiable { private static final AtomicIntegerFieldUpdater SEQUENCE_UPDATER = @@ -108,6 +111,7 @@ public class LoginInboundConnection implements LoginPhaseConnection, KeyIdentifi /** * Disconnects the connection from the server. + * * @param reason the reason for disconnecting */ public void disconnect(Component reason) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java index 328f9492d..8b9a55044 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java @@ -32,6 +32,9 @@ import io.netty.buffer.ByteBuf; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Handles server list ping packets from a client. + */ public class StatusSessionHandler implements MinecraftSessionHandler { private static final Logger logger = LogManager.getLogger(StatusSessionHandler.class); @@ -66,7 +69,7 @@ public class StatusSessionHandler implements MinecraftSessionHandler { server.getServerListPingHandler().getInitialPing(this.inbound) .thenCompose(ping -> server.getEventManager().fire(new ProxyPingEvent(inbound, ping))) .thenAcceptAsync(event -> connection.closeWith( - LegacyDisconnect.fromServerPing(event.getPing(), packet.getVersion())), + LegacyDisconnect.fromServerPing(event.getPing(), packet.getVersion())), connection.eventLoop()) .exceptionally((ex) -> { logger.error("Exception while handling legacy ping {}", packet, ex); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeConstants.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeConstants.java index 7dff8855a..9a83cc223 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeConstants.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeConstants.java @@ -23,9 +23,8 @@ package com.velocitypowered.proxy.connection.forge.legacy; public class LegacyForgeConstants { /** - * Clients attempting to connect to 1.8-1.12.2 Forge servers will have - * this token appended to the hostname in the initial handshake - * packet. + * Clients attempting to connect to 1.8-1.12.2 Forge servers will have this token appended to the + * hostname in the initial handshake packet. */ public static final String HANDSHAKE_HOSTNAME_TOKEN = "\0FML\0"; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeBackendPhase.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeBackendPhase.java index ed4350111..dfb7f10f0 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeBackendPhase.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeBackendPhase.java @@ -27,13 +27,13 @@ import com.velocitypowered.proxy.protocol.packet.PluginMessage; import javax.annotation.Nullable; /** - * Allows for simple tracking of the phase that the Legacy - * Forge handshake is in (server side). + * Allows for simple tracking of the phase that the Legacy Forge handshake is in (server side). */ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { /** - * Indicates that the handshake has not started, used for {@link BackendConnectionPhases#UNKNOWN}. + * Indicates that the handshake has not started, used for + * {@link BackendConnectionPhases#UNKNOWN}. */ NOT_STARTED(LegacyForgeConstants.SERVER_HELLO_DISCRIMINATOR) { @Override @@ -43,8 +43,7 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { }, /** - * Sent a hello to the client, waiting for a hello back before sending - * the mod list. + * Sent a hello to the client, waiting for a hello back before sending the mod list. */ HELLO(LegacyForgeConstants.MOD_LIST_DISCRIMINATOR) { @Override @@ -65,8 +64,8 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { }, /** - * The mod list from the client has been accepted and a server mod list - * has been sent. Waiting for the client to acknowledge. + * The mod list from the client has been accepted and a server mod list has been sent. Waiting for + * the client to acknowledge. */ SENT_MOD_LIST(LegacyForgeConstants.REGISTRY_DISCRIMINATOR) { @Override @@ -76,8 +75,8 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { }, /** - * The server data is being sent or has been sent, and is waiting for - * the client to acknowledge it has processed this. + * The server data is being sent or has been sent, and is waiting for the client to acknowledge it + * has processed this. */ SENT_SERVER_DATA(LegacyForgeConstants.ACK_DISCRIMINATOR) { @Override @@ -106,16 +105,16 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { } }; - @Nullable private final Integer packetToAdvanceOn; + @Nullable + private final Integer packetToAdvanceOn; /** * Creates an instance of the {@link LegacyForgeHandshakeBackendPhase}. * - * @param packetToAdvanceOn The ID of the packet discriminator that indicates - * that the server has moved onto a new phase, and - * as such, Velocity should do so too (inspecting - * {@link #nextPhase()}. A null indicates there is no - * further phase to transition to. + * @param packetToAdvanceOn The ID of the packet discriminator that indicates that the server has + * moved onto a new phase, and as such, Velocity should do so too + * (inspecting {@link #nextPhase()}. A null indicates there is no further + * phase to transition to. */ LegacyForgeHandshakeBackendPhase(@Nullable Integer packetToAdvanceOn) { this.packetToAdvanceOn = packetToAdvanceOn; @@ -123,8 +122,8 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { @Override public final boolean handle(VelocityServerConnection serverConnection, - ConnectedPlayer player, - PluginMessage message) { + ConnectedPlayer player, + PluginMessage message) { if (message.getChannel().equals(LegacyForgeConstants.FORGE_LEGACY_HANDSHAKE_CHANNEL)) { // Get the phase and check if we need to start the next phase. LegacyForgeHandshakeBackendPhase newPhase = getNewPhase(serverConnection, message); @@ -148,7 +147,7 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { @Override public void onDepartForNewServer(VelocityServerConnection serverConnection, - ConnectedPlayer player) { + ConnectedPlayer player) { // If the server we are departing is modded, we must always reset the client's handshake. player.getPhase().resetConnectionPhase(player); } @@ -162,8 +161,7 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { } /** - * Gets the next phase, if any (will return self if we are at the end - * of the handshake). + * Gets the next phase, if any (will return self if we are at the end of the handshake). * * @return The next phase */ @@ -175,11 +173,11 @@ public enum LegacyForgeHandshakeBackendPhase implements BackendConnectionPhase { * Get the phase to act on, depending on the packet that has been sent. * * @param serverConnection The server Velocity is connecting to - * @param packet The packet + * @param packet The packet * @return The phase to transition to, which may be the same as before. */ private LegacyForgeHandshakeBackendPhase getNewPhase(VelocityServerConnection serverConnection, - PluginMessage packet) { + PluginMessage packet) { if (packetToAdvanceOn != null && LegacyForgeUtil.getHandshakePacketDiscriminator(packet) == packetToAdvanceOn) { LegacyForgeHandshakeBackendPhase phaseToTransitionTo = nextPhase(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeClientPhase.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeClientPhase.java index 3bb1510fe..6e8fcf907 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeClientPhase.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeHandshakeClientPhase.java @@ -34,8 +34,8 @@ import javax.annotation.Nullable; public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { /** - * No handshake packets have yet been sent. Transition to {@link #HELLO} when the ClientHello - * is sent. + * No handshake packets have yet been sent. Transition to {@link #HELLO} when the ClientHello is + * sent. */ NOT_STARTED(LegacyForgeConstants.CLIENT_HELLO_DISCRIMINATOR) { @Override @@ -75,12 +75,10 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { } }, - - /** - * The Mod list is sent to the server, captured by Velocity. - * Transition to {@link #WAITING_SERVER_DATA} when an ACK is sent, which - * indicates to the server to start sending state data. + * The Mod list is sent to the server, captured by Velocity. Transition to + * {@link #WAITING_SERVER_DATA} when an ACK is sent, which indicates to the server to start + * sending state data. */ MOD_LIST(LegacyForgeConstants.ACK_DISCRIMINATOR) { @Override @@ -105,9 +103,8 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { }, /** - * Waiting for state data to be received. - * Transition to {@link #WAITING_SERVER_COMPLETE} when this is complete - * and the client sends an ACK packet to confirm + * Waiting for state data to be received. Transition to {@link #WAITING_SERVER_COMPLETE} when this + * is complete and the client sends an ACK packet to confirm */ WAITING_SERVER_DATA(LegacyForgeConstants.ACK_DISCRIMINATOR) { @Override @@ -117,9 +114,8 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { }, /** - * Waiting on the server to send another ACK. - * Transition to {@link #PENDING_COMPLETE} when client sends another - * ACK + * Waiting on the server to send another ACK. Transition to {@link #PENDING_COMPLETE} when client + * sends another ACK */ WAITING_SERVER_COMPLETE(LegacyForgeConstants.ACK_DISCRIMINATOR) { @Override @@ -129,9 +125,8 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { }, /** - * Waiting on the server to send yet another ACK. - * Transition to {@link #COMPLETE} when client sends another - * ACK + * Waiting on the server to send yet another ACK. Transition to {@link #COMPLETE} when client + * sends another ACK */ PENDING_COMPLETE(LegacyForgeConstants.ACK_DISCRIMINATOR) { @Override @@ -144,11 +139,10 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { * The handshake is complete. The handshake can be reset. * *

Note that a successful connection to a server does not mean that - * we will be in this state. After a handshake reset, if the next server - * is vanilla we will still be in the {@link #NOT_STARTED} phase, - * which means we must NOT send a reset packet. This is handled by - * overriding the {@link #resetConnectionPhase(ConnectedPlayer)} in this - * element (it is usually a no-op).

+ * we will be in this state. After a handshake reset, if the next server is vanilla we will still + * be in the {@link #NOT_STARTED} phase, which means we must NOT send a reset packet. This is + * handled by overriding the {@link #resetConnectionPhase(ConnectedPlayer)} in this element (it is + * usually a no-op).

*/ COMPLETE(null) { @Override @@ -180,16 +174,16 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { } }; - @Nullable private final Integer packetToAdvanceOn; + @Nullable + private final Integer packetToAdvanceOn; /** * Creates an instance of the {@link LegacyForgeHandshakeClientPhase}. * - * @param packetToAdvanceOn The ID of the packet discriminator that indicates - * that the client has moved onto a new phase, and - * as such, Velocity should do so too (inspecting - * {@link #nextPhase()}. A null indicates there is no - * further phase to transition to. + * @param packetToAdvanceOn The ID of the packet discriminator that indicates that the client has + * moved onto a new phase, and as such, Velocity should do so too + * (inspecting {@link #nextPhase()}. A null indicates there is no further + * phase to transition to. */ LegacyForgeHandshakeClientPhase(Integer packetToAdvanceOn) { this.packetToAdvanceOn = packetToAdvanceOn; @@ -221,10 +215,9 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { /** * Handles the phase tasks. * - * @param player The player - * @param message The message to handle + * @param player The player + * @param message The message to handle * @param backendConn The backend connection to write to, if required. - * * @return true if handled, false otherwise. */ boolean onHandle(ConnectedPlayer player, @@ -243,8 +236,7 @@ public enum LegacyForgeHandshakeClientPhase implements ClientConnectionPhase { } /** - * Gets the next phase, if any (will return self if we are at the end - * of the handshake). + * Gets the next phase, if any (will return self if we are at the end of the handshake). * * @return The next phase */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeUtil.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeUtil.java index f541c789e..8b0bd4b9a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeUtil.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/legacy/LegacyForgeUtil.java @@ -57,7 +57,7 @@ class LegacyForgeUtil { static List readModList(PluginMessage message) { Preconditions.checkNotNull(message, "message"); Preconditions.checkArgument(message.getChannel().equals(FORGE_LEGACY_HANDSHAKE_CHANNEL), - "message is not a FML HS plugin message"); + "message is not a FML HS plugin message"); ByteBuf contents = message.content().slice(); byte discriminator = contents.readByte(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/player/VelocityResourcePackInfo.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/player/VelocityResourcePackInfo.java index 743bba876..df60e0bca 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/player/VelocityResourcePackInfo.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/player/VelocityResourcePackInfo.java @@ -22,7 +22,11 @@ import com.velocitypowered.api.proxy.player.ResourcePackInfo; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Implements {@link ResourcePackInfo}. + */ public final class VelocityResourcePackInfo implements ResourcePackInfo { + private final String url; private final @Nullable byte[] hash; private final boolean shouldForce; @@ -31,7 +35,7 @@ public final class VelocityResourcePackInfo implements ResourcePackInfo { private Origin originalOrigin; private VelocityResourcePackInfo(String url, @Nullable byte[] hash, boolean shouldForce, - @Nullable Component prompt, Origin origin) { + @Nullable Component prompt, Origin origin) { this.url = url; this.hash = hash; this.shouldForce = shouldForce; @@ -77,20 +81,24 @@ public final class VelocityResourcePackInfo implements ResourcePackInfo { @Override public Builder asBuilder() { return new BuilderImpl(url) - .setShouldForce(shouldForce) - .setHash(hash) - .setPrompt(prompt); + .setShouldForce(shouldForce) + .setHash(hash) + .setPrompt(prompt); } @Override public Builder asBuilder(String newUrl) { return new BuilderImpl(newUrl) - .setShouldForce(shouldForce) - .setHash(hash) - .setPrompt(prompt); + .setShouldForce(shouldForce) + .setHash(hash) + .setPrompt(prompt); } + /** + * Implements the builder for {@link ResourcePackInfo} instances. + */ public static final class BuilderImpl implements ResourcePackInfo.Builder { + private final String url; private boolean shouldForce; private @Nullable byte[] hash; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/ChatData.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/ChatData.java deleted file mode 100644 index bb09edcad..000000000 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/ChatData.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2018 Velocity Contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.velocitypowered.proxy.connection.registry; - -/* -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import net.kyori.adventure.nbt.*; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; -import net.kyori.adventure.text.format.TextFormat; -import net.kyori.adventure.translation.Translatable; -import org.jetbrains.annotations.NotNull; - -import java.util.List; -*/ - -// TODO Implement -public class ChatData { - /* - private static final ListBinaryTag EMPTY_LIST_TAG = ListBinaryTag.empty(); - - - private final String identifier; - private final int id; - private final Map<> - - - public static class Decoration implements Translatable { - - private final List parameters; - private final List style; - private final String translationKey; - - public List getParameters() { - return parameters; - } - - public List getStyle() { - return style; - } - - @Override - public @NotNull String translationKey() { - return translationKey; - } - - public Decoration(List parameters, List style, String translationKey) { - this.parameters = Preconditions.checkNotNull(parameters); - this.style = Preconditions.checkNotNull(style); - this.translationKey = Preconditions.checkNotNull(translationKey); - Preconditions.checkArgument(translationKey.length() > 0); - } - - public static Decoration decodeRegistryEntry(CompoundBinaryTag toDecode) { - ImmutableList.Builder parameters = ImmutableList.builder(); - ListBinaryTag paramList = toDecode.getList("parameters", EMPTY_LIST_TAG); - if (paramList != EMPTY_LIST_TAG) { - paramList.forEach(binaryTag -> parameters.add(binaryTag.toString())); - } - - ImmutableList.Builder style = ImmutableList.builder(); - CompoundBinaryTag styleList = toDecode.getCompound("style"); - for (String key : styleList.keySet()) { - if ("color".equals(key)) { - NamedTextColor color = Preconditions.checkNotNull( - NamedTextColor.NAMES.value(styleList.getString(key))); - style.add(color); - } else { - // Key is a Style option instead - TextDecoration deco = TextDecoration.NAMES.value(key); - // This wouldn't be here if it wasn't applied, but here it goes anyway: - byte val = styleList.getByte(key); - if (val != 0) { - style.add(deco); - } - } - } - - String translationKey = toDecode.getString("translation_key"); - - return new Decoration(parameters.build(), style.build(), translationKey); - } - - public void encodeRegistryEntry(CompoundBinaryTag ) - - } - - public static enum Priority { - SYSTEM, - CHAT - } -*/ -} diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionData.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionData.java index 398c024d4..007b58a6a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionData.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionData.java @@ -22,7 +22,11 @@ import com.velocitypowered.api.network.ProtocolVersion; import net.kyori.adventure.nbt.CompoundBinaryTag; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents a dimension sent to the client by the server. + */ public final class DimensionData { + private static final String UNKNOWN_DIMENSION_ID = "velocity:unknown_dimension"; private final String registryIdentifier; @@ -53,41 +57,50 @@ public final class DimensionData { * * @param registryIdentifier the identifier for the dimension from the registry. * @param dimensionId the dimension ID contained in the registry (the "id" tag) - * @param isNatural indicates if the dimension use natural world generation (e.g. overworld) + * @param isNatural indicates if the dimension use natural world generation + * (e.g. overworld) * @param ambientLight the light level the client sees without external lighting - * @param isShrunk indicates if the world is shrunk, aka not the full 256 blocks (e.g. nether) + * @param isShrunk indicates if the world is shrunk, aka not the full 256 + * blocks (e.g. nether) * @param isUltrawarm internal dimension warmth flag * @param hasCeiling indicates if the dimension has a ceiling layer * @param hasSkylight indicates if the dimension should display the sun - * @param isPiglinSafe indicates if piglins should naturally zombify in this dimension - * @param doBedsWork indicates if players should be able to sleep in beds in this dimension - * @param doRespawnAnchorsWork indicates if player respawn points can be used in this dimension + * @param isPiglinSafe indicates if piglins should naturally zombify in this + * dimension + * @param doBedsWork indicates if players should be able to sleep in beds in this + * dimension + * @param doRespawnAnchorsWork indicates if player respawn points can be used in this + * dimension * @param hasRaids indicates if raids can be spawned in the dimension * @param logicalHeight the natural max height for the given dimension * @param burningBehaviourIdentifier the identifier for how burning blocks work in the dimension - * @param fixedTime optional. If set to any game daytime value will deactivate time cycle + * @param fixedTime optional. If set to any game daytime value will deactivate + * time cycle * @param createDragonFight optional. Internal flag used in the end dimension * @param coordinateScale optional, unknown purpose * @param effects optional, unknown purpose * @param minY the world effective lowest build-level * @param height the world height above zero - * @param monsterSpawnBlockLightLimit an integer controlling the block light needed to prevent monster spawns. - * @param monsterSpawnLightLevel an int provider which is evaluated to find a value to compare the current - * overall brightness with to determine if a monster should be allowed to spawn. + * @param monsterSpawnBlockLightLimit an integer controlling the block light needed to prevent + * monster spawns. + * @param monsterSpawnLightLevel an int provider which is evaluated to find a value to + * compare the current overall brightness with to determine if + * a monster should be allowed to spawn. */ public DimensionData(String registryIdentifier, - @Nullable Integer dimensionId, - boolean isNatural, - float ambientLight, boolean isShrunk, boolean isUltrawarm, - boolean hasCeiling, boolean hasSkylight, - boolean isPiglinSafe, boolean doBedsWork, - boolean doRespawnAnchorsWork, boolean hasRaids, - int logicalHeight, String burningBehaviourIdentifier, - @Nullable Long fixedTime, @Nullable Boolean createDragonFight, - @Nullable Double coordinateScale, - @Nullable String effects, - @Nullable Integer minY, @Nullable Integer height, @Nullable Integer monsterSpawnBlockLightLimit, - @Nullable Integer monsterSpawnLightLevel) { + @Nullable Integer dimensionId, + boolean isNatural, + float ambientLight, boolean isShrunk, boolean isUltrawarm, + boolean hasCeiling, boolean hasSkylight, + boolean isPiglinSafe, boolean doBedsWork, + boolean doRespawnAnchorsWork, boolean hasRaids, + int logicalHeight, String burningBehaviourIdentifier, + @Nullable Long fixedTime, @Nullable Boolean createDragonFight, + @Nullable Double coordinateScale, + @Nullable String effects, + @Nullable Integer minY, @Nullable Integer height, + @Nullable Integer monsterSpawnBlockLightLimit, + @Nullable Integer monsterSpawnLightLevel) { this.monsterSpawnBlockLightLimit = monsterSpawnBlockLightLimit; this.monsterSpawnLightLevel = monsterSpawnLightLevel; Preconditions.checkNotNull( @@ -198,19 +211,20 @@ public final class DimensionData { } /** - * Returns a fresh {@link DimensionData} with the specified {@code registryIdentifier} - * and {@code dimensionId}. + * Returns a fresh {@link DimensionData} with the specified {@code registryIdentifier} and + * {@code dimensionId}. * * @param registryIdentifier the identifier for the dimension from the registry * @param dimensionId optional, dimension ID * @return a new {@link DimensionData} */ public DimensionData annotateWith(String registryIdentifier, - @Nullable Integer dimensionId) { + @Nullable Integer dimensionId) { return new DimensionData(registryIdentifier, dimensionId, isNatural, ambientLight, isShrunk, isUltrawarm, hasCeiling, hasSkylight, isPiglinSafe, doBedsWork, doRespawnAnchorsWork, hasRaids, logicalHeight, burningBehaviourIdentifier, fixedTime, createDragonFight, - coordinateScale, effects, minY, height, monsterSpawnBlockLightLimit, monsterSpawnLightLevel); + coordinateScale, effects, minY, height, monsterSpawnBlockLightLimit, + monsterSpawnLightLevel); } public boolean isUnannotated() { @@ -226,7 +240,7 @@ public final class DimensionData { * @return game dimension data */ public static DimensionData decodeBaseCompoundTag(CompoundBinaryTag details, - ProtocolVersion version) { + ProtocolVersion version) { boolean isNatural = details.getBoolean("natural"); float ambientLight = details.getFloat("ambient_light"); boolean isShrunk = details.getBoolean("shrunk"); @@ -249,10 +263,12 @@ public final class DimensionData { : null; Integer minY = details.keySet().contains("min_y") ? details.getInt("min_y") : null; Integer height = details.keySet().contains("height") ? details.getInt("height") : null; - Integer monsterSpawnBlockLightLimit = details.keySet().contains("monster_spawn_block_light_limit") - ? details.getInt("monster_spawn_block_light_limit") : null; + Integer monsterSpawnBlockLightLimit = + details.keySet().contains("monster_spawn_block_light_limit") + ? details.getInt("monster_spawn_block_light_limit") : null; Integer monsterSpawnLightLevel = - details.keySet().contains("monster_spawn_light_level") ? details.getInt("monster_spawn_block_light_limit") : + details.keySet().contains("monster_spawn_light_level") ? details.getInt( + "monster_spawn_block_light_limit") : null; if (version.compareTo(ProtocolVersion.MINECRAFT_1_17) >= 0) { Preconditions.checkNotNull(height, @@ -262,27 +278,30 @@ public final class DimensionData { } if (version.compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0) { Preconditions.checkNotNull(monsterSpawnBlockLightLimit, - "DimensionData requires 'monster_spawn_block_light_limit' to be present for this version."); + "DimensionData requires 'monster_spawn_block_light_limit' to be present" + + " for this version."); Preconditions.checkNotNull(monsterSpawnLightLevel, - "DimensionData requires 'monster_spawn_light_level' to be present for this version."); + "DimensionData requires 'monster_spawn_light_level' to be present" + + " for this version."); } return new DimensionData( UNKNOWN_DIMENSION_ID, null, isNatural, ambientLight, isShrunk, isUltrawarm, hasCeiling, hasSkylight, isPiglinSafe, doBedsWork, doRespawnAnchorsWork, hasRaids, logicalHeight, burningBehaviourIdentifier, fixedTime, hasEnderdragonFight, - coordinateScale, effects, minY, height, monsterSpawnBlockLightLimit, monsterSpawnLightLevel); + coordinateScale, effects, minY, height, monsterSpawnBlockLightLimit, + monsterSpawnLightLevel); } /** - * Parses a given CompoundTag to a DimensionData instance. Assumes the data is part of a - * dimension registry. + * Parses a given CompoundTag to a DimensionData instance. Assumes the data is part of a dimension + * registry. * * @param dimTag the compound from the registry to read * @param version the protocol version * @return game dimension data */ public static DimensionData decodeRegistryEntry(CompoundBinaryTag dimTag, - ProtocolVersion version) { + ProtocolVersion version) { String registryIdentifier = dimTag.getString("name"); CompoundBinaryTag details; Integer dimensionId = null; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionInfo.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionInfo.java index 8c7abd8cf..0f7e261ed 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionInfo.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionInfo.java @@ -20,6 +20,9 @@ package com.velocitypowered.proxy.connection.registry; import com.google.common.base.Preconditions; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents basic information for a Minecraft dimension. + */ public final class DimensionInfo { private final String registryIdentifier; @@ -29,10 +32,12 @@ public final class DimensionInfo { /** * Initializes a new {@link DimensionInfo} instance. + * * @param registryIdentifier the identifier for the dimension from the registry - * @param levelName the level name as displayed in the F3 menu and logs - * @param isFlat if true will set world lighting below surface-level to not display fog - * @param isDebugType if true constrains the world to the very limited debug-type world + * @param levelName the level name as displayed in the F3 menu and logs + * @param isFlat if true will set world lighting below surface-level to not display + * fog + * @param isDebugType if true constrains the world to the very limited debug-type world */ public DimensionInfo(String registryIdentifier, @Nullable String levelName, boolean isFlat, boolean isDebugType) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionRegistry.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionRegistry.java index 28c4c84c5..a9d1e8f36 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionRegistry.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/registry/DimensionRegistry.java @@ -29,21 +29,24 @@ import net.kyori.adventure.nbt.CompoundBinaryTag; import net.kyori.adventure.nbt.ListBinaryTag; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents a registry of dimensions sent to the client by the server. + */ public final class DimensionRegistry { private final Map registeredDimensions; private final ImmutableSet levelNames; /** - * Initializes a new {@link DimensionRegistry} instance. - * This registry is required for 1.16+ clients/servers to communicate, - * it constrains the dimension types and names the client can be sent - * in a Respawn action (dimension change). - * This WILL raise an IllegalArgumentException if the following is not met: - * - At least one valid DimensionData instance is provided - * - At least one valid world name is provided + * Initializes a new {@link DimensionRegistry} instance. This registry is required for 1.16+ + * clients/servers to communicate, it constrains the dimension types and names the client can be + * sent in a Respawn action (dimension change). This WILL raise an IllegalArgumentException if the + * following is not met: - At least one valid DimensionData instance is provided - At least one + * valid world name is provided + * * @param registeredDimensions a populated {@link ImmutableSet} containing dimension data types - * @param levelNames a populated {@link ImmutableSet} of the level (world) names the server offers + * @param levelNames a populated {@link ImmutableSet} of the level (world) names the + * server offers */ public DimensionRegistry(ImmutableSet registeredDimensions, ImmutableSet levelNames) { @@ -70,6 +73,7 @@ public final class DimensionRegistry { /** * Returns the internal dimension data type as used by the game. + * * @param dimensionIdentifier how the dimension is identified by the connection * @return game dimension data or null if not registered */ @@ -79,6 +83,7 @@ public final class DimensionRegistry { /** * Checks a {@link DimensionInfo} against this registry. + * * @param toValidate the {@link DimensionInfo} to validate * @return true: the dimension information is valid for this registry */ @@ -92,6 +97,7 @@ public final class DimensionRegistry { /** * Encodes the stored Dimension registry as CompoundTag. + * * @return the CompoundTag containing identifier:type mappings */ public ListBinaryTag encodeRegistry(ProtocolVersion version) { @@ -105,6 +111,7 @@ public final class DimensionRegistry { /** * Decodes a CompoundTag storing a dimension registry. + * * @param toParse CompoundTag containing a dimension registry */ public static ImmutableSet fromGameData(ListBinaryTag toParse, diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionMessages.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionMessages.java index 5e29672ce..7bf315b7a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionMessages.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionMessages.java @@ -22,6 +22,9 @@ import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.format.NamedTextColor; +/** + * Common messages that might be sent a client for various connection-related states. + */ public class ConnectionMessages { public static final TranslatableComponent ALREADY_CONNECTED = Component diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java index 9c8dbd5ce..40df1006b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java @@ -26,6 +26,9 @@ import javax.annotation.Nullable; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +/** + * Common connection request results. + */ public class ConnectionRequestResults { private ConnectionRequestResults() { @@ -38,6 +41,7 @@ public class ConnectionRequestResults { /** * Returns a plain result (one with a status but no reason). + * * @param status the status to use * @param server the server to use * @return the result @@ -50,8 +54,9 @@ public class ConnectionRequestResults { /** * Returns a disconnect result with a reason. + * * @param component the reason for disconnecting from the server - * @param server the server to use + * @param server the server to use * @return the result */ public static Impl forDisconnect(Component component, RegisteredServer server) { @@ -68,6 +73,9 @@ public class ConnectionRequestResults { return new Impl(Status.SERVER_DISCONNECTED, deserialized, server, false); } + /** + * Base implementation. + */ public static class Impl implements ConnectionRequestBuilder.Result { private final Status status; @@ -100,6 +108,7 @@ public class ConnectionRequestResults { /** * Returns whether or not it is safe to attempt a reconnect. + * * @return whether we can try to reconnect */ public boolean isSafe() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionTypeImpl.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionTypeImpl.java index 38735283b..944b3f37a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionTypeImpl.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionTypeImpl.java @@ -32,7 +32,7 @@ public class ConnectionTypeImpl implements ConnectionType { private final BackendConnectionPhase initialBackendPhase; public ConnectionTypeImpl(ClientConnectionPhase initialClientPhase, - BackendConnectionPhase initialBackendPhase) { + BackendConnectionPhase initialBackendPhase) { this.initialClientPhase = initialClientPhase; this.initialBackendPhase = initialBackendPhase; } @@ -49,7 +49,7 @@ public class ConnectionTypeImpl implements ConnectionType { @Override public GameProfile addGameProfileTokensIfRequired(GameProfile original, - PlayerInfoForwarding forwardingType) { + PlayerInfoForwarding forwardingType) { return original; } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java index 6bc29e5ca..6ed0ad69f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java @@ -34,6 +34,9 @@ import java.util.Locale; import java.util.Optional; import java.util.concurrent.CompletableFuture; +/** + * Common utilities for handling server list ping results. + */ public class ServerListPingHandler { private final VelocityServer server; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/VelocityInboundConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/VelocityInboundConnection.java index 8cde57bd1..a24a97ed7 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/VelocityInboundConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/VelocityInboundConnection.java @@ -20,6 +20,10 @@ package com.velocitypowered.proxy.connection.util; import com.velocitypowered.api.proxy.InboundConnection; import com.velocitypowered.proxy.connection.MinecraftConnection; +/** + * Base internal interface for a {@link InboundConnection}. + */ public interface VelocityInboundConnection extends InboundConnection { + MinecraftConnection getConnection(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java b/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java index 2a72c6848..aa24fe5a8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java @@ -48,6 +48,10 @@ import org.jline.reader.Candidate; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; +/** + * Implements the Velocity console, including sending commands and being the recipient + * of messages from plugins. + */ public final class VelocityConsole extends SimpleTerminalConsole implements ConsoleCommandSource { private static final Logger logger = LogManager.getLogger(VelocityConsole.class); @@ -55,18 +59,19 @@ public final class VelocityConsole extends SimpleTerminalConsole implements Cons private final VelocityServer server; private PermissionFunction permissionFunction = ALWAYS_TRUE; private final @NotNull Pointers pointers = ConsoleCommandSource.super.pointers().toBuilder() - .withDynamic(PermissionChecker.POINTER, this::getPermissionChecker) - .withDynamic(Identity.LOCALE, () -> ClosestLocaleMatcher.INSTANCE - .lookupClosest(Locale.getDefault())) - .withStatic(FacetPointers.TYPE, Type.CONSOLE) - .build(); + .withDynamic(PermissionChecker.POINTER, this::getPermissionChecker) + .withDynamic(Identity.LOCALE, () -> ClosestLocaleMatcher.INSTANCE + .lookupClosest(Locale.getDefault())) + .withStatic(FacetPointers.TYPE, Type.CONSOLE) + .build(); public VelocityConsole(VelocityServer server) { this.server = server; } @Override - public void sendMessage(@NonNull Identity identity, @NonNull Component message, @NonNull MessageType messageType) { + public void sendMessage(@NonNull Identity identity, @NonNull Component message, + @NonNull MessageType messageType) { Component translated = GlobalTranslator.render(message, ClosestLocaleMatcher.INSTANCE .lookupClosest(Locale.getDefault())); logger.info(LegacyComponentSerializer.legacySection().serialize(translated)); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/crypto/EncryptionUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/crypto/EncryptionUtils.java index 7c9636239..7d4ea6e5d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/crypto/EncryptionUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/crypto/EncryptionUtils.java @@ -41,27 +41,30 @@ import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import javax.crypto.Cipher; +/** + * Generic utilities for dealing with encryption operations in Minecraft. + */ public enum EncryptionUtils { ; public static final Pair PEM_RSA_PUBLIC_KEY_DESCRIPTOR = - Pair.of("-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----"); + Pair.of("-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----"); public static final Pair PEM_RSA_PRIVATE_KEY_DESCRIPTOR = - Pair.of("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----"); + Pair.of("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----"); public static final String SHA1_WITH_RSA = "SHA1withRSA"; public static final String SHA256_WITH_RSA = "SHA256withRSA"; public static final QuietDecoderException INVALID_SIGNATURE - = new QuietDecoderException("Incorrectly signed chat message"); + = new QuietDecoderException("Incorrectly signed chat message"); public static final QuietDecoderException PREVIEW_SIGNATURE_MISSING - = new QuietDecoderException("Unsigned chat message requested signed preview"); + = new QuietDecoderException("Unsigned chat message requested signed preview"); public static final byte[] EMPTY = new byte[0]; private static PublicKey YGGDRASIL_SESSION_KEY; private static KeyFactory RSA_KEY_FACTORY; private static final Base64.Encoder MIME_SPECIAL_ENCODER - = Base64.getMimeEncoder(76, "\n".getBytes(StandardCharsets.UTF_8)); + = Base64.getMimeEncoder(76, "\n".getBytes(StandardCharsets.UTF_8)); static { try { @@ -72,8 +75,9 @@ public enum EncryptionUtils { try { byte[] bytes = ByteStreams.toByteArray( - EncryptionUtils.class.getClassLoader().getResourceAsStream("yggdrasil_session_pubkey.der")); - YGGDRASIL_SESSION_KEY = parseRsaPublicKey(bytes); + EncryptionUtils.class.getClassLoader() + .getResourceAsStream("yggdrasil_session_pubkey.der")); + YGGDRASIL_SESSION_KEY = parseRsaPublicKey(bytes); } catch (IOException | NullPointerException err) { throw new RuntimeException(err); } @@ -87,12 +91,13 @@ public enum EncryptionUtils { * Verifies a key signature. * * @param algorithm the signature algorithm - * @param base the public key to verify with + * @param base the public key to verify with * @param signature the signature to verify against - * @param toVerify the byte array(s) of data to verify + * @param toVerify the byte array(s) of data to verify * @return validity of the signature */ - public static boolean verifySignature(String algorithm, PublicKey base, byte[] signature, byte[]... toVerify) { + public static boolean verifySignature(String algorithm, PublicKey base, byte[] signature, + byte[]... toVerify) { Preconditions.checkArgument(toVerify.length > 0); try { Signature construct = Signature.getInstance(algorithm); @@ -110,8 +115,8 @@ public enum EncryptionUtils { * Generates a signature for input data. * * @param algorithm the signature algorithm - * @param base the private key to sign with - * @param toSign the byte array(s) of data to sign + * @param base the private key to sign with + * @param toSign the byte array(s) of data to sign * @return the generated signature */ public static byte[] generateSignature(String algorithm, PrivateKey base, byte[]... toSign) { @@ -153,7 +158,7 @@ public enum EncryptionUtils { /** * Parse a cer-encoded RSA key into its key bytes. * - * @param toParse the cer-encoded key String + * @param toParse the cer-encoded key String * @param descriptors the type of key * @return the parsed key bytes */ @@ -184,8 +189,8 @@ public enum EncryptionUtils { } return encoder.first() + "\n" - + encodeUrlEncoded(toEncode.getEncoded()) + "\n" - + encoder.second() + "\n"; + + encodeUrlEncoded(toEncode.getEncoded()) + "\n" + + encoder.second() + "\n"; } /** @@ -232,7 +237,7 @@ public enum EncryptionUtils { * Decrypts an RSA message. * * @param keyPair the key pair to use - * @param bytes the bytes of the encrypted message + * @param bytes the bytes of the encrypted message * @return the decrypted message * @throws GeneralSecurityException if the message couldn't be decoded */ @@ -246,7 +251,7 @@ public enum EncryptionUtils { * Generates the server ID for the hasJoined endpoint. * * @param sharedSecret the shared secret between the client and the proxy - * @param key the RSA public key + * @param key the RSA public key * @return the server ID */ public static String generateServerId(byte[] sharedSecret, PublicKey key) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/crypto/IdentifiedKeyImpl.java b/proxy/src/main/java/com/velocitypowered/proxy/crypto/IdentifiedKeyImpl.java index e70434c3f..983c17122 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/crypto/IdentifiedKeyImpl.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/crypto/IdentifiedKeyImpl.java @@ -30,6 +30,9 @@ import java.util.UUID; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents the contents of a {@link IdentifiedKey}. + */ public class IdentifiedKeyImpl implements IdentifiedKey { private final Revision revision; @@ -40,14 +43,16 @@ public class IdentifiedKeyImpl implements IdentifiedKey { private @MonotonicNonNull UUID holder; public IdentifiedKeyImpl(Revision revision, byte[] keyBits, long expiry, - byte[] signature) { - this(revision, EncryptionUtils.parseRsaPublicKey(keyBits), Instant.ofEpochMilli(expiry), signature); + byte[] signature) { + this(revision, EncryptionUtils.parseRsaPublicKey(keyBits), + Instant.ofEpochMilli(expiry), signature); } /** * Creates an Identified key from data. */ - public IdentifiedKeyImpl(Revision revision, PublicKey publicKey, Instant expiryTemporal, byte[] signature) { + public IdentifiedKeyImpl( + Revision revision, PublicKey publicKey, Instant expiryTemporal, byte[] signature) { this.revision = revision; this.publicKey = publicKey; this.expiryTemporal = expiryTemporal; @@ -85,8 +90,7 @@ public class IdentifiedKeyImpl implements IdentifiedKey { } /** - * Sets the uuid for this key. - * Returns false if incorrect. + * Sets the uuid for this key. Returns false if incorrect. */ public boolean internalAddHolder(UUID holder) { if (holder == null) { @@ -118,7 +122,8 @@ public class IdentifiedKeyImpl implements IdentifiedKey { long expires = expiryTemporal.toEpochMilli(); byte[] toVerify = ("" + expires + pemKey).getBytes(StandardCharsets.US_ASCII); return EncryptionUtils.verifySignature( - EncryptionUtils.SHA1_WITH_RSA, EncryptionUtils.getYggdrasilSessionKey(), signature, toVerify); + EncryptionUtils.SHA1_WITH_RSA, EncryptionUtils.getYggdrasilSessionKey(), signature, + toVerify); } else { if (verify == null) { return null; @@ -131,14 +136,15 @@ public class IdentifiedKeyImpl implements IdentifiedKey { fixedDataSet.putLong(expiryTemporal.toEpochMilli()); fixedDataSet.put(keyBytes); return EncryptionUtils.verifySignature(EncryptionUtils.SHA1_WITH_RSA, - EncryptionUtils.getYggdrasilSessionKey(), signature, toVerify); + EncryptionUtils.getYggdrasilSessionKey(), signature, toVerify); } } @Override public boolean verifyDataSignature(byte[] signature, byte[]... toVerify) { try { - return EncryptionUtils.verifySignature(EncryptionUtils.SHA256_WITH_RSA, publicKey, signature, toVerify); + return EncryptionUtils.verifySignature(EncryptionUtils.SHA256_WITH_RSA, publicKey, signature, + toVerify); } catch (IllegalArgumentException e) { return false; } @@ -164,11 +170,12 @@ public class IdentifiedKeyImpl implements IdentifiedKey { if (!(o instanceof IdentifiedKey)) { return false; } - IdentifiedKey that = (IdentifiedKey) o; // This cannot be simplified because checkstyle doesn't like it. + + 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()); + && Objects.equal(this.getExpiryTemporal(), that.getExpiryTemporal()) + && Arrays.equals(this.getSignature(), that.getSignature()) + && Objects.equal(this.getSigner(), that.getSigner()); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignaturePair.java b/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignaturePair.java index 4f45eb895..6e249275c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignaturePair.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignaturePair.java @@ -15,12 +15,14 @@ * along with this program. If not, see . */ - package com.velocitypowered.proxy.crypto; import java.util.Arrays; import java.util.UUID; +/** + * Represents a signer and a signature. + */ public class SignaturePair { private final UUID signer; @@ -42,8 +44,8 @@ public class SignaturePair { @Override public String toString() { return "SignaturePair{" - + "signer=" + signer - + ", signature=" + Arrays.toString(signature) - + '}'; + + "signer=" + signer + + ", signature=" + Arrays.toString(signature) + + '}'; } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignedChatCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignedChatCommand.java index 8a0b291f2..dc89c448a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignedChatCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/crypto/SignedChatCommand.java @@ -25,7 +25,11 @@ import java.util.Map; import java.util.UUID; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents a signed chat command. + */ public class SignedChatCommand implements KeySigned { + private final String command; private final PublicKey signer; private final Instant expiry; @@ -43,9 +47,9 @@ public class SignedChatCommand implements KeySigned { * Create a signed command from data. */ public SignedChatCommand(String command, PublicKey signer, UUID sender, - Instant expiry, Map signature, byte[] salt, - boolean isPreviewSigned, SignaturePair[] previousSignatures, - @Nullable SignaturePair lastSignature) { + Instant expiry, Map signature, byte[] salt, + boolean isPreviewSigned, SignaturePair[] previousSignatures, + @Nullable SignaturePair lastSignature) { this.command = Preconditions.checkNotNull(command); this.signer = Preconditions.checkNotNull(signer); this.sender = Preconditions.checkNotNull(sender); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/event/UntargetedEventHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/event/UntargetedEventHandler.java index 614f84da9..406e53c49 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/event/UntargetedEventHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/event/UntargetedEventHandler.java @@ -23,10 +23,16 @@ import com.velocitypowered.api.event.EventHandler; import com.velocitypowered.api.event.EventTask; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Core class for invoking event handlers registered by plugins. + */ public interface UntargetedEventHandler { EventHandler buildHandler(Object targetInstance); + /** + * Interface used for invoking listeners that return {@link EventTask}. + */ interface EventTaskHandler extends UntargetedEventHandler { @Nullable EventTask execute(Object targetInstance, Object event); @@ -37,6 +43,9 @@ public interface UntargetedEventHandler { } } + /** + * Interface used for invoking listeners that return nothing. + */ interface VoidHandler extends UntargetedEventHandler { void execute(Object targetInstance, Object event); @@ -50,6 +59,9 @@ public interface UntargetedEventHandler { } } + /** + * Interface used for invoking listeners that take a {@link Continuation} along with an event. + */ interface WithContinuationHandler extends UntargetedEventHandler { void execute(Object targetInstance, Object event, Continuation continuation); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/event/VelocityEventManager.java b/proxy/src/main/java/com/velocitypowered/proxy/event/VelocityEventManager.java index c0c884dac..7f2d6016b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/event/VelocityEventManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/event/VelocityEventManager.java @@ -72,6 +72,9 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.lanternpowered.lmbda.LambdaFactory; import org.lanternpowered.lmbda.LambdaType; +/** + * Implements the Velocity event handler. + */ public class VelocityEventManager implements EventManager { private static final Logger logger = LogManager.getLogger(VelocityEventManager.class); @@ -90,7 +93,8 @@ public class VelocityEventManager implements EventManager { private final ExecutorService asyncExecutor; private final PluginManager pluginManager; - private final ListMultimap, HandlerRegistration> handlersByType = ArrayListMultimap.create(); + private final ListMultimap, HandlerRegistration> handlersByType = + ArrayListMultimap.create(); private final LoadingCache, HandlersCache> handlersCache = Caffeine.newBuilder().build(this::bakeHandlers); @@ -159,8 +163,7 @@ public class VelocityEventManager implements EventManager { */ ALWAYS, /** - * The event will never run async, everything is handled on - * the netty thread. + * The event will never run async, everything is handled on the netty thread. */ NEVER } @@ -198,9 +201,8 @@ public class VelocityEventManager implements EventManager { /** * Creates an {@link UntargetedEventHandler} for the given {@link Method}. This essentially * implements the {@link UntargetedEventHandler} (or the no async task variant) to invoke the - * target method. The implemented class is defined in the same package as the declaring class. - * The {@link UntargetedEventHandler} interface must be public so the implementation can access - * it. + * target method. The implemented class is defined in the same package as the declaring class. The + * {@link UntargetedEventHandler} interface must be public so the implementation can access it. * * @param method The method to generate an untargeted handler for * @return The untargeted handler @@ -364,7 +366,7 @@ public class VelocityEventManager implements EventManager { * Registers the listener for a given plugin. * * @param pluginContainer registering plugin - * @param listener listener to register + * @param listener listener to register */ public void registerInternally(final PluginContainer pluginContainer, final Object listener) { final Class targetClass = listener.getClass(); @@ -537,8 +539,8 @@ public class VelocityEventManager implements EventManager { } /** - * Executes the task and returns whether the next one should be executed - * immediately after this one without scheduling. + * Executes the task and returns whether the next one should be executed immediately after this + * one without scheduling. */ boolean execute() { state = TASK_STATE_EXECUTING; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializer.java b/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializer.java index 0e41fd68a..5f13c7bce 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializer.java @@ -36,6 +36,9 @@ import io.netty.channel.ChannelInitializer; import io.netty.handler.timeout.ReadTimeoutHandler; import java.util.concurrent.TimeUnit; +/** + * Backend channel initializer. + */ @SuppressWarnings("WeakerAccess") public class BackendChannelInitializer extends ChannelInitializer { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializerHolder.java b/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializerHolder.java index 8d667ffaa..4933e0f77 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializerHolder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/BackendChannelInitializerHolder.java @@ -23,6 +23,9 @@ import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Backend channel initializer holder. + */ public class BackendChannelInitializerHolder implements Supplier> { private static final Logger LOGGER = LogManager.getLogger(ConnectionManager.class); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java b/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java index 9bf9e78b0..6173c649c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java @@ -27,7 +27,7 @@ import com.velocitypowered.api.network.ListenerType; import com.velocitypowered.natives.util.Natives; import com.velocitypowered.proxy.VelocityServer; import com.velocitypowered.proxy.network.netty.SeparatePoolInetNameResolver; -import com.velocitypowered.proxy.protocol.netty.GS4QueryHandler; +import com.velocitypowered.proxy.protocol.netty.GameSpyQueryHandler; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; @@ -49,6 +49,9 @@ import org.asynchttpclient.filter.FilterContext.FilterContextBuilder; import org.asynchttpclient.filter.RequestFilter; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Manages endpoints managed by Velocity, along with initializing the Netty event loop group. + */ public final class ConnectionManager { private static final WriteBufferWaterMark SERVER_WRITE_MARK = new WriteBufferWaterMark(1 << 20, @@ -144,14 +147,14 @@ public final class ConnectionManager { * Binds a GS4 listener to the specified {@code hostname} and {@code port}. * * @param hostname the hostname to bind to - * @param port the port to bind to + * @param port the port to bind to */ public void queryBind(final String hostname, final int port) { InetSocketAddress address = new InetSocketAddress(hostname, port); final Bootstrap bootstrap = new Bootstrap() .channelFactory(this.transportType.datagramChannelFactory) .group(this.workerGroup) - .handler(new GS4QueryHandler(this.server)) + .handler(new GameSpyQueryHandler(this.server)) .localAddress(address); bootstrap.bind() .addListener((ChannelFutureListener) future -> { @@ -173,7 +176,6 @@ public final class ConnectionManager { * Creates a TCP {@link Bootstrap} using Velocity's event loops. * * @param group the event loop group to use. Use {@code null} for the default worker group. - * * @return a new {@link Bootstrap} */ public Bootstrap createWorker(@Nullable EventLoopGroup group) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java b/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java index 1e0fae2db..75e6ee97b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java @@ -17,6 +17,9 @@ package com.velocitypowered.proxy.network; +/** + * Constants used for the pipeline. + */ public class Connections { public static final String CIPHER_DECODER = "cipher-decoder"; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/Endpoint.java b/proxy/src/main/java/com/velocitypowered/proxy/network/Endpoint.java index af453e636..dbfd81280 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/Endpoint.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/Endpoint.java @@ -25,6 +25,7 @@ import io.netty.channel.Channel; * Represents a listener endpoint. */ public final class Endpoint { + private final Channel channel; private final ListenerType type; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializer.java b/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializer.java index 55f7d6f88..85fe89c09 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializer.java @@ -41,6 +41,9 @@ import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; import io.netty.handler.timeout.ReadTimeoutHandler; import java.util.concurrent.TimeUnit; +/** + * Server channel initializer. + */ @SuppressWarnings("WeakerAccess") public class ServerChannelInitializer extends ChannelInitializer { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializerHolder.java b/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializerHolder.java index ab125cc8b..e7729ed25 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializerHolder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializerHolder.java @@ -23,6 +23,9 @@ import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Holder for the server channel initializer. + */ public class ServerChannelInitializerHolder implements Supplier> { private static final Logger LOGGER = LogManager.getLogger(ConnectionManager.class); @@ -39,6 +42,7 @@ public class ServerChannelInitializerHolder implements Supplier loaders = new CopyOnWriteArraySet<>(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java index 57fadaec2..fd9b73abd 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java @@ -53,6 +53,9 @@ import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +/** + * Handles loading plugins and provides a registry for loaded plugins. + */ public class VelocityPluginManager implements PluginManager { private static final Logger logger = LogManager.getLogger(VelocityPluginManager.class); @@ -73,6 +76,7 @@ public class VelocityPluginManager implements PluginManager { /** * Loads all plugins from the specified {@code directory}. + * * @param directory the directory to load from * @throws IOException if we could not open the directory */ @@ -137,8 +141,8 @@ 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())) - .toInstance(container); + .annotatedWith(Names.named(container.getDescription().getId())) + .toInstance(container); } } }; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/PluginLoader.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/PluginLoader.java index 8b176a75b..41fddb9f5 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/PluginLoader.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/PluginLoader.java @@ -46,21 +46,20 @@ public interface PluginLoader { PluginDescription createPluginFromCandidate(PluginDescription candidate) throws Exception; /** - * Creates a {@link Module} for the provided {@link PluginContainer} - * and verifies that the container's {@link PluginDescription} is correct. + * Creates a {@link Module} for the provided {@link PluginContainer} and verifies that the + * container's {@link PluginDescription} is correct. * *

Does not create an instance of the plugin.

* * @param container the plugin container * @return the module containing bindings specific to this plugin - * @throws IllegalArgumentException If the {@link PluginDescription} - * is missing the path + * @throws IllegalArgumentException If the {@link PluginDescription} is missing the path */ Module createModule(PluginContainer container) throws Exception; /** - * Creates an instance of the plugin as specified by the - * plugin's main class found in the {@link PluginDescription}. + * Creates an instance of the plugin as specified by the plugin's main class found in the + * {@link PluginDescription}. * *

The provided {@link Module modules} are used to create an * injector which is then used to create the plugin instance.

@@ -69,8 +68,8 @@ public interface PluginLoader { * * @param container the plugin container * @param modules the modules to be used when creating this plugin's injector - * @throws IllegalStateException If the plugin instance could not be - * created from the provided modules + * @throws IllegalStateException If the plugin instance could not be created from the provided + * modules */ void createPlugin(PluginContainer container, Module... modules) throws Exception; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginContainer.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginContainer.java index 6c07ac3fb..db479b423 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginContainer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginContainer.java @@ -21,6 +21,9 @@ import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.PluginDescription; import java.util.Optional; +/** + * Implements {@link PluginContainer}. + */ public class VelocityPluginContainer implements PluginContainer { private final PluginDescription description; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginDescription.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginDescription.java index b799dbbf3..17e3c0fb6 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginDescription.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/VelocityPluginDescription.java @@ -31,6 +31,9 @@ import java.util.Map; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Implements {@link PluginDescription}. + */ public class VelocityPluginDescription implements PluginDescription { private final String id; @@ -44,14 +47,15 @@ public class VelocityPluginDescription implements PluginDescription { /** * Creates a new plugin description. - * @param id the ID - * @param name the name of the plugin - * @param version the plugin version - * @param description a description of the plugin - * @param url the website for the plugin - * @param authors the authors of this plugin + * + * @param id the ID + * @param name the name of the plugin + * @param version the plugin version + * @param description a description of the plugin + * @param url the website for the plugin + * @param authors the authors of this plugin * @param dependencies the dependencies for this plugin - * @param source the original source for the plugin + * @param source the original source for the plugin */ public VelocityPluginDescription(String id, @Nullable String name, @Nullable String version, @Nullable String description, @Nullable String url, diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java index 1756c2677..42aff0c92 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java @@ -46,6 +46,9 @@ import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; +/** + * Implements loading a Java plugin. + */ public class JavaPluginLoader implements PluginLoader { private final ProxyServer server; @@ -122,7 +125,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.getId()); } ((VelocityPluginContainer) container).setInstance(instance); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/VelocityPluginModule.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/VelocityPluginModule.java index 2e8bd6ebc..46521c762 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/VelocityPluginModule.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/VelocityPluginModule.java @@ -36,7 +36,7 @@ class VelocityPluginModule implements Module { private final Path basePluginPath; VelocityPluginModule(ProxyServer server, JavaVelocityPluginDescription description, - PluginContainer pluginContainer, Path basePluginPath) { + PluginContainer pluginContainer, Path basePluginPath) { this.server = server; this.description = description; this.pluginContainer = pluginContainer; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java index 36d75e49b..ec1740a54 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java @@ -32,6 +32,9 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +/** + * Handles sorting plugin dependencies into an order that satisfies all dependencies. + */ public class PluginDependencyUtils { private PluginDependencyUtils() { @@ -39,8 +42,8 @@ public class PluginDependencyUtils { } /** - * Attempts to topographically sort all plugins for the proxy to load in dependency order using - * a depth-first search. + * Attempts to topographically sort all plugins for the proxy to load in dependency order using a + * depth-first search. * * @param candidates the plugins to sort * @return the sorted list of plugins diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/MinecraftPacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/MinecraftPacket.java index 7115bb8bf..e760070e0 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/MinecraftPacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/MinecraftPacket.java @@ -21,6 +21,9 @@ import com.velocitypowered.api.network.ProtocolVersion; import com.velocitypowered.proxy.connection.MinecraftSessionHandler; import io.netty.buffer.ByteBuf; +/** + * Represents a Minecraft packet. + */ public interface MinecraftPacket { void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java index 51cc7ff50..f18d9c70a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java @@ -45,6 +45,9 @@ import net.kyori.adventure.nbt.BinaryTagIO; import net.kyori.adventure.nbt.CompoundBinaryTag; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +/** + * Utilities for writing and reading data in the Minecraft protocol. + */ public enum ProtocolUtils { ; @@ -73,6 +76,7 @@ public enum ProtocolUtils { /** * Reads a Minecraft-style VarInt from the specified {@code buf}. + * * @param buf the buffer to read from * @return the decoded VarInt */ @@ -89,6 +93,7 @@ public enum ProtocolUtils { * Reads a Minecraft-style VarInt from the specified {@code buf}. The difference between this * method and {@link #readVarInt(ByteBuf)} is that this function returns a sentinel value if the * varint is invalid. + * * @param buf the buffer to read from * @return the decoded VarInt, or {@code Integer.MIN_VALUE} if the varint is invalid */ @@ -107,6 +112,7 @@ public enum ProtocolUtils { /** * Returns the exact byte size of {@code value} if it were encoded as a VarInt. + * * @param value the value to encode * @return the byte size of {@code value} if encoded as a VarInt */ @@ -116,7 +122,8 @@ public enum ProtocolUtils { /** * Writes a Minecraft-style VarInt to the specified {@code buf}. - * @param buf the buffer to read from + * + * @param buf the buffer to read from * @param value the integer to write */ public static void writeVarInt(ByteBuf buf, int value) { @@ -157,7 +164,8 @@ public enum ProtocolUtils { /** * Writes the specified {@code value} as a 21-bit Minecraft VarInt to the specified {@code buf}. * The upper 11 bits will be discarded. - * @param buf the buffer to read from + * + * @param buf the buffer to read from * @param value the integer to write */ public static void write21BitVarInt(ByteBuf buf, int value) { @@ -173,6 +181,7 @@ public enum ProtocolUtils { /** * Reads a VarInt length-prefixed UTF-8 string from the {@code buf}, making sure to not go over * {@code cap} size. + * * @param buf the buffer to read from * @param cap the maximum size of the string, in UTF-8 character length * @return the decoded string @@ -200,6 +209,7 @@ public enum ProtocolUtils { /** * Writes the specified {@code str} to the {@code buf} with a VarInt prefix. + * * @param buf the buffer to write to * @param str the string to write */ @@ -216,6 +226,7 @@ public enum ProtocolUtils { /** * Reads a VarInt length-prefixed byte array from the {@code buf}, making sure to not go over * {@code cap} size. + * * @param buf the buffer to read from * @param cap the maximum size of the string, in UTF-8 character length * @return the byte array @@ -239,6 +250,7 @@ public enum ProtocolUtils { /** * Reads an VarInt-prefixed array of VarInt integers from the {@code buf}. + * * @param buf the buffer to read from * @return an array of integers */ @@ -254,6 +266,7 @@ public enum ProtocolUtils { /** * Reads an UUID from the {@code buf}. + * * @param buf the buffer to read from * @return the UUID from the buffer */ @@ -270,6 +283,7 @@ public enum ProtocolUtils { /** * Reads an UUID stored as an Integer Array from the {@code buf}. + * * @param buf the buffer to read from * @return the UUID from the buffer */ @@ -285,7 +299,8 @@ public enum ProtocolUtils { /** * Writes an UUID as an Integer Array to the {@code buf}. - * @param buf the buffer to write to + * + * @param buf the buffer to write to * @param uuid the UUID to write */ public static void writeUuidIntArray(ByteBuf buf, UUID uuid) { @@ -297,7 +312,8 @@ public enum ProtocolUtils { /** * Reads a {@link net.kyori.adventure.nbt.CompoundBinaryTag} from the {@code buf}. - * @param buf the buffer to read from + * + * @param buf the buffer to read from * @param reader the NBT reader to use * @return {@link net.kyori.adventure.nbt.CompoundBinaryTag} the CompoundTag from the buffer */ @@ -306,13 +322,14 @@ public enum ProtocolUtils { return reader.read((DataInput) new ByteBufInputStream(buf)); } catch (IOException thrown) { throw new DecoderException( - "Unable to parse NBT CompoundTag, full error: " + thrown.getMessage()); + "Unable to parse NBT CompoundTag, full error: " + thrown.getMessage()); } } /** * Writes a CompoundTag to the {@code buf}. - * @param buf the buffer to write to + * + * @param buf the buffer to write to * @param compoundTag the CompoundTag to write */ public static void writeCompoundTag(ByteBuf buf, CompoundBinaryTag compoundTag) { @@ -325,6 +342,7 @@ public enum ProtocolUtils { /** * Reads a String array from the {@code buf}. + * * @param buf the buffer to read from * @return the String array from the buffer */ @@ -339,7 +357,8 @@ public enum ProtocolUtils { /** * Writes a String Array to the {@code buf}. - * @param buf the buffer to write to + * + * @param buf the buffer to write to * @param stringArray the array to write */ public static void writeStringArray(ByteBuf buf, String[] stringArray) { @@ -351,7 +370,8 @@ public enum ProtocolUtils { /** * Writes a list of {@link com.velocitypowered.api.util.GameProfile.Property} to the buffer. - * @param buf the buffer to write to + * + * @param buf the buffer to write to * @param properties the properties to serialize */ public static void writeProperties(ByteBuf buf, List properties) { @@ -371,6 +391,7 @@ public enum ProtocolUtils { /** * Reads a list of {@link com.velocitypowered.api.util.GameProfile.Property} from the buffer. + * * @param buf the buffer to read from * @return the read properties */ @@ -433,8 +454,8 @@ public enum ProtocolUtils { /** * Writes an byte array for legacy version 1.7 to the specified {@code buf} * - * @param b array - * @param buf buf + * @param b array + * @param buf buf * @param allowExtended forge */ public static void writeByteArray17(byte[] b, ByteBuf buf, boolean allowExtended) { @@ -457,8 +478,8 @@ public enum ProtocolUtils { /** * Writes an {@link ByteBuf} for legacy version 1.7 to the specified {@code buf} * - * @param b array - * @param buf buf + * @param b array + * @param buf buf * @param allowExtended forge */ public static void writeByteBuf17(ByteBuf b, ByteBuf buf, boolean allowExtended) { @@ -497,7 +518,7 @@ public enum ProtocolUtils { /** * Writes a Minecraft-style extended short to the specified {@code buf}. * - * @param buf buf to write + * @param buf buf to write * @param toWrite the extended short to write */ public static void writeExtendedForgeShort(ByteBuf buf, int toWrite) { @@ -524,8 +545,8 @@ public enum ProtocolUtils { } /** - * Returns the appropriate {@link GsonComponentSerializer} for the given protocol version. This - * is used to constrain messages sent to older clients. + * Returns the appropriate {@link GsonComponentSerializer} for the given protocol version. This is + * used to constrain messages sent to older clients. * * @param version the protocol version used by the client. * @return the appropriate {@link GsonComponentSerializer} @@ -540,7 +561,7 @@ public enum ProtocolUtils { /** * Writes a players {@link IdentifiedKey} to the buffer. * - * @param buf the buffer + * @param buf the buffer * @param playerKey the key to write */ public static void writePlayerKey(ByteBuf buf, IdentifiedKey playerKey) { @@ -560,18 +581,15 @@ public enum ProtocolUtils { byte[] key = ProtocolUtils.readByteArray(buf); byte[] signature = ProtocolUtils.readByteArray(buf, 4096); IdentifiedKey.Revision revision = version.compareTo(ProtocolVersion.MINECRAFT_1_19) == 0 - ? IdentifiedKey.Revision.GENERIC_V1 : IdentifiedKey.Revision.LINKED_V2; + ? IdentifiedKey.Revision.GENERIC_V1 : IdentifiedKey.Revision.LINKED_V2; return new IdentifiedKeyImpl(revision, key, expiry, signature); } + /** + * Represents the direction in which a packet flows. + */ public enum Direction { SERVERBOUND, - CLIENTBOUND; - - public StateRegistry.PacketRegistry.ProtocolRegistry getProtocolRegistry(StateRegistry state, - ProtocolVersion version) { - return (this == SERVERBOUND ? state.serverbound : state.clientbound) - .getProtocolRegistry(version); - } + CLIENTBOUND } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java index 10ba18422..7c4c6497f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java @@ -39,6 +39,8 @@ import static com.velocitypowered.api.network.ProtocolVersion.MINECRAFT_1_9_4; import static com.velocitypowered.api.network.ProtocolVersion.MINIMUM_VERSION; import static com.velocitypowered.api.network.ProtocolVersion.SUPPORTED_VERSIONS; import static com.velocitypowered.proxy.protocol.ProtocolUtils.Direction; +import static com.velocitypowered.proxy.protocol.ProtocolUtils.Direction.CLIENTBOUND; +import static com.velocitypowered.proxy.protocol.ProtocolUtils.Direction.SERVERBOUND; import com.velocitypowered.api.network.ProtocolVersion; import com.velocitypowered.proxy.protocol.packet.AvailableCommands; @@ -95,6 +97,9 @@ import java.util.Objects; import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Registry of all Minecraft protocol states and the packets for each state. + */ public enum StateRegistry { HANDSHAKE { @@ -397,9 +402,17 @@ public enum StateRegistry { public static final int STATUS_ID = 1; public static final int LOGIN_ID = 2; - public final PacketRegistry clientbound = new PacketRegistry(Direction.CLIENTBOUND); - public final PacketRegistry serverbound = new PacketRegistry(Direction.SERVERBOUND); + protected final PacketRegistry clientbound = new PacketRegistry(CLIENTBOUND); + protected final PacketRegistry serverbound = new PacketRegistry(SERVERBOUND); + public StateRegistry.PacketRegistry.ProtocolRegistry getProtocolRegistry(Direction direction, + ProtocolVersion version) { + return (direction == SERVERBOUND ? serverbound : clientbound).getProtocolRegistry(version); + } + + /** + * Packet registry. + */ public static class PacketRegistry { private final Direction direction; @@ -431,7 +444,7 @@ public enum StateRegistry { }

void register(Class

clazz, Supplier

packetSupplier, - PacketMapping... mappings) { + PacketMapping... mappings) { if (mappings.length == 0) { throw new IllegalArgumentException("At least one mapping must be provided."); } @@ -490,6 +503,9 @@ public enum StateRegistry { } } + /** + * Protocol registry. + */ public class ProtocolRegistry { public final ProtocolVersion version; @@ -537,6 +553,9 @@ public enum StateRegistry { } } + /** + * Packet mapping. + */ public static final class PacketMapping { private final int id; @@ -545,7 +564,7 @@ public enum StateRegistry { private final @Nullable ProtocolVersion lastValidProtocolVersion; PacketMapping(int id, ProtocolVersion protocolVersion, - ProtocolVersion lastValidProtocolVersion, boolean packetDecoding) { + ProtocolVersion lastValidProtocolVersion, boolean packetDecoding) { this.id = id; this.protocolVersion = protocolVersion; this.lastValidProtocolVersion = lastValidProtocolVersion; @@ -604,7 +623,7 @@ public enum StateRegistry { * @return PacketMapping with the provided arguments */ private static PacketMapping map(int id, ProtocolVersion version, - ProtocolVersion lastValidProtocolVersion, boolean encodeOnly) { + ProtocolVersion lastValidProtocolVersion, boolean encodeOnly) { return new PacketMapping(id, version, lastValidProtocolVersion, encodeOnly); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/AutoReadHolderHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/AutoReadHolderHandler.java index 9083f72a1..c0ecef52b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/AutoReadHolderHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/AutoReadHolderHandler.java @@ -24,8 +24,8 @@ import java.util.ArrayDeque; import java.util.Queue; /** - * A variation on {@link io.netty.handler.flow.FlowControlHandler} that explicitly holds messages - * on {@code channelRead} and only releases them on an explicit read operation. + * A variation on {@link io.netty.handler.flow.FlowControlHandler} that explicitly holds messages on + * {@code channelRead} and only releases them on an explicit read operation. */ public class AutoReadHolderHandler extends ChannelDuplexHandler { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java similarity index 97% rename from proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java rename to proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java index 22789efe1..e545f332b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java @@ -48,7 +48,10 @@ import java.util.stream.Collectors; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.apache.logging.log4j.LogManager; -public class GS4QueryHandler extends SimpleChannelInboundHandler { +/** + * Implements the GameSpy protocol for Velocity. + */ +public class GameSpyQueryHandler extends SimpleChannelInboundHandler { private static final short QUERY_MAGIC_FIRST = 0xFE; private static final short QUERY_MAGIC_SECOND = 0xFD; @@ -76,14 +79,15 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler private final SecureRandom random; private final VelocityServer server; - public GS4QueryHandler(VelocityServer server) { + public GameSpyQueryHandler(VelocityServer server) { this.server = server; this.random = new SecureRandom(); } private QueryResponse createInitialResponse() { return QueryResponse.builder() - .hostname(PlainTextComponentSerializer.plainText().serialize(server.getConfiguration().getMotd())) + .hostname( + PlainTextComponentSerializer.plainText().serialize(server.getConfiguration().getMotd())) .gameVersion(ProtocolVersion.SUPPORTED_VERSION_STRING) .map(server.getConfiguration().getQueryMap()) .currentPlayers(server.getPlayerCount()) @@ -264,7 +268,7 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler if (isBasic) { return; } - + StringBuilder pluginsString = new StringBuilder(); pluginsString.append(serverVersion).append(':').append(' '); Iterator iterator = plugins.iterator(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingDecoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingDecoder.java index be716ec29..25fbdd79f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingDecoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingDecoder.java @@ -29,6 +29,9 @@ import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.List; +/** + * Decodes Minecraft 1.3-1.6.4 server ping requests. + */ public class LegacyPingDecoder extends ByteToMessageDecoder { private static final String MC_1_6_CHANNEL = "MC|PingHost"; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingEncoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingEncoder.java index 1383493b9..8ac10aa8d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingEncoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/LegacyPingEncoder.java @@ -24,6 +24,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.nio.charset.StandardCharsets; +/** + * Encodes {@code LegacyDisconnect} for Minecraft 1.3-1.6.4. + */ @ChannelHandler.Sharable public class LegacyPingEncoder extends MessageToByteEncoder { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherDecoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherDecoder.java index 1f662fd57..52c6bb303 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherDecoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherDecoder.java @@ -25,6 +25,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import java.util.List; +/** + * Handler for decrypting Minecraft packets. + */ public class MinecraftCipherDecoder extends MessageToMessageDecoder { private final VelocityCipher cipher; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherEncoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherEncoder.java index b4fd027ec..6e2e91aa1 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherEncoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCipherEncoder.java @@ -25,6 +25,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import java.util.List; +/** + * Encrypts Minecraft protocol packets using {@link VelocityCipher}. + */ public class MinecraftCipherEncoder extends MessageToMessageEncoder { private final VelocityCipher cipher; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressDecoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressDecoder.java index 82fb4c153..6944d6dd8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressDecoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressDecoder.java @@ -28,6 +28,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import java.util.List; +/** + * Decompresses a Minecraft packet. + */ public class MinecraftCompressDecoder extends MessageToMessageDecoder { private static final int VANILLA_MAXIMUM_UNCOMPRESSED_SIZE = 8 * 1024 * 1024; // 8MiB @@ -55,7 +58,7 @@ public class MinecraftCompressDecoder extends MessageToMessageDecoder { } checkFrame(claimedUncompressedSize >= threshold, "Uncompressed size %s is less than" - + " threshold %s", claimedUncompressedSize, threshold); + + " threshold %s", claimedUncompressedSize, threshold); checkFrame(claimedUncompressedSize <= UNCOMPRESSED_CAP, "Uncompressed size %s exceeds hard threshold of %s", claimedUncompressedSize, UNCOMPRESSED_CAP); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressorAndLengthEncoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressorAndLengthEncoder.java index 67ec9e1e2..bdd5ef42a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressorAndLengthEncoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftCompressorAndLengthEncoder.java @@ -27,6 +27,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.util.zip.DataFormatException; +/** + * Handler for compressing Minecraft packets. + */ public class MinecraftCompressorAndLengthEncoder extends MessageToByteEncoder { private int threshold; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java index 5243a6796..81fbee08b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java @@ -28,6 +28,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.CorruptedFrameException; +/** + * Decodes Minecraft packets. + */ public class MinecraftDecoder extends ChannelInboundHandlerAdapter { public static final boolean DEBUG = Boolean.getBoolean("velocity.packet-decode-logging"); @@ -46,8 +49,8 @@ public class MinecraftDecoder extends ChannelInboundHandlerAdapter { */ public MinecraftDecoder(ProtocolUtils.Direction direction) { this.direction = Preconditions.checkNotNull(direction, "direction"); - this.registry = direction.getProtocolRegistry(StateRegistry.HANDSHAKE, - ProtocolVersion.MINIMUM_VERSION); + this.registry = StateRegistry.HANDSHAKE.getProtocolRegistry( + direction, ProtocolVersion.MINIMUM_VERSION); this.state = StateRegistry.HANDSHAKE; } @@ -137,7 +140,7 @@ public class MinecraftDecoder extends ChannelInboundHandlerAdapter { } public void setProtocolVersion(ProtocolVersion protocolVersion) { - this.registry = direction.getProtocolRegistry(state, protocolVersion); + this.registry = state.getProtocolRegistry(direction, protocolVersion); } public void setState(StateRegistry state) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java index 7ed59202b..159b9aa4d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java @@ -26,6 +26,9 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; +/** + * Encodes {@link MinecraftPacket} instances. + */ public class MinecraftEncoder extends MessageToByteEncoder { private final ProtocolUtils.Direction direction; @@ -39,8 +42,8 @@ public class MinecraftEncoder extends MessageToByteEncoder { */ public MinecraftEncoder(ProtocolUtils.Direction direction) { this.direction = Preconditions.checkNotNull(direction, "direction"); - this.registry = direction - .getProtocolRegistry(StateRegistry.HANDSHAKE, ProtocolVersion.MINIMUM_VERSION); + this.registry = StateRegistry.HANDSHAKE.getProtocolRegistry( + direction, ProtocolVersion.MINIMUM_VERSION); this.state = StateRegistry.HANDSHAKE; } @@ -52,7 +55,7 @@ public class MinecraftEncoder extends MessageToByteEncoder { } public void setProtocolVersion(final ProtocolVersion protocolVersion) { - this.registry = direction.getProtocolRegistry(state, protocolVersion); + this.registry = state.getProtocolRegistry(direction, protocolVersion); } public void setState(StateRegistry state) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintFrameDecoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintFrameDecoder.java index 675ddf7f7..e1f5a077a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintFrameDecoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintFrameDecoder.java @@ -24,6 +24,9 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; +/** + * Frames Minecraft server packets which are prefixed by a 21-bit VarInt encoding. + */ public class MinecraftVarintFrameDecoder extends ByteToMessageDecoder { private static final QuietDecoderException BAD_LENGTH_CACHED = diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintLengthEncoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintLengthEncoder.java index f65764bf0..cf33e9ed8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintLengthEncoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftVarintLengthEncoder.java @@ -25,6 +25,9 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; +/** + * Handler for appending a length for Minecraft packets. + */ @ChannelHandler.Sharable public class MinecraftVarintLengthEncoder extends MessageToByteEncoder { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommands.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommands.java index c349dc65a..84d41fd76 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommands.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommands.java @@ -54,6 +54,7 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; public class AvailableCommands implements MinecraftPacket { + private static final Command PLACEHOLDER_COMMAND = source -> 0; private static final byte NODE_TYPE_ROOT = 0x00; @@ -69,6 +70,7 @@ public class AvailableCommands implements MinecraftPacket { /** * Returns the root node. + * * @return the root node */ public RootCommandNode getRootNode() { @@ -168,11 +170,11 @@ public class AvailableCommands implements MinecraftPacket { if (node instanceof ArgumentCommandNode) { ProtocolUtils.writeString(buf, node.getName()); ArgumentPropertyRegistry.serialize(buf, - ((ArgumentCommandNode) node).getType(), protocolVersion); + ((ArgumentCommandNode) node).getType(), protocolVersion); if (((ArgumentCommandNode) node).getCustomSuggestions() != null) { SuggestionProvider provider = ((ArgumentCommandNode) node) - .getCustomSuggestions(); + .getCustomSuggestions(); String name = "minecraft:ask_server"; if (provider instanceof ProtocolSuggestionProvider) { name = ((ProtocolSuggestionProvider) provider).name; @@ -219,6 +221,7 @@ public class AvailableCommands implements MinecraftPacket { } private static class WireNode { + private final int idx; private final byte flags; private final int[] children; @@ -319,10 +322,10 @@ public class AvailableCommands implements MinecraftPacket { if (args != null) { if (args instanceof LiteralArgumentBuilder) { helper.add("argsLabel", - ((LiteralArgumentBuilder) args).getLiteral()); + ((LiteralArgumentBuilder) args).getLiteral()); } else if (args instanceof RequiredArgumentBuilder) { helper.add("argsName", - ((RequiredArgumentBuilder) args).getName()); + ((RequiredArgumentBuilder) args).getName()); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/EncryptionResponse.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/EncryptionResponse.java index 8bb4f69cb..3c6670793 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/EncryptionResponse.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/EncryptionResponse.java @@ -32,7 +32,8 @@ import java.util.Arrays; public class EncryptionResponse implements MinecraftPacket { - private final static QuietDecoderException NO_SALT = new QuietDecoderException("Encryption response didn't contain salt"); + private final static QuietDecoderException NO_SALT = new QuietDecoderException( + "Encryption response didn't contain salt"); private byte[] sharedSecret = EMPTY_BYTE_ARRAY; private byte[] verifyToken = EMPTY_BYTE_ARRAY; @@ -67,13 +68,13 @@ public class EncryptionResponse implements MinecraftPacket { this.sharedSecret = ProtocolUtils.readByteArray(buf, 128); if (version.compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0 - && version.compareTo(ProtocolVersion.MINECRAFT_1_19_3) < 0 - && !buf.readBoolean()) { + && version.compareTo(ProtocolVersion.MINECRAFT_1_19_3) < 0 + && !buf.readBoolean()) { salt = buf.readLong(); } this.verifyToken = ProtocolUtils.readByteArray(buf, - version.compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0 ? 256 : 128); + version.compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0 ? 256 : 128); } else { this.sharedSecret = ProtocolUtils.readByteArray17(buf); this.verifyToken = ProtocolUtils.readByteArray17(buf); @@ -89,7 +90,7 @@ public class EncryptionResponse implements MinecraftPacket { if (salt != null) { buf.writeBoolean(false); buf.writeLong(salt); - } else { + } else { buf.writeBoolean(true); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/HeaderAndFooter.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/HeaderAndFooter.java index 8001012a4..67c795ffc 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/HeaderAndFooter.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/HeaderAndFooter.java @@ -70,7 +70,7 @@ public class HeaderAndFooter implements MinecraftPacket { } public static HeaderAndFooter create(Component header, - Component footer, ProtocolVersion protocolVersion) { + Component footer, ProtocolVersion protocolVersion) { GsonComponentSerializer serializer = ProtocolUtils.getJsonChatSerializer(protocolVersion); return new HeaderAndFooter(serializer.serialize(header), serializer.serialize(footer)); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/JoinGame.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/JoinGame.java index aba321564..a4ea56419 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/JoinGame.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/JoinGame.java @@ -167,7 +167,7 @@ public class JoinGame implements MinecraftPacket { return currentDimensionData; } - public int getSimulationDistance(){ + public int getSimulationDistance() { return simulationDistance; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyDisconnect.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyDisconnect.java index 285918bdd..99578f00d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyDisconnect.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyDisconnect.java @@ -40,8 +40,9 @@ public class LegacyDisconnect { /** * Converts a modern server list ping response into an legacy disconnect packet. + * * @param response the server ping to convert - * @param version the requesting clients' version + * @param version the requesting clients' version * @return the disconnect packet */ public static LegacyDisconnect fromServerPing(ServerPing response, @@ -86,6 +87,7 @@ public class LegacyDisconnect { /** * Converts a {@link TextComponent} into a legacy disconnect packet. + * * @param component the component to convert * @return the disconnect packet */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/RemovePlayerInfo.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/RemovePlayerInfo.java index 5827215b7..a55f6c779 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/RemovePlayerInfo.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/RemovePlayerInfo.java @@ -28,6 +28,7 @@ import java.util.Collection; import java.util.UUID; public class RemovePlayerInfo implements MinecraftPacket { + private Collection profilesToRemove; public RemovePlayerInfo() { @@ -47,7 +48,8 @@ public class RemovePlayerInfo implements MinecraftPacket { } @Override - public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void decode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { int length = ProtocolUtils.readVarInt(buf); Collection profilesToRemove = Lists.newArrayListWithCapacity(length); for (int idx = 0; idx < length; idx++) { @@ -57,7 +59,8 @@ public class RemovePlayerInfo implements MinecraftPacket { } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { ProtocolUtils.writeVarInt(buf, this.profilesToRemove.size()); for (UUID uuid : this.profilesToRemove) { ProtocolUtils.writeUuid(buf, uuid); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Respawn.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Respawn.java index 7126c8c16..26acd6535 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Respawn.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Respawn.java @@ -46,9 +46,9 @@ public class Respawn implements MinecraftPacket { } public Respawn(int dimension, long partialHashedSeed, short difficulty, short gamemode, - String levelType, byte dataToKeep, DimensionInfo dimensionInfo, - short previousGamemode, DimensionData currentDimensionData, - @Nullable Pair lastDeathPosition) { + String levelType, byte dataToKeep, DimensionInfo dimensionInfo, + short previousGamemode, DimensionData currentDimensionData, + @Nullable Pair lastDeathPosition) { this.dimension = dimension; this.partialHashedSeed = partialHashedSeed; this.difficulty = difficulty; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerData.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerData.java index 5b654e80e..bae3f29cf 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerData.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerData.java @@ -61,7 +61,8 @@ public class ServerData implements MinecraftPacket { } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { boolean hasDescription = this.description != null; buf.writeBoolean(hasDescription); if (hasDescription) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerLogin.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerLogin.java index ee98d8d9c..5323cdc04 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerLogin.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/ServerLogin.java @@ -32,7 +32,8 @@ import java.util.UUID; public class ServerLogin implements MinecraftPacket { - private static final QuietDecoderException EMPTY_USERNAME = new QuietDecoderException("Empty username!"); + private static final QuietDecoderException EMPTY_USERNAME = new QuietDecoderException( + "Empty username!"); private @Nullable String username; private @Nullable IdentifiedKey playerKey; // Introduced in 1.19.3 diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TabCompleteResponse.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TabCompleteResponse.java index c983fed84..97e489764 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TabCompleteResponse.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TabCompleteResponse.java @@ -125,6 +125,7 @@ public class TabCompleteResponse implements MinecraftPacket { } public static class Offer implements Comparable { + private final String text; private final @Nullable Component tooltip; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/UpsertPlayerInfo.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/UpsertPlayerInfo.java index 765aab2c9..84054ba27 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/UpsertPlayerInfo.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/UpsertPlayerInfo.java @@ -35,6 +35,7 @@ import net.kyori.adventure.text.Component; import org.jetbrains.annotations.Nullable; public class UpsertPlayerInfo implements MinecraftPacket { + private final EnumSet actions; private final List entries; @@ -82,7 +83,8 @@ public class UpsertPlayerInfo implements MinecraftPacket { } @Override - public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void decode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { Action[] actions = Action.class.getEnumConstants(); byte[] bytes = new byte[-Math.floorDiv(-actions.length, 8)]; buf.readBytes(bytes); @@ -105,7 +107,8 @@ public class UpsertPlayerInfo implements MinecraftPacket { } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { Action[] actions = Action.class.getEnumConstants(); BitSet set = new BitSet(actions.length); for (int idx = 0; idx < actions.length; idx++) { @@ -198,15 +201,18 @@ public class UpsertPlayerInfo implements MinecraftPacket { } private interface Read { + void read(ProtocolVersion version, ByteBuf buf, Entry info); } private interface Write { + void write(ProtocolVersion version, ByteBuf buf, Entry info); } } public static class Entry { + private final UUID profileId; private GameProfile profile; private boolean listed; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentIdentifier.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentIdentifier.java index 61305e8e0..452605fc9 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentIdentifier.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentIdentifier.java @@ -40,10 +40,11 @@ public class ArgumentIdentifier { for (int i = 0; i < versions.length; i++) { VersionSet current = Preconditions.checkNotNull(versions[i]); - Preconditions.checkArgument(current.getVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0, - "Version too old for ID index"); + Preconditions.checkArgument( + current.getVersion().compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0, + "Version too old for ID index"); Preconditions.checkArgument(previous == null || previous.compareTo(current.getVersion()) > 0, - "Invalid protocol version order"); + "Invalid protocol version order"); for (ProtocolVersion v : ProtocolVersion.values()) { if (v.compareTo(current.getVersion()) >= 0) { @@ -77,6 +78,7 @@ public class ArgumentIdentifier { * This class is purely for convenience. */ public static class VersionSet { + private final ProtocolVersion version; private final int id; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertyRegistry.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertyRegistry.java index 54b4d1007..66517de78 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertyRegistry.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertyRegistry.java @@ -44,6 +44,7 @@ import java.util.HashMap; import java.util.Map; public class ArgumentPropertyRegistry { + private ArgumentPropertyRegistry() { throw new AssertionError(); } @@ -56,7 +57,7 @@ public class ArgumentPropertyRegistry { new HashMap<>(); private static > void register(ArgumentIdentifier identifier, - Class klazz, ArgumentPropertySerializer serializer) { + Class klazz, ArgumentPropertySerializer serializer) { byIdentifier.put(identifier, serializer); byClass.put(klazz, serializer); classToId.put(klazz, identifier); @@ -67,7 +68,7 @@ public class ArgumentPropertyRegistry { } private static void empty(ArgumentIdentifier identifier, - ArgumentPropertySerializer serializer) { + ArgumentPropertySerializer serializer) { byIdentifier.put(identifier, serializer); } @@ -100,7 +101,7 @@ public class ArgumentPropertyRegistry { * @param type the type to serialize */ public static void serialize(ByteBuf buf, ArgumentType type, - ProtocolVersion protocolVersion) { + ProtocolVersion protocolVersion) { if (type instanceof PassthroughProperty) { PassthroughProperty property = (PassthroughProperty) type; writeIdentifier(buf, property.getIdentifier(), protocolVersion); @@ -131,7 +132,7 @@ public class ArgumentPropertyRegistry { * @param protocolVersion the protocol version to use */ public static void writeIdentifier(ByteBuf buf, ArgumentIdentifier identifier, - ProtocolVersion protocolVersion) { + ProtocolVersion protocolVersion) { if (protocolVersion.compareTo(MINECRAFT_1_19) >= 0) { Integer id = identifier.getIdByProtocolVersion(protocolVersion); Preconditions.checkNotNull(id, "Don't know how to serialize type " + identifier); @@ -181,13 +182,14 @@ public class ArgumentPropertyRegistry { @Override public void serialize(BoolArgumentType object, ByteBuf buf, - ProtocolVersion protocolVersion) { + ProtocolVersion protocolVersion) { } }); register(id("brigadier:float", mapSet(MINECRAFT_1_19, 1)), FloatArgumentType.class, FLOAT); register(id("brigadier:double", mapSet(MINECRAFT_1_19, 2)), DoubleArgumentType.class, DOUBLE); - register(id("brigadier:integer", mapSet(MINECRAFT_1_19, 3)), IntegerArgumentType.class, INTEGER); + register(id("brigadier:integer", mapSet(MINECRAFT_1_19, 3)), IntegerArgumentType.class, + INTEGER); register(id("brigadier:long", mapSet(MINECRAFT_1_19, 4)), LongArgumentType.class, LONG); register(id("brigadier:string", mapSet(MINECRAFT_1_19, 5)), StringArgumentType.class, STRING); @@ -214,7 +216,8 @@ public class ArgumentPropertyRegistry { empty(id("minecraft:angle", mapSet(MINECRAFT_1_19, 26))); // added in 1.16.2 empty(id("minecraft:rotation", mapSet(MINECRAFT_1_19, 27))); empty(id("minecraft:scoreboard_slot", mapSet(MINECRAFT_1_19, 28))); - empty(id("minecraft:score_holder", mapSet(MINECRAFT_1_19, 29)), ByteArgumentPropertySerializer.BYTE); + empty(id("minecraft:score_holder", mapSet(MINECRAFT_1_19, 29)), + ByteArgumentPropertySerializer.BYTE); empty(id("minecraft:swizzle", mapSet(MINECRAFT_1_19, 30))); empty(id("minecraft:team", mapSet(MINECRAFT_1_19, 31))); empty(id("minecraft:item_slot", mapSet(MINECRAFT_1_19, 32))); @@ -224,20 +227,25 @@ public class ArgumentPropertyRegistry { empty(id("minecraft:entity_anchor", mapSet(MINECRAFT_1_19_3, 35), mapSet(MINECRAFT_1_19, 36))); empty(id("minecraft:int_range", mapSet(MINECRAFT_1_19_3, 36), mapSet(MINECRAFT_1_19, 37))); empty(id("minecraft:float_range", mapSet(MINECRAFT_1_19_3, 37), mapSet(MINECRAFT_1_19, 38))); - empty(id("minecraft:item_enchantment", mapSet(MINECRAFT_1_19_3, -1), mapSet(MINECRAFT_1_19, 39))); + empty( + id("minecraft:item_enchantment", mapSet(MINECRAFT_1_19_3, -1), mapSet(MINECRAFT_1_19, 39))); empty(id("minecraft:entity_summon", mapSet(MINECRAFT_1_19_3, -1), mapSet(MINECRAFT_1_19, 40))); empty(id("minecraft:dimension", mapSet(MINECRAFT_1_19_3, 38), mapSet(MINECRAFT_1_19, 41))); empty(id("minecraft:gamemode", mapSet(MINECRAFT_1_19_3, 39))); // 1.19.3 - empty(id("minecraft:time", mapSet(MINECRAFT_1_19_3, 40), mapSet(MINECRAFT_1_19, 42))); // added in 1.14 + empty(id("minecraft:time", mapSet(MINECRAFT_1_19_3, 40), + mapSet(MINECRAFT_1_19, 42))); // added in 1.14 - register(id("minecraft:resource_or_tag", mapSet(MINECRAFT_1_19_3, 41), mapSet(MINECRAFT_1_19, 43)), + register( + id("minecraft:resource_or_tag", mapSet(MINECRAFT_1_19_3, 41), mapSet(MINECRAFT_1_19, 43)), RegistryKeyArgument.class, RegistryKeyArgumentSerializer.REGISTRY); register(id("minecraft:resource_or_tag_key", mapSet(MINECRAFT_1_19_3, 42)), - RegistryKeyArgumentList.ResourceOrTagKey.class, RegistryKeyArgumentList.ResourceOrTagKey.Serializer.REGISTRY); + RegistryKeyArgumentList.ResourceOrTagKey.class, + RegistryKeyArgumentList.ResourceOrTagKey.Serializer.REGISTRY); register(id("minecraft:resource", mapSet(MINECRAFT_1_19_3, 43), mapSet(MINECRAFT_1_19, 44)), RegistryKeyArgument.class, RegistryKeyArgumentSerializer.REGISTRY); register(id("minecraft:resource_key", mapSet(MINECRAFT_1_19_3, 44)), - RegistryKeyArgumentList.ResourceKey.class, RegistryKeyArgumentList.ResourceKey.Serializer.REGISTRY); + RegistryKeyArgumentList.ResourceKey.class, + RegistryKeyArgumentList.ResourceKey.Serializer.REGISTRY); empty(id("minecraft:template_mirror", mapSet(MINECRAFT_1_19, 45))); // 1.19 empty(id("minecraft:template_rotation", mapSet(MINECRAFT_1_19, 46))); // 1.19 @@ -245,7 +253,8 @@ public class ArgumentPropertyRegistry { empty(id("minecraft:uuid", mapSet(MINECRAFT_1_19, 47))); // added in 1.16 // Crossstitch support - register(id("crossstitch:mod_argument", mapSet(MINECRAFT_1_19, -256)), ModArgumentProperty.class, MOD); + register(id("crossstitch:mod_argument", mapSet(MINECRAFT_1_19, -256)), + ModArgumentProperty.class, MOD); empty(id("minecraft:nbt")); // No longer in 1.19+ } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertySerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertySerializer.java index 6b05377d6..fdb330f3f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertySerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ArgumentPropertySerializer.java @@ -22,6 +22,7 @@ import io.netty.buffer.ByteBuf; import org.checkerframework.checker.nullness.qual.Nullable; public interface ArgumentPropertySerializer { + @Nullable T deserialize(ByteBuf buf, ProtocolVersion protocolVersion); void serialize(T object, ByteBuf buf, ProtocolVersion protocolVersion); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ModArgumentPropertySerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ModArgumentPropertySerializer.java index db4e6e31d..46c5f1287 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ModArgumentPropertySerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/ModArgumentPropertySerializer.java @@ -24,6 +24,7 @@ import io.netty.buffer.Unpooled; import org.checkerframework.checker.nullness.qual.Nullable; class ModArgumentPropertySerializer implements ArgumentPropertySerializer { + static final ModArgumentPropertySerializer MOD = new ModArgumentPropertySerializer(); private ModArgumentPropertySerializer() { @@ -36,7 +37,7 @@ class ModArgumentPropertySerializer implements ArgumentPropertySerializer= 0) { int idx = ProtocolUtils.readVarInt(buf); identifier = ArgumentIdentifier.id("crossstitch:identified_" + (idx < 0 ? "n" + (-idx) : idx), - ArgumentIdentifier.mapSet(version, idx)); + ArgumentIdentifier.mapSet(version, idx)); } else { identifier = ArgumentIdentifier.id(ProtocolUtils.readString(buf)); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgument.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgument.java index dc08785eb..1e6e56580 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgument.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgument.java @@ -29,6 +29,7 @@ import java.util.List; import java.util.concurrent.CompletableFuture; public class RegistryKeyArgument implements ArgumentType { + private static final List EXAMPLES = Arrays.asList("foo", "foo:bar", "012"); private String identifier; @@ -46,7 +47,8 @@ public class RegistryKeyArgument implements ArgumentType { } @Override - public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + public CompletableFuture listSuggestions(CommandContext context, + SuggestionsBuilder builder) { return Suggestions.empty(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentList.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentList.java index 2b5873a7b..dd5abd1e4 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentList.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentList.java @@ -30,6 +30,7 @@ public final class RegistryKeyArgumentList { } public static class Serializer implements ArgumentPropertySerializer { + static final ResourceOrTag.Serializer REGISTRY = new ResourceOrTag.Serializer(); @Override @@ -51,6 +52,7 @@ public final class RegistryKeyArgumentList { } public static class Serializer implements ArgumentPropertySerializer { + static final ResourceOrTagKey.Serializer REGISTRY = new ResourceOrTagKey.Serializer(); @Override @@ -72,6 +74,7 @@ public final class RegistryKeyArgumentList { } public static class Serializer implements ArgumentPropertySerializer { + static final Resource.Serializer REGISTRY = new Resource.Serializer(); @Override @@ -93,6 +96,7 @@ public final class RegistryKeyArgumentList { } public static class Serializer implements ArgumentPropertySerializer { + static final ResourceKey.Serializer REGISTRY = new ResourceKey.Serializer(); @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentSerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentSerializer.java index 3ba179c46..a82c12b00 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentSerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/RegistryKeyArgumentSerializer.java @@ -21,7 +21,9 @@ import com.velocitypowered.api.network.ProtocolVersion; import com.velocitypowered.proxy.protocol.ProtocolUtils; import io.netty.buffer.ByteBuf; -public class RegistryKeyArgumentSerializer implements ArgumentPropertySerializer { +public class RegistryKeyArgumentSerializer implements + ArgumentPropertySerializer { + static final RegistryKeyArgumentSerializer REGISTRY = new RegistryKeyArgumentSerializer(); @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatHandler.java index f0ee3175a..386de6f4b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatHandler.java @@ -20,6 +20,7 @@ package com.velocitypowered.proxy.protocol.packet.chat; import com.velocitypowered.proxy.protocol.MinecraftPacket; public interface ChatHandler { + Class packetClass(); void handlePlayerChatInternal(T packet); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatQueue.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatQueue.java index 28b0b9fc5..c37a0b6a7 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatQueue.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatQueue.java @@ -26,9 +26,11 @@ import java.util.function.BiConsumer; import org.apache.logging.log4j.LogManager; /** - * A precisely ordered queue which allows for outside entries into the ordered queue through piggybacking timestamps. + * A precisely ordered queue which allows for outside entries into the ordered queue through + * piggybacking timestamps. */ public class ChatQueue { + private final Object internalLock; private final ConnectedPlayer player; private CompletableFuture packetFuture; @@ -45,10 +47,9 @@ public class ChatQueue { } /** - * Queues a packet sent from the player - all packets must wait until this processes to send their packets. - *
- * This maintains order on the server-level for the client insertions of commands and messages. All entries are locked - * through an internal object lock. + * Queues a packet sent from the player - all packets must wait until this processes to send their + * packets. This maintains order on the server-level for the client insertions of commands + * and messages. All entries are locked through an internal object lock. * * @param nextPacket the {@link CompletableFuture} which will provide the next-processed packet. * @param timestamp the {@link Instant} timestamp of this packet so we can allow piggybacking. @@ -58,22 +59,24 @@ public class ChatQueue { MinecraftConnection smc = player.ensureAndGetCurrentServer().ensureConnected(); CompletableFuture nextInLine = WrappedPacket.wrap(timestamp, nextPacket); - awaitChat(smc, this.packetFuture, nextInLine); // we await chat, binding `this.packetFuture` -> `nextInLine` + awaitChat(smc, this.packetFuture, + nextInLine); // we await chat, binding `this.packetFuture` -> `nextInLine` this.packetFuture = nextInLine; } } /** - * Hijacks the latest sent packet's timestamp to provide an in-order packet without polling the physical, or prior - * packets sent through the stream. + * Hijacks the latest sent packet's timestamp to provide an in-order packet without polling the + * physical, or prior packets sent through the stream. * * @param packet the {@link MinecraftPacket} to send. - * @param instantMapper the {@link InstantPacketMapper} which maps the prior timestamp and current packet to a new - * packet. + * @param instantMapper the {@link InstantPacketMapper} which maps the prior timestamp and current + * packet to a new packet. * @param the type of base to expect when mapping the packet. * @param the type of packet for instantMapper type-checking. */ - public void hijack(K packet, InstantPacketMapper instantMapper) { + public void hijack(K packet, + InstantPacketMapper instantMapper) { synchronized (internalLock) { CompletableFuture trueFuture = CompletableFuture.completedFuture(packet); MinecraftConnection smc = player.ensureAndGetCurrentServer().ensureConnected(); @@ -109,9 +112,11 @@ public class ChatQueue { // the binder will complete -> then the future will get the `write packet` caller binder.whenComplete((previous, ignored) -> { // map the new packet into a better "designed" packet with the hijacked packet's timestamp - WrappedPacket.wrap(previous.timestamp, future.thenApply(item -> packetMapper.map(previous.timestamp, item))) + WrappedPacket.wrap(previous.timestamp, + future.thenApply(item -> packetMapper.map(previous.timestamp, item))) .whenCompleteAsync(writePacket(connection), connection.eventLoop()) - .whenComplete((packet, throwable) -> awaitedFuture.complete(throwable != null ? null : packet)); + .whenComplete( + (packet, throwable) -> awaitedFuture.complete(throwable != null ? null : packet)); }); return awaitedFuture; } @@ -123,6 +128,7 @@ public class ChatQueue { * @param The resulting packet type. */ public interface InstantPacketMapper { + /** * Maps a value into a packet with it and a timestamp. * @@ -134,6 +140,7 @@ public class ChatQueue { } private static class WrappedPacket { + private final Instant timestamp; private final MinecraftPacket packet; @@ -149,7 +156,7 @@ public class ChatQueue { } private static CompletableFuture wrap(Instant timestamp, - CompletableFuture nextPacket) { + CompletableFuture nextPacket) { return nextPacket .thenApply(pkt -> new WrappedPacket(timestamp, pkt)) .exceptionally(ignored -> new WrappedPacket(timestamp, null)); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatTimeKeeper.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatTimeKeeper.java index 653662002..e62161784 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatTimeKeeper.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ChatTimeKeeper.java @@ -20,6 +20,7 @@ package com.velocitypowered.proxy.protocol.packet.chat; import java.time.Instant; public class ChatTimeKeeper { + private Instant lastTimestamp; public ChatTimeKeeper() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/CommandHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/CommandHandler.java index 20c295cc9..e8af00a0a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/CommandHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/CommandHandler.java @@ -30,6 +30,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public interface CommandHandler { + Logger logger = LogManager.getLogger(CommandHandler.class); Class packetClass(); @@ -44,16 +45,19 @@ public interface CommandHandler { return false; } - default CompletableFuture runCommand(VelocityServer server, ConnectedPlayer player, String command, - Function hasRunPacketFunction) { - return server.getCommandManager().executeImmediatelyAsync(player, command).thenApply(hasRunPacketFunction); + default CompletableFuture runCommand(VelocityServer server, + ConnectedPlayer player, String command, + Function hasRunPacketFunction) { + return server.getCommandManager().executeImmediatelyAsync(player, command) + .thenApply(hasRunPacketFunction); } default void queueCommandResult(VelocityServer server, ConnectedPlayer player, - Function> futurePacketCreator, - String message, Instant timestamp) { + Function> futurePacketCreator, + String message, Instant timestamp) { player.getChatQueue().queuePacket( - server.getCommandManager().callCommandEvent(player, message).thenComposeAsync(futurePacketCreator) + server.getCommandManager().callCommandEvent(player, message) + .thenComposeAsync(futurePacketCreator) .thenApply(pkt -> { if (server.getConfiguration().isLogCommandExecutions()) { logger.info("{} -> executed command /{}", player, message); @@ -61,7 +65,8 @@ public interface CommandHandler { return pkt; }).exceptionally(e -> { logger.info("Exception occurred while running command for {}", player.getUsername(), e); - player.sendMessage(Component.translatable("velocity.command.generic-error", NamedTextColor.RED)); + player.sendMessage( + Component.translatable("velocity.command.generic-error", NamedTextColor.RED)); return null; }), timestamp); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/LastSeenMessages.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/LastSeenMessages.java index dea8e3e17..a61d19d7d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/LastSeenMessages.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/LastSeenMessages.java @@ -23,6 +23,7 @@ import java.util.Arrays; import java.util.BitSet; public class LastSeenMessages { + private static final int DIV_FLOOR = -Math.floorDiv(-20, 8); private int offset; private BitSet acknowledged; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/PlayerChatCompletion.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/PlayerChatCompletion.java index 212c90476..5fd4f831c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/PlayerChatCompletion.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/PlayerChatCompletion.java @@ -46,13 +46,15 @@ public class PlayerChatCompletion implements MinecraftPacket { } @Override - public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void decode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { action = Action.values()[ProtocolUtils.readVarInt(buf)]; completions = ProtocolUtils.readStringArray(buf); } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { ProtocolUtils.writeVarInt(buf, action.ordinal()); ProtocolUtils.writeStringArray(buf, completions); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/RemoteChatSession.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/RemoteChatSession.java index fdd37726a..4536079bf 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/RemoteChatSession.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/RemoteChatSession.java @@ -27,6 +27,7 @@ import java.util.UUID; import org.checkerframework.checker.nullness.qual.Nullable; public class RemoteChatSession implements ChatSession { + private final @Nullable UUID sessionId; private final IdentifiedKey identifiedKey; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChat.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChat.java index 237c8cafc..1cbfd5524 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChat.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChat.java @@ -26,7 +26,8 @@ import net.kyori.adventure.text.Component; public class SystemChat implements MinecraftPacket { - public SystemChat() {} + public SystemChat() { + } public SystemChat(Component component, ChatType type) { this.component = component; @@ -45,15 +46,19 @@ public class SystemChat implements MinecraftPacket { } @Override - public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { - component = ProtocolUtils.getJsonChatSerializer(protocolVersion).deserialize(ProtocolUtils.readString(buf)); + public void decode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { + component = ProtocolUtils.getJsonChatSerializer(protocolVersion) + .deserialize(ProtocolUtils.readString(buf)); // System chat is never decoded so this doesn't matter for now type = ChatType.values()[ProtocolUtils.readVarInt(buf)]; } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { - ProtocolUtils.writeString(buf, ProtocolUtils.getJsonChatSerializer(protocolVersion).serialize(component)); + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { + ProtocolUtils.writeString(buf, + ProtocolUtils.getJsonChatSerializer(protocolVersion).serialize(component)); if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_19_1) >= 0) { switch (type) { case SYSTEM: diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderFactory.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderFactory.java index cc415b693..ff782df02 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderFactory.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderFactory.java @@ -24,6 +24,7 @@ import com.velocitypowered.proxy.protocol.packet.chat.session.SessionChatBuilder import java.util.function.Function; public class ChatBuilderFactory { + private final ProtocolVersion version; private final Function builderFunction; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderV2.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderV2.java index b96fe3871..8eff4eb5a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderV2.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/builder/ChatBuilderV2.java @@ -28,6 +28,7 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; public abstract class ChatBuilderV2 { + protected final ProtocolVersion version; protected @MonotonicNonNull Component component; protected @MonotonicNonNull String message; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatBuilder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatBuilder.java index ab377ee97..717f97911 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatBuilder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatBuilder.java @@ -26,6 +26,7 @@ import com.velocitypowered.proxy.protocol.packet.chat.builder.ChatBuilderV2; import net.kyori.adventure.text.Component; public class KeyedChatBuilder extends ChatBuilderV2 { + public KeyedChatBuilder(ProtocolVersion version) { super(version); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatHandler.java index 9f895295f..5afb246b9 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedChatHandler.java @@ -30,7 +30,9 @@ import net.kyori.adventure.text.Component; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -public class KeyedChatHandler implements com.velocitypowered.proxy.protocol.packet.chat.ChatHandler { +public class KeyedChatHandler implements + com.velocitypowered.proxy.protocol.packet.chat.ChatHandler { + private static final Logger logger = LogManager.getLogger(KeyedChatHandler.class); private final VelocityServer server; @@ -84,7 +86,8 @@ public class KeyedChatHandler implements com.velocitypowered.proxy.protocol.pack } return player.getChatBuilderFactory().builder() - .message(chatResult.getMessage().orElse(packet.getMessage())).setTimestamp(packet.getExpiry()).toServer(); + .message(chatResult.getMessage().orElse(packet.getMessage())) + .setTimestamp(packet.getExpiry()).toServer(); }); } chatQueue.queuePacket( @@ -101,7 +104,8 @@ public class KeyedChatHandler implements com.velocitypowered.proxy.protocol.pack assert playerKey != null; return pme -> { PlayerChatEvent.ChatResult chatResult = pme.getResult(); - if (!chatResult.isAllowed() && playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) { + if (!chatResult.isAllowed() + && playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) { invalidCancel(logger, player); return null; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedCommandHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedCommandHandler.java index 2427c973e..669c1be63 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedCommandHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedCommandHandler.java @@ -27,6 +27,7 @@ import java.util.concurrent.CompletableFuture; import net.kyori.adventure.text.Component; public class KeyedCommandHandler implements CommandHandler { + private final ConnectedPlayer player; private final VelocityServer server; @@ -47,11 +48,14 @@ public class KeyedCommandHandler implements CommandHandler { IdentifiedKey playerKey = player.getIdentifiedKey(); if (result == CommandExecuteEvent.CommandResult.denied()) { if (playerKey != null) { - if (!packet.isUnsigned() && playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) { - logger.fatal("A plugin tried to deny a command with signable component(s). " + "This is not supported. " + if (!packet.isUnsigned() + && playerKey.getKeyRevision().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()); player.disconnect(Component.text( - "A proxy plugin caused an illegal protocol state. " + "Contact your network administrator.")); + "A proxy plugin caused an illegal protocol state. " + + "Contact your network administrator.")); } } return CompletableFuture.completedFuture(null); @@ -69,10 +73,12 @@ public class KeyedCommandHandler implements CommandHandler { } else { if (!packet.isUnsigned() && playerKey != null && playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) { - logger.fatal("A plugin tried to change a command with signed component(s). " + "This is not supported. " + logger.fatal("A plugin tried to change a command with signed component(s). " + + "This is not supported. " + "Disconnecting player " + player.getUsername()); player.disconnect(Component.text( - "A proxy plugin caused an illegal protocol state. " + "Contact your network administrator.")); + "A proxy plugin caused an illegal protocol state. " + + "Contact your network administrator.")); return CompletableFuture.completedFuture(null); } write.message("/" + commandToRun); @@ -87,10 +93,12 @@ public class KeyedCommandHandler implements CommandHandler { if (!packet.isUnsigned() && playerKey != null && playerKey.getKeyRevision().compareTo(IdentifiedKey.Revision.LINKED_V2) >= 0) { - logger.fatal("A plugin tried to change a command with signed component(s). " + "This is not supported. " + logger.fatal("A plugin tried to change a command with signed component(s). " + + "This is not supported. " + "Disconnecting player " + player.getUsername()); player.disconnect(Component.text( - "A proxy plugin caused an illegal protocol state. " + "Contact your network administrator.")); + "A proxy plugin caused an illegal protocol state. " + + "Contact your network administrator.")); return null; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerChat.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerChat.java index f3a88671d..2c428bd34 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerChat.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerChat.java @@ -74,7 +74,8 @@ public class KeyedPlayerChat implements MinecraftPacket { } @Override - public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void decode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { message = ProtocolUtils.readString(buf, 256); long expiresAt = buf.readLong(); @@ -105,18 +106,21 @@ public class KeyedPlayerChat implements MinecraftPacket { SignaturePair[] lastSignatures = new SignaturePair[size]; for (int i = 0; i < size; i++) { - lastSignatures[i] = new SignaturePair(ProtocolUtils.readUuid(buf), ProtocolUtils.readByteArray(buf)); + lastSignatures[i] = new SignaturePair(ProtocolUtils.readUuid(buf), + ProtocolUtils.readByteArray(buf)); } previousMessages = lastSignatures; if (buf.readBoolean()) { - lastMessage = new SignaturePair(ProtocolUtils.readUuid(buf), ProtocolUtils.readByteArray(buf)); + lastMessage = new SignaturePair(ProtocolUtils.readUuid(buf), + ProtocolUtils.readByteArray(buf)); } } } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { ProtocolUtils.writeString(buf, message); buf.writeLong(unsigned ? Instant.now().toEpochMilli() : expiry.toEpochMilli()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerCommand.java index 661026b48..666fb7a95 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/keyed/KeyedPlayerCommand.java @@ -85,7 +85,8 @@ public class KeyedPlayerCommand implements MinecraftPacket { } @Override - public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void decode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { command = ProtocolUtils.readString(buf, 256); timestamp = Instant.ofEpochMilli(buf.readLong()); @@ -116,12 +117,14 @@ public class KeyedPlayerCommand implements MinecraftPacket { SignaturePair[] lastSignatures = new SignaturePair[size]; for (int i = 0; i < size; i++) { - lastSignatures[i] = new SignaturePair(ProtocolUtils.readUuid(buf), ProtocolUtils.readByteArray(buf)); + lastSignatures[i] = new SignaturePair(ProtocolUtils.readUuid(buf), + ProtocolUtils.readByteArray(buf)); } previousMessages = lastSignatures; if (buf.readBoolean()) { - lastMessage = new SignaturePair(ProtocolUtils.readUuid(buf), ProtocolUtils.readByteArray(buf)); + lastMessage = new SignaturePair(ProtocolUtils.readUuid(buf), + ProtocolUtils.readByteArray(buf)); } } @@ -132,7 +135,8 @@ public class KeyedPlayerCommand implements MinecraftPacket { } @Override - public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion protocolVersion) { + public void encode(ByteBuf buf, ProtocolUtils.Direction direction, + ProtocolVersion protocolVersion) { ProtocolUtils.writeString(buf, command); buf.writeLong(timestamp.toEpochMilli()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChat.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChat.java index 0314994cf..e2f8e9ea2 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChat.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChat.java @@ -92,7 +92,8 @@ public class LegacyChat implements MinecraftPacket { @Override public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) { message = ProtocolUtils.readString(buf); - if (direction == ProtocolUtils.Direction.CLIENTBOUND && version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { + if (direction == ProtocolUtils.Direction.CLIENTBOUND + && version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { type = buf.readByte(); if (version.compareTo(ProtocolVersion.MINECRAFT_1_16) >= 0) { sender = ProtocolUtils.readUuid(buf); @@ -106,7 +107,8 @@ public class LegacyChat implements MinecraftPacket { throw new IllegalStateException("Message is not specified"); } ProtocolUtils.writeString(buf, message); - if (direction == ProtocolUtils.Direction.CLIENTBOUND && version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { + if (direction == ProtocolUtils.Direction.CLIENTBOUND + && version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) { buf.writeByte(type); if (version.compareTo(ProtocolVersion.MINECRAFT_1_16) >= 0) { ProtocolUtils.writeUuid(buf, sender == null ? EMPTY_SENDER : sender); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatBuilder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatBuilder.java index 4bdaccd3f..8f13f3798 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatBuilder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatBuilder.java @@ -26,6 +26,7 @@ import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; public class LegacyChatBuilder extends ChatBuilderV2 { + public LegacyChatBuilder(ProtocolVersion version) { super(version); } @@ -37,7 +38,8 @@ public class LegacyChatBuilder extends ChatBuilderV2 { : senderIdentity.uuid()) : sender.getUniqueId(); Component msg = component == null ? Component.text(message) : component; - return new LegacyChat(ProtocolUtils.getJsonChatSerializer(version).serialize(msg), type.getId(), identity); + return new LegacyChat(ProtocolUtils.getJsonChatSerializer(version).serialize(msg), type.getId(), + identity); } @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatHandler.java index 767c59543..0749939cc 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyChatHandler.java @@ -24,6 +24,7 @@ import com.velocitypowered.proxy.connection.client.ConnectedPlayer; import com.velocitypowered.proxy.protocol.packet.chat.ChatHandler; public class LegacyChatHandler implements ChatHandler { + private final VelocityServer server; private final ConnectedPlayer player; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyCommandHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyCommandHandler.java index e8c8be6cb..27e40b587 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyCommandHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/legacy/LegacyCommandHandler.java @@ -25,6 +25,7 @@ import java.time.Instant; import java.util.concurrent.CompletableFuture; public class LegacyCommandHandler implements CommandHandler { + private final ConnectedPlayer player; private final VelocityServer server; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatBuilder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatBuilder.java index beb245253..80bce9e13 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatBuilder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatBuilder.java @@ -26,6 +26,7 @@ import com.velocitypowered.proxy.protocol.packet.chat.builder.ChatBuilderV2; import net.kyori.adventure.text.Component; public class SessionChatBuilder extends ChatBuilderV2 { + public SessionChatBuilder(ProtocolVersion version) { super(version); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatHandler.java index 5085d78fa..406e2e906 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionChatHandler.java @@ -30,6 +30,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SessionChatHandler implements ChatHandler { + private static final Logger logger = LogManager.getLogger(SessionChatHandler.class); private final ConnectedPlayer player; @@ -61,7 +62,8 @@ public class SessionChatHandler implements ChatHandler { return null; } - if (chatResult.getMessage().map(str -> !str.equals(packet.getMessage())).orElse(false)) { + if (chatResult.getMessage().map(str -> !str.equals(packet.getMessage())) + .orElse(false)) { if (packet.isSigned()) { invalidChange(logger, player); return null; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionCommandHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionCommandHandler.java index b21238ff3..3d9082b6f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionCommandHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/session/SessionCommandHandler.java @@ -25,6 +25,7 @@ import java.util.concurrent.CompletableFuture; import net.kyori.adventure.text.Component; public class SessionCommandHandler implements CommandHandler { + private final ConnectedPlayer player; private final VelocityServer server; @@ -44,10 +45,12 @@ public class SessionCommandHandler implements CommandHandler entries; public ArgumentSignatures() { @@ -80,7 +84,8 @@ public class SessionPlayerCommand implements MinecraftPacket { public ArgumentSignatures(ByteBuf buf) { int size = ProtocolUtils.readVarInt(buf); if (size > 8) { - throw new QuietDecoderException(String.format("Too many argument signatures, %d is above limit %d", size, 8)); + throw new QuietDecoderException( + String.format("Too many argument signatures, %d is above limit %d", size, 8)); } this.entries = Lists.newArrayListWithCapacity(size); @@ -102,6 +107,7 @@ public class SessionPlayerCommand implements MinecraftPacket { } public static class ArgumentSignature { + private final String name; private final byte[] signature; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java index 38c890c03..d4d0fca68 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java @@ -41,7 +41,7 @@ public abstract class GenericTitlePacket implements MinecraftPacket { public int getAction(ProtocolVersion version) { return version.compareTo(ProtocolVersion.MINECRAFT_1_11) < 0 - ? action > 2 ? action - 1 : action : action; + ? action > 2 ? action - 1 : action : action; } } @@ -89,18 +89,17 @@ public abstract class GenericTitlePacket implements MinecraftPacket { } - @Override public final void decode(ByteBuf buf, ProtocolUtils.Direction direction, - ProtocolVersion version) { + ProtocolVersion version) { throw new UnsupportedOperationException(); // encode only } /** * Creates a version and type dependent TitlePacket. * - * @param type Action the packet should invoke - * @param version Protocol version of the target player + * @param type Action the packet should invoke + * @param version Protocol version of the target player * @return GenericTitlePacket instance that follows the invoker type/version */ public static GenericTitlePacket constructTitlePacket(ActionType type, ProtocolVersion version) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java index 7b25325e6..1d0350945 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java @@ -33,7 +33,7 @@ public class LegacyTitlePacket extends GenericTitlePacket { @Override public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) { if (version.compareTo(ProtocolVersion.MINECRAFT_1_11) < 0 - && getAction() == ActionType.SET_ACTION_BAR) { + && getAction() == ActionType.SET_ACTION_BAR) { throw new IllegalStateException("Action bars are only supported on 1.11 and newer"); } ProtocolUtils.writeVarInt(buf, getAction().getAction(version)); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java index b1447c87c..da41f2d58 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java @@ -24,8 +24,12 @@ import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.velocitypowered.api.util.Favicon; +import com.velocitypowered.api.util.GameProfile; import java.lang.reflect.Type; +/** + * Serializes {@link Favicon} instances into JSON. + */ public final class FaviconSerializer implements JsonSerializer, JsonDeserializer { public static final FaviconSerializer INSTANCE = new FaviconSerializer(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/GameProfileSerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/GameProfileSerializer.java index 96de26103..63aae16bc 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/GameProfileSerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/GameProfileSerializer.java @@ -30,11 +30,15 @@ import com.velocitypowered.api.util.GameProfile.Property; import java.lang.reflect.Type; import java.util.List; +/** + * Serializes {@link GameProfile} instances into JSON. + */ public final class GameProfileSerializer implements JsonSerializer, JsonDeserializer { public static final GameProfileSerializer INSTANCE = new GameProfileSerializer(); - private static final Type propertyList = new TypeToken>() {}.getType(); + private static final Type propertyList = new TypeToken>() { + }.getType(); private GameProfileSerializer() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/NettyPreconditions.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/NettyPreconditions.java index 52bdb75dc..42ba250ac 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/NettyPreconditions.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/NettyPreconditions.java @@ -23,9 +23,11 @@ import com.velocitypowered.proxy.util.except.QuietDecoderException; import io.netty.handler.codec.CorruptedFrameException; /** - * Extends {@link com.google.common.base.Preconditions} for Netty's {@link CorruptedFrameException}. + * Extends {@link com.google.common.base.Preconditions} for Netty's + * {@link CorruptedFrameException}. */ public final class NettyPreconditions { + private static final QuietDecoderException BAD = new QuietDecoderException( "Invalid packet received. Launch Velocity with -Dvelocity.packet-decode-logging=true " + "to see more."); @@ -36,7 +38,8 @@ public final class NettyPreconditions { /** * Throws {@link CorruptedFrameException} if {@code b} is false. - * @param b the expression to check + * + * @param b the expression to check * @param message the message to include in the thrown {@link CorruptedFrameException} */ public static void checkFrame(boolean b, String message) { @@ -47,11 +50,12 @@ public final class NettyPreconditions { /** * Throws {@link CorruptedFrameException} if {@code b} is false. - * @param b the expression to check + * + * @param b the expression to check * @param message the message to include in the thrown {@link CorruptedFrameException}, formatted * like {@link com.google.common.base.Preconditions#checkArgument(boolean)} and * friends - * @param arg1 the first argument to format the message with + * @param arg1 the first argument to format the message with */ public static void checkFrame(boolean b, String message, Object arg1) { if (!b) { @@ -65,12 +69,13 @@ public final class NettyPreconditions { /** * Throws {@link CorruptedFrameException} if {@code b} is false. - * @param b the expression to check + * + * @param b the expression to check * @param message the message to include in the thrown {@link CorruptedFrameException}, formatted * like {@link com.google.common.base.Preconditions#checkArgument(boolean)} and * friends - * @param arg1 the first argument to format the message with - * @param arg2 the second argument to format the message with + * @param arg1 the first argument to format the message with + * @param arg2 the second argument to format the message with */ public static void checkFrame(boolean b, String message, Object arg1, Object arg2) { if (!b) { @@ -84,11 +89,12 @@ public final class NettyPreconditions { /** * Throws {@link CorruptedFrameException} if {@code b} is false. - * @param b the expression to check + * + * @param b the expression to check * @param message the message to include in the thrown {@link CorruptedFrameException}, formatted * like {@link com.google.common.base.Preconditions#checkArgument(boolean)} and * friends - * @param args the arguments to format the message with- + * @param args the arguments to format the message with- */ public static void checkFrame(boolean b, String message, Object... args) { if (!b) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java index 51787428c..101d73b4a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java @@ -33,6 +33,9 @@ import java.util.List; import java.util.Locale; import java.util.regex.Pattern; +/** + * Utilities for handling plugin messages. + */ public final class PluginMessageUtil { private static final String BRAND_CHANNEL_LEGACY = "MC|Brand"; @@ -48,6 +51,7 @@ public final class PluginMessageUtil { /** * Determines whether or not this is a brand plugin message. This is shown on the client. + * * @param message the plugin message * @return whether or not this is a brand plugin message */ @@ -59,6 +63,7 @@ public final class PluginMessageUtil { /** * Determines whether or not this plugin message is being used to register plugin channels. + * * @param message the plugin message * @return whether we are registering plugin channels or not */ @@ -70,6 +75,7 @@ public final class PluginMessageUtil { /** * Determines whether or not this plugin message is being used to unregister plugin channels. + * * @param message the plugin message * @return whether we are unregistering plugin channels or not */ @@ -81,13 +87,14 @@ public final class PluginMessageUtil { /** * Fetches all the channels in a register or unregister plugin message. + * * @param message the message to get the channels from * @return the channels, as an immutable list */ public static List getChannels(PluginMessage message) { checkNotNull(message, "message"); checkArgument(isRegister(message) || isUnregister(message), "Unknown channel type %s", - message.getChannel()); + message.getChannel()); if (!message.content().isReadable()) { // If we try to split this, we will get an one-element array with the empty string, which // has caused issues with 1.13+ compatibility. Just return an empty list. @@ -99,12 +106,13 @@ public final class PluginMessageUtil { /** * Constructs a channel (un)register packet. + * * @param protocolVersion the client/server's protocol version - * @param channels the channels to register + * @param channels the channels to register * @return the plugin message to send */ public static PluginMessage constructChannelsPacket(ProtocolVersion protocolVersion, - Collection channels) { + Collection channels) { checkNotNull(channels, "channels"); checkArgument(!channels.isEmpty(), "no channels specified"); String channelName = protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0 @@ -116,6 +124,7 @@ public final class PluginMessageUtil { /** * Rewrites the brand message to indicate the presence of Velocity. + * * @param message the plugin message * @param version the proxy version * @return the rewritten plugin message @@ -140,10 +149,11 @@ public final class PluginMessageUtil { } /** - * Some clients (mostly poorly-implemented bots) do not send validly-formed brand messages. - * In order to accommodate their broken behavior, we'll first try to read in the 1.8 format, and - * if that fails, treat it as a 1.7-format message (which has no prefixed length). (The message + * Some clients (mostly poorly-implemented bots) do not send validly-formed brand messages. In + * order to accommodate their broken behavior, we'll first try to read in the 1.8 format, and if + * that fails, treat it as a 1.7-format message (which has no prefixed length). (The message * Velocity sends will be in the correct format depending on the protocol.) + * * @param content the brand packet * @return the client brand */ @@ -158,7 +168,8 @@ public final class PluginMessageUtil { private static final Pattern INVALID_IDENTIFIER_REGEX = Pattern.compile("[^a-z0-9\\-_]*"); /** - * Transform a plugin message channel from a "legacy" (<1.13) form to a modern one. + * Transform a plugin message channel from a "legacy" (less than 1.13) form to a modern one. + * * @param name the existing name * @return the new name */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/VelocityLegacyHoverEventSerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/VelocityLegacyHoverEventSerializer.java index 07e2dec38..a43ca1c85 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/VelocityLegacyHoverEventSerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/VelocityLegacyHoverEventSerializer.java @@ -35,8 +35,8 @@ import net.kyori.adventure.util.Codec.Encoder; import org.checkerframework.checker.nullness.qual.NonNull; /** - * An implementation of {@link LegacyHoverEventSerializer} that implements the interface in the - * most literal, albeit "incompatible" way possible. + * An implementation of {@link LegacyHoverEventSerializer} that implements the interface in the most + * literal, albeit "incompatible" way possible. */ public class VelocityLegacyHoverEventSerializer implements LegacyHoverEventSerializer { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/scheduler/VelocityScheduler.java b/proxy/src/main/java/com/velocitypowered/proxy/scheduler/VelocityScheduler.java index 5e9b0013e..18dbf2cf8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/scheduler/VelocityScheduler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/scheduler/VelocityScheduler.java @@ -43,6 +43,12 @@ import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * The Velocity "scheduler", which is actually a thin wrapper around + * {@link ScheduledExecutorService} and a dynamically-sized {@link ExecutorService}. + * Many plugins are accustomed to the Bukkit Scheduler model although it is not relevant + * in a proxy context. + */ public class VelocityScheduler implements Scheduler { private final PluginManager pluginManager; @@ -93,6 +99,7 @@ public class VelocityScheduler implements Scheduler { /** * Shuts down the Velocity scheduler. + * * @return {@code true} if all tasks finished, {@code false} otherwise * @throws InterruptedException if the current thread was interrupted */ @@ -166,7 +173,8 @@ public class VelocityScheduler implements Scheduler { private @Nullable ScheduledFuture future; private volatile @Nullable Thread currentTaskThread; - private VelocityTask(Object plugin, Runnable runnable, Consumer consumer, long delay, long repeat) { + private VelocityTask(Object plugin, Runnable runnable, Consumer consumer, + long delay, long repeat) { this.plugin = plugin; this.runnable = runnable; this.consumer = consumer; @@ -236,7 +244,7 @@ public class VelocityScheduler implements Scheduler { } else { String friendlyPluginName = pluginManager.fromInstance(plugin) .map(container -> container.getDescription().getName() - .orElse(container.getDescription().getId())) + .orElse(container.getDescription().getId())) .orElse("UNKNOWN"); Log.logger.error("Exception in task {} by plugin {}", runnable, friendlyPluginName, e); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/server/PingSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/server/PingSessionHandler.java index 0e2c5a57a..493bf1c14 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/server/PingSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/server/PingSessionHandler.java @@ -27,9 +27,14 @@ import com.velocitypowered.proxy.protocol.StateRegistry; import com.velocitypowered.proxy.protocol.packet.Handshake; import com.velocitypowered.proxy.protocol.packet.StatusRequest; import com.velocitypowered.proxy.protocol.packet.StatusResponse; +import io.netty.channel.EventLoop; import java.io.IOException; import java.util.concurrent.CompletableFuture; +/** + * Session handler used to implement + * {@link VelocityRegisteredServer#ping(EventLoop, ProtocolVersion)}. + */ public class PingSessionHandler implements MinecraftSessionHandler { private final CompletableFuture result; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/server/ServerMap.java b/proxy/src/main/java/com/velocitypowered/proxy/server/ServerMap.java index 00fc2edd6..e16751095 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/server/ServerMap.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/server/ServerMap.java @@ -29,6 +29,9 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Implements the Velocity server registry. + */ public class ServerMap { private final @Nullable VelocityServer server; @@ -55,8 +58,8 @@ public class ServerMap { } /** - * Creates a raw implementation of a {@link RegisteredServer} without - * tying it to the internal server map. + * Creates a raw implementation of a {@link RegisteredServer} without tying it to the internal + * server map. * * @param serverInfo the server to create a registered server with * @return the {@link RegisteredServer} built from the {@link ServerInfo} diff --git a/proxy/src/main/java/com/velocitypowered/proxy/server/VelocityRegisteredServer.java b/proxy/src/main/java/com/velocitypowered/proxy/server/VelocityRegisteredServer.java index af49cf1e2..bd74ae50b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/server/VelocityRegisteredServer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/server/VelocityRegisteredServer.java @@ -59,6 +59,9 @@ import net.kyori.adventure.audience.ForwardingAudience; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Represents a server registered on the proxy. + */ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAudience { private final @Nullable VelocityServer server; @@ -88,7 +91,8 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud /** * Pings the specified server using the specified event {@code loop}, claiming to be * {@code version}. - * @param loop the event loop to use + * + * @param loop the event loop to use * @param version the version to report * @return the server list ping response */ @@ -146,7 +150,7 @@ public class VelocityRegisteredServer implements RegisteredServer, ForwardingAud * afterwards. * * @param identifier the channel ID to use - * @param data the data + * @param data the data * @return whether or not the message was sent */ public boolean sendPluginMessage(ChannelIdentifier identifier, ByteBuf data) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/InternalTabList.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/InternalTabList.java index 0d8d5c512..c01b5619e 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/InternalTabList.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/InternalTabList.java @@ -22,7 +22,11 @@ import com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItem; import com.velocitypowered.proxy.protocol.packet.RemovePlayerInfo; import com.velocitypowered.proxy.protocol.packet.UpsertPlayerInfo; +/** + * Tab list interface with methods for handling player info packets. + */ public interface InternalTabList extends TabList { + default void processLegacy(LegacyPlayerListItem packet) { } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabList.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabList.java index a32aee8de..ced8fc147 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabList.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabList.java @@ -42,6 +42,9 @@ import java.util.concurrent.ConcurrentHashMap; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Exposes the tab list to plugins. + */ public class KeyedVelocityTabList implements InternalTabList { protected final ConnectedPlayer player; @@ -83,7 +86,8 @@ public class KeyedVelocityTabList implements InternalTabList { LegacyPlayerListItem.Item packetItem = LegacyPlayerListItem.Item.from(entry); connection.write( - new LegacyPlayerListItem(LegacyPlayerListItem.ADD_PLAYER, Collections.singletonList(packetItem))); + new LegacyPlayerListItem(LegacyPlayerListItem.ADD_PLAYER, + Collections.singletonList(packetItem))); entries.put(entry.getProfile().getId(), (KeyedVelocityTabListEntry) entry); } @@ -95,7 +99,8 @@ public class KeyedVelocityTabList implements InternalTabList { if (entry != null) { LegacyPlayerListItem.Item packetItem = LegacyPlayerListItem.Item.from(entry); connection.write( - new LegacyPlayerListItem(LegacyPlayerListItem.REMOVE_PLAYER, Collections.singletonList(packetItem))); + new LegacyPlayerListItem(LegacyPlayerListItem.REMOVE_PLAYER, + Collections.singletonList(packetItem))); } return Optional.ofNullable(entry); @@ -108,9 +113,9 @@ public class KeyedVelocityTabList implements InternalTabList { } /** - * Clears all entries from the tab list. Note that the entries are written with {@link - * MinecraftConnection#delayedWrite(Object)}, so make sure to do an explicit {@link - * MinecraftConnection#flush()}. + * Clears all entries from the tab list. Note that the entries are written with + * {@link MinecraftConnection#delayedWrite(Object)}, so make sure to do an explicit + * {@link MinecraftConnection#flush()}. */ @Override public void clearAll() { @@ -133,14 +138,15 @@ public class KeyedVelocityTabList implements InternalTabList { @Override public TabListEntry buildEntry(GameProfile profile, - net.kyori.adventure.text.@Nullable Component displayName, - int latency, int gameMode, @Nullable IdentifiedKey key) { + net.kyori.adventure.text.@Nullable Component displayName, + int latency, int gameMode, @Nullable IdentifiedKey key) { return new KeyedVelocityTabListEntry(this, profile, displayName, latency, gameMode, key); } @Override - public TabListEntry buildEntry(GameProfile profile, @Nullable Component displayName, int latency, int gameMode, - @Nullable ChatSession chatSession, boolean listed) { + public TabListEntry buildEntry(GameProfile profile, @Nullable Component displayName, int latency, + int gameMode, + @Nullable ChatSession chatSession, boolean listed) { return new KeyedVelocityTabListEntry(this, profile, displayName, latency, gameMode, chatSession == null ? null : chatSession.getIdentifiedKey()); } @@ -165,24 +171,6 @@ public class KeyedVelocityTabList implements InternalTabList { if (name == null || properties == null) { throw new IllegalStateException("Got null game profile for ADD_PLAYER"); } - /* why are we verifying the key here - multi-proxy setups break this - // Verify key - IdentifiedKey providedKey = item.getPlayerKey(); - Optional connected = proxyServer.getPlayer(uuid); - if (connected.isPresent()) { - IdentifiedKey expectedKey = connected.get().getIdentifiedKey(); - if (providedKey != null) { - if (!Objects.equals(expectedKey, providedKey)) { - throw new IllegalStateException("Server provided incorrect player key in playerlist for " - + name + " UUID: " + uuid); - } - } else { - // Substitute the key - // It shouldn't be propagated to remove the signature. - providedKey = expectedKey; - } - } - */ entries.putIfAbsent(item.getUuid(), (KeyedVelocityTabListEntry) TabListEntry.builder() .tabList(this) @@ -236,7 +224,8 @@ public class KeyedVelocityTabList implements InternalTabList { } if (selectedKey != null - && selectedKey.getKeyRevision().getApplicableTo().contains(connection.getProtocolVersion()) + && selectedKey.getKeyRevision().getApplicableTo() + .contains(connection.getProtocolVersion()) && Objects.equals(selectedKey.getSignatureHolder(), entry.getProfile().getId())) { packetItem.setPlayerKey(selectedKey); } else { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabListEntry.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabListEntry.java index 049991650..3db2482d6 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabListEntry.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/KeyedVelocityTabListEntry.java @@ -27,6 +27,9 @@ import com.velocitypowered.proxy.protocol.packet.chat.RemoteChatSession; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Handles modern tab list entries. + */ public class KeyedVelocityTabListEntry implements TabListEntry { private final KeyedVelocityTabList tabList; @@ -37,8 +40,8 @@ public class KeyedVelocityTabListEntry implements TabListEntry { private @Nullable IdentifiedKey playerKey; KeyedVelocityTabListEntry(KeyedVelocityTabList tabList, GameProfile profile, - net.kyori.adventure.text.@Nullable Component displayName, int latency, int gameMode, - @Nullable IdentifiedKey playerKey) { + net.kyori.adventure.text.@Nullable Component displayName, int latency, int gameMode, + @Nullable IdentifiedKey playerKey) { this.tabList = tabList; this.profile = profile; this.displayName = displayName; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabList.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabList.java index ddc524641..28d407ca1 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabList.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabList.java @@ -45,12 +45,21 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Base class for handling tab lists. + */ public class VelocityTabList implements InternalTabList { + private static final Logger logger = LogManager.getLogger(VelocityConsole.class); private final ConnectedPlayer player; private final MinecraftConnection connection; private final Map entries; + /** + * Constructs the instance. + * + * @param player player associated with this tab list + */ public VelocityTabList(ConnectedPlayer player) { this.player = player; this.connection = player.getConnection(); @@ -75,7 +84,8 @@ public class VelocityTabList implements InternalTabList { if (entry1 instanceof VelocityTabListEntry) { entry = (VelocityTabListEntry) entry1; } else { - entry = new VelocityTabListEntry(this, entry1.getProfile(), entry1.getDisplayNameComponent().orElse(null), + entry = new VelocityTabListEntry(this, entry1.getProfile(), + entry1.getDisplayNameComponent().orElse(null), entry1.getLatency(), entry1.getGameMode(), entry1.getChatSession(), entry1.isListed()); } @@ -113,7 +123,8 @@ public class VelocityTabList implements InternalTabList { ChatSession from = entry.getChatSession(); if (from != null) { actions.add(UpsertPlayerInfo.Action.INITIALIZE_CHAT); - playerInfoEntry.setChatSession(new RemoteChatSession(from.getSessionId(), from.getIdentifiedKey())); + playerInfoEntry.setChatSession( + new RemoteChatSession(from.getSessionId(), from.getIdentifiedKey())); } } } else { @@ -128,7 +139,8 @@ public class VelocityTabList implements InternalTabList { if (entry.getChatSession() != null) { actions.add(UpsertPlayerInfo.Action.INITIALIZE_CHAT); ChatSession from = entry.getChatSession(); - playerInfoEntry.setChatSession(new RemoteChatSession(from.getSessionId(), from.getIdentifiedKey())); + playerInfoEntry.setChatSession( + new RemoteChatSession(from.getSessionId(), from.getIdentifiedKey())); } if (entry.getGameMode() != -1 && entry.getGameMode() != 256) { actions.add(UpsertPlayerInfo.Action.UPDATE_GAME_MODE); @@ -163,9 +175,11 @@ public class VelocityTabList implements InternalTabList { } @Override - public TabListEntry buildEntry(GameProfile profile, @Nullable Component displayName, int latency, int gameMode, - @Nullable ChatSession chatSession, boolean listed) { - return new VelocityTabListEntry(this, profile, displayName, latency, gameMode, chatSession, listed); + public TabListEntry buildEntry(GameProfile profile, @Nullable Component displayName, int latency, + int gameMode, + @Nullable ChatSession chatSession, boolean listed) { + return new VelocityTabListEntry(this, profile, displayName, latency, gameMode, chatSession, + listed); } @Override @@ -183,10 +197,12 @@ public class VelocityTabList implements InternalTabList { } protected void emitActionRaw(UpsertPlayerInfo.Action action, UpsertPlayerInfo.Entry entry) { - this.connection.write(new UpsertPlayerInfo(EnumSet.of(action), Collections.singletonList(entry))); + this.connection.write( + new UpsertPlayerInfo(EnumSet.of(action), Collections.singletonList(entry))); } - private void processUpsert(EnumSet actions, UpsertPlayerInfo.Entry entry) { + private void processUpsert(EnumSet actions, + UpsertPlayerInfo.Entry entry) { Preconditions.checkNotNull(entry.getProfileId(), "Profile ID cannot be null"); UUID profileId = entry.getProfileId(); VelocityTabListEntry currentEntry = this.entries.get(profileId); @@ -208,7 +224,8 @@ public class VelocityTabList implements InternalTabList { } } else if (currentEntry == null) { logger.debug( - "Received a partial player before an ADD_PLAYER action; profile could not be built. {}", entry); + "Received a partial player before an ADD_PLAYER action; profile could not be built. {}", + entry); return; } if (actions.contains(UpsertPlayerInfo.Action.UPDATE_GAME_MODE)) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntry.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntry.java index 6c9bca80a..c39643d97 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntry.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntry.java @@ -27,7 +27,11 @@ import java.util.Optional; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Generic tab list entry implementation. + */ public class VelocityTabListEntry implements TabListEntry { + private final VelocityTabList tabList; private final GameProfile profile; private Component displayName; @@ -36,8 +40,12 @@ public class VelocityTabListEntry implements TabListEntry { private boolean listed; private @Nullable ChatSession session; - public VelocityTabListEntry(VelocityTabList tabList, GameProfile profile, Component displayName, int latency, - int gameMode, @Nullable ChatSession session, boolean listed) { + /** + * Constructs the instance. + */ + public VelocityTabListEntry(VelocityTabList tabList, GameProfile profile, Component displayName, + int latency, + int gameMode, @Nullable ChatSession session, boolean listed) { this.tabList = tabList; this.profile = profile; this.displayName = displayName; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntryLegacy.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntryLegacy.java index ab1d8f6af..b94feb13b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntryLegacy.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListEntryLegacy.java @@ -22,6 +22,9 @@ import com.velocitypowered.api.util.GameProfile; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Handles 1.7 tab list entries. + */ public class VelocityTabListEntryLegacy extends KeyedVelocityTabListEntry { VelocityTabListEntryLegacy(VelocityTabListLegacy tabList, GameProfile profile, diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java index 48ed518af..a4bcba824 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java @@ -32,6 +32,9 @@ import java.util.concurrent.ConcurrentHashMap; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Exposes the legacy 1.7 tab list to plugins. + */ public class VelocityTabListLegacy extends KeyedVelocityTabList { private final Map nameMapping = new ConcurrentHashMap<>(); @@ -112,7 +115,8 @@ public class VelocityTabListLegacy extends KeyedVelocityTabList { case LegacyPlayerListItem.UPDATE_LATENCY: case LegacyPlayerListItem.UPDATE_DISPLAY_NAME: // Add here because we removed beforehand connection - .write(new LegacyPlayerListItem(LegacyPlayerListItem.ADD_PLAYER, // ADD_PLAYER also updates ping + .write(new LegacyPlayerListItem(LegacyPlayerListItem.ADD_PLAYER, + // ADD_PLAYER also updates ping Collections.singletonList(LegacyPlayerListItem.Item.from(entry)))); break; default: diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/AddressUtil.java b/proxy/src/main/java/com/velocitypowered/proxy/util/AddressUtil.java index 600aee59a..b53f338ac 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/AddressUtil.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/AddressUtil.java @@ -23,7 +23,11 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; +/** + * Utilities to parse addresses. + */ public final class AddressUtil { + private static final int DEFAULT_MINECRAFT_PORT = 25565; private AddressUtil() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/CharacterUtil.java b/proxy/src/main/java/com/velocitypowered/proxy/util/CharacterUtil.java index 169d34d70..e1341eb3d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/CharacterUtil.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/CharacterUtil.java @@ -17,10 +17,14 @@ package com.velocitypowered.proxy.util; +/** + * Utilities for handling characters in the context of Minecraft chat handling. + */ public final class CharacterUtil { /** * Checks if a character is allowed. + * * @param c character to check * @return true if the character is allowed */ @@ -31,9 +35,9 @@ public final class CharacterUtil { } /** - * It is not possible to send certain characters in the chat like: - * section symbol, DEL, and all characters below space. - * Checks if a message contains illegal characters. + * It is not possible to send certain characters in the chat like: section symbol, DEL, and all + * characters below space. Checks if a message contains illegal characters. + * * @param message the message to check * @return true if the message contains illegal characters */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/ClosestLocaleMatcher.java b/proxy/src/main/java/com/velocitypowered/proxy/util/ClosestLocaleMatcher.java index f0381a150..faf194b50 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/ClosestLocaleMatcher.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/ClosestLocaleMatcher.java @@ -23,7 +23,11 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +/** + * Matches a player's locale to the "closest" Velocity locale, for message localization. + */ public class ClosestLocaleMatcher { + public static final ClosestLocaleMatcher INSTANCE = new ClosestLocaleMatcher(); private final Map byLanguage; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/DurationUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/util/DurationUtils.java index 2307d6869..fe7fca5e8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/DurationUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/DurationUtils.java @@ -23,6 +23,7 @@ import java.time.Duration; * Provides utility functions for working with durations. */ public final class DurationUtils { + private static final long ONE_TICK_IN_MILLISECONDS = 50; private DurationUtils() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java index 22d47eee9..50a8ef749 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java @@ -41,19 +41,22 @@ import java.net.InetSocketAddress; import java.util.List; import java.util.Map; +/** + * Helper class for {@code /velocity dump}. + */ public enum InformationUtils { ; /** - * Retrieves a {@link JsonArray} containing basic information about all - * running plugins on the {@link ProxyServer} instance. + * Retrieves a {@link JsonArray} containing basic information about all running plugins on the + * {@link ProxyServer} instance. * * @param proxy the proxy instance to retrieve from * @return {@link JsonArray} containing zero or more {@link JsonObject} */ public static JsonArray collectPluginInfo(ProxyServer proxy) { List allPlugins = ImmutableList.copyOf( - proxy.getPluginManager().getPlugins()); + proxy.getPluginManager().getPlugins()); JsonArray plugins = new JsonArray(); for (PluginContainer plugin : allPlugins) { @@ -92,8 +95,8 @@ public enum InformationUtils { } /** - * Creates a {@link JsonObject} containing information about the - * current environment the project is run under. + * Creates a {@link JsonObject} containing information about the current environment the project + * is run under. * * @return {@link JsonObject} containing environment info */ @@ -116,15 +119,15 @@ public enum InformationUtils { } /** - * Creates a {@link JsonObject} containing information about the - * forced hosts of the {@link ProxyConfig} instance. + * Creates a {@link JsonObject} containing information about the forced hosts of the + * {@link ProxyConfig} instance. * * @return {@link JsonArray} containing forced hosts */ public static JsonObject collectForcedHosts(ProxyConfig config) { JsonObject forcedHosts = new JsonObject(); Map> allForcedHosts = ImmutableMap.copyOf( - config.getForcedHosts()); + config.getForcedHosts()); for (Map.Entry> entry : allForcedHosts.entrySet()) { JsonArray host = new JsonArray(); for (int i = 0; i < entry.getValue().size(); i++) { @@ -136,8 +139,7 @@ public enum InformationUtils { } /** - * Anonymises or redacts a given {@link InetAddress} - * public address bits. + * Anonymises or redacts a given {@link InetAddress} public address bits. * * @param address The address to redact * @return {@link String} address with public parts redacted @@ -146,8 +148,8 @@ public enum InformationUtils { if (address instanceof Inet4Address) { Inet4Address v4 = (Inet4Address) address; if (v4.isAnyLocalAddress() || v4.isLoopbackAddress() - || v4.isLinkLocalAddress() - || v4.isSiteLocalAddress()) { + || v4.isLinkLocalAddress() + || v4.isSiteLocalAddress()) { return address.getHostAddress(); } else { byte[] addr = v4.getAddress(); @@ -156,8 +158,8 @@ public enum InformationUtils { } else if (address instanceof Inet6Address) { Inet6Address v6 = (Inet6Address) address; if (v6.isAnyLocalAddress() || v6.isLoopbackAddress() - || v6.isSiteLocalAddress() - || v6.isSiteLocalAddress()) { + || v6.isSiteLocalAddress() + || v6.isSiteLocalAddress()) { return address.getHostAddress(); } else { String[] bits = v6.getHostAddress().split(":"); @@ -185,8 +187,8 @@ public enum InformationUtils { } /** - * Creates a {@link JsonObject} containing most relevant - * information of the {@link RegisteredServer} for diagnosis. + * Creates a {@link JsonObject} containing most relevant information of the + * {@link RegisteredServer} for diagnosis. * * @param server the server to evaluate * @return {@link JsonObject} containing server and diagnostic info @@ -206,8 +208,8 @@ public enum InformationUtils { } /** - * Creates a {@link JsonObject} containing information about the - * current environment the project is run under. + * Creates a {@link JsonObject} containing information about the current environment the project + * is run under. * * @param version the proxy instance to retrieve from * @return {@link JsonObject} containing environment info @@ -217,8 +219,8 @@ public enum InformationUtils { } /** - * Creates a {@link JsonObject} containing most relevant - * information of the {@link ProxyConfig} for diagnosis. + * Creates a {@link JsonObject} containing most relevant information of the {@link ProxyConfig} + * for diagnosis. * * @param config the config instance to retrieve from * @return {@link JsonObject} containing select config values @@ -249,18 +251,18 @@ public enum InformationUtils { private static JsonElement serializeObject(Object toSerialize, boolean withExcludes) { return JsonParser.parseString( - withExcludes ? GSON_WITH_EXCLUDES.toJson(toSerialize) : + withExcludes ? GSON_WITH_EXCLUDES.toJson(toSerialize) : GSON_WITHOUT_EXCLUDES.toJson(toSerialize)); } private static final Gson GSON_WITH_EXCLUDES = new GsonBuilder() - .setPrettyPrinting() - .excludeFieldsWithoutExposeAnnotation() - .create(); + .setPrettyPrinting() + .excludeFieldsWithoutExposeAnnotation() + .create(); private static final Gson GSON_WITHOUT_EXCLUDES = new GsonBuilder() - .setPrettyPrinting() - .create(); + .setPrettyPrinting() + .create(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/FileSystemUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/util/ResourceUtils.java similarity index 87% rename from proxy/src/main/java/com/velocitypowered/proxy/util/FileSystemUtils.java rename to proxy/src/main/java/com/velocitypowered/proxy/util/ResourceUtils.java index 86b59a8d9..06a921c1f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/FileSystemUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/ResourceUtils.java @@ -32,22 +32,25 @@ import java.util.List; import java.util.Map; import java.util.function.Consumer; -public class FileSystemUtils { +/** + * Utilities to load resources. + */ +public class ResourceUtils { /** - * Visits the resources at the given {@link Path} within the resource - * path of the given {@link Class}. + * Visits the resources at the given {@link Path} within the resource path of the given + * {@link Class}. * - * @param target The target class of the resource path to scan - * @param consumer The consumer to visit the resolved path - * @param firstPathComponent First path component + * @param target The target class of the resource path to scan + * @param consumer The consumer to visit the resolved path + * @param firstPathComponent First path component * @param remainingPathComponents Remaining path components */ @SuppressFBWarnings({"RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}) public static boolean visitResources(Class target, Consumer consumer, String firstPathComponent, String... remainingPathComponents) throws IOException { - final URL knownResource = FileSystemUtils.class.getClassLoader() + final URL knownResource = ResourceUtils.class.getClassLoader() .getResource("default-velocity.toml"); if (knownResource == null) { throw new IllegalStateException( diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/VelocityChannelRegistrar.java b/proxy/src/main/java/com/velocitypowered/proxy/util/VelocityChannelRegistrar.java index 1ce6e98c5..9f4200a04 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/VelocityChannelRegistrar.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/VelocityChannelRegistrar.java @@ -30,6 +30,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.checkerframework.checker.nullness.qual.Nullable; +/** + * Registry for channels recognized by the proxy. + */ public class VelocityChannelRegistrar implements ChannelRegistrar { private final Map identifierMap = new ConcurrentHashMap<>(); @@ -107,6 +110,7 @@ public class VelocityChannelRegistrar implements ChannelRegistrar { /** * Returns all the channel names to register depending on the Minecraft protocol version. + * * @param protocolVersion the protocol version in use * @return the list of channels to register */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/bossbar/AdventureBossBarManager.java b/proxy/src/main/java/com/velocitypowered/proxy/util/bossbar/AdventureBossBarManager.java index 3dc8ea131..2968de8f7 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/bossbar/AdventureBossBarManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/bossbar/AdventureBossBarManager.java @@ -39,6 +39,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; * Manages all boss bars known to the proxy. */ public class AdventureBossBarManager implements BossBar.Listener { + private static final Enum2IntMap COLORS_TO_PROTOCOL = new Enum2IntMap.Builder<>(Color.class) .put(Color.PINK, 0) @@ -94,8 +95,9 @@ public class AdventureBossBarManager implements BossBar.Listener { /** * Adds the specified player to the boss bar's viewers and spawns the boss bar, registering the * boss bar if needed. + * * @param player the intended viewer - * @param bar the boss bar to show + * @param bar the boss bar to show */ public void addBossBar(ConnectedPlayer player, BossBar bar) { BossBarHolder holder = this.getOrCreateHandler(bar); @@ -106,8 +108,9 @@ public class AdventureBossBarManager implements BossBar.Listener { /** * Removes the specified player to the boss bar's viewers and despawns the boss bar. + * * @param player the intended viewer - * @param bar the boss bar to hide + * @param bar the boss bar to hide */ public void removeBossBar(ConnectedPlayer player, BossBar bar) { BossBarHolder holder = this.getHandler(bar); @@ -185,6 +188,7 @@ public class AdventureBossBarManager implements BossBar.Listener { } private class BossBarHolder { + private final UUID id = UUID.randomUUID(); private final BossBar bar; private final Set subscribers = Collections.newSetFromMap( diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/collect/CappedSet.java b/proxy/src/main/java/com/velocitypowered/proxy/util/collect/CappedSet.java index 8e54d7754..f401ab590 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/collect/CappedSet.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/collect/CappedSet.java @@ -38,8 +38,9 @@ public final class CappedSet extends ForwardingSet { /** * Creates a capped collection backed by a {@link HashSet}. + * * @param maxSize the maximum size of the collection - * @param the type of elements in the collection + * @param the type of elements in the collection * @return the new collection */ public static Set create(int maxSize) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/collect/Enum2IntMap.java b/proxy/src/main/java/com/velocitypowered/proxy/util/collect/Enum2IntMap.java index 27db57407..3cf55f7a8 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/collect/Enum2IntMap.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/collect/Enum2IntMap.java @@ -21,9 +21,11 @@ import java.util.EnumSet; /** * An immutable map of {@link Enum} entries to {@code int}s. + * * @param the enum type */ public final class Enum2IntMap> { + private final int[] mappings; private Enum2IntMap(int[] mappings) { @@ -34,7 +36,13 @@ public final class Enum2IntMap> { return mappings[key.ordinal()]; } + /** + * A builder for {@link Enum2IntMap}. + * + * @param the enum type to use + */ public static class Builder> { + private final int[] mappings; private final EnumSet populated; private int defaultValue = -1; @@ -46,7 +54,8 @@ public final class Enum2IntMap> { /** * Adds a mapping to the map. - * @param key the key to use + * + * @param key the key to use * @param value the value to associate with the key * @return {@code this}, for chaining */ @@ -68,6 +77,7 @@ public final class Enum2IntMap> { /** * Fetches a mapping from the map. + * * @param key the key to use * @return the value in the map */ @@ -80,6 +90,7 @@ public final class Enum2IntMap> { /** * Builds the map. + * * @return the built map */ public Enum2IntMap build() { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/collect/IdentityHashStrategy.java b/proxy/src/main/java/com/velocitypowered/proxy/util/collect/IdentityHashStrategy.java index 516c7cc74..9276f2c79 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/collect/IdentityHashStrategy.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/collect/IdentityHashStrategy.java @@ -19,6 +19,11 @@ package com.velocitypowered.proxy.util.collect; import it.unimi.dsi.fastutil.Hash.Strategy; +/** + * An identity hash strategy for fastutil. + * + * @param the type + */ public final class IdentityHashStrategy implements Strategy { @SuppressWarnings("rawtypes") diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/Once.java b/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/Once.java index 20397f292..b28b6ce29 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/Once.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/Once.java @@ -18,12 +18,13 @@ package com.velocitypowered.proxy.util.concurrent; /** - * A class that guarantees that a given initialization shall only occur once. The implementation - * is (almost) a direct Java port of the Go {@code sync.Once} type (see the + * A class that guarantees that a given initialization shall only occur once. The implementation is + * (almost) a direct Java port of the Go {@code sync.Once} type (see the * Go documentation) and thus has similar * semantics. */ public final class Once { + private static final int NOT_STARTED = 0; private static final int COMPLETED = 1; @@ -33,8 +34,8 @@ public final class Once { /** * Calls {@code runnable.run()} exactly once if this instance is being called for the first time, * otherwise the invocation shall wait until {@code runnable.run()} completes. The first runnable - * used when this function is called is run. Future calls to this method once the initial - * runnable completes are no-ops - a new instance should be used instead. + * used when this function is called is run. Future calls to this method once the initial runnable + * completes are no-ops - a new instance should be used instead. * * @param runnable the runnable to run */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/VelocityNettyThreadFactory.java b/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/VelocityNettyThreadFactory.java index 4ac6a48c3..4f582854c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/VelocityNettyThreadFactory.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/concurrent/VelocityNettyThreadFactory.java @@ -23,6 +23,9 @@ import io.netty.util.concurrent.FastThreadLocalThread; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; +/** + * Factory to create threads for the Netty event loop groups. + */ public class VelocityNettyThreadFactory implements ThreadFactory { private final AtomicInteger threadNumber = new AtomicInteger(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietDecoderException.java b/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietDecoderException.java index 441e1f3de..f5a034550 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietDecoderException.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietDecoderException.java @@ -20,8 +20,8 @@ package com.velocitypowered.proxy.util.except; import io.netty.handler.codec.DecoderException; /** - * A special-purpose exception thrown when we want to indicate an error decoding but do not want - * to see a large stack trace in logs. + * A special-purpose exception thrown when we want to indicate an error decoding but do not want to + * see a large stack trace in logs. */ public class QuietDecoderException extends DecoderException { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietRuntimeException.java b/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietRuntimeException.java index bb143a614..b682b2f18 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietRuntimeException.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/except/QuietRuntimeException.java @@ -18,8 +18,8 @@ package com.velocitypowered.proxy.util.except; /** - * A special-purpose exception thrown when we want to indicate an error but do not want - * to see a large stack trace in logs. + * A special-purpose exception thrown when we want to indicate an error but do not want to see a + * large stack trace in logs. */ public class QuietRuntimeException extends RuntimeException { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiter.java b/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiter.java index 088370912..45c5446be 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiter.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiter.java @@ -26,6 +26,7 @@ public interface Ratelimiter { /** * Determines whether or not to allow the connection. + * * @param address the address to rate limit * @return true if allowed, false if not */ diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiters.java b/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiters.java index b9d7a2938..9f09dcf7a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiters.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/ratelimit/Ratelimiters.java @@ -19,7 +19,11 @@ package com.velocitypowered.proxy.util.ratelimit; import java.util.concurrent.TimeUnit; +/** + * Factory to create rate limiters. + */ public final class Ratelimiters { + private Ratelimiters() { throw new AssertionError(); } diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages.properties index 5ac4ea9ea..9bfd94d9d 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages.properties @@ -30,14 +30,11 @@ velocity.error.modern-forwarding-failed=Your server did not send a forwarding re velocity.error.moved-to-new-server=You were kicked from {0}: {1} velocity.error.no-available-servers=There are no available servers to connect you to. Try again later or contact an admin. velocity.error.illegal-chat-characters=Illegal characters in chat - # Commands velocity.command.generic-error=An error occurred while running this command. velocity.command.command-does-not-exist=This command does not exist. - velocity.command.players-only=Only players can run this command. velocity.command.server-does-not-exist=The specified server {0} does not exist. - velocity.command.server-current-server=You are currently connected to {0}. velocity.command.server-too-many=There are too many servers set up. Use tab completion to view all servers available. velocity.command.server-available=Available servers: @@ -45,28 +42,22 @@ velocity.command.server-tooltip-player-online={0} player online velocity.command.server-tooltip-players-online={0} players online velocity.command.server-tooltip-current-server=Currently connected to this server velocity.command.server-tooltip-offer-connect-server=Click to connect to this server - velocity.command.glist-player-singular={0} player is currently connected to the proxy. velocity.command.glist-player-plural={0} players are currently connected to the proxy. velocity.command.glist-view-all=To view all players on servers, use /glist all. - velocity.command.reload-success=Velocity configuration successfully reloaded. velocity.command.reload-failure=Unable to reload your Velocity configuration. Check the console for more details. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is licensed under the terms of the GNU General Public License v3. - velocity.command.no-plugins=There are no plugins currently installed. velocity.command.plugins-list=Plugins: {0} velocity.command.plugin-tooltip-website=Website: {0} velocity.command.plugin-tooltip-author=Author: {0} velocity.command.plugin-tooltip-authors=Authors: {0} - velocity.command.dump-uploading=Uploading gathered information... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them: velocity.command.dump-will-expire=This link will expire in a few days. velocity.command.dump-server-error=An error occurred on the Velocity servers and the dump could not be completed. Please contact the Velocity staff about this problem and provide the details about this error from the Velocity console or server log. velocity.command.dump-offline=Likely cause: Invalid system DNS settings or no internet connection - # Kick velocity.kick.shutdown=Proxy shutting down. \ No newline at end of file diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ar_SA.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ar_SA.properties index b0402a159..053f004f7 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ar_SA.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ar_SA.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=هذا السيرفر متوا velocity.error.modern-forwarding-failed=السيرفر الخاص بك لم يرسل طلب إعادة توجيه إلى الوكيل. تأكد من إعداد الخادم لإعادة التوجيه بـVelocity. velocity.error.moved-to-new-server=لقد تم طردك من {0}\: {1} velocity.error.no-available-servers=لا توجد سيرفرات متاحة للاتصال. حاول مرة أخرى أو اتصل بالأدمِن. - # Commands velocity.command.generic-error=حدث خطأ أثناء تنفيذ هذا الأمر. velocity.command.command-does-not-exist=هذا الأمر غير موجود. - velocity.command.players-only=يمكن للاعبين فقط تشغيل هذا الأمر. velocity.command.server-does-not-exist=السيرفر المطلوب {0} غير موجود. - velocity.command.server-current-server=أنت الآن متصل بـ{0} velocity.command.server-too-many=هناك العديد من السيرفرات المتاحة، استخدم البحث بزر tab لتصفح قائمة السيرفرات. velocity.command.server-available=السيرفرات المتاحة\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online=لاعب واحد متصل velocity.command.server-tooltip-players-online={0} لاعبين متصلون velocity.command.server-tooltip-current-server=انت متصل حاليًا بهذا السيرفر velocity.command.server-tooltip-offer-connect-server=انقر للاتصال بهذا السيرفر - velocity.command.glist-player-singular=هناك لاعب واحد متصل بالوكيل. velocity.command.glist-player-plural=هناك {0} لاعبين متصلون بالوكيل. velocity.command.glist-view-all=لعرض اللاعبين على جميع السيرفرات استخدم /glist all - velocity.command.reload-success=تم إعادة تحميل إعدادات Velocity بنجاح. velocity.command.reload-failure=فشلت إعادة تحميل إعدادات Velocity. تفقد الـconsole للمزيد من التفاصيل. - velocity.command.version-copyright=حقوق الطبع والنشر 2018-2021 {0}. {1} مرخصة بموجب شروط الإصدار الثالث لرخصة GNU العامة (GPLv3). - velocity.command.no-plugins=لا توجد إضافات مثبتة على Velocity. velocity.command.plugins-list=الإضافات\: {0} velocity.command.plugin-tooltip-website=موقعها\: {0} velocity.command.plugin-tooltip-author=تصميم\: {0} velocity.command.plugin-tooltip-authors=تصميم\: {0} - velocity.command.dump-uploading=جاري تجميع و رفع معلومات نظامك... velocity.command.dump-send-error=حدث خطأ أثناء الاتصال بسيرفر Velocity. قد يكون السيرفر غير متاح مؤقتاً أو هناك مشكلة في إعدادات الشبكة الخاصة بك. يمكنك العثور على مزيد من المعلومات في log أو console وكيل Velocity الخاص بك. velocity.command.dump-success=تم إنشاء تقرير مفصل يحتوي على معلومات مفيدة عن الوكيل الخاص بك. إذا طلبه المطور، يمكنك مشاركة الرابط التالي معه\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_bg_BG.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_bg_BG.properties index 32d2c70ea..df66bac08 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_bg_BG.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_bg_BG.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=This server is only compatible velocity.error.modern-forwarding-failed=Your server did not send a forwarding request to the proxy. Make sure the server is configured for Velocity forwarding. velocity.error.moved-to-new-server=You were kicked from {0}\: {1} velocity.error.no-available-servers=There are no available servers to connect you to. Try again later or contact an admin. - # Commands velocity.command.generic-error=An error occurred while running this command. velocity.command.command-does-not-exist=This command does not exist. - velocity.command.players-only=Only players can run this command. velocity.command.server-does-not-exist=The specified server {0} does not exist. - velocity.command.server-current-server=You are currently connected to {0}. velocity.command.server-too-many=There are too many servers set up. Use tab completion to view all servers available. velocity.command.server-available=Available servers\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} player online velocity.command.server-tooltip-players-online={0} players online velocity.command.server-tooltip-current-server=Currently connected to this server velocity.command.server-tooltip-offer-connect-server=Click to connect to this server - velocity.command.glist-player-singular={0} player is currently connected to the proxy. velocity.command.glist-player-plural={0} players are currently connected to the proxy. velocity.command.glist-view-all=To view all players on servers, use /glist all. - velocity.command.reload-success=Velocity configuration successfully reloaded. velocity.command.reload-failure=Unable to reload your Velocity configuration. Check the console for more details. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is licensed under the terms of the GNU General Public License v3. - velocity.command.no-plugins=There are no plugins currently installed. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Website\: {0} velocity.command.plugin-tooltip-author=Author\: {0} velocity.command.plugin-tooltip-authors=Authors\: {0} - velocity.command.dump-uploading=Uploading gathered information... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_cs_CZ.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_cs_CZ.properties index ed93a6747..fd25238e4 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_cs_CZ.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_cs_CZ.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Tento server je kompatibilní velocity.error.modern-forwarding-failed=Tvůj server neodeslal přesměrovávací požadavek na proxy server. Ujisti se, že je server nastaven na Velocity přesměrování. velocity.error.moved-to-new-server=Byl jsi vyhozen ze serveru {0}\: {1} velocity.error.no-available-servers=Nejsou k dispozici žádné servery, ke kterým by ses mohl připojit. Zkus to později nebo kontaktuj správce. - # Commands velocity.command.generic-error=Při vykonávání tohoto příkazu nastala chyba. velocity.command.command-does-not-exist=Tento příkaz neexistuje. - velocity.command.players-only=Tento příkaz mohou vykonávat pouze hráči. velocity.command.server-does-not-exist=Zadaný server {0} neexistuje. - velocity.command.server-current-server=Právě jsi připojen k serveru {0}. velocity.command.server-too-many=Je nastaveno příliš mnoho serverů. Klávesa tab ukáže všechny dostupné servery. velocity.command.server-available=Dostupné servery\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} hráč online velocity.command.server-tooltip-players-online=Počet hráčů online\: {0} velocity.command.server-tooltip-current-server=Právě jsi připojen k tomuto serveru velocity.command.server-tooltip-offer-connect-server=Kliknutím se připojíš k tomuto serveru - velocity.command.glist-player-singular=K tomuto proxy serveru je připojen {0} hráč. velocity.command.glist-player-plural=Počet hráčů připojených k tomuto proxy serveru\: {0} velocity.command.glist-view-all=Ke zobrazení všech hráčů na všech serverech použij /glist all. - velocity.command.reload-success=Konfigurace Velocity úspěšně načtena. velocity.command.reload-failure=Nebylo možné načíst konfiguraci Velocity. Podrobnosti jsou na konzoli. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} je licencovaný pod podmínkami GNU General Public License v3. - velocity.command.no-plugins=V tuto chvíli nejsou nainstalovány žádné zásuvné moduly. velocity.command.plugins-list=Zásuvné moduly\: {0} velocity.command.plugin-tooltip-website=Webová stránka\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Autoři\: {0} - velocity.command.dump-uploading=Nahrávání získaných informací... velocity.command.dump-send-error=Nastala chyba při komunikaci s Velocity servery. Servery mohou být dočasně nedostupné nebo je chyba v přístupu na internet. Podrobnosti jsou v logu a na konzoli Velocity serveru. velocity.command.dump-success=Byla vytvořena anonymizovaná zpráva obsahující užitečné informace o tomto serveru. Vyžádal-li si je vývojář, můžeš mu poslat nasledující odkaz\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_da_DK.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_da_DK.properties index d63e24b1a..a7c871eaf 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_da_DK.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_da_DK.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Denne server er kun kompatibel velocity.error.modern-forwarding-failed=Din server sendte ikke en viderestillingsanmodning til proxyen. Sørg for, at serveren er konfigureret til Velocity forwarding. velocity.error.moved-to-new-server=Du blev smidt ud fra {0}\: {1} velocity.error.no-available-servers=Der er ingen tilgængelige servere at forbinde dig til. Prøv igen senere eller kontakt en administrator. - # Commands velocity.command.generic-error=Der opstod en fejl under kørsel af denne kommando. velocity.command.command-does-not-exist=Denne kommando eksisterer ikke. - velocity.command.players-only=Kun spillere kan køre denne kommando. velocity.command.server-does-not-exist=Den angivne server {0} findes ikke. - velocity.command.server-current-server=Du er i øjeblikket forbundet til {0}. velocity.command.server-too-many=Der er sat for mange servere op. Brug tab færdiggørelse til at se alle tilgængelige servere. velocity.command.server-available=Tilgængelige servere\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} spiller online velocity.command.server-tooltip-players-online={0} spillere online velocity.command.server-tooltip-current-server=I øjeblikket forbundet til serveren velocity.command.server-tooltip-offer-connect-server=Klik for at forbinde til denne server - velocity.command.glist-player-singular={0} spiller er i øjeblikket forbundet til proxyen. velocity.command.glist-player-plural={0} spillere er i øjeblikket forbundet til proxyen. velocity.command.glist-view-all=For at se alle spillere på servere, brug /glist all. - velocity.command.reload-success=Velocity konfiguration blev indlæst. velocity.command.reload-failure=Kan ikke genindlæse din Velocity konfiguration. Tjek konsollen for flere detaljer. - velocity.command.version-copyright=Ophavsret 2018-2021 {0}. {1} er licenseret under betingelserne i GNU General Public License v3. - velocity.command.no-plugins=Der er ingen plugins installeret i øjeblikket. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Hjemmeside\: {0} velocity.command.plugin-tooltip-author=Skaber\: {0} velocity.command.plugin-tooltip-authors=Skabere\: {0} - velocity.command.dump-uploading=Uploader indsamlet information... velocity.command.dump-send-error=Der opstod en fejl under kommunikation med Velocity serverne. Serverne kan være midlertidigt utilgængelige, eller der er et problem med dine netværksindstillinger. Du kan finde mere information i loggen eller konsollen på din Velocity server. velocity.command.dump-success=Oprettet en anonymiseret rapport med nyttige oplysninger om denne proxy. Hvis en udvikler anmodede om det, kan du dele følgende link med dem\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_de_DE.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_de_DE.properties index 2094bb5f2..cd44a4c49 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_de_DE.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_de_DE.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Dieser Server ist nur mit der velocity.error.modern-forwarding-failed=Dein Server hat keine Weiterleitungsanforderung an den Proxy gesendet. Stelle sicher, dass der Server für die Velocity Weiterleitung konfiguriert ist. velocity.error.moved-to-new-server=Du wurdest von {0} vom Server geworfen\: {1} velocity.error.no-available-servers=Es gibt keine verfügbaren Server mit denen du dich verbinden kannst. Versuche es später erneut oder kontaktiere einen Admin. - # Commands velocity.command.generic-error=Beim Ausführen des Befehls ist ein Fehler aufgetreten. velocity.command.command-does-not-exist=Dieser Befehl existiert nicht. - velocity.command.players-only=Nur Spieler können diesen Befehl ausführen. velocity.command.server-does-not-exist=Der angegebene Server {0} existiert nicht. - velocity.command.server-current-server=Du bist derzeit mit {0} verbunden. velocity.command.server-too-many=Es sind zu viele Server eingerichtet. Verwende die Tabvervollständigung, um alle verfügbaren Server aufzulisten. velocity.command.server-available=Verfügbare Server\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} Spieler online velocity.command.server-tooltip-players-online={0} Spieler online velocity.command.server-tooltip-current-server=Du bist derzeit mit diesem Server verbunden velocity.command.server-tooltip-offer-connect-server=Klicke, um dich mit diesem Server zu verbinden - velocity.command.glist-player-singular={0} Spieler ist derzeit mit dem Proxy verbunden. velocity.command.glist-player-plural={0} Spieler sind derzeit mit dem Proxy verbunden. velocity.command.glist-view-all=Um alle Spieler auf Servern aufzulisten, verwende /glist all. - velocity.command.reload-success=Velocity-Konfiguration erfolgreich neu geladen. velocity.command.reload-failure=Die Velocity-Konfiguration konnte nicht neu geladen werden. Prüfe die Konsole für weitere Details. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} ist lizenziert unter den Bedingungen der GNU General Public License v3. - velocity.command.no-plugins=Es sind derzeit keine Plugins installiert. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Webseite\: {0} velocity.command.plugin-tooltip-author=Entwickler\: {0} velocity.command.plugin-tooltip-authors=Entwickler\: {0} - velocity.command.dump-uploading=Erfasste Daten werden hochgeladen... velocity.command.dump-send-error=Bei der Kommunikation mit den Velocity-Servern ist ein Fehler aufgetreten. Diese Server sind möglicherweise vorübergehend nicht verfügbar oder es gibt ein Problem mit deinen Netzwerkeinstellungen. Weitere Informationen findest du in der Log-Datei oder in der Konsole deines Velocity-Servers. velocity.command.dump-success=Ein anonymisierter Bericht mit nützlichen Informationen über diesen Proxy wurde erstellt. Wenn ein Entwickler den Bericht angefordert hat, kannst über folgenden Link diesen mit ihm teilen\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_es_ES.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_es_ES.properties index 0cd5282ce..4314f09df 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_es_ES.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_es_ES.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Este servidor solo es compatib velocity.error.modern-forwarding-failed=El servidor no ha enviado una solicitud de reenvío al proxy. Asegúrate de que tu servidor está configurado para usar el método de reenvío de Velocity. velocity.error.moved-to-new-server=Has sido echado de {0}\: {1} velocity.error.no-available-servers=No hay servidores disponibles a los que conectarte. Inténtalo de nuevo más tarde o contacta con un administrador. - # Commands velocity.command.generic-error=Se ha producido un error al ejecutar este comando. velocity.command.command-does-not-exist=Este comando no existe. - velocity.command.players-only=Solo los jugadores pueden ejecutar este comando. velocity.command.server-does-not-exist=El servidor especificado {0} no existe. - velocity.command.server-current-server=Estás conectado a {0}. velocity.command.server-too-many=Hay demasiados servidores registrados. Usa la finalización con tabulación para ver todos los servidores disponibles. velocity.command.server-available=Servidores disponibles\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} jugador conectado velocity.command.server-tooltip-players-online={0} jugadores conectados velocity.command.server-tooltip-current-server=Estás conectado a este servidor velocity.command.server-tooltip-offer-connect-server=Haz clic para conectarte a este servidor - velocity.command.glist-player-singular={0} jugador está conectado al proxy. velocity.command.glist-player-plural={0} jugadores están conectados al proxy. velocity.command.glist-view-all=Para ver todos los jugadores por servidores, usa /glist all. - velocity.command.reload-success=La configuración de Velocity ha sido recargada correctamente. velocity.command.reload-failure=No ha sido posible recargar la configuración de Velocity. Para obtener más información, revisa la consola. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} está licenciado bajo los términos de la Licencia Pública General de GNU v3. - velocity.command.no-plugins=Actualmente no hay plugins instalados. velocity.command.plugins-list=Complementos\: {0} velocity.command.plugin-tooltip-website=Página web\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Autores\: {0} - velocity.command.dump-uploading=Subiendo la información recopilada... velocity.command.dump-send-error=Se ha producido un error al comunicarse con los servidores de Velocity. Es posible que los servidores no estén disponibles temporalmente o que exista un problema en tu configuración de red. Puedes encontrar más información en el archivo de registro o la consola de tu servidor Velocity. velocity.command.dump-success=Se ha creado un informe anónimo que contiene información útil sobre este proxy. Si un desarrollador lo solicita, puedes compartir el siguiente enlace con él\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_et_EE.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_et_EE.properties index 3062c953c..9cd64b6ce 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_et_EE.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_et_EE.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=This server is only compatible velocity.error.modern-forwarding-failed=Your server did not send a forwarding request to the proxy. Make sure the server is configured for Velocity forwarding. velocity.error.moved-to-new-server=You were kicked from {0}\: {1} velocity.error.no-available-servers=There are no available servers to connect you to. Try again later or contact an admin. - # Commands velocity.command.generic-error=An error occurred while running this command. velocity.command.command-does-not-exist=Antud käsklust ei eksisteeri. - velocity.command.players-only=Ainult mängijad saavad antud käsklust kasutada. velocity.command.server-does-not-exist=Server {0} ei eksisteeri. - velocity.command.server-current-server=Sa oled hetkel ühendatud serveriga {0}. velocity.command.server-too-many=There are too many servers set up. Use tab completion to view all servers available. velocity.command.server-available=Saadaolevad serverid\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} mängija online velocity.command.server-tooltip-players-online={0} mängijat online velocity.command.server-tooltip-current-server=Currently connected to this server velocity.command.server-tooltip-offer-connect-server=Vajuta, et ühendada antud serveriga - velocity.command.glist-player-singular={0} player is currently connected to the proxy. velocity.command.glist-player-plural={0} players are currently connected to the proxy. velocity.command.glist-view-all=Et näha kõiki mängijaid kõikides serverites, kasuta käsklust /glist all. - velocity.command.reload-success=Velocity seadistus edukalt taaslaetud. velocity.command.reload-failure=Unable to reload your Velocity configuration. Check the console for more details. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is licensed under the terms of the GNU General Public License v3. - velocity.command.no-plugins=There are no plugins currently installed. velocity.command.plugins-list=Pluginad\: {0} velocity.command.plugin-tooltip-website=Veebileht\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Autorid\: {0} - velocity.command.dump-uploading=Kogutud informatsiooni üleslaadimine... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fi_FI.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fi_FI.properties index a90567a79..a57cf226b 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fi_FI.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fi_FI.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Tämä palvelin on yhteensopiv velocity.error.modern-forwarding-failed=Valitsemasi palvelin ei lähettänyt välityspyyntöä välityspalvelimelle. Tarkista että palvelin on määritetty oikein Velocityä varten. velocity.error.moved-to-new-server=Sinut potkittiin pois palvelimelta {0}\: {1} velocity.error.no-available-servers=Yhtään palvelinta ei ole tällä hetkellä saatavilla. Yritä myöhemmin uudelleen tai ota yhteyttä palvelimen ylläpitäjään. - # Commands velocity.command.generic-error=Tämän komennon suorittamisessa tapahtui virhe. velocity.command.command-does-not-exist=Tuota komentoa ei ole olemassa. - velocity.command.players-only=Vain pelaajat voivat käyttää tuota komentoa. velocity.command.server-does-not-exist=Palvelinta {0} ei ole olemassa. - velocity.command.server-current-server=Olet tällä hetkellä yhdistettynä palvelimeen {0}. velocity.command.server-too-many=Liian monta palvelinta on määritetty. Paina Tab -näppäintä nähdäksesi kaikki saatavilla olevat palvelimet. velocity.command.server-available=Saatavilla olevat palvelimet\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} pelaaja paikalla velocity.command.server-tooltip-players-online={0} pelaajaa paikalla velocity.command.server-tooltip-current-server=Tällä hetkellä yhdistetty tähän palvelimeen velocity.command.server-tooltip-offer-connect-server=Napsauta yhdistääksesi tähän palvelimeen - velocity.command.glist-player-singular={0} pelaaja on tällä hetkellä paikalla verkostossa. velocity.command.glist-player-plural={0} pelaajaa on tällä hetkellä paikalla verkostossa. velocity.command.glist-view-all=Nähdäksesi pelaajat kaikilta palvelimilta, käytä komentoa /glist all. - velocity.command.reload-success=Velocityn konfiguraatio uudelleenladattiin onnistuneesti. velocity.command.reload-failure=Velocityn konfiguraation uudelleenlataus epäonnistui. Katso tarkemmat lisätiedot konsolista. - velocity.command.version-copyright=Tekijänoikeus 2018-2021 {0}. {1} on lisensoitu GNU General Public License v3\:n ehtojen mukaisesti. - velocity.command.no-plugins=Yhtäkään pluginia ei ole asennettu. velocity.command.plugins-list=Pluginit\: {0} velocity.command.plugin-tooltip-website=Verkkosivu\: {0} velocity.command.plugin-tooltip-author=Tekijä\: {0} velocity.command.plugin-tooltip-authors=Tekijät\: {0} - velocity.command.dump-uploading=Lähetetään kerättyjä tietoja... velocity.command.dump-send-error=Velocity-palvelimien kanssa kommunikoidessa tapahtui virhe. Palvelimet eivät ehkä ole tilapäisesti käytettävissä tai verkkoasetuksissa on ongelma. Löydät lisätietoja Velocity-palvelimesi lokista tai konsolista. velocity.command.dump-success=Luotiin anonyymi raportti, joka sisältää hyödyllistä tietoa tästä välityspalvelimesta. Jos jokin kehittäjä on pyytänyt sitä, voit jakaa seuraavan linkin heidän kanssaan\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fr_FR.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fr_FR.properties index 123a8a853..2e8cea8f7 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fr_FR.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_fr_FR.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Ce serveur est uniquement comp velocity.error.modern-forwarding-failed=Votre serveur n'a pas envoyé de requête de transfert vers le proxy. Assurez-vous que le serveur est configuré pour le transfert Velocity. velocity.error.moved-to-new-server=Vous avez été expulsé(e) de {0} \: {1} velocity.error.no-available-servers=Il n'y a pas de serveurs disponibles auxquels vous connecter. Réessayez ultérieurement ou contactez un administrateur. - # Commands velocity.command.generic-error=Une erreur est survenue lors de l'exécution de cette commande. velocity.command.command-does-not-exist=Cette commande n'existe pas. - velocity.command.players-only=Seuls les joueurs peuvent exécuter cette commande. velocity.command.server-does-not-exist=Le serveur spécifié {0} n''existe pas. - velocity.command.server-current-server=Vous êtes actuellement connecté(e) à {0}. velocity.command.server-too-many=Il y a trop de serveurs configurés. Utilisez la saisie semi-automatique via la touche Tab pour afficher tous les serveurs disponibles. velocity.command.server-available=Serveurs disponibles \: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} joueur connecté velocity.command.server-tooltip-players-online={0} joueurs connectés velocity.command.server-tooltip-current-server=Actuellement connecté(e) à ce serveur velocity.command.server-tooltip-offer-connect-server=Cliquez pour vous connecter à ce serveur - velocity.command.glist-player-singular={0} joueur est actuellement connecté au proxy. velocity.command.glist-player-plural={0} joueurs sont actuellement connectés au proxy. velocity.command.glist-view-all=Pour afficher tous les joueurs connectés aux serveurs, utilisez /glist all. - velocity.command.reload-success=Configuration de Velocity rechargée avec succès. velocity.command.reload-failure=Impossible de recharger votre configuration de Velocity. Consultez la console pour plus de détails. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} est sous la licence GNU General Public License v3. - velocity.command.no-plugins=Il n'y a aucun plugin actuellement installé. velocity.command.plugins-list=Plugins \: {0} velocity.command.plugin-tooltip-website=Site Internet \: {0} velocity.command.plugin-tooltip-author=Auteur \: {0} velocity.command.plugin-tooltip-authors=Auteurs \: {0} - velocity.command.dump-uploading=Envoi des informations collectées... velocity.command.dump-send-error=Une erreur est survenue lors de la communication avec les serveurs Velocity. Soit les serveurs sont temporairement indisponibles, soit il y a un problème avec les paramètres de votre réseau. Vous trouverez plus d'informations dans le journal ou la console de votre serveur Velocity. velocity.command.dump-success=Un rapport anonyme contenant des informations utiles sur ce proxy a été créé. Si un développeur vous le demande, vous pouvez le partager avec le lien suivant \: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_he_IL.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_he_IL.properties index 37cfdf46f..6f49c3905 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_he_IL.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_he_IL.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=שרת זה תואם רק עם velocity.error.modern-forwarding-failed=השרת שלך לא שלח בקשת העברה ל- proxy. ודא שתצורת השרת נקבעה להעברת Velocity. velocity.error.moved-to-new-server=אתה הורחקתה מ- {0}\: {1} velocity.error.no-available-servers=אין שרתים זמינים אליהם יש לחבר אותך. נסה שוב מאוחר יותר או פנה למנהל מערכת. - # Commands velocity.command.generic-error=התרחש שגיאה בעת הפעלת פקודה זו. velocity.command.command-does-not-exist=פקודה זו אינה קיימת. - velocity.command.players-only=רק שחקנים יכולים להפעיל פקודה זו. velocity.command.server-does-not-exist=השרת {0} שצוין אינו קיים. - velocity.command.server-current-server=אתה מחובר כעת ל- {0}. velocity.command.server-too-many=הוגדרו שרתים רבים מדי. השתמש בהשלמת כרטיסיה כדי להציג את כל השרתים הזמינים. velocity.command.server-available=שרתים זמינים\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online=שחקן {0} מחובר velocity.command.server-tooltip-players-online={0} שחקנים מחוברים velocity.command.server-tooltip-current-server=מחובר כעת לשרת זה velocity.command.server-tooltip-offer-connect-server=לחץ על מנת להתחבר לשרת זה - velocity.command.glist-player-singular=שחקן {0} כעת מחובר ל- proxy. velocity.command.glist-player-plural={0} שחקנים מחוברים כעת ל- proxy. velocity.command.glist-view-all=כדי להציג את כל השחקנים בשרתים, השתמש ב- /glist all. - velocity.command.reload-success=תצורת Velocity נטענה מחדש בהצלחה. velocity.command.reload-failure=אין אפשרות לטעון מחדש את תצורת ה- Velocity שלך. עיין בקונסולה לקבלת פרטים נוספים. - velocity.command.version-copyright=זכויות יוצרים 2018-2021 {0}. {1} מורשה על פי תנאי v3 הרישיון הציבורי הכללי של GNU. - velocity.command.no-plugins=לא מותקנים כעת תוספים. velocity.command.plugins-list=תוספים\: {0} velocity.command.plugin-tooltip-website=אתר אינטרנט\: {0} velocity.command.plugin-tooltip-author=יוצר\: {0} velocity.command.plugin-tooltip-authors=יוצר\: {0} - velocity.command.dump-uploading=מעלה מידע שנאסף... velocity.command.dump-send-error=התרחש שגיאה בעת קיום תקשורת עם שרתי ה- Velocity. ייתכן שהשרתים אינם זמינים באופן זמני או שקיימת בעיה בהגדרות הרשת שלך. באפשרותך למצוא מידע נוסף ביומן הרישום או בקונסולה של שרת ה- Velocity שלך. velocity.command.dump-success=נוצר דוח אנונימיות המכיל מידע שימושי אודות proxy זה. אם מפתח ביקש זאת, באפשרותך לשתף איתם את הקישור הבא\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_hu_HU.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_hu_HU.properties index c654e0968..14e618911 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_hu_HU.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_hu_HU.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Ez a szerver csak a Minecraft velocity.error.modern-forwarding-failed=A szerver ahonnan csatlakoztál nem küldött modern átirányítási kérelmet a proxy felé. Bizonyosodj meg róla, hogy a szerver be van állítva a modern Velocity átirányítás használatára. velocity.error.moved-to-new-server=Ki lettél rúgva a(z) {0} szerverről\: {1} velocity.error.no-available-servers=Jelenleg nincs elérhető szerver ahová csatlakoztatni tudnánk. Próbáld újra később, vagy lépj kapcsolatba egy adminisztrátorral. - # Commands velocity.command.generic-error=Hiba történt a parancs futtatása közben. velocity.command.command-does-not-exist=Ilyen parancs nem létezik. - velocity.command.players-only=Ezt a parancsot csak játékosok használhatják. velocity.command.server-does-not-exist=A megadott szerver ({0}) nem létezik. - velocity.command.server-current-server=Jelenleg a(z) {0} szerveren tartózkodsz. velocity.command.server-too-many=Túl sok szerver van beállítva. Használd a tab parancs befejező funkciót, hogy megnézd az összes elérhető szervert. velocity.command.server-available=Elérhető szerverek\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} játékos online velocity.command.server-tooltip-players-online={0} játékos online velocity.command.server-tooltip-current-server=Jelenleg ezen a szerveren tartózkodsz velocity.command.server-tooltip-offer-connect-server=Kattints ide, hogy csatlakozz erre a szerverre - velocity.command.glist-player-singular={0} játékos van jelenleg csatlakozva a proxyhoz. velocity.command.glist-player-plural={0} játékos van jelenleg csatlakozva a proxyhoz. velocity.command.glist-view-all=Hogy megnézd az összes játékost az összes szerveren, használd a /glist all parancsot. - velocity.command.reload-success=A Velocity beállításai sikeresen frissítve lettek. velocity.command.reload-failure=Hiba történt a Velocity beállításainak frissítése közben. Több információt a konzolban találsz. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} licenszelve van a GNU General Public License v3 alatt. - velocity.command.no-plugins=Jelenleg egyetlen plugin sincs telepítve. velocity.command.plugins-list=Pluginok\: {0} velocity.command.plugin-tooltip-website=Weboldal\: {0} velocity.command.plugin-tooltip-author=Készítő\: {0} velocity.command.plugin-tooltip-authors=Készítők\: {0} - velocity.command.dump-uploading=Az összegyűjtött információ feltöltése... velocity.command.dump-send-error=Egy hiba lépett fel miközben kommunikálni próbáltunk a Velocity szerverekkel. Lehetséges, hogy a szerver(ek) ideiglenesen elérhetetlenek, vagy ez egy hiba a te hálózati beállításaiddal. Több információt a logban, vagy a Velocity konzoljában találsz. velocity.command.dump-success=Egy anonimizált jelentés sikeresen el lett készítve erről a proxyról. Ha egy fejlesztő kérte, akkor innen kimásolhatod a linket, és megoszthatod velük\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_it_IT.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_it_IT.properties index 8f88bee32..51618e9a1 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_it_IT.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_it_IT.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Questo server è compatibile s velocity.error.modern-forwarding-failed=Il server non ha inviato una richiesta di inoltro al proxy. Assicurati che il server sia configurato per l'inoltro di Velocity. velocity.error.moved-to-new-server=Sei stato cacciato da {0}\: {1} velocity.error.no-available-servers=Non ci sono server disponibili per connetterti. Riprova più tardi o contatta un amministratore. - # Commands velocity.command.generic-error=Si è verificato un errore durante l'esecuzione di questo comando. velocity.command.command-does-not-exist=Questo comando non esiste. - velocity.command.players-only=Solo i giocatori possono eseguire questo comando. velocity.command.server-does-not-exist=Il server {0} non esiste. - velocity.command.server-current-server=Sei già connesso a {0}. velocity.command.server-too-many=Ci sono troppi server impostati. Usa il completamento con il tasto tab per visualizzare tutti i server disponibili. velocity.command.server-available=Server disponibili\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} giocatore online velocity.command.server-tooltip-players-online={0} giocatori online velocity.command.server-tooltip-current-server=Sei già connesso a questo server velocity.command.server-tooltip-offer-connect-server=Clicca per connetterti a questo server - velocity.command.glist-player-singular={0} giocatore è attualmente connesso al proxy. velocity.command.glist-player-plural={0} giocatori sono attualmente connessi al proxy. velocity.command.glist-view-all=Per visualizzare tutti i giocatori sui server, usa /glist all. - velocity.command.reload-success=La configurazione di Velocity è stata ricaricata con successo. velocity.command.reload-failure=Impossibile ricaricare la configurazione di Velocity. Controlla la console per maggiori dettagli. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} è concesso in licenza secondo i termini della GNU General Public License v3. - velocity.command.no-plugins=Non ci sono plugin installati. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Sito web\: {0} velocity.command.plugin-tooltip-author=Autore\: {0} velocity.command.plugin-tooltip-authors=Autori\: {0} - velocity.command.dump-uploading=Caricamento informazioni raccolte... velocity.command.dump-send-error=Si è verificato un errore durante la comunicazione con i server Velocity. I server potrebbero essere temporaneamente non disponibili o c'è un problema con le impostazioni di rete. Puoi trovare maggiori informazioni nel log o nella console del tuo server Velocity. velocity.command.dump-success=Creato un report anonimo contenente informazioni utili su questo proxy. Se uno sviluppatore lo richiede, è possibile condividere con loro il seguente link\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ja_JP.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ja_JP.properties index bfcbf86df..085bfe0b4 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ja_JP.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ja_JP.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=このサーバーは Minecraf velocity.error.modern-forwarding-failed=サーバーがプロキシに転送要求を送信しませんでした。 サーバーが Velocity 用に構成されていることを確認してください。 velocity.error.moved-to-new-server=あなたは {0} からキックされました\: {1} velocity.error.no-available-servers=接続できるサーバーがありません。後でもう一度試すか、管理者にお問い合わせください。 - # Commands velocity.command.generic-error=このコマンドの実行中にエラーが発生しました。 velocity.command.command-does-not-exist=未知のコマンドです。 - velocity.command.players-only=このコマンドはプレイヤーのみ実行できます。 velocity.command.server-does-not-exist=指定されたサーバー {0} は存在しません。 - velocity.command.server-current-server=現在 {0} に接続しています。 velocity.command.server-too-many=設定されているサーバー数が多すぎます。タブ補完を使い、利用可能なすべてのサーバーを表示してください。 velocity.command.server-available=利用可能なサーバー\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} 人のプレイヤーがオン velocity.command.server-tooltip-players-online={0} 人のプレイヤーがオンライン velocity.command.server-tooltip-current-server=現在、このサーバーに接続しています velocity.command.server-tooltip-offer-connect-server=クリックしてこのサーバーに接続 - velocity.command.glist-player-singular={0} 人が現在プロキシに接続しています。 velocity.command.glist-player-plural={0} 人が現在プロキシに接続しています。 velocity.command.glist-view-all=サーバー上のすべてのプレイヤーを表示するには、/glist allを使用してください。 - velocity.command.reload-success=Velocityの設定が再読み込みされました。 velocity.command.reload-failure=Velocityの設定を再読み込みできません。詳細はコンソールで確認してください。 - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} は、GNU General Public License v3に基づいてライセンスされています。 - velocity.command.no-plugins=現在インストールされているプラグインはありません。 velocity.command.plugins-list=プラグイン\: {0} velocity.command.plugin-tooltip-website=ウェブサイト\: {0} velocity.command.plugin-tooltip-author=作者\: {0} velocity.command.plugin-tooltip-authors=作者\: {0} - velocity.command.dump-uploading=収集した情報をアップロードしています... velocity.command.dump-send-error=Velocityサーバーとの通信中にエラーが発生しました。サーバーが一時的に利用できないか、ネットワーク設定に問題がある可能性があります。詳細はコンソールまたはサーバーログで確認できます。 velocity.command.dump-success=このプロキシに関する有用な情報を含む匿名化されたレポートを作成しました。開発者が要求した場合は、次のリンクを共有してください\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ko_KR.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ko_KR.properties index 253d0c258..311adaa87 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ko_KR.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ko_KR.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=이 서버는 Minecraft 1.13 velocity.error.modern-forwarding-failed=서버가 프록시에 포워딩 요청을 보내지 않았습니다. 서버가 Velocity 포워딩이 설정되어 있는지 확인하세요. velocity.error.moved-to-new-server={0}\: {1} 에서 추방됐습니다. velocity.error.no-available-servers=연결할 수 있는 서버가 없습니다. 나중에 다시 시도하거나 관리자에게 문의하세요. - # Commands velocity.command.generic-error=명령어를 실행하는 도중 오류가 발생했습니다. velocity.command.command-does-not-exist=그 명령어는 존재하지 않습니다. - velocity.command.players-only=이 명령어는 플레이어만 사용할 수 있습니다. velocity.command.server-does-not-exist=서버 {0} (은)는 존재하지 않습니다. - velocity.command.server-current-server={0} 에 연결되어 있습니다. velocity.command.server-too-many=너무 많은 서버가 존재합니다. tab 자동완성으로 가능한 모든 서버를 보세요. velocity.command.server-available=사용 가능한 서버\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} 플레이어 접속중 velocity.command.server-tooltip-players-online={0} 플레이어 접속중 velocity.command.server-tooltip-current-server=이 서버에 연결되어 있습니다 velocity.command.server-tooltip-offer-connect-server=클릭해 이 서버에 연결합니다. - velocity.command.glist-player-singular={0} 플레이어가 현재 프록시에 연결되어 있습니다. velocity.command.glist-player-plural={0} 플레이어가 현재 프록시에 연결되어 있습니다. velocity.command.glist-view-all=서버에 있는 모든 플레이어를 보려면, /glist all 를 사용하세요. - velocity.command.reload-success=Velocity 설정이 성공적으로 리로드되었습니다. velocity.command.reload-failure=Velocity 설정을 리로드할 수 없습니다. 콘솔에서 더 많은 정보를 확인하세요. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} 는 GNU General Public License v3 라이센스의 약관을 따릅니다. - velocity.command.no-plugins=설치된 플러그인이 없습니다. velocity.command.plugins-list=플러그인\: {0} velocity.command.plugin-tooltip-website=웹사이트\: {0} velocity.command.plugin-tooltip-author=제작자\: {0} velocity.command.plugin-tooltip-authors=제작자\: {0} - velocity.command.dump-uploading=모인 정보를 업로드하는 중... velocity.command.dump-send-error=Velocity 서버와 통신하는데 오류가 발생했습니다. 서버가 일시적으로 사용할 수 없거나 네트워크 설정에 문제가 있습니다. Velocity 서버의 콘솔 또는 로그에서 자세한 정보를 찾아볼 수 있습니다. velocity.command.dump-success=이 프록시와 관련된 유용한 정보를 담은 익명 보고서를 만들었습니다. 만약 개발자가 요청한다면, 다음 링크를 그들에게 공유해보세요\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nb_NO.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nb_NO.properties index d18def671..a317ae640 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nb_NO.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nb_NO.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Denne serveren er bare kompati velocity.error.modern-forwarding-failed=Din server sendte ikke en viderekoblingsforespørsel til proxyen. Pass på at serveren er konfigurert for Velocity viderekobling. velocity.error.moved-to-new-server=Du ble sparket ut fra {0}\: {1} velocity.error.no-available-servers=Det finnes ingen tilgjengelige servere å koble deg til. Prøv igjen senere eller kontakt en administrator. - # Commands velocity.command.generic-error=En feil oppstod under gjennomføringen av denne kommandoen. velocity.command.command-does-not-exist=Denne kommandoen finnes ikke. - velocity.command.players-only=Bare spillere kan utføre denne kommandoen. velocity.command.server-does-not-exist=Den spesifiserte serveren {0} finnes ikke. - velocity.command.server-current-server=Du er for øyeblikket tilkoblet {0}. velocity.command.server-too-many=Det er for mange servere satt opp. Bruk tabfullførelse for å se alle tilgjengelige servere. velocity.command.server-available=Tilgjengelige servere\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} spiller tilkoblet velocity.command.server-tooltip-players-online={0} spillere tilkoblet velocity.command.server-tooltip-current-server=Du er for øyeblikket tilkoblet denne serveren velocity.command.server-tooltip-offer-connect-server=Trykk for å koble til denne serveren - velocity.command.glist-player-singular={0} spiller er for øyeblikket tilkoblet denne proxyen. velocity.command.glist-player-plural={0} spillere er for øyeblikket tilkoblet denne proxyen. velocity.command.glist-view-all=For å se alle tilkoblede spillere, utfør /glist all. - velocity.command.reload-success=Velocity konfigurasjonen ble lastet inn på nytt. velocity.command.reload-failure=Kan ikke laste inn Velocity konfigurasjonen din. Sjekk konsollen for mer detaljer. - velocity.command.version-copyright=Opphavsrett 2018-2021 {0}. {1} er lisensiert under betingelsene av GNU General Public License v3. - velocity.command.no-plugins=Ingen plugin er installert. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Hjemmeside\: {0} velocity.command.plugin-tooltip-author=Skaper\: {0} velocity.command.plugin-tooltip-authors=Skapere\: {0} - velocity.command.dump-uploading=Laster opp diagnostisk informasjon... velocity.command.dump-send-error=En feil oppstod under kommunikasjon med Velocityserverne. Enten er disse serverne midlertidig utilgjengelige, ellers er det noe galt med dine nettverksinnstillinger. Du kan finne mer informasjon i din logg eller i konsollen på Velocityservern. velocity.command.dump-success=Skapte en anonymisert rapport med utfyllende informasjon om denne proxyen. Om en utvikler forespurte den, kan du dele følgende lenke med dem\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nl_NL.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nl_NL.properties index 58d1f7b26..670230de5 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nl_NL.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nl_NL.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Deze server is alleen compatib velocity.error.modern-forwarding-failed=Je server heeft geen forwarding request naar de proxy gestuurd. Zorg ervoor dat de server is geconfigureerd voor Velocity forwarding. velocity.error.moved-to-new-server=Je bent verwijderd van {0}\: {1} velocity.error.no-available-servers=Er zijn geen beschikbare servers om je met te verbinden. Probeer het later opnieuw of neem contact op met een administrator. - # Commands velocity.command.generic-error=Er is een fout opgetreden bij het uitvoeren van dit commando. velocity.command.command-does-not-exist=Dit commando bestaat niet. - velocity.command.players-only=Alleen spelers kunnen dit commando uitvoeren. velocity.command.server-does-not-exist=De opgegeven server {0} bestaat niet. - velocity.command.server-current-server=Je bent op dit moment verbonden met {0}. velocity.command.server-too-many=Er zijn te veel servers ingesteld. Gebruik tabvervollediging om alle beschikbare servers te bekijken. velocity.command.server-available=Beschikbare servers\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} speler online velocity.command.server-tooltip-players-online={0} spelers online velocity.command.server-tooltip-current-server=Momenteel verbonden met deze server velocity.command.server-tooltip-offer-connect-server=Klik om te verbinden met deze server - velocity.command.glist-player-singular={0} speler is momenteel verbonden met de proxy. velocity.command.glist-player-plural={0} spelers zijn momenteel verbonden met de proxy. velocity.command.glist-view-all=Om alle spelers op de servers te bekijken, gebruik /glist all. - velocity.command.reload-success=Velocity configuratie succesvol herladen. velocity.command.reload-failure=De Velocity-configuratie kan niet opnieuw worden geladen. Kijk op de console voor meer details. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is gelicentieerd onder de voorwaarden van de GNU General Public License v3. - velocity.command.no-plugins=Er zijn momenteel geen plugins geïnstalleerd. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Website\: {0} velocity.command.plugin-tooltip-author=Auteur\: {0} velocity.command.plugin-tooltip-authors=Auteurs\: {0} - velocity.command.dump-uploading=Verzamelde informatie uploaden... velocity.command.dump-send-error=Er is een fout opgetreden tijdens de communicatie met de Velocity-servers. De servers zijn mogelijk tijdelijk niet beschikbaar of er is een probleem met je netwerkinstellingen. Je kunt meer informatie vinden in de logs of de console van je Velocity-server. velocity.command.dump-success=Een anoniem rapport is gemaakt met nuttige informatie over deze proxy. Als een ontwikkelaar dit heeft verzocht, kun je de volgende link delen\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nn_NO.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nn_NO.properties index 1396137b5..fc4e441e7 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nn_NO.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_nn_NO.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Denne sørvaren er bare kompat velocity.error.modern-forwarding-failed=Din server sende ikkje ein vidarekoplingsførespurnad til proxyen. Pass på at sørvaren er konfigurert for Velocity vidarekopling. velocity.error.moved-to-new-server=Du blei sparka ut frå {0}\: {1} velocity.error.no-available-servers=Det finst ingen tilgjengelege sørvarar å kopla deg til. Prøv igjen seinare eller kontakt ein administrator. - # Commands velocity.command.generic-error=Ein feil oppstod under utføringa av denne kommandoen. velocity.command.command-does-not-exist=Denne kommandoen finst ikkje. - velocity.command.players-only=Bare spelarar kan utføra denne kommandoen. velocity.command.server-does-not-exist=Den oppgjevne sørvaren {0} finst ikkje. - velocity.command.server-current-server=Du er for augneblinken tilkopla {0}. velocity.command.server-too-many=Det er for mange sørvarar sette opp. Bruk tabfullføring for å sjå alle tilgjengelege sørvarar. velocity.command.server-available=Tilgjengelege sørvarar\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} spelar tilkopla velocity.command.server-tooltip-players-online={0} spelarar tilkopla velocity.command.server-tooltip-current-server=Du er for augneblinken tilkopla denne sørvaren velocity.command.server-tooltip-offer-connect-server=Trykk for å kopla til denne sørvaren - velocity.command.glist-player-singular={0} spelar er for augneblinken tilkopla denne proxyen. velocity.command.glist-player-plural={0} spelare er for augneblinken tilkopla denne proxyen. velocity.command.glist-view-all=For å sjå alle tilkopla spelarar, gjer /glist all. - velocity.command.reload-success=Velocity konfigurasjonen blei lasta inn på nytt. velocity.command.reload-failure=Kan ikkje lasta inn Velocity konfigurasjonen din. Sjekk konsollen for meir detaljar. - velocity.command.version-copyright=Opphavsrett 2018-2021 {0}. {1} er lisensiert under vilkåra av GNU General Public License v3. - velocity.command.no-plugins=Det er ingen plugins installert. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Heimeside\: {0} velocity.command.plugin-tooltip-author=Skapar\: {0} velocity.command.plugin-tooltip-authors=Skaparar\: {0} - velocity.command.dump-uploading=Uploading gathered information... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pl_PL.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pl_PL.properties index 9dc179d19..e406f62a7 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pl_PL.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pl_PL.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Ten serwer jest kompatybilny t velocity.error.modern-forwarding-failed=Twój serwer nie wysłał żądania przekazania do serwera proxy. Upewnij się, że serwer jest skonfigurowany do przekazywania Velocity. velocity.error.moved-to-new-server=Zostałeś wyrzucony z serwera {0}\: {1} velocity.error.no-available-servers=Brak dostępnych serwerów, z którymi można by Cię połączyć. Spróbuj ponownie później lub skontaktuj się z administratorem. - # Commands velocity.command.generic-error=Podczas wykonywania tego polecenia wystąpił błąd. velocity.command.command-does-not-exist=To polecenie nie istnieje. - velocity.command.players-only=Jedynie gracze mogą wykonywać to polecenie. velocity.command.server-does-not-exist=Wybrany serwer {0} nie istnieje. - velocity.command.server-current-server=Jesteś obecnie połączony z serwerem {0}. velocity.command.server-too-many=Skonfigurowano zbyt wiele serwerów. Użyj uzupełniania klawiszem tab, aby wyświetlić wszystkie dostępne serwery. velocity.command.server-available=Dostępne serwery\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} gracz online velocity.command.server-tooltip-players-online={0} graczy online velocity.command.server-tooltip-current-server=Jesteś obecnie połączony z tym serwerem velocity.command.server-tooltip-offer-connect-server=Kliknij, aby połączyć się z tym serwerem - velocity.command.glist-player-singular=Z tym „proxy” jest obecnie połączony {0} gracz. velocity.command.glist-player-plural=Liczba graczy obecnie połączonych z tym „proxy”\: {0} velocity.command.glist-view-all=Aby zobaczyć wszystkich graczy na serwerach, użyj /glist all. - velocity.command.reload-success=Konfiguracja Velocity została pomyślnie załadowana ponownie. velocity.command.reload-failure=Nie udało się załadować konfiguracji Velocity. Sprawdź konsolę, aby uzyskać więcej informacji. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} jest objęty licencją na warunkach GNU General Public License v3. - velocity.command.no-plugins=Brak zainstalowanych wtyczek. velocity.command.plugins-list=Wtyczki\: {0} velocity.command.plugin-tooltip-website=Strona internetowa\: {0} velocity.command.plugin-tooltip-author=Twórca\: {0} velocity.command.plugin-tooltip-authors=Twórcy\: {0} - velocity.command.dump-uploading=Przesyłanie zebranych informacji… velocity.command.dump-send-error=Wystąpił błąd podczas komunikacji z serwerami Velocity. Serwery mogą być chwilowo niedostępne lub wystąpił problem z ustawieniami sieci. Więcej informacji można znaleźć w dzienniku lub konsoli serwera Velocity. velocity.command.dump-success=Utworzono zanonimizowany raport zawierający przydatne informacje o tym proxy. Jeśli programista o to poprosił, możesz udostępnić mu następujący link\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pt_BR.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pt_BR.properties index c7031527e..9eb4c76eb 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pt_BR.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_pt_BR.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Este servidor é compatível a velocity.error.modern-forwarding-failed=Seu servidor não enviou uma solicitação de encaminhamento para o proxy. Certifique-se de que o servidor está configurado para encaminhamento Velocity. velocity.error.moved-to-new-server=Você foi expulso de {0}\: {1} velocity.error.no-available-servers=Não há servidores disponíveis para conectá-lo. Tente novamente mais tarde ou contate um administrador. - # Commands velocity.command.generic-error=Ocorreu um erro ao executar este comando. velocity.command.command-does-not-exist=Esse comando não existe. - velocity.command.players-only=Apenas jogadores podem executar esse comando. velocity.command.server-does-not-exist=O servidor {0} não existe. - velocity.command.server-current-server=Você está atualmente conectado a {0}. velocity.command.server-too-many=Há muitos servidores configurados. Utilize o auto-preenchimento tab para ver todos os servidores disponíveis. velocity.command.server-available=Servidores disponíveis\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} jogador conectado velocity.command.server-tooltip-players-online={0} jogadores conectados velocity.command.server-tooltip-current-server=Atualmente conectado a este servidor velocity.command.server-tooltip-offer-connect-server=Clique para conectar a este servidor - velocity.command.glist-player-singular=O jogador {0} está atualmente conectado ao proxy. velocity.command.glist-player-plural={0} jogadores estão atualmente conectados ao proxy. velocity.command.glist-view-all=Para ver todos os jogadores em todos os servidores, use /glist all. - velocity.command.reload-success=Configuração do Velocity recarregada com êxito. velocity.command.reload-failure=Não foi possível recarregar a configuração do Velocity. Verifique o console para mais detalhes. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} está licenciado sobre os termos da Licença Pública Geral GNU v3. - velocity.command.no-plugins=Não há plugins instalados atualmente. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Site\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Autores\: {0} - velocity.command.dump-uploading=Enviando informações coletadas... velocity.command.dump-send-error=Ocorreu um erro ao se comunicar com os servidores Velocity. Os servidores podem estar temporariamente indisponíveis ou há um problema com suas configurações de rede. Você pode encontrar mais informações no log ou no console de seu servidor Velocity. velocity.command.dump-success=Foi criado um relatório anônimo contendo informações úteis sobre este proxy. Se um desenvolvedor o solicitou, você pode compartilhar o seguinte link com eles\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ru_RU.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ru_RU.properties index 55949fbd2..d09f6e9d0 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ru_RU.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_ru_RU.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Этот сервер совм velocity.error.modern-forwarding-failed=Ваш сервер не посылал запрос на переадресацию на прокси-сервер. Убедитесь, что сервер настроен на переадресацию Velocity. velocity.error.moved-to-new-server=Вы были кикнуты с сервера {0}\: {1} velocity.error.no-available-servers=Нет серверов, доступных для подключения. Попробуйте позже или свяжитесь с администратором. - # Commands velocity.command.generic-error=Во время выполнения этой команды произошла ошибка. velocity.command.command-does-not-exist=Этой команды не существует. - velocity.command.players-only=Только игроки могут использовать эту команду. velocity.command.server-does-not-exist=Указанный сервер {0} не существует. - velocity.command.server-current-server=На данный момент вы подключены к серверу {0}. velocity.command.server-too-many=Настроено слишком много серверов. Для просмотра всех доступных серверов, используйте автозаполнение клавишей Tab. velocity.command.server-available=Доступные серверы\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} игрок онлайн velocity.command.server-tooltip-players-online={0} игрок(а, ов) онлайн velocity.command.server-tooltip-current-server=Подключен к этому серверу velocity.command.server-tooltip-offer-connect-server=Кликните, чтобы присоединиться к этому серверу - velocity.command.glist-player-singular={0} игрок подключен к прокси на данный момент. velocity.command.glist-player-plural={0} игрок(а, ов) подключены к прокси на данный момент. velocity.command.glist-view-all=Чтобы просмотреть всех игроков на серверах, используйте /glist all. - velocity.command.reload-success=Конфигурация Velocity успешно перезагружена. velocity.command.reload-failure=Не удалось перезагрузить конфигурацию Velocity. Проверьте консоль для подробностей. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} лицензирована на условиях GNU General Public License v3. - velocity.command.no-plugins=Ни одного плагина не установлено. velocity.command.plugins-list=Плагины\: {0} velocity.command.plugin-tooltip-website=Вебсайт\: {0} velocity.command.plugin-tooltip-author=Автор\: {0} velocity.command.plugin-tooltip-authors=Авторы\: {0} - velocity.command.dump-uploading=Загрузка полученной информации... velocity.command.dump-send-error=Во время связи с серверами Velocity произошла ошибка. Возможно, серверы временно недоступны или проблема в настройках вашей сети. Более подробную информацию можно найти в логе или консоли вашего сервера Velocity. velocity.command.dump-success=Создан анонимный отчет, содержащий полезную информацию об этом прокси. Если этот отчёт запросил разработчик, вы можете поделиться с ним следующей ссылкой\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sk_SK.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sk_SK.properties index 6dfb48ad6..a1d12121f 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sk_SK.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sk_SK.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Tento server je kompatibilný velocity.error.modern-forwarding-failed=Tvoj server neodoslal presmerovaciu požiadavku proxy serveru. Uisti sa, že server je nastavený na presmerovanie Velocity. velocity.error.moved-to-new-server=Bol si odpojený z {0}\: {1} velocity.error.no-available-servers=Nie sú k dispozícii žiadne servery na pripojenie. Skús to neskôr alebo kontaktuj admina. - # Commands velocity.command.generic-error=Nastala chyba pri vykonávaní tohto príkazu. velocity.command.command-does-not-exist=Tento príkaz neexistuje. - velocity.command.players-only=Len hráči môžu vykonať tento príkaz. velocity.command.server-does-not-exist=Zadaný server {0} neexistuje. - velocity.command.server-current-server=Aktuálne si pripojený na {0}. velocity.command.server-too-many=Je nastavených príliš veľa serverov. Použi tab pre zobrazenie dostupných serverov. velocity.command.server-available=Dostupné servery\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} hráč online velocity.command.server-tooltip-players-online={0} hráčov online velocity.command.server-tooltip-current-server=Aktuálne si pripojený na tento server velocity.command.server-tooltip-offer-connect-server=Klikni pre pripojenie na tento server - velocity.command.glist-player-singular={0} hráč je pripojený na tento proxy server. velocity.command.glist-player-plural={0} hráčov je pripojených na tento proxy server. velocity.command.glist-view-all=Pre zobrazenie všetkých hráčov na všetkých serveroch použi /glist all. - velocity.command.reload-success=Konfigurácia Velocity úspešne načítaná. velocity.command.reload-failure=Nepodarilo sa načítať konfiguráciu Velocity. Pozri sa do konzoly pre viac informácií. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} je licencovaný pod podmienkami GNU General Public License v3. - velocity.command.no-plugins=Aktuálne nie sú nainštalované žiadne pluginy. velocity.command.plugins-list=Pluginy\: {0} velocity.command.plugin-tooltip-website=Webstránka\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Autori\: {0} - velocity.command.dump-uploading=Nahrávanie získaných informácií... velocity.command.dump-send-error=Nastala chyba pri komunikácii s Velocity servermi. Servery môžu byť dočasne nedostupné alebo je chyba v prístupe na internet. Viac informácií je v logu a v konzole tvojho Velocity servera. velocity.command.dump-success=Bol vytvorený anonymný záznam o tomto serveri. Ak si ho vyžiadal developer, môžeš mu poslať nasledujúci odkaz\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sq_AL.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sq_AL.properties index a5af20c8a..d6bfe9af2 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sq_AL.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sq_AL.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Ky server është i pajtueshë velocity.error.modern-forwarding-failed=Serveri juaj nuk i dërgoi një kërkesë për transferim përfaqësuesit. Sigurohuni që serveri të jetë konfiguruar për transferimin e shpejtësisë. velocity.error.moved-to-new-server=Ju kanë dëbuar nga {0}\: {1} velocity.error.no-available-servers=Nuk ka servera të disponueshëm për t'ju lidhur. Provo përsëri më vonë ose kontakto një administrator. - # Commands velocity.command.generic-error=Ndodhi një gabim gjatë ekzekutimit të kësaj komande. velocity.command.command-does-not-exist=Kjo komandë nuk ekziston. - velocity.command.players-only=Vetëm lojtarët mund ta drejtojnë këtë komandë. velocity.command.server-does-not-exist=Serveri i specifikuar {0} nuk ekziston. - velocity.command.server-current-server=Aktualisht jeni i lidhur me {0}. velocity.command.server-too-many=Ka shumë servera të konfiguruar. Përdorni përfundimin e skedave për të parë të gjithë serverat e disponueshëm. velocity.command.server-available=Serverat e disponueshëm\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} lojtar në internet velocity.command.server-tooltip-players-online={0} lojtarë në internet velocity.command.server-tooltip-current-server=Aktualisht e lidhur me këtë server velocity.command.server-tooltip-offer-connect-server=Klikoni për t'u lidhur me këtë server - velocity.command.glist-player-singular={0} lojtari aktualisht është i lidhur me përfaqësuesin. velocity.command.glist-player-plural={0} lojtarët janë aktualisht të lidhur me përfaqësuesin. velocity.command.glist-view-all=Për të parë të gjithë lojtarët në servera, përdorni /glist all. - velocity.command.reload-success=Konfigurimi i shpejtësisë u ringarkua me sukses. velocity.command.reload-failure=Nuk mund të ringarkohet konfigurimi i shpejtësisë. Kontrolloni konsolën për më shumë detaje. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is licensed under the terms of the GNU General Public License v3. - velocity.command.no-plugins=There are no plugins currently installed. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Website\: {0} velocity.command.plugin-tooltip-author=Author\: {0} velocity.command.plugin-tooltip-authors=Authors\: {0} - velocity.command.dump-uploading=Uploading gathered information... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sr_CS.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sr_CS.properties index 40cf80d55..9963ad7d7 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sr_CS.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sr_CS.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Ovaj server je kompatibilan sa velocity.error.modern-forwarding-failed=Vaš server nije poslao zahtev za prosleđivanje na proxy. Proverite je li server konfigurisan za Velocity prosleđivanje. velocity.error.moved-to-new-server=Izbačeni ste iz {0}\: {1} velocity.error.no-available-servers=Nema dostupnih servera za povezati Vas. Pokušajte ponovo kasnije ili kontaktirajte nekog admina. - # Commands velocity.command.generic-error=Došlo je do greške pri pokretanju te komande. velocity.command.command-does-not-exist=Ta komanda ne postoji. - velocity.command.players-only=Tu komandu mogu pokrenuti samo igrači. velocity.command.server-does-not-exist=Navedeni server {0} ne postoji. - velocity.command.server-current-server=Trenutno ste povezani na {0}. velocity.command.server-too-many=Postoji mnogo servera. Koristite tab dovršavanje za pregled svih dostupnih servera. velocity.command.server-available=Dostupni serveri\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} igrač online velocity.command.server-tooltip-players-online={0} igrača online velocity.command.server-tooltip-current-server=Trenutno ste povezani na ovaj server velocity.command.server-tooltip-offer-connect-server=Kliknite za povezivanje na ovaj server - velocity.command.glist-player-singular={0} igrač je trenutno povezan na proxy. velocity.command.glist-player-plural={0} igrača je trenutno povezano na proxy. velocity.command.glist-view-all=Za pregled svih igrača na serverima koristite /glist all. - velocity.command.reload-success=Velocity konfiguracija uspešno ponovno učitana. velocity.command.reload-failure=Nije moguće ponovo učitati Vašu Velocity konfiguraciju. Proverite konzolu za više detalja. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} je licenciran pod uslovima licence GNU General Public License v3. - velocity.command.no-plugins=Trenutno nema instaliranih plugin-a. velocity.command.plugins-list=Plugin-i\: {0} velocity.command.plugin-tooltip-website=Web stranica\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Autori\: {0} - velocity.command.dump-uploading=Otpremanje prikupljenih informacija... velocity.command.dump-send-error=Dogodila se greška pri komunikaciji sa Velocity serverima. Serveri su ili trenutno nedostupni, ili postoji problem sa Vašim mrežnim podešavanjima. Možete saznati više informacija u log-u ili konzoli Vašeg Velocity servera. velocity.command.dump-success=Kreiran anonimiziran izveštaj koji sadrži korisne informacije o ovom proxy-u. Ako ga developer zatraži, možete mu poslati ovaj link\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sv_SE.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sv_SE.properties index 32d2c70ea..df66bac08 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sv_SE.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_sv_SE.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=This server is only compatible velocity.error.modern-forwarding-failed=Your server did not send a forwarding request to the proxy. Make sure the server is configured for Velocity forwarding. velocity.error.moved-to-new-server=You were kicked from {0}\: {1} velocity.error.no-available-servers=There are no available servers to connect you to. Try again later or contact an admin. - # Commands velocity.command.generic-error=An error occurred while running this command. velocity.command.command-does-not-exist=This command does not exist. - velocity.command.players-only=Only players can run this command. velocity.command.server-does-not-exist=The specified server {0} does not exist. - velocity.command.server-current-server=You are currently connected to {0}. velocity.command.server-too-many=There are too many servers set up. Use tab completion to view all servers available. velocity.command.server-available=Available servers\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} player online velocity.command.server-tooltip-players-online={0} players online velocity.command.server-tooltip-current-server=Currently connected to this server velocity.command.server-tooltip-offer-connect-server=Click to connect to this server - velocity.command.glist-player-singular={0} player is currently connected to the proxy. velocity.command.glist-player-plural={0} players are currently connected to the proxy. velocity.command.glist-view-all=To view all players on servers, use /glist all. - velocity.command.reload-success=Velocity configuration successfully reloaded. velocity.command.reload-failure=Unable to reload your Velocity configuration. Check the console for more details. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is licensed under the terms of the GNU General Public License v3. - velocity.command.no-plugins=There are no plugins currently installed. velocity.command.plugins-list=Plugins\: {0} velocity.command.plugin-tooltip-website=Website\: {0} velocity.command.plugin-tooltip-author=Author\: {0} velocity.command.plugin-tooltip-authors=Authors\: {0} - velocity.command.dump-uploading=Uploading gathered information... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tl_PH.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tl_PH.properties index 78b8b5bb7..6c58c2cf9 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tl_PH.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tl_PH.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Ang server na ito magkasundo l velocity.error.modern-forwarding-failed=Hindi ipadala ang serbidor mo ng forwarding request sa proxy. Dapat nae-ensure mo ng naka-configure ang server para ng forwarding ng Velocity. velocity.error.moved-to-new-server=Nanipa ka mula sa {0} dahil {1} velocity.error.no-available-servers=Wala na ang mga serbidor na magagamit para sa'yo. Paki-ulitin mo ulit o magcontact ka isang admin. - # Commands velocity.command.generic-error=Nangyari isang pagkakamali kapag sinubukan ng serbidor magamit ang komando ng ito. velocity.command.command-does-not-exist=Walang komando sa serbidor. - velocity.command.players-only=Mga manlalaro lang makagamit ang komando ito. velocity.command.server-does-not-exist=Walang serbidor {0}. - velocity.command.server-current-server=Nakakonekta ka sa {0}. velocity.command.server-too-many=Meron masyadong serbidor sa konfig. Magamit ka ng tab completion sa makita lahat ng serbidor na magagamit. velocity.command.server-available=Magagamit na mga serbidor\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} manlalaro sa online velocity.command.server-tooltip-players-online={0} mga manlalaro sa online velocity.command.server-tooltip-current-server=Nakakonekta ka sa serbidor na ito velocity.command.server-tooltip-offer-connect-server=I-click dito sa kumonekta sa serbidor na ito - velocity.command.glist-player-singular={0} manlalaro nasa proxy. velocity.command.glist-player-plural={0} mga manlalaro nasa proxy. velocity.command.glist-view-all=Para sa makita ang mga lahat ng manlalaro sa mga serbidor, magamit ka ng /glist all. - velocity.command.reload-success=Matagumpay ang reload ng konfigurasyon ng Velocity. velocity.command.reload-failure=Hindi kaya ang magreload ng konfigurasyon mo sa Velocity. Magsiyasat ang konsole para mas maraming detalye. - velocity.command.version-copyright=Copyright 2018-2021 {0}. {1} is licensed under the terms of the GNU General Public License v3. - velocity.command.no-plugins=Walang plugin nang naka-install. velocity.command.plugins-list=Mga plugin\: {0} velocity.command.plugin-tooltip-website=Website\: {0} velocity.command.plugin-tooltip-author=Autor\: {0} velocity.command.plugin-tooltip-authors=Mga autor\: {0} - velocity.command.dump-uploading=Inu-upload ang ipong impormasyon... velocity.command.dump-send-error=Nangyari isang pagkakamali sa panahon ng koneksiyon kasama ang mga serbidor ng Velocity. Baka hindi magagamit na pansamantalang ang mga serbidor o may isang isyu sa mga network settings mo. Hinapin mo mas impormasyon sa log o console sa serbidor ng Velocity mo. velocity.command.dump-success=Lumikha isang report ng hindi nagpapakilala ng may impormasyon mahalaga tungkol sa proxy ng ito. Kung hingin ito ng developer, makashare ka ang link na ito kasama siya\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tr_TR.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tr_TR.properties index 8666df838..b9ee2dfae 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tr_TR.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_tr_TR.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=Bu sunucuya Minecraft'ın sade velocity.error.modern-forwarding-failed=Sunucun Velocity'ye yönlendirme isteğinde bulunmadı. Sunucunun Velocity'nin ayarlarında ayarlandığına emin ol. velocity.error.moved-to-new-server={0}\:{1} sunucusundan atıldınız velocity.error.no-available-servers=Seni bağlayabileceğimiz bir sunucu bulamadık. Lütfen daha sonra tekrar dene veya bir yetkili ile iletişime geç. - # Commands velocity.command.generic-error=Bu komutu çalıştırırken bir hata meydana geldi. velocity.command.command-does-not-exist=Böyle bir komut yok. - velocity.command.players-only=Sadece oyuncular bu komutu çalıştırabilir. velocity.command.server-does-not-exist=Belirlenmiş sunucu {0} bulunmuyor. - velocity.command.server-current-server=Şu anda {0} sunucusuna bağlısın. velocity.command.server-too-many=Ayarlanmış birçok sunucu mevcut. Mevcut bütün sunucuları görmek için tamamlama özelliğini kullan. velocity.command.server-available=Müsait sunucular\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} oyuncu çevrimiçi velocity.command.server-tooltip-players-online={0} oyuncu çevrimiçi velocity.command.server-tooltip-current-server=Şu anda bu sunucuya bağlısın velocity.command.server-tooltip-offer-connect-server=Bu sunucuya bağlanmak için tıkla - velocity.command.glist-player-singular=Şu anda sunucuya toplam {0} oyuncu bağlı. velocity.command.glist-player-plural=Şu anda sunucuya toplam {0} oyuncu bağlı. velocity.command.glist-view-all=Sunucudaki bütün oyuncuları görüntülemek için /glist all komutunu kullan. - velocity.command.reload-success=Velocity ayarları başarıyla güncellendi. velocity.command.reload-failure=Velocity ayarlarınız güncellenemiyor. Daha fazla bilgi için konsolu kontrol edin. - velocity.command.version-copyright=Talif hakkı 2018-2021 {0}. {1}, GNU General Public License v3 adı altında lisanslanmıştır. - velocity.command.no-plugins=Yüklenmiş herhangi bir eklenti yok. velocity.command.plugins-list=Eklentiler\: {0} velocity.command.plugin-tooltip-website=Website\: {0} velocity.command.plugin-tooltip-author=Yapımcı\: {0} velocity.command.plugin-tooltip-authors=Yapımcılar\: {0} - velocity.command.dump-uploading=Toplanılan bilgiler yükleniyor... velocity.command.dump-send-error=Velocity sunucuları ile iletişim sırasında bir hata oluştu. Sunucular geçici olarak kullanılamıyor olabilir veya ağ ayarlarınızla ilgili bir sorun olabilir. Velocity sunucunuzun logunda veya konsolunda daha fazla bilgi bulabilirsiniz. velocity.command.dump-success=Bu proxy hakkında faydalı bilgiler içeren anonim bir rapor oluşturdu. Bir geliştirici talep ettiyse, aşağıdaki bağlantıyı onlarla paylaşabilirsiniz\: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_CN.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_CN.properties index e22e751be..382c8e42c 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_CN.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_CN.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=此服务器仅兼容 Minecraf velocity.error.modern-forwarding-failed=您的服务器未向代理服务器转发请求,请确保已配置 Velocity 转发。 velocity.error.moved-to-new-server=您已被踢出 {0}:{1} velocity.error.no-available-servers=您当前没有可连接的服务器,请稍后重试或联系管理员。 - # Commands velocity.command.generic-error=执行此命令时发生错误。 velocity.command.command-does-not-exist=此命令不存在。 - velocity.command.players-only=只有玩家才能执行此命令。 velocity.command.server-does-not-exist=指定的服务器 {0} 不存在。 - velocity.command.server-current-server=您已连接至 {0}。 velocity.command.server-too-many=设置的服务器过多,请使用 Tab 键补全来查看所有可用的服务器。 velocity.command.server-available=可用的服务器: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} 名玩家在线 velocity.command.server-tooltip-players-online={0} 名玩家在线 velocity.command.server-tooltip-current-server=当前已连接至此服务器 velocity.command.server-tooltip-offer-connect-server=点击连接至此服务器 - velocity.command.glist-player-singular=共有 {0} 名玩家已连接至此代理服务器。 velocity.command.glist-player-plural=共有 {0} 名玩家已连接至此代理服务器。 velocity.command.glist-view-all=使用 /glist all 命令来查看所有服务器的全部玩家列表。 - velocity.command.reload-success=Velocity 配置已成功重载。 velocity.command.reload-failure=无法重载 Velocity 配置,请查看控制台了解详情。 - velocity.command.version-copyright=Copyright 2018-2021 {0}。{1} 以 GNU 通用公共许可证第三版授权。 - velocity.command.no-plugins=当前没有安装任何插件。 velocity.command.plugins-list=插件:{0} velocity.command.plugin-tooltip-website=网站:{0} velocity.command.plugin-tooltip-author=作者:{0} velocity.command.plugin-tooltip-authors=作者:{0} - velocity.command.dump-uploading=正在上传已收集的信息... velocity.command.dump-send-error=与 Velocity 服务器通信时发生错误,服务器可能暂不可用或您的网络设置存在问题。您可在 Velocity 服务器日志或控制台中了解详情。 velocity.command.dump-success=已创建关于此代理的匿名反馈数据。若开发者需要,您可与其分享以下链接: diff --git a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_HK.properties b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_HK.properties index b1630092f..0eed30eae 100644 --- a/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_HK.properties +++ b/proxy/src/main/resources/com/velocitypowered/proxy/l10n/messages_zh_HK.properties @@ -29,14 +29,11 @@ velocity.error.modern-forwarding-needs-new-client=This server is only compatible velocity.error.modern-forwarding-failed=Your server did not send a forwarding request to the proxy. Make sure the server is configured for Velocity forwarding. velocity.error.moved-to-new-server=You were kicked from {0}\: {1} velocity.error.no-available-servers=There are no available servers to connect you to. Try again later or contact an admin. - # Commands velocity.command.generic-error=An error occurred while running this command. velocity.command.command-does-not-exist=This command does not exist. - velocity.command.players-only=Only players can run this command. velocity.command.server-does-not-exist=The specified server {0} does not exist. - velocity.command.server-current-server=You are currently connected to {0}. velocity.command.server-too-many=There are too many servers set up. Use tab completion to view all servers available. velocity.command.server-available=Available servers\: @@ -44,22 +41,17 @@ velocity.command.server-tooltip-player-online={0} player online velocity.command.server-tooltip-players-online={0} players online velocity.command.server-tooltip-current-server=Currently connected to this server velocity.command.server-tooltip-offer-connect-server=Click to connect to this server - velocity.command.glist-player-singular={0} player is currently connected to the proxy. velocity.command.glist-player-plural={0} players are currently connected to the proxy. velocity.command.glist-view-all=To view all players on servers, use /glist all. - velocity.command.reload-success=Velocity configuration successfully reloaded. velocity.command.reload-failure=Unable to reload your Velocity configuration. Check the console for more details. - velocity.command.version-copyright=Copyright 2018-2021 {0} ( {1} 的授權條款爲: GNU 通用公共授權條款第三版) - velocity.command.no-plugins=目前未有安裝任何 Velocity 插件。 velocity.command.plugins-list=插件: {0} velocity.command.plugin-tooltip-website=網站: {0} velocity.command.plugin-tooltip-author=作者: {0} velocity.command.plugin-tooltip-authors=作者: {0} - velocity.command.dump-uploading=正在收集並上載 Velocity 設定資料... velocity.command.dump-send-error=An error occurred while communicating with the Velocity servers. The servers may be temporarily unavailable or there is an issue with your network settings. You can find more information in the log or console of your Velocity server. velocity.command.dump-success=Created an anonymised report containing useful information about this proxy. If a developer requested it, you may share the following link with them\: diff --git a/proxy/src/main/resources/default-velocity.toml b/proxy/src/main/resources/default-velocity.toml index b8ac82fa5..8c2afe2e2 100644 --- a/proxy/src/main/resources/default-velocity.toml +++ b/proxy/src/main/resources/default-velocity.toml @@ -78,19 +78,19 @@ minigames = "127.0.0.1:30068" # In what order we should try servers when a player logs in or is kicked from a server. try = [ - "lobby" + "lobby" ] [forced-hosts] # Configure your forced hosts here. "lobby.example.com" = [ - "lobby" + "lobby" ] "factions.example.com" = [ - "factions" + "factions" ] "minigames.example.com" = [ - "minigames" + "minigames" ] [advanced] diff --git a/proxy/src/main/resources/log4j2.xml b/proxy/src/main/resources/log4j2.xml index d9f95ce73..b93b9a7a1 100644 --- a/proxy/src/main/resources/log4j2.xml +++ b/proxy/src/main/resources/log4j2.xml @@ -32,7 +32,8 @@ - + diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/BrigadierCommandTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/BrigadierCommandTests.java index 1e6cb706a..1b93ac5e2 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/BrigadierCommandTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/BrigadierCommandTests.java @@ -34,6 +34,9 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; +/** + * Tests for {@link BrigadierCommand}. + */ public class BrigadierCommandTests extends CommandTestSuite { // Execution @@ -43,15 +46,15 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> { - assertEquals(source, context.getSource()); - assertEquals("hello", context.getInput()); - assertEquals(1, context.getNodes().size()); - callCount.incrementAndGet(); - return 1; - }) - .build(); + .literal("hello") + .executes(context -> { + assertEquals(source, context.getSource()); + assertEquals("hello", context.getInput()); + assertEquals(1, context.getNodes().size()); + callCount.incrementAndGet(); + return 1; + }) + .build(); manager.register(new BrigadierCommand(node)); assertHandled("hello"); @@ -63,13 +66,13 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> { - assertEquals("hello", context.getInput()); - callCount.incrementAndGet(); - return 1; - }) - .build(); + .literal("hello") + .executes(context -> { + assertEquals("hello", context.getInput()); + callCount.incrementAndGet(); + return 1; + }) + .build(); manager.register(new BrigadierCommand(node)); assertHandled("Hello"); @@ -81,13 +84,13 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> { - assertEquals("hello", context.getInput()); - callCount.incrementAndGet(); - return 1; - }) - .build(); + .literal("hello") + .executes(context -> { + assertEquals("hello", context.getInput()); + callCount.incrementAndGet(); + return 1; + }) + .build(); manager.register(new BrigadierCommand(node)); assertHandled(" hello"); @@ -100,9 +103,9 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testExecuteAfterUnregisterForwards() { final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> fail()) - .build(); + .literal("hello") + .executes(context -> fail()) + .build(); manager.register(new BrigadierCommand(node)); manager.unregister("hello"); @@ -114,14 +117,14 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> fail()) - .requires(actualSource -> { - assertEquals(source, actualSource); - callCount.incrementAndGet(); - return false; - }) - .build(); + .literal("hello") + .executes(context -> fail()) + .requires(actualSource -> { + assertEquals(source, actualSource); + callCount.incrementAndGet(); + return false; + }) + .build(); manager.register(new BrigadierCommand(node)); assertForwarded("hello"); @@ -133,16 +136,16 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> fail()) - .requiresWithContext((context, reader) -> { - assertEquals(source, context.getSource()); - assertEquals("hello", reader.getRead()); - assertEquals(1, context.getNodes().size()); - callCount.incrementAndGet(); - return false; - }) - .build(); + .literal("hello") + .executes(context -> fail()) + .requiresWithContext((context, reader) -> { + assertEquals(source, context.getSource()); + assertEquals("hello", reader.getRead()); + assertEquals(1, context.getNodes().size()); + callCount.incrementAndGet(); + return false; + }) + .build(); manager.register(new BrigadierCommand(node)); assertForwarded("hello"); @@ -154,18 +157,18 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("buy") - .executes(context -> fail()) - .then(RequiredArgumentBuilder - .argument("quantity", integer()) - .executes(context -> { - assertEquals("buy 12", context.getInput()); - assertEquals(12, getInteger(context, "quantity")); - assertEquals(2, context.getNodes().size()); - callCount.incrementAndGet(); - return 1; - })) - .build(); + .literal("buy") + .executes(context -> fail()) + .then(RequiredArgumentBuilder + .argument("quantity", integer()) + .executes(context -> { + assertEquals("buy 12", context.getInput()); + assertEquals(12, getInteger(context, "quantity")); + assertEquals(2, context.getNodes().size()); + callCount.incrementAndGet(); + return 1; + })) + .build(); manager.register(new BrigadierCommand(node)); assertHandled("buy 12"); @@ -177,16 +180,16 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("hello") + .literal("hello") + .executes(context -> fail()) + .then(LiteralArgumentBuilder + .literal("world") .executes(context -> fail()) - .then(LiteralArgumentBuilder - .literal("world") - .executes(context -> fail()) - .requires(source -> { - callCount.incrementAndGet(); - return false; - })) - .build(); + .requires(source -> { + callCount.incrementAndGet(); + return false; + })) + .build(); manager.register(new BrigadierCommand(node)); assertHandled("hello world"); @@ -197,15 +200,15 @@ public class BrigadierCommandTests extends CommandTestSuite { void testExecuteAsyncCompletesExceptionallyOnCallbackException() { final var expected = new RuntimeException(); final var node = LiteralArgumentBuilder - .literal("hello") - .executes(context -> { - throw expected; - }) - .build(); + .literal("hello") + .executes(context -> { + throw expected; + }) + .build(); manager.register(new BrigadierCommand(node)); final Exception wrapper = assertThrows(CompletionException.class, () -> - manager.executeAsync(source, "hello").join()); + manager.executeAsync(source, "hello").join()); assertSame(expected, wrapper.getCause().getCause()); } @@ -214,16 +217,16 @@ public class BrigadierCommandTests extends CommandTestSuite { void testExecuteAsyncCompletesExceptionallyOnRequirementException() { final var expected = new RuntimeException(); final var node = LiteralArgumentBuilder - .literal("hello") - .requires(source1 -> { - throw expected; - }) - .executes(context -> fail()) // needed for dispatcher to consider the node - .build(); + .literal("hello") + .requires(source1 -> { + throw expected; + }) + .executes(context -> fail()) // needed for dispatcher to consider the node + .build(); manager.register(new BrigadierCommand(node)); final Exception wrapper = assertThrows(CompletionException.class, () -> - manager.executeAsync(source, "hello").join()); + manager.executeAsync(source, "hello").join()); assertSame(expected, wrapper.getCause().getCause()); } @@ -233,8 +236,8 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestAliasAfterUnregister() { final var node = LiteralArgumentBuilder - .literal("hello") - .build(); + .literal("hello") + .build(); manager.register(new BrigadierCommand(node)); manager.unregister("hello"); @@ -244,15 +247,15 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testArgumentSuggestions() { final var node = LiteralArgumentBuilder - .literal("hello") - .then(RequiredArgumentBuilder - .argument("argument", word()) - .suggests((context, builder) -> builder - .suggest("foo") - .suggest("bar") - .suggest("baz") - .buildFuture())) - .build(); + .literal("hello") + .then(RequiredArgumentBuilder + .argument("argument", word()) + .suggests((context, builder) -> builder + .suggest("foo") + .suggest("bar") + .suggest("baz") + .buildFuture())) + .build(); manager.register(new BrigadierCommand(node)); assertSuggestions("hello ", "bar", "baz", "foo"); @@ -266,11 +269,11 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testSuggestsEvenIfImpermissible() { final var node = LiteralArgumentBuilder - .literal("parent") - .then(LiteralArgumentBuilder - .literal("child") - .requiresWithContext((context, reader) -> fail())) - .build(); + .literal("parent") + .then(LiteralArgumentBuilder + .literal("child") + .requiresWithContext((context, reader) -> fail())) + .build(); manager.register(new BrigadierCommand(node)); assertSuggestions("parent ", "child"); @@ -282,19 +285,19 @@ public class BrigadierCommandTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var node = LiteralArgumentBuilder - .literal("parent") - .then(LiteralArgumentBuilder - .literal("child") - .requiresWithContext((context, reader) -> { - // CommandDispatcher#parseNodes checks whether the child node can be added - // to the context object. CommandDispatcher#getCompletionSuggestions then - // considers a suggestion context with "parent" as the parent, and considers - // the suggestions of relevant children, which includes "child". - assertEquals(2, context.getNodes().size()); - callCount.incrementAndGet(); - return false; - })) - .build(); + .literal("parent") + .then(LiteralArgumentBuilder + .literal("child") + .requiresWithContext((context, reader) -> { + // CommandDispatcher#parseNodes checks whether the child node can be added + // to the context object. CommandDispatcher#getCompletionSuggestions then + // considers a suggestion context with "parent" as the parent, and considers + // the suggestions of relevant children, which includes "child". + assertEquals(2, context.getNodes().size()); + callCount.incrementAndGet(); + return false; + })) + .build(); manager.register(new BrigadierCommand(node)); assertSuggestions("parent child"); @@ -304,12 +307,12 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestIfCustomSuggestionProviderFutureCompletesExceptionally() { final var node = LiteralArgumentBuilder - .literal("parent") - .then(RequiredArgumentBuilder - .argument("child", word()) - .suggests((context, builder) -> - CompletableFuture.failedFuture(new RuntimeException()))) - .build(); + .literal("parent") + .then(RequiredArgumentBuilder + .argument("child", word()) + .suggests((context, builder) -> + CompletableFuture.failedFuture(new RuntimeException()))) + .build(); manager.register(new BrigadierCommand(node)); assertSuggestions("parent "); @@ -318,13 +321,13 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestIfCustomSuggestionProviderThrows() { final var node = LiteralArgumentBuilder - .literal("parent") - .then(RequiredArgumentBuilder - .argument("child", word()) - .suggests((context, builder) -> { - throw new RuntimeException(); - })) - .build(); + .literal("parent") + .then(RequiredArgumentBuilder + .argument("child", word()) + .suggests((context, builder) -> { + throw new RuntimeException(); + })) + .build(); manager.register(new BrigadierCommand(node)); assertSuggestions("parent "); @@ -333,17 +336,17 @@ public class BrigadierCommandTests extends CommandTestSuite { @Test void testSuggestCompletesExceptionallyIfRequirementPredicateThrows() { final var node = LiteralArgumentBuilder - .literal("parent") - .requires(source1 -> { - throw new RuntimeException(); - }) - .then(RequiredArgumentBuilder - .argument("child", word()) - .suggests((context, builder) -> fail())) - .build(); + .literal("parent") + .requires(source1 -> { + throw new RuntimeException(); + }) + .then(RequiredArgumentBuilder + .argument("child", word()) + .suggests((context, builder) -> fail())) + .build(); manager.register(new BrigadierCommand(node)); assertThrows(CompletionException.class, () -> - manager.offerSuggestions(source, "parent ").join()); + manager.offerSuggestions(source, "parent ").join()); } } diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/CommandGraphInjectorTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/CommandGraphInjectorTests.java index 3f86b8c4a..4bd8f4d38 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/CommandGraphInjectorTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/CommandGraphInjectorTests.java @@ -36,6 +36,9 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +/** + * Tests for injecting Velocity commnads into a server Brigadier command tree. + */ public class CommandGraphInjectorTests extends CommandTestSuite { private RootCommandNode dest; @@ -86,11 +89,11 @@ public class CommandGraphInjectorTests extends CommandTestSuite { @Test void testInjectsHintsOfInvocableCommand() { final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, (SimpleCommand) invocation -> fail()); manager.getInjector().inject(dest, source); @@ -104,11 +107,11 @@ public class CommandGraphInjectorTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { @@ -130,10 +133,10 @@ public class CommandGraphInjectorTests extends CommandTestSuite { @Test void testInjectsBrigadierCommand() { final LiteralCommandNode node = LiteralArgumentBuilder - .literal("hello") - .then(literal("world")) - .then(argument("count", integer())) - .build(); + .literal("hello") + .then(literal("world")) + .then(argument("count", integer())) + .build(); manager.register(new BrigadierCommand(node)); manager.getInjector().inject(dest, source); @@ -145,20 +148,20 @@ public class CommandGraphInjectorTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var registered = LiteralArgumentBuilder - .literal("greet") - .then(LiteralArgumentBuilder - .literal("somebody") - .requires(source -> { - callCount.incrementAndGet(); - return false; - })) - .build(); + .literal("greet") + .then(LiteralArgumentBuilder + .literal("somebody") + .requires(source -> { + callCount.incrementAndGet(); + return false; + })) + .build(); manager.register(new BrigadierCommand(registered)); manager.getInjector().inject(dest, source); final var expected = LiteralArgumentBuilder - .literal("greet") - .build(); + .literal("greet") + .build(); assertEquals(expected, dest.getChild("greet")); assertEquals(1, callCount.get()); } @@ -166,20 +169,20 @@ public class CommandGraphInjectorTests extends CommandTestSuite { @Test void testInjectPreservesBrigadierCommandAliasRedirect() { final var registered = LiteralArgumentBuilder - .literal("origin") - .redirect(LiteralArgumentBuilder - .literal("target") - .build()) - .build(); + .literal("origin") + .redirect(LiteralArgumentBuilder + .literal("target") + .build()) + .build(); manager.register(new BrigadierCommand(registered)); manager.getInjector().inject(dest, source); final var expected = LiteralArgumentBuilder - .literal("origin") - .redirect(LiteralArgumentBuilder - .literal("target") - .build()) - .build(); + .literal("origin") + .redirect(LiteralArgumentBuilder + .literal("target") + .build()) + .build(); assertEquals(expected, dest.getChild("origin")); } @@ -188,26 +191,26 @@ public class CommandGraphInjectorTests extends CommandTestSuite { final var callCount = new AtomicInteger(); final var registered = LiteralArgumentBuilder - .literal("hello") - .then(LiteralArgumentBuilder - .literal("origin") - .redirect(LiteralArgumentBuilder - .literal("target") - .requires(source -> { - callCount.incrementAndGet(); - return false; - }) - .build() - ) + .literal("hello") + .then(LiteralArgumentBuilder + .literal("origin") + .redirect(LiteralArgumentBuilder + .literal("target") + .requires(source -> { + callCount.incrementAndGet(); + return false; + }) + .build() ) - .build(); + ) + .build(); manager.register(new BrigadierCommand(registered)); manager.getInjector().inject(dest, source); final var expected = LiteralArgumentBuilder - .literal("hello") - .then(literal("origin")) - .build(); + .literal("hello") + .then(literal("origin")) + .build(); assertEquals(expected, dest.getChild("hello")); assertEquals(1, callCount.get()); } @@ -215,15 +218,15 @@ public class CommandGraphInjectorTests extends CommandTestSuite { @Test void testInjectOverridesAliasInDestination() { final var registered = LiteralArgumentBuilder - .literal("foo") - .then(literal("bar")) - .build(); + .literal("foo") + .then(literal("bar")) + .build(); manager.register(new BrigadierCommand(registered)); final var original = LiteralArgumentBuilder - .literal("foo") - .then(literal("baz")) - .build(); + .literal("foo") + .then(literal("baz")) + .build(); dest.addChild(original); manager.getInjector().inject(dest, source); diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/CommandManagerTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/CommandManagerTests.java index 37cccc4f6..89b6f0711 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/CommandManagerTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/CommandManagerTests.java @@ -34,6 +34,9 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; +/** + * Command manager tests. + */ public class CommandManagerTests extends CommandTestSuite { // Registration @@ -51,9 +54,9 @@ public class CommandManagerTests extends CommandTestSuite { @Test void testRegisterWithMetaContainingMultipleAliases() { final var meta = manager.metaBuilder("foo") - .aliases("bar") - .aliases("baz", "qux") - .build(); + .aliases("bar") + .aliases("baz", "qux") + .build(); manager.register(meta, DummyCommand.INSTANCE); assertTrue(manager.hasCommand("foo")); @@ -70,8 +73,8 @@ public class CommandManagerTests extends CommandTestSuite { @Test void testRegisterAliasesAreCaseInsensitive() { final var meta = manager.metaBuilder("Foo") - .aliases("Bar") - .build(); + .aliases("Bar") + .build(); manager.register(meta, DummyCommand.INSTANCE); assertTrue(manager.hasCommand("foo")); @@ -82,8 +85,8 @@ public class CommandManagerTests extends CommandTestSuite { @Test void testRegisterBrigadierCommand() { final var node = LiteralArgumentBuilder - .literal("hello") - .build(); + .literal("hello") + .build(); manager.register(new BrigadierCommand(node)); assertTrue(manager.hasCommand("hello")); @@ -109,9 +112,9 @@ public class CommandManagerTests extends CommandTestSuite { @Test void testAddingExecutableHintToMetaThrows() { final var hintNode = LiteralArgumentBuilder - .literal("hint") - .executes(context -> fail()) - .build(); + .literal("hint") + .executes(context -> fail()) + .build(); assertThrows(IllegalArgumentException.class, () -> { manager.metaBuilder("hello").hint(hintNode); @@ -121,12 +124,12 @@ public class CommandManagerTests extends CommandTestSuite { @Test void testAddingHintWithRedirectToMetaThrows() { final var targetNode = LiteralArgumentBuilder - .literal("target") - .build(); + .literal("target") + .build(); final var hintNode = LiteralArgumentBuilder - .literal("origin") - .redirect(targetNode) - .build(); + .literal("origin") + .redirect(targetNode) + .build(); assertThrows(IllegalArgumentException.class, () -> { manager.metaBuilder("hello").hint(hintNode); @@ -155,8 +158,8 @@ public class CommandManagerTests extends CommandTestSuite { @Test void testUnregisterSecondaryAlias() { final var meta = manager.metaBuilder("foo") - .aliases("bar") - .build(); + .aliases("bar") + .build(); manager.register(meta, DummyCommand.INSTANCE); manager.unregister("bar"); @@ -214,7 +217,8 @@ public class CommandManagerTests extends CommandTestSuite { static final DummyCommand INSTANCE = new DummyCommand(); - private DummyCommand() {} + private DummyCommand() { + } @Override public void execute(final Invocation invocation) { diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/MockCommandSource.java b/proxy/src/test/java/com/velocitypowered/proxy/command/MockCommandSource.java index d3c6c5d1d..0f07ddafe 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/MockCommandSource.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/MockCommandSource.java @@ -20,6 +20,9 @@ package com.velocitypowered.proxy.command; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.permission.Tristate; +/** + * A fake {@link CommandSource}. + */ public class MockCommandSource implements CommandSource { public static final CommandSource INSTANCE = new MockCommandSource(); diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/RawCommandTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/RawCommandTests.java index 1c92c7787..ce617184c 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/RawCommandTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/RawCommandTests.java @@ -34,6 +34,9 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; +/** + * Tests for {@link RawCommand}. + */ public class RawCommandTests extends CommandTestSuite { // Execution @@ -377,7 +380,7 @@ public class RawCommandTests extends CommandTestSuite { }); assertThrows(CompletionException.class, () -> - manager.offerSuggestions(source, "hello ").join()); + manager.offerSuggestions(source, "hello ").join()); } // Hinting @@ -387,11 +390,11 @@ public class RawCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestHintIfImpermissibleAlias() { final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { @@ -410,11 +413,11 @@ public class RawCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestHintIfImpermissibleArguments() { final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { @@ -433,12 +436,12 @@ public class RawCommandTests extends CommandTestSuite { @Test void testSuggestsMergesIgnoringHintsWhoseCustomSuggestionProviderFutureCompletesExceptionally() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException())) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException())) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { @@ -457,14 +460,14 @@ public class RawCommandTests extends CommandTestSuite { @Test void testSuggestsMergesIgnoringHintsWhoseCustomSuggestionProviderThrows() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> { - throw new RuntimeException(); - }) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> { + throw new RuntimeException(); + }) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/SimpleCommandTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/SimpleCommandTests.java index a6471bf45..ee356d58a 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/SimpleCommandTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/SimpleCommandTests.java @@ -35,6 +35,9 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; +/** + * Tests for {@link SimpleCommand}. + */ public class SimpleCommandTests extends CommandTestSuite { // Execution @@ -42,7 +45,7 @@ public class SimpleCommandTests extends CommandTestSuite { @Test void testExecutesAlias() { final var callCount = new AtomicInteger(); - + final var meta = manager.metaBuilder("hello").build(); manager.register(meta, (SimpleCommand) invocation -> { assertEquals(source, invocation.source()); @@ -50,7 +53,7 @@ public class SimpleCommandTests extends CommandTestSuite { assertArrayEquals(new String[0], invocation.arguments()); callCount.incrementAndGet(); }); - + assertHandled("hello"); assertEquals(1, callCount.get()); } @@ -128,7 +131,7 @@ public class SimpleCommandTests extends CommandTestSuite { final var meta = manager.metaBuilder("hello").build(); manager.register(meta, (SimpleCommand) invocation -> { assertEquals("hello", invocation.alias()); - assertArrayEquals(new String[] { "dear", "world" }, invocation.arguments()); + assertArrayEquals(new String[]{"dear", "world"}, invocation.arguments()); callCount.incrementAndGet(); }); @@ -150,7 +153,7 @@ public class SimpleCommandTests extends CommandTestSuite { @Override public boolean hasPermission(final Invocation invocation) { assertEquals("color", invocation.alias()); - assertArrayEquals(new String[] { "red" }, invocation.arguments()); + assertArrayEquals(new String[]{"red"}, invocation.arguments()); callCount.incrementAndGet(); return false; } @@ -254,7 +257,7 @@ public class SimpleCommandTests extends CommandTestSuite { @Override public List suggest(final Invocation invocation) { - assertArrayEquals(new String[] { "12345678" }, invocation.arguments()); + assertArrayEquals(new String[]{"12345678"}, invocation.arguments()); return Collections.singletonList("9"); } }); @@ -305,7 +308,7 @@ public class SimpleCommandTests extends CommandTestSuite { @Override public boolean hasPermission(final Invocation invocation) { assertEquals("foo", invocation.alias()); - assertArrayEquals(new String[] { "bar", "baz", "" }, invocation.arguments()); + assertArrayEquals(new String[]{"bar", "baz", ""}, invocation.arguments()); callCount.incrementAndGet(); return false; } @@ -378,7 +381,7 @@ public class SimpleCommandTests extends CommandTestSuite { }); assertThrows(CompletionException.class, () -> - manager.offerSuggestions(source, "hello ").join()); + manager.offerSuggestions(source, "hello ").join()); } // Hinting @@ -388,11 +391,11 @@ public class SimpleCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestHintIfImpermissibleAlias() { final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new SimpleCommand() { @Override public void execute(final Invocation invocation) { @@ -411,11 +414,11 @@ public class SimpleCommandTests extends CommandTestSuite { @Test void testDoesNotSuggestHintIfImpermissibleArguments() { final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new SimpleCommand() { @Override public void execute(final Invocation invocation) { @@ -434,12 +437,12 @@ public class SimpleCommandTests extends CommandTestSuite { @Test void testSuggestsMergesIgnoringHintsWhoseCustomSuggestionProviderFutureCompletesExceptionally() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException())) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException())) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new SimpleCommand() { @Override public void execute(final Invocation invocation) { @@ -458,14 +461,14 @@ public class SimpleCommandTests extends CommandTestSuite { @Test void testSuggestsMergesIgnoringHintsWhoseCustomSuggestionProviderThrows() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> { - throw new RuntimeException(); - }) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> { + throw new RuntimeException(); + }) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new SimpleCommand() { @Override public void execute(final Invocation invocation) { diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/SuggestionsProviderTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/SuggestionsProviderTests.java index 5e768d4fb..338919d8e 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/SuggestionsProviderTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/SuggestionsProviderTests.java @@ -116,8 +116,8 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testSuggestsAllAliases() { final var meta = manager.metaBuilder("foo") - .aliases("bar", "baz") - .build(); + .aliases("bar", "baz") + .build(); manager.register(meta, NoSuggestionsCommand.INSTANCE); assertSuggestions("", "bar", "baz", "foo"); @@ -126,8 +126,8 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testSuggestsArgumentsViaAlias() { final var meta = manager.metaBuilder("hello") - .aliases("hi") - .build(); + .aliases("hi") + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { @@ -148,11 +148,11 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testSuggestsHintLiteral() { final var hint = LiteralArgumentBuilder - .literal("hint") - .build(); + .literal("hint") + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, NoSuggestionsCommand.INSTANCE); assertSuggestions("hello ", "hint"); @@ -163,16 +163,16 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testSuggestsHintCustomSuggestions() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> builder - .suggest("one") - .suggest("two") - .suggest("three") - .buildFuture()) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> builder + .suggest("one") + .suggest("two") + .suggest("three") + .buildFuture()) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, NoSuggestionsCommand.INSTANCE); assertSuggestions("hello ", "one", "three", "two"); @@ -182,11 +182,11 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testSuggestsMergesArgumentsSuggestionsWithHintSuggestions() { final var hint = LiteralArgumentBuilder - .literal("bar") - .build(); + .literal("bar") + .build(); final var meta = manager.metaBuilder("foo") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, new RawCommand() { @Override public void execute(final Invocation invocation) { @@ -209,13 +209,13 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testSuggestIgnoresHintRequirementPredicateResults() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .requires(source1 -> fail()) - .suggests((context, builder) -> builder.suggest("suggestion").buildFuture()) - .build(); + .argument("hint", word()) + .requires(source1 -> fail()) + .suggests((context, builder) -> builder.suggest("suggestion").buildFuture()) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, NoSuggestionsCommand.INSTANCE); assertSuggestions("hello ", "suggestion"); @@ -242,12 +242,12 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testDoesNotSuggestHintIfHintSuggestionProviderFutureCompletesExceptionally() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException())) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> CompletableFuture.failedFuture(new RuntimeException())) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, NoSuggestionsCommand.INSTANCE); assertSuggestions("hello "); @@ -256,14 +256,14 @@ public class SuggestionsProviderTests extends CommandTestSuite { @Test void testDoesNotSuggestHintIfCustomSuggestionProviderThrows() { final var hint = RequiredArgumentBuilder - .argument("hint", word()) - .suggests((context, builder) -> { - throw new RuntimeException(); - }) - .build(); + .argument("hint", word()) + .suggests((context, builder) -> { + throw new RuntimeException(); + }) + .build(); final var meta = manager.metaBuilder("hello") - .hint(hint) - .build(); + .hint(hint) + .build(); manager.register(meta, NoSuggestionsCommand.INSTANCE); assertSuggestions("hello "); @@ -273,7 +273,8 @@ public class SuggestionsProviderTests extends CommandTestSuite { static final NoSuggestionsCommand INSTANCE = new NoSuggestionsCommand(); - private NoSuggestionsCommand() {} + private NoSuggestionsCommand() { + } @Override public void execute(final Invocation invocation) { diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentTypeTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentTypeTests.java index 80740ac2a..42e56be80 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentTypeTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/StringArrayArgumentTypeTests.java @@ -24,6 +24,9 @@ import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import org.junit.jupiter.api.Test; +/** + * Tests for {@link StringArrayArgumentType}. + */ public class StringArrayArgumentTypeTests { private static final StringArrayArgumentType TYPE = StringArrayArgumentType.INSTANCE; @@ -37,56 +40,56 @@ public class StringArrayArgumentTypeTests { @Test void testParseWord() throws CommandSyntaxException { final StringReader reader = new StringReader("Hello"); - assertArrayEquals(new String[] { "Hello" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"Hello"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testParseString() throws CommandSyntaxException { final StringReader reader = new StringReader("Hello world!"); - assertArrayEquals(new String[] { "Hello", "world!" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"Hello", "world!"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testNoEscaping() throws CommandSyntaxException { final StringReader reader = new StringReader("\"My house\" is blue"); - assertArrayEquals(new String[] { "\"My", "house\"", "is", "blue" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"\"My", "house\"", "is", "blue"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testUnbalancedEscapingIsIgnored() throws CommandSyntaxException { final StringReader reader = new StringReader("This is a \"sentence"); - assertArrayEquals(new String[] { "This", "is", "a", "\"sentence" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"This", "is", "a", "\"sentence"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testLeadingWhitespace() throws CommandSyntaxException { final StringReader reader = new StringReader(" ¡Hola!"); - assertArrayEquals(new String[] { "", "¡Hola!" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"", "¡Hola!"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testMultipleLeadingWhitespace() throws CommandSyntaxException { final StringReader reader = new StringReader(" Anguish Languish"); - assertArrayEquals(new String[] { "", "", "", "Anguish", "Languish" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"", "", "", "Anguish", "Languish"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testTrailingWhitespace() throws CommandSyntaxException { final StringReader reader = new StringReader("This is a test. "); - assertArrayEquals(new String[] { "This", "is", "a", "test.", "" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"This", "is", "a", "test.", ""}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @Test void testMultipleTrailingWhitespace() throws CommandSyntaxException { final StringReader reader = new StringReader("Lorem ipsum "); - assertArrayEquals(new String[] { "Lorem", "ipsum", "", "" }, TYPE.parse(reader)); + assertArrayEquals(new String[]{"Lorem", "ipsum", "", ""}, TYPE.parse(reader)); assertFalse(reader.canRead()); } @@ -94,7 +97,7 @@ public class StringArrayArgumentTypeTests { void testMultipleWhitespaceCharsArePreserved() throws CommandSyntaxException { final StringReader reader = new StringReader( " This is a message that shouldn't be normalized "); - assertArrayEquals(new String[] { + assertArrayEquals(new String[]{ "", "This", "", "is", "a", "", "", "message", "", "that", "shouldn't", "", "", "", "be", "normalized", "", ""}, TYPE.parse(reader)); assertFalse(reader.canRead()); @@ -105,7 +108,7 @@ public class StringArrayArgumentTypeTests { final StringReader reader = new StringReader("Hello beautiful world"); reader.setCursor(6); - assertArrayEquals(new String[] { "beautiful", "world"}, TYPE.parse(reader)); + assertArrayEquals(new String[]{"beautiful", "world"}, TYPE.parse(reader)); assertFalse(reader.canRead()); } } diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java index 1c1d6084b..a3e7f25a9 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java @@ -35,6 +35,9 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +/** + * Tests for {@link VelocityArgumentCommandNode}. + */ @SuppressWarnings("unchecked") public class VelocityArgumentCommandNodeTests { @@ -46,13 +49,13 @@ public class VelocityArgumentCommandNodeTests { void setUp() { final CommandDispatcher dispatcher = new CommandDispatcher<>(); this.contextBuilder = new CommandContextBuilder<>(dispatcher, new Object(), - dispatcher.getRoot(), 0); + dispatcher.getRoot(), 0); } @Test void testParse() throws CommandSyntaxException { final VelocityArgumentCommandNode node = - velocityArgument("foo", STRING_ARRAY).build(); + velocityArgument("foo", STRING_ARRAY).build(); final StringReader reader = new StringReader("hello world"); node.parse(reader, this.contextBuilder); @@ -66,17 +69,17 @@ public class VelocityArgumentCommandNodeTests { assertTrue(this.contextBuilder.getArguments().containsKey("foo")); final ParsedArgument parsed = - (ParsedArgument) this.contextBuilder.getArguments().get("foo"); - assertArrayEquals(new String[] { "hello", "world" }, parsed.getResult()); + (ParsedArgument) this.contextBuilder.getArguments().get("foo"); + assertArrayEquals(new String[]{"hello", "world"}, parsed.getResult()); assertEquals(expectedRange, parsed.getRange()); } @Test void testDefaultSuggestions() throws CommandSyntaxException { final VelocityArgumentCommandNode node = - velocityArgument("foo", STRING_ARRAY).build(); + velocityArgument("foo", STRING_ARRAY).build(); final Suggestions result = node.listSuggestions( - this.contextBuilder.build(""), new SuggestionsBuilder("", 0)).join(); + this.contextBuilder.build(""), new SuggestionsBuilder("", 0)).join(); assertTrue(result.isEmpty()); } @@ -86,15 +89,15 @@ public class VelocityArgumentCommandNodeTests { @Test void testCustomSuggestions() throws CommandSyntaxException { final VelocityArgumentCommandNode node = - velocityArgument("foo", STRING_ARRAY) - .suggests((context, builder) -> { - builder.suggest("bar"); - builder.suggest("baz"); - return builder.buildFuture(); - }) + velocityArgument("foo", STRING_ARRAY) + .suggests((context, builder) -> { + builder.suggest("bar"); + builder.suggest("baz"); + return builder.buildFuture(); + }) .build(); final Suggestions result = node.listSuggestions( - this.contextBuilder.build(""), new SuggestionsBuilder("", 0)).join(); + this.contextBuilder.build(""), new SuggestionsBuilder("", 0)).join(); assertEquals("bar", result.getList().get(0).getText()); assertEquals("baz", result.getList().get(1).getText()); diff --git a/proxy/src/test/java/com/velocitypowered/proxy/event/EventTaskTest.java b/proxy/src/test/java/com/velocitypowered/proxy/event/EventTaskTest.java index 1f1414f7f..a6f28badf 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/event/EventTaskTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/event/EventTaskTest.java @@ -27,6 +27,9 @@ import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.function.Consumer; import org.junit.jupiter.api.Test; +/** + * Tests {@link EventTask}. + */ public class EventTaskTest { @Test @@ -79,10 +82,10 @@ public class EventTaskTest { CountDownLatch latch = new CountDownLatch(1); continuation.onComplete = (ignored) -> latch.countDown(); CompletableFuture async = CompletableFuture.supplyAsync(() -> null) - .thenAccept((v) -> { - throw new RuntimeException(); - }) - .thenCompose((v) -> CompletableFuture.completedFuture(null)); + .thenAccept((v) -> { + throw new RuntimeException(); + }) + .thenCompose((v) -> CompletableFuture.completedFuture(null)); EventTask.resumeWhenComplete(async).execute(continuation); latch.await(); @@ -90,8 +93,8 @@ public class EventTaskTest { } /** - * An extremely simplified implementation of {@link Continuation} for verifying the completion - * of an operation. + * An extremely simplified implementation of {@link Continuation} for verifying the completion of + * an operation. */ private static class WitnessContinuation implements Continuation { diff --git a/proxy/src/test/java/com/velocitypowered/proxy/event/EventTest.java b/proxy/src/test/java/com/velocitypowered/proxy/event/EventTest.java index 4a066ef68..9f3ed8cf9 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/event/EventTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/event/EventTest.java @@ -34,6 +34,9 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +/** + * Event firing tests. + */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EventTest { @@ -47,6 +50,7 @@ public class EventTest { } static final class TestEvent { + } static void assertAsyncThread(final Thread thread) { @@ -68,18 +72,18 @@ public class EventTest { @Test void listenerOrderPreserved() throws Exception { - final AtomicLong listenerAInvoked = new AtomicLong(); - final AtomicLong listenerBInvoked = new AtomicLong(); - final AtomicLong listenerCInvoked = new AtomicLong(); + final AtomicLong listener1Invoked = new AtomicLong(); + final AtomicLong listener2Invoked = new AtomicLong(); + final AtomicLong listener3Invoked = new AtomicLong(); eventManager.register(FakePluginManager.PLUGIN_A, TestEvent.class, event -> { - listenerAInvoked.set(System.nanoTime()); + listener1Invoked.set(System.nanoTime()); }); eventManager.register(FakePluginManager.PLUGIN_B, TestEvent.class, event -> { - listenerBInvoked.set(System.nanoTime()); + listener2Invoked.set(System.nanoTime()); }); eventManager.register(FakePluginManager.PLUGIN_A, TestEvent.class, event -> { - listenerCInvoked.set(System.nanoTime()); + listener3Invoked.set(System.nanoTime()); }); try { @@ -88,30 +92,28 @@ public class EventTest { eventManager.unregisterListeners(FakePluginManager.PLUGIN_A); } - // Check that the order is A < B < C. Check only that A < B and B < C as B < C and A < B => A < C. - assertTrue(listenerAInvoked.get() < listenerBInvoked.get(), "Listener B invoked before A!"); - assertTrue(listenerBInvoked.get() < listenerCInvoked.get(), "Listener C invoked before B!"); + // Check that the order is A < B < C. + assertTrue(listener1Invoked.get() < listener2Invoked.get(), "Listener B invoked before A!"); + assertTrue(listener2Invoked.get() < listener3Invoked.get(), "Listener C invoked before B!"); } @Test void listenerOrderPreservedWithContinuation() throws Exception { - final AtomicLong listenerAInvoked = new AtomicLong(); - final AtomicLong listenerBInvoked = new AtomicLong(); - final AtomicLong listenerCInvoked = new AtomicLong(); + final AtomicLong listener1Invoked = new AtomicLong(); + final AtomicLong listener2Invoked = new AtomicLong(); + final AtomicLong listener3Invoked = new AtomicLong(); - eventManager.register(FakePluginManager.PLUGIN_A, TestEvent.class, event -> { - listenerAInvoked.set(System.nanoTime()); - }); + eventManager.register(FakePluginManager.PLUGIN_A, TestEvent.class, event -> + listener1Invoked.set(System.nanoTime())); eventManager.register(FakePluginManager.PLUGIN_B, TestEvent.class, (AwaitingEventExecutor) event -> EventTask.withContinuation(continuation -> { new Thread(() -> { - listenerBInvoked.set(System.nanoTime()); + listener2Invoked.set(System.nanoTime()); continuation.resume(); }).start(); })); - eventManager.register(FakePluginManager.PLUGIN_A, TestEvent.class, event -> { - listenerCInvoked.set(System.nanoTime()); - }); + eventManager.register(FakePluginManager.PLUGIN_A, TestEvent.class, event -> + listener3Invoked.set(System.nanoTime())); try { eventManager.fire(new TestEvent()).get(); @@ -119,9 +121,9 @@ public class EventTest { eventManager.unregisterListeners(FakePluginManager.PLUGIN_A); } - // Check that the order is A < B < C. Check only that A < B and B < C as B < C and A < B => A < C. - assertTrue(listenerAInvoked.get() < listenerBInvoked.get(), "Listener B invoked before A!"); - assertTrue(listenerBInvoked.get() < listenerCInvoked.get(), "Listener C invoked before B!"); + // Check that the order is A < B < C. + assertTrue(listener1Invoked.get() < listener2Invoked.get(), "Listener B invoked before A!"); + assertTrue(listener2Invoked.get() < listener3Invoked.get(), "Listener C invoked before B!"); } @Test @@ -164,30 +166,30 @@ public class EventTest { void testContinuation() throws Exception { final ContinuationListener listener = new ContinuationListener(); handleMethodListener(listener); - assertAsyncThread(listener.threadA); - assertAsyncThread(listener.threadB); - assertContinuationThread(listener.threadBCustom); - assertAsyncThread(listener.threadC); + assertAsyncThread(listener.thread1); + assertAsyncThread(listener.thread2); + assertContinuationThread(listener.thread2Custom); + assertAsyncThread(listener.thread3); assertEquals(2, listener.value.get()); } static final class ContinuationListener { - @MonotonicNonNull Thread threadA; - @MonotonicNonNull Thread threadB; - @MonotonicNonNull Thread threadBCustom; - @MonotonicNonNull Thread threadC; + @MonotonicNonNull Thread thread1; + @MonotonicNonNull Thread thread2; + @MonotonicNonNull Thread thread2Custom; + @MonotonicNonNull Thread thread3; final AtomicInteger value = new AtomicInteger(); @Subscribe(order = PostOrder.EARLY) EventTask continuation(TestEvent event) { - threadA = Thread.currentThread(); + thread1 = Thread.currentThread(); return EventTask.withContinuation(continuation -> { value.incrementAndGet(); - threadB = Thread.currentThread(); + thread2 = Thread.currentThread(); new Thread(() -> { - threadBCustom = Thread.currentThread(); + thread2Custom = Thread.currentThread(); value.incrementAndGet(); continuation.resume(); }, CONTINUATION_TEST_THREAD_NAME).start(); @@ -196,7 +198,7 @@ public class EventTest { @Subscribe(order = PostOrder.LATE) void afterContinuation(TestEvent event) { - threadC = Thread.currentThread(); + thread3 = Thread.currentThread(); } } @@ -239,34 +241,34 @@ public class EventTest { void testContinuationParameter() throws Exception { final ContinuationParameterListener listener = new ContinuationParameterListener(); handleMethodListener(listener); - assertAsyncThread(listener.threadA); - assertAsyncThread(listener.threadB); - assertContinuationThread(listener.threadBCustom); - assertAsyncThread(listener.threadC); + assertAsyncThread(listener.thread1); + assertAsyncThread(listener.thread2); + assertContinuationThread(listener.thread2Custom); + assertAsyncThread(listener.thread3); assertEquals(3, listener.result.get()); } static final class ContinuationParameterListener { - @MonotonicNonNull Thread threadA; - @MonotonicNonNull Thread threadB; - @MonotonicNonNull Thread threadBCustom; - @MonotonicNonNull Thread threadC; + @MonotonicNonNull Thread thread1; + @MonotonicNonNull Thread thread2; + @MonotonicNonNull Thread thread2Custom; + @MonotonicNonNull Thread thread3; final AtomicInteger result = new AtomicInteger(); @Subscribe void resume(TestEvent event, Continuation continuation) { - threadA = Thread.currentThread(); + thread1 = Thread.currentThread(); result.incrementAndGet(); continuation.resume(); } @Subscribe(order = PostOrder.LATE) void resumeFromCustomThread(TestEvent event, Continuation continuation) { - threadB = Thread.currentThread(); + thread2 = Thread.currentThread(); new Thread(() -> { - threadBCustom = Thread.currentThread(); + thread2Custom = Thread.currentThread(); result.incrementAndGet(); continuation.resume(); }, CONTINUATION_TEST_THREAD_NAME).start(); @@ -274,7 +276,7 @@ public class EventTest { @Subscribe(order = PostOrder.LAST) void afterCustomThread(TestEvent event, Continuation continuation) { - threadC = Thread.currentThread(); + thread3 = Thread.currentThread(); result.incrementAndGet(); continuation.resume(); } @@ -326,7 +328,8 @@ public class EventTest { + "the second is the fancy continuation"); } }, - new TypeToken>() {}, + new TypeToken>() { + }, invokeFunction -> (instance, event) -> EventTask.withContinuation(continuation -> invokeFunction.accept(instance, event, new FancyContinuationImpl(continuation)) diff --git a/proxy/src/test/java/com/velocitypowered/proxy/event/RegistrationTest.java b/proxy/src/test/java/com/velocitypowered/proxy/event/RegistrationTest.java index ad9e1de33..828e429ef 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/event/RegistrationTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/event/RegistrationTest.java @@ -36,6 +36,9 @@ import org.junit.jupiter.api.DynamicNode; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; +/** + * Tests event listener registration. + */ public class RegistrationTest { private EventManager eventManager; @@ -54,13 +57,16 @@ public class RegistrationTest { } // Must be public in order to generate a method calling it - public static class SimpleEvent { + private static class SimpleEvent { + int value; } - public static class SimpleSubclassedEvent extends SimpleEvent { } + private static class SimpleSubclassedEvent extends SimpleEvent { - public static class HandlerListener implements EventHandler { + } + + private static class HandlerListener implements EventHandler { @Override public void execute(SimpleEvent event) { @@ -68,7 +74,7 @@ public class RegistrationTest { } } - public static class AnnotatedListener { + private static class AnnotatedListener { @Subscribe public void increment(SimpleEvent event) { @@ -88,7 +94,7 @@ public class RegistrationTest { private Stream composeTests(String name, TestFunction testFunction) { Set tests = new HashSet<>(); - boolean[] trueAndFalse = new boolean[] {true, false}; + boolean[] trueAndFalse = new boolean[]{true, false}; for (boolean annotated : trueAndFalse) { for (boolean subclassed : trueAndFalse) { @@ -98,13 +104,14 @@ public class RegistrationTest { assertSame(simpleEvent, shouldBeSameEvent); assertEquals(value, simpleEvent.value); }; - tests.add(DynamicTest.dynamicTest(name + ". Annotated : " + annotated + ", Subclassed: " + subclassed, () -> { - try { - testFunction.runTest(annotated, generator); - } finally { - resetEventManager(); - } - })); + tests.add(DynamicTest.dynamicTest( + name + ". Annotated : " + annotated + ", Subclassed: " + subclassed, () -> { + try { + testFunction.runTest(annotated, generator); + } finally { + resetEventManager(); + } + })); } } return tests.stream(); @@ -121,7 +128,8 @@ public class RegistrationTest { generator.assertFiredEventValue(1); eventManager.unregisterListeners(PLUGIN_A); generator.assertFiredEventValue(0); - assertDoesNotThrow(() -> eventManager.unregisterListeners(PLUGIN_A), "Extra unregister is a no-op"); + assertDoesNotThrow(() -> eventManager.unregisterListeners(PLUGIN_A), + "Extra unregister is a no-op"); }); } diff --git a/proxy/src/test/java/com/velocitypowered/proxy/plugin/MockPluginManager.java b/proxy/src/test/java/com/velocitypowered/proxy/plugin/MockPluginManager.java index 33864a168..515fdd5e2 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/plugin/MockPluginManager.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/plugin/MockPluginManager.java @@ -24,6 +24,9 @@ import java.nio.file.Path; import java.util.Collection; import java.util.Optional; +/** + * Mock of {@link PluginManager}. + */ public class MockPluginManager implements PluginManager { public static final PluginManager INSTANCE = new MockPluginManager(); diff --git a/proxy/src/test/java/com/velocitypowered/proxy/protocol/PacketRegistryTest.java b/proxy/src/test/java/com/velocitypowered/proxy/protocol/PacketRegistryTest.java index 88679261f..5c23ddb0c 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/protocol/PacketRegistryTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/protocol/PacketRegistryTest.java @@ -78,7 +78,7 @@ class PacketRegistryTest { assertNull(registry.getProtocolRegistry(MINECRAFT_1_14_2).createPacket(0x01), "Registry should return a null"); assertNull(registry.getProtocolRegistry(MINECRAFT_1_16_2).createPacket(0), - "Registry should return null"); + "Registry should return null"); } @Test diff --git a/proxy/src/test/java/com/velocitypowered/proxy/protocol/ProtocolUtilsTest.java b/proxy/src/test/java/com/velocitypowered/proxy/protocol/ProtocolUtilsTest.java index 04b2f3193..16018c5e7 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/protocol/ProtocolUtilsTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/protocol/ProtocolUtilsTest.java @@ -26,6 +26,9 @@ import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import org.junit.jupiter.api.Test; +/** + * Protocol utils test. + */ public class ProtocolUtilsTest { @Test diff --git a/proxy/src/test/java/com/velocitypowered/proxy/scheduler/VelocitySchedulerTest.java b/proxy/src/test/java/com/velocitypowered/proxy/scheduler/VelocitySchedulerTest.java index 400b71cd6..45229d6dc 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/scheduler/VelocitySchedulerTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/scheduler/VelocitySchedulerTest.java @@ -79,8 +79,8 @@ class VelocitySchedulerTest { latch.countDown(); } }).delay(50, TimeUnit.MILLISECONDS) - .repeat(Duration.ofMillis(5)) - .schedule(); + .repeat(Duration.ofMillis(5)) + .schedule(); assertEquals(scheduler.tasksByPlugin(FakePluginManager.PLUGIN_A).size(), 1); @@ -94,10 +94,11 @@ class VelocitySchedulerTest { VelocityScheduler scheduler = new VelocityScheduler(new FakePluginManager()); CountDownLatch latch = new CountDownLatch(1); - ScheduledTask task = scheduler.buildTask(FakePluginManager.PLUGIN_B, actualTask -> { - actualTask.cancel(); - latch.countDown(); - }) + ScheduledTask task = scheduler.buildTask( + FakePluginManager.PLUGIN_B, actualTask -> { + actualTask.cancel(); + latch.countDown(); + }) .repeat(5, TimeUnit.MILLISECONDS) .schedule(); diff --git a/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java b/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java index 64a64f4c4..f5694393d 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java @@ -26,6 +26,9 @@ import java.util.Collection; import java.util.Optional; import org.checkerframework.checker.nullness.qual.NonNull; +/** + * A fake plugin manager. + */ public class FakePluginManager implements PluginManager { public static final Object PLUGIN_A = new Object(); diff --git a/proxy/src/test/java/com/velocitypowered/proxy/util/concurrent/OnceTest.java b/proxy/src/test/java/com/velocitypowered/proxy/util/concurrent/OnceTest.java index aeb7ffb50..795f34f8c 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/util/concurrent/OnceTest.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/util/concurrent/OnceTest.java @@ -27,7 +27,11 @@ import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; +/** + * Tests the proper functionality of {@code Once}. + */ public class OnceTest { + @Test void uncontendedOnce() { AtomicInteger i = new AtomicInteger(); diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index d0f3098b4..000000000 --- a/settings.gradle +++ /dev/null @@ -1,9 +0,0 @@ -rootProject.name = 'velocity' -include( - 'api', - 'proxy', - 'native' -) -findProject(':api')?.name = 'velocity-api' -findProject(':proxy')?.name = 'velocity-proxy' -findProject(':native')?.name = 'velocity-native' \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 000000000..fe0599639 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,9 @@ +rootProject.name = "velocity" +include( + "api", + "proxy", + "native" +) +findProject(":api")?.name = "velocity-api" +findProject(":proxy")?.name = "velocity-proxy" +findProject(":native")?.name = "velocity-native" \ No newline at end of file