Update gradle to 8.14.2, add auto-formatting

This commit is contained in:
NotAlexNoyle committed 2025-06-18 19:57:54 -04:00
1 parent d7d9d6008f
commit e6be6980c4
13 files changed
+3033 -2934

No files matched your search

+23 -21
View File
@@ -1,8 +1,9 @@
plugins {
id("java") // Tell gradle this is a java project.
id("java-library") // Import helper for source-based libraries.
id("com.diffplug.spotless") version "7.0.4" // Import auto-formatter.
id("com.gradleup.shadow") version "8.3.6" // Import shadow API.
java // Tell gradle this is a java project.
eclipse // Import eclipse plugin for IDE integration.
kotlin("jvm") version "2.1.21" // Import kotlin jvm plugin for kotlin/java integration.
}
java {
@@ -11,20 +12,17 @@ java {
}
group = "com.hm.mcshared" // Declare bundle identifier.
version = "1.1.8" // Declare plugin version (will be in .jar).
val apiVersion = "1.19" // Declare minecraft server target version.
tasks.named<ProcessResources>("processResources") {
val props = mapOf(
"version" to version,
"apiVersion" to apiVersion
)
val props = mapOf("version" to version, "apiVersion" to apiVersion)
inputs.properties(props) // Indicates to rerun if version changes.
filesMatching("plugin.yml") {
expand(props)
}
filesMatching("plugin.yml") { expand(props) }
from("LICENSE") { // Bundle license into .jars.
into("/")
}
@@ -33,15 +31,13 @@ tasks.named<ProcessResources>("processResources") {
repositories {
mavenCentral()
gradlePluginPortal()
maven {
url = uri("https://repo.purpurmc.org/snapshots")
}
maven { url = uri("https://repo.purpurmc.org/snapshots") }
}
dependencies {
compileOnly("org.purpurmc.purpur:purpur-api:1.19.4-R0.1-SNAPSHOT") // Declare purpur API version to be packaged.
compileOnly("io.github.miniplaceholders:miniplaceholders-api:2.2.3") // Import MiniPlaceholders API.
compileOnly(project(":libs:Utilities-OG")) // Import TrueOG Network Utilities-OG API.
compileOnlyApi(project(":libs:Utilities-OG")) // Import TrueOG Network Utilities-OG API.
}
tasks.withType<AbstractArchiveTask>().configureEach { // Ensure reproducible .jars
@@ -50,18 +46,17 @@ tasks.withType<AbstractArchiveTask>().configureEach { // Ensure reproducible .ja
}
tasks.shadowJar {
archiveClassifier.set("") // Use empty string instead of null.
exclude("io.github.miniplaceholders.*") // Exclude the MiniPlaceholders package from being shadowed.
archiveClassifier.set("") // Use empty string instead of null.
minimize()
}
tasks.build {
dependsOn(tasks.spotlessApply)
dependsOn(tasks.shadowJar)
}
tasks.jar {
archiveClassifier.set("part")
}
tasks.jar { archiveClassifier.set("part") }
tasks.withType<JavaCompile>().configureEach {
options.compilerArgs.add("-parameters")
@@ -70,13 +65,20 @@ tasks.withType<JavaCompile>().configureEach {
options.isFork = true
}
kotlin {
jvmToolchain(17)
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
vendor = JvmVendorSpec.GRAAL_VM
}
}
spotless {
java {
removeUnusedImports()
palantirJavaFormat()
}
kotlinGradle {
ktfmt().kotlinlangStyle().configure { it.setMaxWidth(120) }
target("build.gradle.kts", "settings.gradle.kts")
}
}
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+6 -4
View File
@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@@ -84,7 +86,7 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -112,7 +114,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
@@ -203,7 +205,7 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
@@ -211,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+4 -2
View File
@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@@ -68,11 +70,11 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
+2 -3
View File
@@ -1,11 +1,10 @@
rootProject.name = "MCShared-OG"
// Run the bootstrap at configuration time.
val process = ProcessBuilder("sh", "bootstrap.sh")
.directory(rootDir)
.start()
val process = ProcessBuilder("sh", "bootstrap.sh").directory(rootDir).start()
val exitValue = process.waitFor()
if (exitValue != 0) {
throw GradleException("bootstrap.sh failed with exit code $exitValue")
}
@@ -9,78 +9,78 @@ import org.bukkit.event.HandlerList;
/**
* Class representing an event fired when a player changes the ownership of one of his pets. The event is fired by the
* PetMaster plugin, and this class can be used by any plugin that needs to listen to this event.
*
*
* @author Pyves
*
*/
public class PlayerChangeAnimalOwnershipEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private static final HandlerList handlers = new HandlerList();
private final AnimalTamer oldOwner;
private final AnimalTamer newOwner;
private final Tameable ownedAnimal;
private final AnimalTamer oldOwner;
private final AnimalTamer newOwner;
private final Tameable ownedAnimal;
private boolean cancelled;
private boolean cancelled;
/**
* Creates a new PlayerChangeAnimalOwnershipEvent with information about old and new owners as well as the animal
* involved in the transaction.
*
* @param oldOwner Old owner of the tameable animal.
* @param newOwner New owner of the tameable animal.
* @param ownedAnimal Tameable animal whose ownership was changed.
*/
public PlayerChangeAnimalOwnershipEvent(AnimalTamer oldOwner, AnimalTamer newOwner, Tameable ownedAnimal) {
this.oldOwner = oldOwner;
this.newOwner = newOwner;
this.ownedAnimal = ownedAnimal;
this.cancelled = false;
}
/**
* Creates a new PlayerChangeAnimalOwnershipEvent with information about old and new owners as well as the animal
* involved in the transaction.
*
* @param oldOwner Old owner of the tameable animal.
* @param newOwner New owner of the tameable animal.
* @param ownedAnimal Tameable animal whose ownership was changed.
*/
public PlayerChangeAnimalOwnershipEvent(AnimalTamer oldOwner, AnimalTamer newOwner, Tameable ownedAnimal) {
this.oldOwner = oldOwner;
this.newOwner = newOwner;
this.ownedAnimal = ownedAnimal;
this.cancelled = false;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
@Override
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
/**
* Returns the previous owner of the tameable animal.
*
* @return Old owner of the tameable animal.
*/
public AnimalTamer getOldOwner() {
return oldOwner;
}
/**
* Returns the previous owner of the tameable animal.
*
* @return Old owner of the tameable animal.
*/
public AnimalTamer getOldOwner() {
return oldOwner;
}
/**
* Returns the new owner of the tameable animal.
*
* @return New owner of the tameable animal.
*/
public AnimalTamer getNewOwner() {
return newOwner;
}
/**
* Returns the new owner of the tameable animal.
*
* @return New owner of the tameable animal.
*/
public AnimalTamer getNewOwner() {
return newOwner;
}
/**
* Returns the tameable animal whose ownership was changed.
*
* @return Tameable animal whose ownership was changed.
*/
public Tameable getOwnedAnimal() {
return ownedAnimal;
}
/**
* Returns the tameable animal whose ownership was changed.
*
* @return Tameable animal whose ownership was changed.
*/
public Tameable getOwnedAnimal() {
return ownedAnimal;
}
}
@@ -5,7 +5,6 @@ import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
@@ -15,148 +14,156 @@ import org.bukkit.plugin.java.JavaPlugin;
* Class to take care of Yaml configuration files by providing some additional methods to the standard Bukkit
* YamlConfiguration class. This class enables more modularity, and contains methods to set new configuration parameters
* with comments as well as various other convenience methods.
*
*
* @author Pyves
*
*/
public class CommentedYamlConfiguration extends YamlConfiguration {
private final FileManager manager;
private final JavaPlugin plugin;
private final FileManager manager;
private final JavaPlugin plugin;
private int numOfComments;
private int numOfComments;
/**
* Creates a new CommentedYamlConfiguration object representing one of the plugin's configuration files.
*
* @param fileName Name of the configuration file situated in the resource folder of the plugin.
* @param plugin The plugin making use of the configuration file.
*/
public CommentedYamlConfiguration(String fileName, JavaPlugin plugin) {
this(fileName, fileName, plugin);
}
/**
* Creates a new CommentedYamlConfiguration object representing one of the plugin's configuration files.
*
* @param fileName Name of the configuration file situated in the resource folder of the plugin.
* @param plugin The plugin making use of the configuration file.
*/
public CommentedYamlConfiguration(String fileName, JavaPlugin plugin) {
this(fileName, fileName, plugin);
}
/**
* Creates a new CommentedYamlConfiguration object representing one of the plugin's configuration files. This
* constructor takes a plugin resource name that may be different for the file name used on the server.
*
* @param fileName Name of the configuration file situated in the resource folder of the plugin.
* @param pluginResourceName The name of the plugin resource.
* @param plugin The plugin making use of the configuration file.
*/
public CommentedYamlConfiguration(String fileName, String pluginResourceName, JavaPlugin plugin) {
super();
if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("Invalid file name.");
}
this.plugin = plugin;
manager = new FileManager(fileName, pluginResourceName, plugin);
}
/**
* Creates a new CommentedYamlConfiguration object representing one of the plugin's configuration files. This
* constructor takes a plugin resource name that may be different for the file name used on the server.
*
* @param fileName Name of the configuration file situated in the resource folder of the plugin.
* @param pluginResourceName The name of the plugin resource.
* @param plugin The plugin making use of the configuration file.
*/
public CommentedYamlConfiguration(String fileName, String pluginResourceName, JavaPlugin plugin) {
super();
if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("Invalid file name.");
}
this.plugin = plugin;
manager = new FileManager(fileName, pluginResourceName, plugin);
}
/**
* Gets a set containing all keys in this section, with only the keys of any direct children, and not their own
* children. Helper method.
*
* @param path
* @return Set containing the shallow configuration keys for the given path.
*/
public Set<String> getShallowKeys(String path) {
return getConfigurationSection(path).getKeys(false);
}
/**
* Gets a set containing all keys in this section, with only the keys of any direct children, and not their own
* children. Helper method.
*
* @param path
* @return Set containing the shallow configuration keys for the given path.
*/
public Set<String> getShallowKeys(String path) {
return getConfigurationSection(path).getKeys(false);
}
/**
* Gets the requested ConfigurationSection by path. Returns an empty ConfigurationSection if it does not exist.
*
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection or empty one.
*/
@Override
public ConfigurationSection getConfigurationSection(String path) {
ConfigurationSection configurationSection = super.getConfigurationSection(path);
return configurationSection == null ? createSection(path) : configurationSection;
}
/**
* Gets the requested ConfigurationSection by path. Returns an empty ConfigurationSection if it does not exist.
*
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection or empty one.
*/
@Override
public ConfigurationSection getConfigurationSection(String path) {
ConfigurationSection configurationSection = super.getConfigurationSection(path);
return configurationSection == null ? createSection(path) : configurationSection;
}
/**
* Gets the requested List by path. Returns a List of type String.
*
* @param path Path of the List to get.
* @return Requested List of Strings.
*/
@SuppressWarnings("unchecked")
@Override
public List<String> getList(String path) {
List<String> list = (List<String>) super.getList(path);
if (list != null) {
return list;
}
return new ArrayList<>();
}
/**
* Gets the requested List by path. Returns a List of type String.
*
* @param path Path of the List to get.
* @return Requested List of Strings.
*/
@SuppressWarnings("unchecked")
@Override
public List<String> getList(String path) {
List<String> list = (List<String>) super.getList(path);
if (list != null) {
return list;
}
return new ArrayList<>();
}
/**
* Sets the specified path to the given value with the given comment.
*
* @param path Path of the object to set.
* @param value New value to set the path to.
* @param comment New comment to set the path to. Ignored if null.
*/
public void set(String path, Object value, String comment) {
if (comment != null) {
// Insert comment as new value in the file; will be converted back to a comment when saved by the
// FileManager.
this.set(plugin.getPluginMeta().getName() + "_COMMENT_" + numOfComments, comment.replace(":", "_COLON_")
.replace("|", "_VERT_").replace("-", "_HYPHEN_").replace(" ", "_SPACE_"));
numOfComments++;
}
this.set(path, value);
}
/**
* Sets the specified path to the given value with the given comment.
*
* @param path Path of the object to set.
* @param value New value to set the path to.
* @param comment New comment to set the path to. Ignored if null.
*/
public void set(String path, Object value, String comment) {
if (comment != null) {
// Insert comment as new value in the file; will be converted back to a comment when saved by the
// FileManager.
this.set(
plugin.getPluginMeta().getName() + "_COMMENT_" + numOfComments,
comment.replace(":", "_COLON_")
.replace("|", "_VERT_")
.replace("-", "_HYPHEN_")
.replace(" ", "_SPACE_"));
numOfComments++;
}
this.set(path, value);
}
/**
* Sets the specified path to the given value with the given comments (one comment per line).
*
* @param path Path of the object to set.
* @param value New value to set the path to.
* @param comments New comments to set the path to. Ignored if empty.
*/
public void set(String path, Object value, String... comments) {
for (String comment : comments) {
// Insert comment as new value in the file; will be converted back to a comment when saved.
this.set(plugin.getPluginMeta().getName() + "_COMMENT_" + numOfComments, comment.replace(":", "_COLON_")
.replace("|", "_VERT_").replace("-", "_HYPHEN_").replace(" ", "_SPACE_"));
numOfComments++;
}
this.set(path, value);
}
/**
* Sets the specified path to the given value with the given comments (one comment per line).
*
* @param path Path of the object to set.
* @param value New value to set the path to.
* @param comments New comments to set the path to. Ignored if empty.
*/
public void set(String path, Object value, String... comments) {
for (String comment : comments) {
// Insert comment as new value in the file; will be converted back to a comment when saved.
this.set(
plugin.getPluginMeta().getName() + "_COMMENT_" + numOfComments,
comment.replace(":", "_COLON_")
.replace("|", "_VERT_")
.replace("-", "_HYPHEN_")
.replace(" ", "_SPACE_"));
numOfComments++;
}
this.set(path, value);
}
/**
* Loads or reloads the configuration file from disk.
*
* @throws IOException
* @throws InvalidConfigurationException
*/
public void loadConfiguration() throws IOException, InvalidConfigurationException {
manager.createConfigurationFileIfNotExists();
map.clear();
load(new StringReader(manager.getConfigurationWithReworkedComments()));
numOfComments = manager.getNumberOfComments();
}
/**
* Loads or reloads the configuration file from disk.
*
* @throws IOException
* @throws InvalidConfigurationException
*/
public void loadConfiguration() throws IOException, InvalidConfigurationException {
manager.createConfigurationFileIfNotExists();
map.clear();
load(new StringReader(manager.getConfigurationWithReworkedComments()));
numOfComments = manager.getNumberOfComments();
}
/**
* Saves the configuration file and any modifications that were performed.
*
* @throws IOException
*/
public void saveConfiguration() throws IOException {
String configString = this.saveToString();
manager.saveConfiguration(configString);
}
/**
* Saves the configuration file and any modifications that were performed.
*
* @throws IOException
*/
public void saveConfiguration() throws IOException {
String configString = this.saveToString();
manager.saveConfiguration(configString);
}
/**
* Performs a backup of the configuration; the backup simply makes a copy of the file and adds a .bak extension to
* it.
*
* @throws IOException
*/
public void backupConfiguration() throws IOException {
manager.backupFile();
}
/**
* Performs a backup of the configuration; the backup simply makes a copy of the file and adds a .bak extension to
* it.
*
* @throws IOException
*/
public void backupConfiguration() throws IOException {
manager.backupFile();
}
}
@@ -10,7 +10,6 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.bukkit.plugin.java.JavaPlugin;
/**
@@ -20,173 +19,179 @@ import org.bukkit.plugin.java.JavaPlugin;
* YamlConfiguration class (otherwise comments are deleted when the file is modified and saved programatically).
* <p>
* Other convenience methods such as doing backups are also provided and can be used for other file types.
*
*
* @author Pyves
*
*/
public class FileManager {
private final JavaPlugin plugin;
private final String pluginResourceName;
private final JavaPlugin plugin;
private final String pluginResourceName;
private File file;
private int numOfComments;
private File file;
private int numOfComments;
/**
* Constructs an instance of the manager.
*
* @param fileName Name of the file situated in the resource folder of the plugin.
* @param plugin The plugin making use of the file.
*/
public FileManager(String fileName, JavaPlugin plugin) {
this(fileName, fileName, plugin);
}
/**
* Constructs an instance of the manager.
*
* @param fileName Name of the file situated in the resource folder of the plugin.
* @param plugin The plugin making use of the file.
*/
public FileManager(String fileName, JavaPlugin plugin) {
this(fileName, fileName, plugin);
}
/**
* Constructs an instance of the manager. This constructor takes a plugin resource name that may be different for
* the file name used on the server.
*
* @param fileName Name of the file situated in the resource folder of the plugin.
* @param pluginResourceName The name of the plugin resource.
* @param plugin The plugin making use of the file.
*/
public FileManager(String fileName, String pluginResourceName, JavaPlugin plugin) {
this.plugin = plugin;
this.pluginResourceName = pluginResourceName;
if (fileName.startsWith("/")) {
file = new File(plugin.getDataFolder() + fileName.replace("/", File.separator));
} else {
file = new File(plugin.getDataFolder() + File.separator + fileName.replace("/", File.separator));
}
}
/**
* Constructs an instance of the manager. This constructor takes a plugin resource name that may be different for
* the file name used on the server.
*
* @param fileName Name of the file situated in the resource folder of the plugin.
* @param pluginResourceName The name of the plugin resource.
* @param plugin The plugin making use of the file.
*/
public FileManager(String fileName, String pluginResourceName, JavaPlugin plugin) {
this.plugin = plugin;
this.pluginResourceName = pluginResourceName;
if (fileName.startsWith("/")) {
file = new File(plugin.getDataFolder() + fileName.replace("/", File.separator));
} else {
file = new File(plugin.getDataFolder() + File.separator + fileName.replace("/", File.separator));
}
}
/**
* Performs a backup of the file contained in the plugin's data folder; the backup simply makes a copy of the file
* and adds a .bak extension to it.
*
* @throws IOException
*/
public void backupFile() throws IOException {
File backupFile = new File(plugin.getDataFolder(), file.getName() + ".bak");
// Overwrite previous backup only if a newer version of the file exists.
if (file.lastModified() > backupFile.lastModified() && file.exists()) {
try (FileInputStream inStream = new FileInputStream(file);
FileOutputStream outStream = new FileOutputStream(backupFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
}
}
}
/**
* Performs a backup of the file contained in the plugin's data folder; the backup simply makes a copy of the file
* and adds a .bak extension to it.
*
* @throws IOException
*/
public void backupFile() throws IOException {
File backupFile = new File(plugin.getDataFolder(), file.getName() + ".bak");
// Overwrite previous backup only if a newer version of the file exists.
if (file.lastModified() > backupFile.lastModified() && file.exists()) {
try (FileInputStream inStream = new FileInputStream(file);
FileOutputStream outStream = new FileOutputStream(backupFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
}
}
}
/**
* Returns a configuration string with comments reworked as key-value pairs to allow them to be saved when using
* Bukkit's YamlConfiguration class.
*
* @return String with reworked comments.
* @throws IOException
*/
protected String getConfigurationWithReworkedComments() throws IOException {
StringBuilder reworkedConfiguration = new StringBuilder();
try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"))) {
numOfComments = 0;
String currentLine;
while ((currentLine = bufferedReader.readLine()) != null) {
if (currentLine.startsWith("#")) {
// Rework comment line so it becomes a standard key-value pair in the configuration file.
// This workaround allows the comment to be saved when using Bukkit's YamlConfiguration class.
reworkedConfiguration.append(currentLine.replace(":", "_COLON_").replace("|", "_VERT_")
.replace("-", "_HYPHEN_").replace(" ", "_SPACE_")
.replaceFirst("#", plugin.getPluginMeta().getName() + "_COMMENT_" + numOfComments + ": "));
numOfComments++;
} else {
reworkedConfiguration.append(currentLine);
}
reworkedConfiguration.append("\n");
}
return reworkedConfiguration.toString();
}
}
/**
* Returns a configuration string with comments reworked as key-value pairs to allow them to be saved when using
* Bukkit's YamlConfiguration class.
*
* @return String with reworked comments.
* @throws IOException
*/
protected String getConfigurationWithReworkedComments() throws IOException {
StringBuilder reworkedConfiguration = new StringBuilder();
try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"))) {
numOfComments = 0;
String currentLine;
while ((currentLine = bufferedReader.readLine()) != null) {
if (currentLine.startsWith("#")) {
// Rework comment line so it becomes a standard key-value pair in the configuration file.
// This workaround allows the comment to be saved when using Bukkit's YamlConfiguration class.
reworkedConfiguration.append(currentLine
.replace(":", "_COLON_")
.replace("|", "_VERT_")
.replace("-", "_HYPHEN_")
.replace(" ", "_SPACE_")
.replaceFirst("#", plugin.getPluginMeta().getName() + "_COMMENT_" + numOfComments + ": "));
numOfComments++;
} else {
reworkedConfiguration.append(currentLine);
}
reworkedConfiguration.append("\n");
}
return reworkedConfiguration.toString();
}
}
/**
* Returns the total number of comments in the file. Should be called after the configuration has been parsed by
* {@link #getConfigurationWithReworkedComments()}.
*
* @return Total number of comments in the file.
*/
protected int getNumberOfComments() {
return numOfComments;
}
/**
* Returns the total number of comments in the file. Should be called after the configuration has been parsed by
* {@link #getConfigurationWithReworkedComments()}.
*
* @return Total number of comments in the file.
*/
protected int getNumberOfComments() {
return numOfComments;
}
/**
* Saves a configuration string into a file.
*
* @param configString The configuration string to save.
* @throws IOException
*/
protected void saveConfiguration(String configString) throws IOException {
String configuration = getConfigurationWithRegeneratedComments(configString);
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
bufferedWriter.write(configuration);
bufferedWriter.flush();
}
}
/**
* Saves a configuration string into a file.
*
* @param configString The configuration string to save.
* @throws IOException
*/
protected void saveConfiguration(String configString) throws IOException {
String configuration = getConfigurationWithRegeneratedComments(configString);
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
bufferedWriter.write(configuration);
bufferedWriter.flush();
}
}
/**
* Writes the configuration file to disk if it does not exist by copying it from the plugin's resources.
*
* @throws IOException
*/
protected void createConfigurationFileIfNotExists() throws IOException {
file.getParentFile().mkdirs();
if (file.createNewFile()) {
try (OutputStream outputStream = new FileOutputStream(file)) {
InputStream resource = plugin.getResource(pluginResourceName);
if (resource != null) {
int length;
byte[] buf = new byte[1024];
while ((length = resource.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
}
}
plugin.getLogger().info("Successfully created " + file.getName() + " file.");
}
}
/**
* Writes the configuration file to disk if it does not exist by copying it from the plugin's resources.
*
* @throws IOException
*/
protected void createConfigurationFileIfNotExists() throws IOException {
file.getParentFile().mkdirs();
if (file.createNewFile()) {
try (OutputStream outputStream = new FileOutputStream(file)) {
InputStream resource = plugin.getResource(pluginResourceName);
if (resource != null) {
int length;
byte[] buf = new byte[1024];
while ((length = resource.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
}
}
plugin.getLogger().info("Successfully created " + file.getName() + " file.");
}
}
/**
* Reworks the configuration string in order to regenerate comments.
*
* @param configString The configuration string with reworked comments.
* @return String representing original config file.
*/
private String getConfigurationWithRegeneratedComments(String configString) {
boolean previousLineComment = false;
String[] lines = configString.split("\n");
StringBuilder config = new StringBuilder();
for (String line : lines) {
if (line.startsWith(plugin.getPluginMeta().getName() + "_COMMENT")) {
// Rework comment line so it is converted back to a normal comment.
String comment = ("#" + line.substring(line.indexOf(": ") + 2)).replace("_COLON_", ":")
.replace("_HYPHEN_", "-").replace("_VERT_", "|").replace("_SPACE_", " ");
// No empty line between consecutive comment lines or between a comment and its corresponding
// parameters; empty line between parameter and new comment.
if (previousLineComment) {
config.append(comment + "\n");
} else {
config.append("\n" + comment + "\n");
}
previousLineComment = true;
} else {
config.append(line + "\n");
previousLineComment = false;
}
}
return config.toString();
}
/**
* Reworks the configuration string in order to regenerate comments.
*
* @param configString The configuration string with reworked comments.
* @return String representing original config file.
*/
private String getConfigurationWithRegeneratedComments(String configString) {
boolean previousLineComment = false;
String[] lines = configString.split("\n");
StringBuilder config = new StringBuilder();
for (String line : lines) {
if (line.startsWith(plugin.getPluginMeta().getName() + "_COMMENT")) {
// Rework comment line so it is converted back to a normal comment.
String comment = ("#" + line.substring(line.indexOf(": ") + 2))
.replace("_COLON_", ":")
.replace("_HYPHEN_", "-")
.replace("_VERT_", "|")
.replace("_SPACE_", " ");
// No empty line between consecutive comment lines or between a comment and its corresponding
// parameters; empty line between parameter and new comment.
if (previousLineComment) {
config.append(comment + "\n");
} else {
config.append("\n" + comment + "\n");
}
previousLineComment = true;
} else {
config.append(line + "\n");
previousLineComment = false;
}
}
return config.toString();
}
}
@@ -1,261 +1,287 @@
package com.hm.mcshared.particle;
import java.util.UUID;
import org.bukkit.entity.Player;
import com.hm.mcshared.particle.ReflectionUtils.PackageType;
import java.util.UUID;
import net.kyori.adventure.text.TextComponent;
import net.trueog.utilitiesog.UtilitiesOG;
import org.bukkit.entity.Player;
/**
* Class used to send fancy messages to the player; can be titles, hoverable chat messages or action bar messages. All
* methods are static and this class cannot be instanciated.
*
*
* @author Pyves
*
*/
public final class FancyMessageSender {
private static final byte CHAT_MESSAGE_BYTE = 1;
private static final byte ACTION_BAR_BYTE = 2;
private static final int MINOR_VERSION_NUMBER = Integer.parseInt(PackageType.getServerVersion().split("_")[1]);
private static final String CLASS_CHAT_BASE_COMPONENT = "IChatBaseComponent";
private static final String CLASS_CRAFT_PLAYER = "CraftPlayer";
private static final String CLASS_ENTITY_PLAYER = "EntityPlayer";
private static final String CLASS_PACKET = "Packet";
private static final String CLASS_PACKET_PLAY_OUT_CHAT = "PacketPlayOutChat";
private static final String CLASS_PACKET_PLAY_OUT_TITLE = "PacketPlayOutTitle";
private static final String CLASS_PLAYER_CONNECTION = "PlayerConnection";
private static final String ENUM_TITLE_ACTION = "EnumTitleAction";
private static final String ENUM_CHAT_MESSAGE_TYPE = "ChatMessageType";
private static final String FIELD_PLAYER_CONNECTION = "playerConnection";
private static final String METHOD_GET_HANDLE = "getHandle";
private static final String METHOD_SEND_PACKET = "sendPacket";
private static final String NESTED_CHAT_SERIALIZER = "ChatSerializer";
private static final String PACKAGE_ENTITY = "entity";
private static final byte CHAT_MESSAGE_BYTE = 1;
private static final byte ACTION_BAR_BYTE = 2;
private static final int MINOR_VERSION_NUMBER =
Integer.parseInt(PackageType.getServerVersion().split("_")[1]);
private static final String CLASS_CHAT_BASE_COMPONENT = "IChatBaseComponent";
private static final String CLASS_CRAFT_PLAYER = "CraftPlayer";
private static final String CLASS_ENTITY_PLAYER = "EntityPlayer";
private static final String CLASS_PACKET = "Packet";
private static final String CLASS_PACKET_PLAY_OUT_CHAT = "PacketPlayOutChat";
private static final String CLASS_PACKET_PLAY_OUT_TITLE = "PacketPlayOutTitle";
private static final String CLASS_PLAYER_CONNECTION = "PlayerConnection";
private static final String ENUM_TITLE_ACTION = "EnumTitleAction";
private static final String ENUM_CHAT_MESSAGE_TYPE = "ChatMessageType";
private static final String FIELD_PLAYER_CONNECTION = "playerConnection";
private static final String METHOD_GET_HANDLE = "getHandle";
private static final String METHOD_SEND_PACKET = "sendPacket";
private static final String NESTED_CHAT_SERIALIZER = "ChatSerializer";
private static final String PACKAGE_ENTITY = "entity";
private FancyMessageSender() {
// Not called.
}
private FancyMessageSender() {
// Not called.
}
/**
* Sends a hoverable message to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the message to.
* @param message The text to display in the chat.
* @param hover The text to display in the hover.
* @param color The color of the hover text.
* @throws Exception
*/
public static void sendHoverableMessage(Player player, String message, String hover, String color) throws Exception {
sendChatPacket(player, constructHoverableMessageJson(message, hover, color), CHAT_MESSAGE_BYTE);
}
/**
* Sends a hoverable message to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the message to.
* @param message The text to display in the chat.
* @param hover The text to display in the hover.
* @param color The color of the hover text.
* @throws Exception
*/
public static void sendHoverableMessage(Player player, String message, String hover, String color)
throws Exception {
sendChatPacket(player, constructHoverableMessageJson(message, hover, color), CHAT_MESSAGE_BYTE);
}
/**
* Sends a clickable and hoverable message to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the message to.
* @param message The text to display in the chat.
* @param command The command that is entered when clicking on the message.
* @param hover The text to display in the hover.
* @param color The color of the hover text.
* @throws Exception
*/
public static void sendHoverableCommandMessage(Player player, String message, String command, String hover, String color)
throws Exception {
sendChatPacket(player, constructHoverableCommandMessageJson(message, command, hover, color), CHAT_MESSAGE_BYTE);
}
/**
* Sends a clickable and hoverable message to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the message to.
* @param message The text to display in the chat.
* @param command The command that is entered when clicking on the message.
* @param hover The text to display in the hover.
* @param color The color of the hover text.
* @throws Exception
*/
public static void sendHoverableCommandMessage(
Player player, String message, String command, String hover, String color) throws Exception {
sendChatPacket(player, constructHoverableCommandMessageJson(message, command, hover, color), CHAT_MESSAGE_BYTE);
}
/**
* Sends an action bar chat message to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the message to.
* @param message The text to display in the action bar.
* @throws Exception
*/
public static void sendActionBarMessage(Player player, String message) throws Exception {
sendChatPacket(player, constructTextJson(message), ACTION_BAR_BYTE);
}
/**
* Sends an action bar chat message to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the message to.
* @param message The text to display in the action bar.
* @throws Exception
*/
public static void sendActionBarMessage(Player player, String message) throws Exception {
sendChatPacket(player, constructTextJson(message), ACTION_BAR_BYTE);
}
/**
* Sends a title and subtitle to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the title and subtitle to.
* @param title The main text that will appear on the player's screen.
* @param subtitle The secondary text that will appear on the player's screen.
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static void sendTitle(Player player, String title, String subtitle) throws Exception {
if (MINOR_VERSION_NUMBER >= 11) {
player.sendTitle(title, subtitle, 10, 70, 20);
} else if (MINOR_VERSION_NUMBER >= 9) {
player.sendTitle(title, subtitle);
} else {
sendTitlePacket(player, constructTextJson(title), constructTextJson(subtitle));
}
}
/**
* Sends a title and subtitle to the player. Only supported in Minecraft 1.8+.
*
* @param player Online player to send the title and subtitle to.
* @param title The main text that will appear on the player's screen.
* @param subtitle The secondary text that will appear on the player's screen.
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static void sendTitle(Player player, String title, String subtitle) throws Exception {
if (MINOR_VERSION_NUMBER >= 11) {
player.sendTitle(title, subtitle, 10, 70, 20);
} else if (MINOR_VERSION_NUMBER >= 9) {
player.sendTitle(title, subtitle);
} else {
sendTitlePacket(player, constructTextJson(title), constructTextJson(subtitle));
}
}
/**
* Sends a title and subtitle packet to the player.
*
* @param player Online player to send the title and subtitle to.
* @param titleJson The title JSON format message to send to the player. See
* http://minecraft.gamepedia.com/Commands#Raw_JSON_text for more information.
* @param subtitleJson The subtitle title JSON format message to send to the player. See
* http://minecraft.gamepedia.com/Commands#Raw_JSON_text for more information.
* @throws ReflectiveOperationException
*/
private static void sendTitlePacket(Player player, String titleJson, String subtitleJson)
throws ReflectiveOperationException {
// Retrieve a CraftPlayer instance and its PlayerConnection instance.
Object craftPlayer = PackageType.CRAFTBUKKIT.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER).cast(player);
Object craftHandle = PackageType.CRAFTBUKKIT.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER)
.getMethod(METHOD_GET_HANDLE).invoke(craftPlayer);
Object playerConnection = PackageType.MINECRAFT_SERVER.getClass(CLASS_ENTITY_PLAYER)
.getField(FIELD_PLAYER_CONNECTION).get(craftHandle);
/**
* Sends a title and subtitle packet to the player.
*
* @param player Online player to send the title and subtitle to.
* @param titleJson The title JSON format message to send to the player. See
* http://minecraft.gamepedia.com/Commands#Raw_JSON_text for more information.
* @param subtitleJson The subtitle title JSON format message to send to the player. See
* http://minecraft.gamepedia.com/Commands#Raw_JSON_text for more information.
* @throws ReflectiveOperationException
*/
private static void sendTitlePacket(Player player, String titleJson, String subtitleJson)
throws ReflectiveOperationException {
// Retrieve a CraftPlayer instance and its PlayerConnection instance.
Object craftPlayer = PackageType.CRAFTBUKKIT
.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER)
.cast(player);
Object craftHandle = PackageType.CRAFTBUKKIT
.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER)
.getMethod(METHOD_GET_HANDLE)
.invoke(craftPlayer);
Object playerConnection = PackageType.MINECRAFT_SERVER
.getClass(CLASS_ENTITY_PLAYER)
.getField(FIELD_PLAYER_CONNECTION)
.get(craftHandle);
Object parsedMainMessage;
Object parsedSubMessage;
Class<?> titleClass;
if (PackageType.getServerVersion().startsWith("1_8_R1")) {
// Prior to version 1.8.3.
parsedMainMessage = PackageType.MINECRAFT_SERVER.getClass(NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(titleJson, player));
parsedSubMessage = PackageType.MINECRAFT_SERVER.getClass(NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(subtitleJson, player));
titleClass = PackageType.MINECRAFT_SERVER.getClass(ENUM_TITLE_ACTION);
} else {
parsedMainMessage = PackageType.MINECRAFT_SERVER
.getClass(CLASS_CHAT_BASE_COMPONENT + "$" + NESTED_CHAT_SERIALIZER).getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(titleJson, player));
parsedSubMessage = PackageType.MINECRAFT_SERVER
.getClass(CLASS_CHAT_BASE_COMPONENT + "$" + NESTED_CHAT_SERIALIZER).getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(subtitleJson, player));
titleClass = PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE + "$" + ENUM_TITLE_ACTION);
}
Object parsedMainMessage;
Object parsedSubMessage;
Class<?> titleClass;
if (PackageType.getServerVersion().startsWith("1_8_R1")) {
// Prior to version 1.8.3.
parsedMainMessage = PackageType.MINECRAFT_SERVER
.getClass(NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(titleJson, player));
parsedSubMessage = PackageType.MINECRAFT_SERVER
.getClass(NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(subtitleJson, player));
titleClass = PackageType.MINECRAFT_SERVER.getClass(ENUM_TITLE_ACTION);
} else {
parsedMainMessage = PackageType.MINECRAFT_SERVER
.getClass(CLASS_CHAT_BASE_COMPONENT + "$" + NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(titleJson, player));
parsedSubMessage = PackageType.MINECRAFT_SERVER
.getClass(CLASS_CHAT_BASE_COMPONENT + "$" + NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(subtitleJson, player));
titleClass = PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE + "$" + ENUM_TITLE_ACTION);
}
// Retrieve parameters for titles and subtitles.
Enum<?> mainTitleEnumValue = null;
Enum<?> subTitleEnumValue = null;
for (Object o : titleClass.getEnumConstants()) {
Enum<?> e = (Enum<?>) o;
if ("TITLE".equalsIgnoreCase(e.name())) {
mainTitleEnumValue = e;
} else if ("SUBTITLE".equalsIgnoreCase(e.name())) {
subTitleEnumValue = e;
}
}
// Retrieve parameters for titles and subtitles.
Enum<?> mainTitleEnumValue = null;
Enum<?> subTitleEnumValue = null;
for (Object o : titleClass.getEnumConstants()) {
Enum<?> e = (Enum<?>) o;
if ("TITLE".equalsIgnoreCase(e.name())) {
mainTitleEnumValue = e;
} else if ("SUBTITLE".equalsIgnoreCase(e.name())) {
subTitleEnumValue = e;
}
}
Object packetPlayOutChatMainTitle = ReflectionUtils
.getConstructor(PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE),
PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE + "$" + ENUM_TITLE_ACTION),
PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT))
.newInstance(mainTitleEnumValue, parsedMainMessage);
Object packetPlayOutChatMainTitle = ReflectionUtils.getConstructor(
PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE),
PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE + "$" + ENUM_TITLE_ACTION),
PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT))
.newInstance(mainTitleEnumValue, parsedMainMessage);
// Send the message packet through the PlayerConnection (title).
PackageType.MINECRAFT_SERVER.getClass(CLASS_PLAYER_CONNECTION)
.getMethod(METHOD_SEND_PACKET, PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET))
.invoke(playerConnection, packetPlayOutChatMainTitle);
// Send the message packet through the PlayerConnection (title).
PackageType.MINECRAFT_SERVER
.getClass(CLASS_PLAYER_CONNECTION)
.getMethod(METHOD_SEND_PACKET, PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET))
.invoke(playerConnection, packetPlayOutChatMainTitle);
Object packetPlayOutChatSubTitle = ReflectionUtils
.getConstructor(PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE),
PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE + "$" + ENUM_TITLE_ACTION),
PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT))
.newInstance(subTitleEnumValue, parsedSubMessage);
Object packetPlayOutChatSubTitle = ReflectionUtils.getConstructor(
PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE),
PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_TITLE + "$" + ENUM_TITLE_ACTION),
PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT))
.newInstance(subTitleEnumValue, parsedSubMessage);
// Send the message packet through the PlayerConnection (subtitle).
PackageType.MINECRAFT_SERVER.getClass(CLASS_PLAYER_CONNECTION)
.getMethod(METHOD_SEND_PACKET, PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET))
.invoke(playerConnection, packetPlayOutChatSubTitle);
}
// Send the message packet through the PlayerConnection (subtitle).
PackageType.MINECRAFT_SERVER
.getClass(CLASS_PLAYER_CONNECTION)
.getMethod(METHOD_SEND_PACKET, PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET))
.invoke(playerConnection, packetPlayOutChatSubTitle);
}
/**
* Sends a chat packet.
*
* @param player Online player to send the title and subtitle to.
* @param json The message JSON format message to send to the player. See
* http://minecraft.gamepedia.com/Commands#Raw_JSON_text for more information.
* @param type Either 1 (chat mesage) or 2 (action bar message).
* @throws ReflectiveOperationException
*/
private static void sendChatPacket(Player player, String json, byte type) throws ReflectiveOperationException {
// Retrieve a CraftPlayer instance and its PlayerConnection instance.
Object craftPlayer = PackageType.CRAFTBUKKIT.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER).cast(player);
Object craftHandle = PackageType.CRAFTBUKKIT.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER)
.getMethod(METHOD_GET_HANDLE).invoke(craftPlayer);
Object playerConnection = PackageType.MINECRAFT_SERVER.getClass(CLASS_ENTITY_PLAYER)
.getField(FIELD_PLAYER_CONNECTION).get(craftHandle);
/**
* Sends a chat packet.
*
* @param player Online player to send the title and subtitle to.
* @param json The message JSON format message to send to the player. See
* http://minecraft.gamepedia.com/Commands#Raw_JSON_text for more information.
* @param type Either 1 (chat mesage) or 2 (action bar message).
* @throws ReflectiveOperationException
*/
private static void sendChatPacket(Player player, String json, byte type) throws ReflectiveOperationException {
// Retrieve a CraftPlayer instance and its PlayerConnection instance.
Object craftPlayer = PackageType.CRAFTBUKKIT
.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER)
.cast(player);
Object craftHandle = PackageType.CRAFTBUKKIT
.getClass(PACKAGE_ENTITY + "." + CLASS_CRAFT_PLAYER)
.getMethod(METHOD_GET_HANDLE)
.invoke(craftPlayer);
Object playerConnection = PackageType.MINECRAFT_SERVER
.getClass(CLASS_ENTITY_PLAYER)
.getField(FIELD_PLAYER_CONNECTION)
.get(craftHandle);
Object parsedMessage;
if (PackageType.getServerVersion().startsWith("1_8_R1")) {
// Prior to version 1.8.3.
parsedMessage = PackageType.MINECRAFT_SERVER.getClass(NESTED_CHAT_SERIALIZER).getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(json, player));
} else {
TextComponent textComponent = UtilitiesOG.trueogExpand(json, player);
parsedMessage = textComponent;
}
Object parsedMessage;
if (PackageType.getServerVersion().startsWith("1_8_R1")) {
// Prior to version 1.8.3.
parsedMessage = PackageType.MINECRAFT_SERVER
.getClass(NESTED_CHAT_SERIALIZER)
.getMethod("a", String.class)
.invoke(null, UtilitiesOG.trueogExpand(json, player));
} else {
TextComponent textComponent = UtilitiesOG.trueogExpand(json, player);
parsedMessage = textComponent;
}
Object packetPlayOutChat;
if (MINOR_VERSION_NUMBER < 12) {
packetPlayOutChat = PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_CHAT)
.getConstructor(PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT), byte.class)
.newInstance(parsedMessage, type);
} else {
// New method uses the ChatMessageType enum rather than a byte.
Class<?> chatMessageTypeClass = PackageType.MINECRAFT_SERVER.getClass(ENUM_CHAT_MESSAGE_TYPE);
Enum<?> chatType = null;
for (Object chatMessageType : chatMessageTypeClass.getEnumConstants()) {
Enum<?> e = (Enum<?>) chatMessageType;
if ("SYSTEM".equalsIgnoreCase(e.name()) && type == CHAT_MESSAGE_BYTE
|| "GAME_INFO".equalsIgnoreCase(e.name()) && type == ACTION_BAR_BYTE) {
chatType = e;
break;
}
}
// Constructor signature Minecraft 1.7 - 1.15:
// public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype)
// Constructor signature Minecraft 1.16+:
// public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype, UUID uuid)
if (MINOR_VERSION_NUMBER < 16) {
packetPlayOutChat = PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_CHAT)
.getConstructor(PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT),
chatMessageTypeClass)
.newInstance(parsedMessage, chatType);
} else {
packetPlayOutChat = PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET_PLAY_OUT_CHAT)
.getConstructor(PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT),
chatMessageTypeClass, UUID.class)
.newInstance(parsedMessage, chatType, player.getUniqueId());
}
}
Object packetPlayOutChat;
if (MINOR_VERSION_NUMBER < 12) {
packetPlayOutChat = PackageType.MINECRAFT_SERVER
.getClass(CLASS_PACKET_PLAY_OUT_CHAT)
.getConstructor(PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT), byte.class)
.newInstance(parsedMessage, type);
} else {
// New method uses the ChatMessageType enum rather than a byte.
Class<?> chatMessageTypeClass = PackageType.MINECRAFT_SERVER.getClass(ENUM_CHAT_MESSAGE_TYPE);
Enum<?> chatType = null;
for (Object chatMessageType : chatMessageTypeClass.getEnumConstants()) {
Enum<?> e = (Enum<?>) chatMessageType;
if ("SYSTEM".equalsIgnoreCase(e.name()) && type == CHAT_MESSAGE_BYTE
|| "GAME_INFO".equalsIgnoreCase(e.name()) && type == ACTION_BAR_BYTE) {
chatType = e;
break;
}
}
// Constructor signature Minecraft 1.7 - 1.15:
// public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype)
// Constructor signature Minecraft 1.16+:
// public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype, UUID
// uuid)
if (MINOR_VERSION_NUMBER < 16) {
packetPlayOutChat = PackageType.MINECRAFT_SERVER
.getClass(CLASS_PACKET_PLAY_OUT_CHAT)
.getConstructor(
PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT), chatMessageTypeClass)
.newInstance(parsedMessage, chatType);
} else {
packetPlayOutChat = PackageType.MINECRAFT_SERVER
.getClass(CLASS_PACKET_PLAY_OUT_CHAT)
.getConstructor(
PackageType.MINECRAFT_SERVER.getClass(CLASS_CHAT_BASE_COMPONENT),
chatMessageTypeClass,
UUID.class)
.newInstance(parsedMessage, chatType, player.getUniqueId());
}
}
// Send the message packet through the PlayerConnection.
PackageType.MINECRAFT_SERVER.getClass(CLASS_PLAYER_CONNECTION)
.getMethod(METHOD_SEND_PACKET, PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET))
.invoke(playerConnection, packetPlayOutChat);
}
// Send the message packet through the PlayerConnection.
PackageType.MINECRAFT_SERVER
.getClass(CLASS_PLAYER_CONNECTION)
.getMethod(METHOD_SEND_PACKET, PackageType.MINECRAFT_SERVER.getClass(CLASS_PACKET))
.invoke(playerConnection, packetPlayOutChat);
}
private static String constructTextJson(String text) {
return "{\"text\":\"" + text.replace("\"", "\\\"") + "\"}";
}
private static String constructTextJson(String text) {
return "{\"text\":\"" + text.replace("\"", "\\\"") + "\"}";
}
private static String constructHoverableMessageJson(String message, String hover, String color) {
return "{\"text\":\"" + message.replace("\"", "\\\"") + "\","
+ "\"hoverEvent\":{\"action\":\"show_text\",\"value\":[{\"text\":\""
+ hover.replace("\"", "\\\"") + "\",\"color\":\"" + color + "\"}]}}";
}
private static String constructHoverableMessageJson(String message, String hover, String color) {
return "{\"text\":\"" + message.replace("\"", "\\\"") + "\","
+ "\"hoverEvent\":{\"action\":\"show_text\",\"value\":[{\"text\":\""
+ hover.replace("\"", "\\\"") + "\",\"color\":\"" + color + "\"}]}}";
}
private static String constructHoverableCommandMessageJson(String message, String command, String hover, String color) {
return "{\"text\":\"" + message.replace("\"", "\\\"") + "\","
+ "\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"" + command + "\"},"
+ "\"hoverEvent\":{\"action\":\"show_text\",\"value\":[{\"text\":\""
+ hover.replace("\"", "\\\"") + "\",\"color\":\"" + color + "\"}]}}";
}
}
private static String constructHoverableCommandMessageJson(
String message, String command, String hover, String color) {
return "{\"text\":\"" + message.replace("\"", "\\\"") + "\","
+ "\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"" + command + "\"},"
+ "\"hoverEvent\":{\"action\":\"show_text\",\"value\":[{\"text\":\""
+ hover.replace("\"", "\\\"") + "\",\"color\":\"" + color + "\"}]}}";
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff