Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] 16606ec351
deps: bump com.google.guava:guava from 33.2.1-jre to 33.3.0-jre
Bumps [com.google.guava:guava](https://github.com/google/guava) from 33.2.1-jre to 33.3.0-jre.
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

---
updated-dependencies:
- dependency-name: com.google.guava:guava
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
3 months ago

@ -9,7 +9,7 @@ plugins {
id 'java' id 'java'
} }
group 'org.inksnow.husk' group 'net.william278'
version "$ext.plugin_version${versionMetadata()}" version "$ext.plugin_version${versionMetadata()}"
description "$ext.plugin_description" description "$ext.plugin_description"
defaultTasks 'licenseFormat', 'build' defaultTasks 'licenseFormat', 'build'
@ -28,12 +28,30 @@ ext {
publishing { publishing {
repositories { repositories {
maven { if (System.getenv("RELEASES_MAVEN_USERNAME") != null) {
name = 'husk-release' maven {
url = findProperty("repository.huskrelease.url") name = "william278-releases"
credentials { url = "https://repo.william278.net/releases"
username = findProperty("repository.huskrelease.username") credentials {
password = findProperty("repository.huskrelease.password") username = System.getenv("RELEASES_MAVEN_USERNAME")
password = System.getenv("RELEASES_MAVEN_PASSWORD")
}
authentication {
basic(BasicAuthentication)
}
}
}
if (System.getenv("SNAPSHOTS_MAVEN_USERNAME") != null) {
maven {
name = "william278-snapshots"
url = "https://repo.william278.net/snapshots"
credentials {
username = System.getenv("SNAPSHOTS_MAVEN_USERNAME")
password = System.getenv("SNAPSHOTS_MAVEN_PASSWORD")
}
authentication {
basic(BasicAuthentication)
}
} }
} }
} }
@ -45,26 +63,23 @@ allprojects {
apply plugin: 'java' apply plugin: 'java'
compileJava.options.encoding = 'UTF-8' compileJava.options.encoding = 'UTF-8'
compileJava.options.release.set 8 compileJava.options.release.set 17
javadoc.options.encoding = 'UTF-8' javadoc.options.encoding = 'UTF-8'
javadoc.options.addStringOption('Xdoclint:none', '-quiet') javadoc.options.addStringOption('Xdoclint:none', '-quiet')
repositories { repositories {
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
maven { maven { url 'https://repo.william278.net/releases/' }
url findProperty('repository.huskpublic.url')
credentials {
username = findProperty('repository.huskpublic.username')
password = findProperty('repository.huskpublic.password')
}
}
maven { url 'https://r.irepo.space/maven/' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' }
maven { url "https://repo.dmulloy2.net/repository/public/" } maven { url "https://repo.dmulloy2.net/repository/public/" }
maven { url 'https://repo.codemc.io/repository/maven-public/' } maven { url 'https://repo.codemc.io/repository/maven-public/' }
maven { url 'https://repo.minebench.de/' }
maven { url 'https://repo.alessiodp.com/releases/' }
maven { url 'https://jitpack.io' }
maven { url 'https://mvn-repo.arim.space/lesser-gpl3/' }
maven { url 'https://libraries.minecraft.net/' }
} }
dependencies { dependencies {
@ -133,7 +148,7 @@ subprojects {
if (['common'].contains(project.name)) { if (['common'].contains(project.name)) {
publications { publications {
mavenJavaCommon(MavenPublication) { mavenJavaCommon(MavenPublication) {
groupId = 'org.inksnow.husk.husksync' groupId = 'net.william278.husksync'
artifactId = 'husksync-common' artifactId = 'husksync-common'
version = "$rootProject.version" version = "$rootProject.version"
artifact shadowJar artifact shadowJar
@ -146,7 +161,7 @@ subprojects {
if (['bukkit'].contains(project.name)) { if (['bukkit'].contains(project.name)) {
publications { publications {
mavenJavaBukkit(MavenPublication) { mavenJavaBukkit(MavenPublication) {
groupId = 'org.inksnow.husk.husksync' groupId = 'net.william278.husksync'
artifactId = 'husksync-bukkit' artifactId = 'husksync-bukkit'
version = "$rootProject.version" version = "$rootProject.version"
artifact shadowJar artifact shadowJar
@ -159,7 +174,7 @@ subprojects {
if (['fabric'].contains(project.name)) { if (['fabric'].contains(project.name)) {
publications { publications {
mavenJavaFabric(MavenPublication) { mavenJavaFabric(MavenPublication) {
groupId = 'org.inksnow.husk.husksync' groupId = 'net.william278.husksync'
artifactId = 'husksync-fabric' artifactId = 'husksync-fabric'
version = "$rootProject.version+${fabric_minecraft_version}" version = "$rootProject.version+${fabric_minecraft_version}"
artifact remapJar artifact remapJar

@ -1,22 +1,15 @@
dependencies { dependencies {
implementation project(path: ':common') implementation project(path: ':common')
implementation 'org.slf4j:slf4j-api:1.7.36' implementation 'net.william278.uniform:uniform-bukkit:1.2.1'
implementation 'org.inksnow.husk.uniform:uniform-bukkit:1.2.1-ad25f16'
implementation 'net.william278:mpdbdataconverter:1.0.1' implementation 'net.william278:mpdbdataconverter:1.0.1'
implementation 'org.inksnow.husk:hsldataconverter:1.0' implementation 'net.william278:hsldataconverter:1.0'
implementation 'net.william278:mapdataapi:1.0.3' implementation 'net.william278:mapdataapi:1.0.3'
implementation 'org.bstats:bstats-bukkit:3.0.2' implementation 'org.bstats:bstats-bukkit:3.0.2'
implementation 'net.kyori:adventure-platform-bukkit:4.3.4' implementation 'net.kyori:adventure-platform-bukkit:4.3.4'
implementation 'dev.triumphteam:triumph-gui:3.1.10' implementation 'dev.triumphteam:triumph-gui:3.1.10'
implementation 'space.arim.morepaperlib:morepaperlib:0.4.4' implementation 'space.arim.morepaperlib:morepaperlib:0.4.4'
implementation 'de.tr7zw:item-nbt-api:2.13.2' implementation 'de.tr7zw:item-nbt-api:2.13.2'
implementation 'com.google.guava:guava:33.2.1-jre'
implementation ("redis.clients:jedis:$jedis_version") {
exclude group: 'org.slf4j', module: 'slf4j-api'
}
implementation "org.xerial.snappy:snappy-java:$snappy_version"
implementation "org.mongodb:mongodb-driver-sync:$mongodb_driver_version"
compileOnly 'org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT' compileOnly 'org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT'
compileOnly 'com.github.retrooper.packetevents:spigot:2.3.0' compileOnly 'com.github.retrooper.packetevents:spigot:2.3.0'
@ -24,27 +17,24 @@ dependencies {
compileOnly 'org.projectlombok:lombok:1.18.34' compileOnly 'org.projectlombok:lombok:1.18.34'
compileOnly 'commons-io:commons-io:2.16.1' compileOnly 'commons-io:commons-io:2.16.1'
compileOnly 'org.json:json:20240303' compileOnly 'org.json:json:20240303'
compileOnly 'de.themoep:minedown-adventure:1.7.3-SNAPSHOT' compileOnly 'net.william278:minedown:1.8.2'
compileOnly 'org.inksnow.husk:configlib-yaml:4.5.4' compileOnly 'de.exlll:configlib-yaml:4.5.0'
compileOnly 'com.zaxxer:HikariCP:4.0.3' compileOnly 'com.zaxxer:HikariCP:5.1.0'
compileOnly 'org.inksnow.husk:desertwell:2.0.5-9962d59:all' compileOnly 'net.william278:DesertWell:2.0.4'
compileOnly 'net.william278:AdvancementAPI:97a9583413' compileOnly 'net.william278:AdvancementAPI:97a9583413'
compileOnly "redis.clients:jedis:$jedis_version"
annotationProcessor 'org.projectlombok:lombok:1.18.34' annotationProcessor 'org.projectlombok:lombok:1.18.34'
} }
shadowJar { shadowJar {
mergeServiceFiles() dependencies {
exclude(dependency('com.mojang:brigadier'))
relocate 'org.inksnow.cputil', 'net.william278.husksync.libraries.cputil' }
relocate 'org.slf4j', 'net.william278.husksync.libraries.slf4j'
relocate 'org.objectweb.asm', 'net.william278.husksync.libraries.asm'
relocate 'org.apache.commons.io', 'net.william278.husksync.libraries.commons.io' relocate 'org.apache.commons.io', 'net.william278.husksync.libraries.commons.io'
relocate 'org.apache.commons.text', 'net.william278.husksync.libraries.commons.text' relocate 'org.apache.commons.text', 'net.william278.husksync.libraries.commons.text'
relocate 'org.apache.commons.lang3', 'net.william278.husksync.libraries.commons.lang3' relocate 'org.apache.commons.lang3', 'net.william278.husksync.libraries.commons.lang3'
relocate 'com.google.gson', 'net.william278.husksync.libraries.gson' relocate 'com.google.gson', 'net.william278.husksync.libraries.gson'
relocate 'com.google.common', 'net.william278.husksync.libraries.guava'
relocate 'com.fatboyindustrial', 'net.william278.husksync.libraries' relocate 'com.fatboyindustrial', 'net.william278.husksync.libraries'
relocate 'de.themoep', 'net.william278.husksync.libraries' relocate 'de.themoep', 'net.william278.husksync.libraries'
relocate 'org.jetbrains', 'net.william278.husksync.libraries' relocate 'org.jetbrains', 'net.william278.husksync.libraries'
@ -64,4 +54,6 @@ shadowJar {
relocate 'dev.triumphteam.gui', 'net.william278.husksync.libraries.triumphgui' relocate 'dev.triumphteam.gui', 'net.william278.husksync.libraries.triumphgui'
relocate 'space.arim.morepaperlib', 'net.william278.husksync.libraries.paperlib' relocate 'space.arim.morepaperlib', 'net.william278.husksync.libraries.paperlib'
relocate 'de.tr7zw.changeme.nbtapi', 'net.william278.husksync.libraries.nbtapi' relocate 'de.tr7zw.changeme.nbtapi', 'net.william278.husksync.libraries.nbtapi'
}
minimize()
}

@ -57,8 +57,6 @@ import net.william278.husksync.util.BukkitLegacyConverter;
import net.william278.husksync.util.BukkitMapPersister; import net.william278.husksync.util.BukkitMapPersister;
import net.william278.husksync.util.BukkitTask; import net.william278.husksync.util.BukkitTask;
import net.william278.husksync.util.LegacyConverter; import net.william278.husksync.util.LegacyConverter;
import net.william278.husksync.util.StringUtil;
import net.william278.husksync.util.ref.RefUtil;
import net.william278.uniform.Uniform; import net.william278.uniform.Uniform;
import net.william278.uniform.bukkit.BukkitUniform; import net.william278.uniform.bukkit.BukkitUniform;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
@ -66,9 +64,6 @@ import org.bukkit.entity.Player;
import org.bukkit.map.MapView; import org.bukkit.map.MapView;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.inksnow.cputil.AuroraCputil;
import org.inksnow.cputil.AuroraUrl;
import org.inksnow.cputil.logger.AuroraLoggerFactory;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import space.arim.morepaperlib.MorePaperLib; import space.arim.morepaperlib.MorePaperLib;
import space.arim.morepaperlib.scheduling.AsynchronousScheduler; import space.arim.morepaperlib.scheduling.AsynchronousScheduler;
@ -86,21 +81,10 @@ import java.util.stream.Collectors;
public class BukkitHuskSync extends JavaPlugin implements HuskSync, BukkitTask.Supplier, public class BukkitHuskSync extends JavaPlugin implements HuskSync, BukkitTask.Supplier,
BukkitEventDispatcher, BukkitMapPersister { BukkitEventDispatcher, BukkitMapPersister {
static {
AuroraLoggerFactory.instance().nameMapping(it -> {
int split = it.lastIndexOf('.');
if (split != -1) {
return "HuskSync-Aurora " + it.substring(split + 1);
} else {
return "HuskSync-Aurora " + it;
}
});
}
/** /**
* Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskSync-Aurora/23157">HuskSync-Aurora</a>. * Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskSync%20-%20Bukkit/13140">HuskSync on Bukkit</a>.
*/ */
private static final int METRICS_ID = 23157; private static final int METRICS_ID = 13140;
private static final String PLATFORM_TYPE_ID = "bukkit"; private static final String PLATFORM_TYPE_ID = "bukkit";
private final TreeMap<Identifier, Serializer<? extends Data>> serializers = Maps.newTreeMap( private final TreeMap<Identifier, Serializer<? extends Data>> serializers = Maps.newTreeMap(
@ -167,21 +151,15 @@ public class BukkitHuskSync extends JavaPlugin implements HuskSync, BukkitTask.S
// Prepare serializers // Prepare serializers
initialize("data serializers", (plugin) -> { initialize("data serializers", (plugin) -> {
if (RefUtil.bootstrapVirtualMethod("Lorg/bukkit/persistence/PersistentDataHolder;getPersistentDataContainer()Lorg/bukkit/persistence/PersistentDataContainer;") != null) { registerSerializer(Identifier.PERSISTENT_DATA, new BukkitSerializer.PersistentData(this));
registerSerializer(Identifier.PERSISTENT_DATA, new BukkitSerializer.PersistentData(this));
}
registerSerializer(Identifier.INVENTORY, new BukkitSerializer.Inventory(this)); registerSerializer(Identifier.INVENTORY, new BukkitSerializer.Inventory(this));
registerSerializer(Identifier.ENDER_CHEST, new BukkitSerializer.EnderChest(this)); registerSerializer(Identifier.ENDER_CHEST, new BukkitSerializer.EnderChest(this));
registerSerializer(Identifier.ADVANCEMENTS, new BukkitSerializer.Advancements(this)); registerSerializer(Identifier.ADVANCEMENTS, new BukkitSerializer.Advancements(this));
if (RefUtil.bootstrapStaticFieldGet("Lorg/bukkit/Registry;STATISTIC:Lorg/bukkit/Registry;") != null) { registerSerializer(Identifier.STATISTICS, new Serializer.Json<>(this, BukkitData.Statistics.class));
registerSerializer(Identifier.STATISTICS, new Serializer.Json<>(this, BukkitData.Statistics.class));
}
registerSerializer(Identifier.POTION_EFFECTS, new BukkitSerializer.PotionEffects(this)); registerSerializer(Identifier.POTION_EFFECTS, new BukkitSerializer.PotionEffects(this));
registerSerializer(Identifier.GAME_MODE, new Serializer.Json<>(this, BukkitData.GameMode.class)); registerSerializer(Identifier.GAME_MODE, new Serializer.Json<>(this, BukkitData.GameMode.class));
registerSerializer(Identifier.FLIGHT_STATUS, new Serializer.Json<>(this, BukkitData.FlightStatus.class)); registerSerializer(Identifier.FLIGHT_STATUS, new Serializer.Json<>(this, BukkitData.FlightStatus.class));
if (RefUtil.bootstrapStaticFieldGet("Lorg/bukkit/Registry;ATTRIBUTE:Lorg/bukkit/Registry;") != null) { registerSerializer(Identifier.ATTRIBUTES, new Serializer.Json<>(this, BukkitData.Attributes.class));
registerSerializer(Identifier.ATTRIBUTES, new Serializer.Json<>(this, BukkitData.Attributes.class));
}
registerSerializer(Identifier.HEALTH, new Serializer.Json<>(this, BukkitData.Health.class)); registerSerializer(Identifier.HEALTH, new Serializer.Json<>(this, BukkitData.Health.class));
registerSerializer(Identifier.HUNGER, new Serializer.Json<>(this, BukkitData.Hunger.class)); registerSerializer(Identifier.HUNGER, new Serializer.Json<>(this, BukkitData.Hunger.class));
registerSerializer(Identifier.EXPERIENCE, new Serializer.Json<>(this, BukkitData.Experience.class)); registerSerializer(Identifier.EXPERIENCE, new Serializer.Json<>(this, BukkitData.Experience.class));
@ -200,24 +178,11 @@ public class BukkitHuskSync extends JavaPlugin implements HuskSync, BukkitTask.S
// Initialize the database // Initialize the database
initialize(getSettings().getDatabase().getType().getDisplayName() + " database connection", (plugin) -> { initialize(getSettings().getDatabase().getType().getDisplayName() + " database connection", (plugin) -> {
switch (settings.getDatabase().getType()) { this.database = switch (settings.getDatabase().getType()) {
case MYSQL: case MYSQL, MARIADB -> new MySqlDatabase(this);
case MARIADB: { case POSTGRES -> new PostgresDatabase(this);
this.database = new MySqlDatabase(this); case MONGO -> new MongoDbDatabase(this);
break; };
}
case POSTGRES: {
this.database = new PostgresDatabase(this);
break;
}
case MONGO: {
this.database = new MongoDbDatabase(this);
break;
}
default: {
// do nothing
}
}
this.database.initialize(); this.database.initialize();
}); });
@ -330,14 +295,14 @@ public class BukkitHuskSync extends JavaPlugin implements HuskSync, BukkitTask.S
// Register bStats metrics // Register bStats metrics
public void registerMetrics(int metricsId) { public void registerMetrics(int metricsId) {
if (!StringUtil.isBlank(getPluginVersion().getMetadata())) { if (!getPluginVersion().getMetadata().isBlank()) {
return; return;
} }
try { try {
new Metrics(this, metricsId); new Metrics(this, metricsId);
} catch (Throwable e) { } catch (Throwable e) {
log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); log(Level.WARNING, "Failed to register bStats metrics (%s)".formatted(e.getMessage()));
} }
} }

@ -33,7 +33,6 @@ import net.william278.husksync.HuskSync;
import net.william278.husksync.adapter.Adaptable; import net.william278.husksync.adapter.Adaptable;
import net.william278.husksync.config.Settings.SynchronizationSettings.AttributeSettings; import net.william278.husksync.config.Settings.SynchronizationSettings.AttributeSettings;
import net.william278.husksync.user.BukkitUser; import net.william278.husksync.user.BukkitUser;
import net.william278.husksync.util.ref.RefUtil;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.advancement.AdvancementProgress; import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.attribute.AttributeInstance; import org.bukkit.attribute.AttributeInstance;
@ -93,8 +92,8 @@ public abstract class BukkitData implements Data {
stack.hasItemMeta() && Objects.requireNonNull(stack.getItemMeta()).hasEnchants() ? stack.hasItemMeta() && Objects.requireNonNull(stack.getItemMeta()).hasEnchants() ?
stack.getItemMeta().getEnchants().keySet().stream() stack.getItemMeta().getEnchants().keySet().stream()
.map(enchantment -> enchantment.getKey().getKey()) .map(enchantment -> enchantment.getKey().getKey())
.collect(Collectors.toList()) .toList()
: Collections.emptyList() : List.of()
) : null) ) : null)
.toArray(Stack[]::new); .toArray(Stack[]::new);
} }
@ -119,8 +118,7 @@ public abstract class BukkitData implements Data {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof BukkitData.Items) { if (obj instanceof BukkitData.Items items) {
BukkitData.Items items = (BukkitData.Items) obj;
return Arrays.equals(contents, items.getContents()); return Arrays.equals(contents, items.getContents());
} }
return false; return false;
@ -191,7 +189,7 @@ public abstract class BukkitData implements Data {
@NotNull @NotNull
public static BukkitData.Items.EnderChest adapt(@NotNull Collection<ItemStack> items) { public static BukkitData.Items.EnderChest adapt(@NotNull Collection<ItemStack> items) {
return adapt(items.toArray(new ItemStack[0])); return adapt(items.toArray(ItemStack[]::new));
} }
@NotNull @NotNull
@ -214,7 +212,7 @@ public abstract class BukkitData implements Data {
@NotNull @NotNull
public static ItemArray adapt(@NotNull Collection<ItemStack> drops) { public static ItemArray adapt(@NotNull Collection<ItemStack> drops) {
return new ItemArray(drops.toArray(new ItemStack[0])); return new ItemArray(drops.toArray(ItemStack[]::new));
} }
@NotNull @NotNull
@ -240,28 +238,26 @@ public abstract class BukkitData implements Data {
@NotNull @NotNull
public static BukkitData.PotionEffects from(@NotNull Collection<PotionEffect> sei) { public static BukkitData.PotionEffects from(@NotNull Collection<PotionEffect> sei) {
return new BukkitData.PotionEffects(Lists.newArrayList( return new BukkitData.PotionEffects(Lists.newArrayList(sei.stream().filter(e -> !e.isAmbient()).toList()));
sei.stream().filter(e -> !e.isAmbient())
.collect(Collectors.toList())
));
} }
@NotNull @NotNull
public static BukkitData.PotionEffects adapt(@NotNull Collection<Effect> effects) { public static BukkitData.PotionEffects adapt(@NotNull Collection<Effect> effects) {
return from(effects.stream() return from(effects.stream()
.map(effect -> { .map(effect -> {
final PotionEffectType type = matchEffectType(effect.getType()); final PotionEffectType type = matchEffectType(effect.type());
return type != null ? new PotionEffect( return type != null ? new PotionEffect(
type, type,
effect.getDuration(), effect.duration(),
effect.getAmplifier(), effect.amplifier(),
effect.isAmbient(), effect.isAmbient(),
effect.isShowParticles(), effect.showParticles(),
effect.isHasIcon() effect.hasIcon()
) : null; ) : null;
}) })
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toList())); .toList());
} }
@NotNull @NotNull
@ -294,7 +290,7 @@ public abstract class BukkitData implements Data {
potionEffect.hasParticles(), potionEffect.hasParticles(),
potionEffect.hasIcon() potionEffect.hasIcon()
)) ))
.collect(Collectors.toList()); .toList();
} }
} }
@ -339,19 +335,16 @@ public abstract class BukkitData implements Data {
final Optional<Advancement> record = completed.stream() final Optional<Advancement> record = completed.stream()
.filter(r -> r.getKey().equals(advancement.getKey().toString())) .filter(r -> r.getKey().equals(advancement.getKey().toString()))
.findFirst(); .findFirst();
if (!record.isPresent()) { if (record.isEmpty()) {
this.setAdvancement(plugin, advancement, player, user, Collections.emptyList(), progress.getAwardedCriteria()); this.setAdvancement(plugin, advancement, player, user, List.of(), progress.getAwardedCriteria());
return; return;
} }
final Map<String, Date> criteria = record.get().getCompletedCriteria(); final Map<String, Date> criteria = record.get().getCompletedCriteria();
this.setAdvancement( this.setAdvancement(
plugin, advancement, player, user, plugin, advancement, player, user,
criteria.keySet().stream() criteria.keySet().stream().filter(key -> !progress.getAwardedCriteria().contains(key)).toList(),
.filter(key -> !progress.getAwardedCriteria().contains(key)) progress.getAwardedCriteria().stream().filter(key -> !criteria.containsKey(key)).toList()
.collect(Collectors.toList()),
progress.getAwardedCriteria().stream().filter(key -> !criteria.containsKey(key))
.collect(Collectors.toList())
); );
})); }));
} }
@ -433,7 +426,7 @@ public abstract class BukkitData implements Data {
public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException {
try { try {
final org.bukkit.Location location = new org.bukkit.Location( final org.bukkit.Location location = new org.bukkit.Location(
Bukkit.getWorld(world.getName()), x, y, z, yaw, pitch Bukkit.getWorld(world.name()), x, y, z, yaw, pitch
); );
user.getPlayer().teleport(location); user.getPlayer().teleport(location);
} catch (Throwable e) { } catch (Throwable e) {
@ -464,25 +457,10 @@ public abstract class BukkitData implements Data {
items = Maps.newHashMap(), entities = Maps.newHashMap(); items = Maps.newHashMap(), entities = Maps.newHashMap();
Registry.STATISTIC.forEach(id -> { Registry.STATISTIC.forEach(id -> {
switch (id.getType()) { switch (id.getType()) {
case UNTYPED: { case UNTYPED -> addStatistic(player, id, generic);
addStatistic(player, id, generic); case BLOCK -> addMaterialStatistic(player, id, blocks, true);
break; case ITEM -> addMaterialStatistic(player, id, items, false);
} case ENTITY -> addEntityStatistic(player, id, entities);
case BLOCK: {
addMaterialStatistic(player, id, blocks, true);
break;
}
case ITEM: {
addMaterialStatistic(player, id, items, false);
break;
}
case ENTITY: {
addEntityStatistic(player, id, entities);
break;
}
default: {
// do nothing
}
} }
}); });
return new BukkitData.Statistics(generic, blocks, items, entities); return new BukkitData.Statistics(generic, blocks, items, entities);
@ -549,22 +527,9 @@ public abstract class BukkitData implements Data {
try { try {
switch (type) { switch (type) {
case UNTYPED: { case UNTYPED -> player.setStatistic(stat, value);
player.setStatistic(stat, value); case BLOCK, ITEM -> player.setStatistic(stat, Objects.requireNonNull(matchMaterial(key[0])), value);
break; case ENTITY -> player.setStatistic(stat, Objects.requireNonNull(matchEntityType(key[0])), value);
}
case BLOCK:
case ITEM: {
player.setStatistic(stat, Objects.requireNonNull(matchMaterial(key[0])), value);
break;
}
case ENTITY: {
player.setStatistic(stat, Objects.requireNonNull(matchEntityType(key[0])), value);
break;
}
default: {
// do nothing
}
} }
} catch (Throwable ignored) { } catch (Throwable ignored) {
} }
@ -626,7 +591,7 @@ public abstract class BukkitData implements Data {
} }
public Optional<Attribute> getAttribute(@NotNull org.bukkit.attribute.Attribute id) { public Optional<Attribute> getAttribute(@NotNull org.bukkit.attribute.Attribute id) {
return attributes.stream().filter(attribute -> attribute.getName().equals(id.getKey().toString())).findFirst(); return attributes.stream().filter(attribute -> attribute.name().equals(id.getKey().toString())).findFirst();
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -683,10 +648,10 @@ public abstract class BukkitData implements Data {
if (instance == null) { if (instance == null) {
return; return;
} }
instance.setBaseValue(attribute == null ? instance.getDefaultValue() : attribute.getBaseValue()); instance.setBaseValue(attribute == null ? instance.getDefaultValue() : attribute.baseValue());
instance.getModifiers().forEach(instance::removeModifier); instance.getModifiers().forEach(instance::removeModifier);
if (attribute != null) { if (attribute != null) {
attribute.getModifiers().stream() attribute.modifiers().stream()
.filter(mod -> instance.getModifiers().stream().map(AttributeModifier::getName) .filter(mod -> instance.getModifiers().stream().map(AttributeModifier::getName)
.noneMatch(n -> n.equals(mod.name()))) .noneMatch(n -> n.equals(mod.name())))
.distinct() .distinct()
@ -757,19 +722,19 @@ public abstract class BukkitData implements Data {
} }
/** /**
* @deprecated Use {@link #from(double, double, boolean)} instead, since 3.5.4 * @deprecated Use {@link #from(double, double, boolean)} instead
*/ */
@NotNull @NotNull
@Deprecated @Deprecated(since = "3.5.4")
public static BukkitData.Health from(double health, double scale) { public static BukkitData.Health from(double health, double scale) {
return from(health, scale, false); return from(health, scale, false);
} }
/** /**
* @deprecated Use {@link #from(double, double, boolean)} instead, since 3.5 * @deprecated Use {@link #from(double, double, boolean)} instead
*/ */
@NotNull @NotNull
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
public static BukkitData.Health from(double health, @SuppressWarnings("unused") double max, double scale) { public static BukkitData.Health from(double health, @SuppressWarnings("unused") double max, double scale) {
return from(health, scale, false); return from(health, scale, false);
} }
@ -792,7 +757,7 @@ public abstract class BukkitData implements Data {
try { try {
player.setHealth(Math.min(health, player.getMaxHealth())); player.setHealth(Math.min(health, player.getMaxHealth()));
} catch (Throwable e) { } catch (Throwable e) {
plugin.log(Level.WARNING, "Error setting " + player.getName() + "'s health to " + health, e); plugin.log(Level.WARNING, "Error setting %s's health to %s".formatted(player.getName(), health), e);
} }
// Set health scale // Set health scale
@ -801,7 +766,7 @@ public abstract class BukkitData implements Data {
player.setHealthScale(scale); player.setHealthScale(scale);
player.setHealthScaled(isHealthScaled); player.setHealthScaled(isHealthScaled);
} catch (Throwable e) { } catch (Throwable e) {
plugin.log(Level.WARNING, "Error setting " + player.getName() + "'s health scale to " + scale, e); plugin.log(Level.WARNING, "Error setting %s's health scale to %s".formatted(player.getName(), scale), e);
} }
} }
@ -890,7 +855,7 @@ public abstract class BukkitData implements Data {
} }
@NotNull @NotNull
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static BukkitData.GameMode from(@NotNull String gameMode, boolean allowFlight, boolean isFlying) { public static BukkitData.GameMode from(@NotNull String gameMode, boolean allowFlight, boolean isFlying) {
return new BukkitData.GameMode(gameMode); return new BukkitData.GameMode(gameMode);

@ -33,7 +33,6 @@ import net.william278.husksync.BukkitHuskSync;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.adapter.Adaptable; import net.william278.husksync.adapter.Adaptable;
import net.william278.husksync.api.HuskSyncAPI; import net.william278.husksync.api.HuskSyncAPI;
import net.william278.husksync.util.ref.RefUtil;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@ -128,13 +127,13 @@ public class BukkitSerializer {
@Nullable @Nullable
default ItemStack[] getItems(@NotNull ReadWriteNBT tag, @NotNull Version mcVersion) { default ItemStack[] getItems(@NotNull ReadWriteNBT tag, @NotNull Version mcVersion) {
if (mcVersion.compareTo(getPlugin().getMinecraftVersion()) < 0) { if (mcVersion.compareTo(getPlugin().getMinecraftVersion()) < 0) {
return private$upgradeItemStacks((NBTCompound) tag, mcVersion); return upgradeItemStacks((NBTCompound) tag, mcVersion);
} }
return NBT.itemStackArrayFromNBT(tag); return NBT.itemStackArrayFromNBT(tag);
} }
@NotNull @NotNull
default ItemStack @NotNull [] private$upgradeItemStacks(@NotNull NBTCompound itemsNbt, @NotNull Version mcVersion) { private ItemStack @NotNull [] upgradeItemStacks(@NotNull NBTCompound itemsNbt, @NotNull Version mcVersion) {
final ReadWriteNBTCompoundList items = itemsNbt.getCompoundList("items"); final ReadWriteNBTCompoundList items = itemsNbt.getCompoundList("items");
final ItemStack[] itemStacks = new ItemStack[itemsNbt.getInteger("size")]; final ItemStack[] itemStacks = new ItemStack[itemsNbt.getInteger("size")];
for (int i = 0; i < items.size(); i++) { for (int i = 0; i < items.size(); i++) {
@ -143,7 +142,7 @@ public class BukkitSerializer {
continue; continue;
} }
try { try {
itemStacks[i] = NBT.itemStackFromNBT(private$upgradeItemData(items.get(i), mcVersion)); itemStacks[i] = NBT.itemStackFromNBT(upgradeItemData(items.get(i), mcVersion));
} catch (Throwable e) { } catch (Throwable e) {
itemStacks[i] = new ItemStack(Material.AIR); itemStacks[i] = new ItemStack(Material.AIR);
} }
@ -152,47 +151,23 @@ public class BukkitSerializer {
} }
@NotNull @NotNull
default ReadWriteNBT private$upgradeItemData(@NotNull ReadWriteNBT tag, @NotNull Version mcVersion) private ReadWriteNBT upgradeItemData(@NotNull ReadWriteNBT tag, @NotNull Version mcVersion)
throws NoSuchFieldException, IllegalAccessException { throws NoSuchFieldException, IllegalAccessException {
return DataFixerUtil.fixUpItemData(tag, private$getDataVersion(mcVersion), DataFixerUtil.getCurrentVersion()); return DataFixerUtil.fixUpItemData(tag, getDataVersion(mcVersion), DataFixerUtil.getCurrentVersion());
} }
default int private$getDataVersion(@NotNull Version mcVersion) { private int getDataVersion(@NotNull Version mcVersion) {
switch (mcVersion.toStringWithoutMetadata()) { return switch (mcVersion.toStringWithoutMetadata()) {
case "1.12": case "1.12.1": case "1.12.2": case "1.16", "1.16.1", "1.16.2", "1.16.3", "1.16.4", "1.16.5" -> DataFixerUtil.VERSION1_16_5;
case "1.13": case "1.13.1": case "1.13.2": case "1.17", "1.17.1" -> DataFixerUtil.VERSION1_17_1;
case "1.14": case "1.14.1": case "1.14.2": case "1.14.3": case "1.14.4": case "1.18", "1.18.1", "1.18.2" -> DataFixerUtil.VERSION1_18_2;
case "1.15": case "1.15.1": case "1.15.2": { case "1.19", "1.19.1", "1.19.2" -> DataFixerUtil.VERSION1_19_2;
return DataFixerUtil.VERSION1_12_2; case "1.20", "1.20.1", "1.20.2" -> DataFixerUtil.VERSION1_20_2;
} case "1.20.3", "1.20.4" -> DataFixerUtil.VERSION1_20_4;
case "1.16": case "1.16.1": case "1.16.2": case "1.16.3": case "1.16.4": case "1.16.5": { case "1.20.5", "1.20.6" -> DataFixerUtil.VERSION1_20_5;
return DataFixerUtil.VERSION1_16_5; case "1.21" -> DataFixerUtil.VERSION1_21;
} default -> DataFixerUtil.getCurrentVersion();
case "1.17": case "1.17.1": { };
return DataFixerUtil.VERSION1_17_1;
}
case "1.18": case "1.18.1": case "1.18.2": {
return DataFixerUtil.VERSION1_18_2;
}
case "1.19": case "1.19.1": case "1.19.2": {
return DataFixerUtil.VERSION1_19_2;
}
case "1.20": case "1.20.1": case "1.20.2": {
return DataFixerUtil.VERSION1_20_2;
}
case "1.20.3": case "1.20.4": {
return DataFixerUtil.VERSION1_20_4;
}
case "1.20.5": case "1.20.6": {
return DataFixerUtil.VERSION1_20_5;
}
case "1.21": {
return DataFixerUtil.VERSION1_21;
}
default: {
return DataFixerUtil.getCurrentVersion();
}
}
} }
@NotNull @NotNull
@ -201,7 +176,7 @@ public class BukkitSerializer {
public static class PotionEffects extends BukkitSerializer implements Serializer<BukkitData.PotionEffects> { public static class PotionEffects extends BukkitSerializer implements Serializer<BukkitData.PotionEffects> {
private static final TypeToken<List<Data.PotionEffects.Effect>> TYPE = new TypeToken<List<Data.PotionEffects.Effect>>() { private static final TypeToken<List<Data.PotionEffects.Effect>> TYPE = new TypeToken<>() {
}; };
public PotionEffects(@NotNull HuskSync plugin) { public PotionEffects(@NotNull HuskSync plugin) {
@ -225,7 +200,7 @@ public class BukkitSerializer {
public static class Advancements extends BukkitSerializer implements Serializer<BukkitData.Advancements> { public static class Advancements extends BukkitSerializer implements Serializer<BukkitData.Advancements> {
private static final TypeToken<List<Data.Advancements.Advancement>> TYPE = new TypeToken<List<Data.Advancements.Advancement>>() { private static final TypeToken<List<Data.Advancements.Advancement>> TYPE = new TypeToken<>() {
}; };
public Advancements(@NotNull HuskSync plugin) { public Advancements(@NotNull HuskSync plugin) {
@ -266,9 +241,9 @@ public class BukkitSerializer {
} }
/** /**
* @deprecated Use {@link Serializer.Json} in the common module instead, since 2.6 * @deprecated Use {@link Serializer.Json} in the common module instead
*/ */
@Deprecated @Deprecated(since = "2.6")
public class Json<T extends Data & Adaptable> extends Serializer.Json<T> { public class Json<T extends Data & Adaptable> extends Serializer.Json<T> {
public Json(@NotNull HuskSync plugin, @NotNull Class<T> type) { public Json(@NotNull HuskSync plugin, @NotNull Class<T> type) {

@ -32,22 +32,22 @@ public interface BukkitUserDataHolder extends UserDataHolder {
@Override @Override
default Optional<? extends Data> getData(@NotNull Identifier id) { default Optional<? extends Data> getData(@NotNull Identifier id) {
if (!id.isCustom()) { if (!id.isCustom()) {
switch (id.getKeyValue()) { return switch (id.getKeyValue()) {
case "inventory": return getInventory(); case "inventory" -> getInventory();
case "ender_chest": return getEnderChest(); case "ender_chest" -> getEnderChest();
case "potion_effects": return getPotionEffects(); case "potion_effects" -> getPotionEffects();
case "advancements": return getAdvancements(); case "advancements" -> getAdvancements();
case "location": return getLocation(); case "location" -> getLocation();
case "statistics": return getStatistics(); case "statistics" -> getStatistics();
case "health": return getHealth(); case "health" -> getHealth();
case "hunger": return getHunger(); case "hunger" -> getHunger();
case "attributes": return getAttributes(); case "attributes" -> getAttributes();
case "experience": return getExperience(); case "experience" -> getExperience();
case "game_mode": return getGameMode(); case "game_mode" -> getGameMode();
case "flight_status": return getFlightStatus(); case "flight_status" -> getFlightStatus();
case "persistent_data": return getPersistentData(); case "persistent_data" -> getPersistentData();
default: throw new IllegalStateException(String.format("Unexpected data type: %s", id)); default -> throw new IllegalStateException(String.format("Unexpected data type: %s", id));
} };
} }
return Optional.ofNullable(getCustomDataStore().get(id)); return Optional.ofNullable(getCustomDataStore().get(id));
} }
@ -154,9 +154,9 @@ public interface BukkitUserDataHolder extends UserDataHolder {
Player getPlayer(); Player getPlayer();
/** /**
* @deprecated Use {@link #getPlayer()} instead, since 3.6 * @deprecated Use {@link #getPlayer()} instead
*/ */
@Deprecated @Deprecated(since = "3.6")
@NotNull @NotNull
default Player getBukkitPlayer() { default Player getBukkitPlayer() {
return getPlayer(); return getPlayer();

@ -30,7 +30,7 @@ public interface BukkitEventDispatcher extends EventDispatcher {
@Override @Override
default <T extends Event> boolean fireIsCancelled(@NotNull T event) { default <T extends Event> boolean fireIsCancelled(@NotNull T event) {
Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event); Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event);
return event instanceof Cancellable && ((Cancellable) event).isCancelled(); return event instanceof Cancellable cancellable && cancellable.isCancelled();
} }
@NotNull @NotNull

@ -23,7 +23,6 @@ import net.william278.husksync.BukkitHuskSync;
import net.william278.husksync.data.BukkitData; import net.william278.husksync.data.BukkitData;
import net.william278.husksync.user.BukkitUser; import net.william278.husksync.user.BukkitUser;
import net.william278.husksync.user.OnlineUser; import net.william278.husksync.user.OnlineUser;
import net.william278.husksync.util.MaterialUtil;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -83,7 +82,7 @@ public class BukkitEventListener extends EventListener implements BukkitJoinEven
public void handlePlayerQuit(@NotNull BukkitUser bukkitUser) { public void handlePlayerQuit(@NotNull BukkitUser bukkitUser) {
final Player player = bukkitUser.getPlayer(); final Player player = bukkitUser.getPlayer();
final ItemStack itemOnCursor = player.getItemOnCursor(); final ItemStack itemOnCursor = player.getItemOnCursor();
if (!bukkitUser.isLocked() && !MaterialUtil.isAir(itemOnCursor.getType())) { if (!bukkitUser.isLocked() && !itemOnCursor.getType().isAir()) {
player.setItemOnCursor(null); player.setItemOnCursor(null);
player.getWorld().dropItem(player.getLocation(), itemOnCursor); player.getWorld().dropItem(player.getLocation(), itemOnCursor);
plugin.debug("Dropped " + itemOnCursor + " for " + player.getName() + " on quit"); plugin.debug("Dropped " + itemOnCursor + " for " + player.getName() + " on quit");

@ -60,8 +60,8 @@ public class BukkitLockedEventListener implements LockedHandler, Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onProjectileLaunch(@NotNull ProjectileLaunchEvent event) { public void onProjectileLaunch(@NotNull ProjectileLaunchEvent event) {
final Projectile projectile = event.getEntity(); final Projectile projectile = event.getEntity();
if (projectile.getShooter() instanceof Player) { if (projectile.getShooter() instanceof Player player) {
cancelPlayerEvent(((Player) projectile.getShooter()).getUniqueId(), event); cancelPlayerEvent(player.getUniqueId(), event);
} }
} }
@ -72,8 +72,8 @@ public class BukkitLockedEventListener implements LockedHandler, Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPickupItem(@NotNull EntityPickupItemEvent event) { public void onPickupItem(@NotNull EntityPickupItemEvent event) {
if (event.getEntity() instanceof Player) { if (event.getEntity() instanceof Player player) {
cancelPlayerEvent(event.getEntity().getUniqueId(), event); cancelPlayerEvent(player.getUniqueId(), event);
} }
} }
@ -104,8 +104,8 @@ public class BukkitLockedEventListener implements LockedHandler, Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryOpen(@NotNull InventoryOpenEvent event) { public void onInventoryOpen(@NotNull InventoryOpenEvent event) {
if (event.getPlayer() instanceof Player) { if (event.getPlayer() instanceof Player player) {
cancelPlayerEvent(event.getPlayer().getUniqueId(), event); cancelPlayerEvent(player.getUniqueId(), event);
} }
} }
@ -116,8 +116,8 @@ public class BukkitLockedEventListener implements LockedHandler, Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerTakeDamage(@NotNull EntityDamageEvent event) { public void onPlayerTakeDamage(@NotNull EntityDamageEvent event) {
if (event.getEntity() instanceof Player) { if (event.getEntity() instanceof Player player) {
cancelPlayerEvent(event.getEntity().getUniqueId(), event); cancelPlayerEvent(player.getUniqueId(), event);
} }
} }

@ -25,7 +25,6 @@ import com.github.retrooper.packetevents.event.PacketListenerPriority;
import com.github.retrooper.packetevents.event.PacketReceiveEvent; import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.event.PacketSendEvent; import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.protocol.packettype.PacketType; import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder; import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
import net.william278.husksync.BukkitHuskSync; import net.william278.husksync.BukkitHuskSync;
@ -60,7 +59,7 @@ public class BukkitPacketEventsLockedPacketListener extends BukkitLockedEventLis
private static class PlayerPacketAdapter extends PacketListenerAbstract { private static class PlayerPacketAdapter extends PacketListenerAbstract {
private static final Set<PacketType.Play.Client> ALLOWED_PACKETS = ImmutableSet.of( private static final Set<PacketType.Play.Client> ALLOWED_PACKETS = Set.of(
PacketType.Play.Client.KEEP_ALIVE, PacketType.Play.Client.PONG, PacketType.Play.Client.PLUGIN_MESSAGE, // Connection packets PacketType.Play.Client.KEEP_ALIVE, PacketType.Play.Client.PONG, PacketType.Play.Client.PLUGIN_MESSAGE, // Connection packets
PacketType.Play.Client.CHAT_MESSAGE, PacketType.Play.Client.CHAT_COMMAND, PacketType.Play.Client.CHAT_SESSION_UPDATE, // Chat / command packets PacketType.Play.Client.CHAT_MESSAGE, PacketType.Play.Client.CHAT_COMMAND, PacketType.Play.Client.CHAT_SESSION_UPDATE, // Chat / command packets
PacketType.Play.Client.PLAYER_POSITION, PacketType.Play.Client.PLAYER_POSITION_AND_ROTATION, PacketType.Play.Client.PLAYER_ROTATION, // Movement packets PacketType.Play.Client.PLAYER_POSITION, PacketType.Play.Client.PLAYER_POSITION_AND_ROTATION, PacketType.Play.Client.PLAYER_ROTATION, // Movement packets
@ -80,10 +79,10 @@ public class BukkitPacketEventsLockedPacketListener extends BukkitLockedEventLis
@Override @Override
public void onPacketReceive(PacketReceiveEvent event) { public void onPacketReceive(PacketReceiveEvent event) {
if (!(event.getPacketType() instanceof PacketType.Play.Client)) { if (!(event.getPacketType() instanceof PacketType.Play.Client client)) {
return; return;
} }
if (!CANCEL_PACKETS.contains((PacketType.Play.Client) event.getPacketType())) { if (!CANCEL_PACKETS.contains(client)) {
return; return;
} }
if (listener.cancelPlayerEvent(event.getUser().getUUID())) { if (listener.cancelPlayerEvent(event.getUser().getUUID())) {
@ -93,10 +92,10 @@ public class BukkitPacketEventsLockedPacketListener extends BukkitLockedEventLis
@Override @Override
public void onPacketSend(PacketSendEvent event) { public void onPacketSend(PacketSendEvent event) {
if (!(event.getPacketType() instanceof PacketType.Play.Client)) { if (!(event.getPacketType() instanceof PacketType.Play.Client client)) {
return; return;
} }
if (!CANCEL_PACKETS.contains((PacketType.Play.Client) event.getPacketType())) { if (!CANCEL_PACKETS.contains(client)) {
return; return;
} }
if (listener.cancelPlayerEvent(event.getUser().getUUID())) { if (listener.cancelPlayerEvent(event.getUser().getUUID())) {

@ -24,7 +24,6 @@ import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority; import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent; import com.comphenix.protocol.events.PacketEvent;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import net.william278.husksync.BukkitHuskSync; import net.william278.husksync.BukkitHuskSync;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -51,7 +50,7 @@ public class BukkitProtocolLibLockedPacketListener extends BukkitLockedEventList
private static class PlayerPacketAdapter extends PacketAdapter { private static class PlayerPacketAdapter extends PacketAdapter {
// Packets we want the player to still be able to send/receiver to/from the server // Packets we want the player to still be able to send/receiver to/from the server
private static final Set<PacketType> ALLOWED_PACKETS = ImmutableSet.of( private static final Set<PacketType> ALLOWED_PACKETS = Set.of(
Client.KEEP_ALIVE, Client.PONG, Client.CUSTOM_PAYLOAD, // Connection packets Client.KEEP_ALIVE, Client.PONG, Client.CUSTOM_PAYLOAD, // Connection packets
Client.CHAT_COMMAND, Client.CLIENT_COMMAND, Client.CHAT, Client.CHAT_SESSION_UPDATE, // Chat / command packets Client.CHAT_COMMAND, Client.CLIENT_COMMAND, Client.CHAT, Client.CHAT_SESSION_UPDATE, // Chat / command packets
Client.POSITION, Client.POSITION_LOOK, Client.LOOK, // Movement packets Client.POSITION, Client.POSITION_LOOK, Client.LOOK, // Movement packets

@ -22,7 +22,6 @@ package net.william278.husksync.migrator;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import lombok.Value;
import me.william278.husksync.bukkit.data.DataSerializer; import me.william278.husksync.bukkit.data.DataSerializer;
import net.william278.hslmigrator.HSLConverter; import net.william278.hslmigrator.HSLConverter;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
@ -44,7 +43,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static net.william278.husksync.config.Settings.DatabaseSettings; import static net.william278.husksync.config.Settings.DatabaseSettings;
@ -97,12 +95,14 @@ public class LegacyMigrator extends Migrator {
plugin.log(Level.INFO, "Downloading raw data from the legacy database (this might take a while)..."); plugin.log(Level.INFO, "Downloading raw data from the legacy database (this might take a while)...");
final List<LegacyData> dataToMigrate = Lists.newArrayList(); final List<LegacyData> dataToMigrate = Lists.newArrayList();
try (final Connection connection = connectionPool.getConnection()) { try (final Connection connection = connectionPool.getConnection()) {
try (final PreparedStatement statement = connection.prepareStatement( try (final PreparedStatement statement = connection.prepareStatement("""
"SELECT `uuid`, `username`, `inventory`, `ender_chest`, `health`, `max_health`, `health_scale`, `hunger`, `saturation`, `saturation_exhaustion`, `selected_slot`, `status_effects`, `total_experience`, `exp_level`, `exp_progress`, `game_mode`, `statistics`, `is_flying`, `advancements`, `location` " + SELECT `uuid`, `username`, `inventory`, `ender_chest`, `health`, `max_health`, `health_scale`, `hunger`, `saturation`, `saturation_exhaustion`, `selected_slot`, `status_effects`, `total_experience`, `exp_level`, `exp_progress`, `game_mode`, `statistics`, `is_flying`, `advancements`, `location`
"FROM `" + sourcePlayersTable + "` " + FROM `%source_players_table%`
"INNER JOIN `" + sourceDataTable + "` " + INNER JOIN `%source_data_table%`
"ON `" + sourcePlayersTable + "`.`id` = `" + sourceDataTable + "`.`player_id` " + ON `%source_players_table%`.`id` = `%source_data_table%`.`player_id`
"WHERE `username` IS NOT NULL;")) { WHERE `username` IS NOT NULL;
""".replaceAll(Pattern.quote("%source_players_table%"), sourcePlayersTable)
.replaceAll(Pattern.quote("%source_data_table%"), sourceDataTable))) {
try (final ResultSet resultSet = statement.executeQuery()) { try (final ResultSet resultSet = statement.executeQuery()) {
int playersMigrated = 0; int playersMigrated = 0;
while (resultSet.next()) { while (resultSet.next()) {
@ -142,11 +142,11 @@ public class LegacyMigrator extends Migrator {
final AtomicInteger playersConverted = new AtomicInteger(); final AtomicInteger playersConverted = new AtomicInteger();
dataToMigrate.forEach(data -> { dataToMigrate.forEach(data -> {
final DataSnapshot.Packed convertedData = data.toUserData(hslConverter, plugin); final DataSnapshot.Packed convertedData = data.toUserData(hslConverter, plugin);
plugin.getDatabase().ensureUser(data.getUser()); plugin.getDatabase().ensureUser(data.user());
try { try {
plugin.getDatabase().addSnapshot(data.getUser(), convertedData); plugin.getDatabase().addSnapshot(data.user(), convertedData);
} catch (Throwable e) { } catch (Throwable e) {
plugin.log(Level.SEVERE, "Failed to migrate legacy data for " + data.getUser().getUsername() + ": " + e.getMessage()); plugin.log(Level.SEVERE, "Failed to migrate legacy data for " + data.user().getUsername() + ": " + e.getMessage());
return; return;
} }
@ -167,53 +167,41 @@ public class LegacyMigrator extends Migrator {
@Override @Override
public void handleConfigurationCommand(@NotNull String[] args) { public void handleConfigurationCommand(@NotNull String[] args) {
if (args.length == 2) { if (args.length == 2) {
boolean $yield; if (switch (args[0].toLowerCase(Locale.ENGLISH)) {
switch (args[0].toLowerCase(Locale.ENGLISH)) { case "host" -> {
case "host": {
this.sourceHost = args[1]; this.sourceHost = args[1];
$yield = true; yield true;
break;
} }
case "port": { case "port" -> {
try { try {
this.sourcePort = Integer.parseInt(args[1]); this.sourcePort = Integer.parseInt(args[1]);
$yield = true; yield true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
$yield = false; yield false;
} }
break;
} }
case "username": { case "username" -> {
this.sourceUsername = args[1]; this.sourceUsername = args[1];
$yield = true; yield true;
break;
} }
case "password": { case "password" -> {
this.sourcePassword = args[1]; this.sourcePassword = args[1];
$yield = true; yield true;
break;
} }
case "database": { case "database" -> {
this.sourceDatabase = args[1]; this.sourceDatabase = args[1];
$yield = true; yield true;
break;
} }
case "players_table": { case "players_table" -> {
this.sourcePlayersTable = args[1]; this.sourcePlayersTable = args[1];
$yield = true; yield true;
break;
} }
case "data_table": { case "data_table" -> {
this.sourceDataTable = args[1]; this.sourceDataTable = args[1];
$yield = true; yield true;
break;
} }
default: { default -> false;
$yield = false; }) {
break;
}
}
if ($yield) {
plugin.log(Level.INFO, getHelpMenu()); plugin.log(Level.INFO, getHelpMenu());
plugin.log(Level.INFO, "Successfully set " + args[0] + " to " + plugin.log(Level.INFO, "Successfully set " + args[0] + " to " +
obfuscateDataString(args[1])); obfuscateDataString(args[1]));
@ -241,65 +229,59 @@ public class LegacyMigrator extends Migrator {
@NotNull @NotNull
@Override @Override
public String getHelpMenu() { public String getHelpMenu() {
return "=== HuskSync v1.x --> v3.x Migration Wizard =========\n" + return """
"This will migrate all user data from HuskSync v1.x to\n" + === HuskSync v1.x --> v3.x Migration Wizard =========
"HuskSync v3.x's new format. To perform the migration,\n" + This will migrate all user data from HuskSync v1.x to
"please follow the steps below carefully.\n" + HuskSync v3.x's new format. To perform the migration,
"\n" + please follow the steps below carefully.
"[!] Existing data in the database will be wiped. [!]\n" +
"\n" + [!] Existing data in the database will be wiped. [!]
"STEP 1] Please ensure no players are on any servers.\n" +
"\n" + STEP 1] Please ensure no players are on any servers.
"STEP 2] HuskSync will need to connect to the database\n" +
"used to hold the existing, legacy HuskSync data.\n" + STEP 2] HuskSync will need to connect to the database
"If this is the same database as the one you are\n" + used to hold the existing, legacy HuskSync data.
"currently using, you probably don't need to change\n" + If this is the same database as the one you are
"anything.\n" + currently using, you probably don't need to change
"Please check that the credentials below are the\n" + anything.
"correct credentials of the source legacy HuskSync\n" + Please check that the credentials below are the
"database.\n" + correct credentials of the source legacy HuskSync
"- host: " + obfuscateDataString(sourceHost) + "\n" + database.
"- port: " + sourcePort + "\n" + - host: %source_host%
"- username: " + obfuscateDataString(sourceUsername) + "\n" + - port: %source_port%
"- password: " + obfuscateDataString(sourcePassword) + "\n" + - username: %source_username%
"- database: " + sourceDatabase + "\n" + - password: %source_password%
"- players_table: " + sourcePlayersTable + "\n" + - database: %source_database%
"- data_table: " + sourceDataTable + "\n" + - players_table: %source_players_table%
"If any of these are not correct, please correct them\n" + - data_table: %source_data_table%
"using the command:\n" + If any of these are not correct, please correct them
"\"husksync migrate legacy set <parameter> <value>\"\n" + using the command:
"(e.g.: \"husksync migrate legacy set host 1.2.3.4\")\n" + "husksync migrate legacy set <parameter> <value>"
"\n" + (e.g.: "husksync migrate legacy set host 1.2.3.4")
"STEP 3] HuskSync will migrate data into the database\n" +
"tables configures in the config.yml file of this\n" + STEP 3] HuskSync will migrate data into the database
"server. Please make sure you're happy with this\n" + tables configures in the config.yml file of this
"before proceeding.\n" + server. Please make sure you're happy with this
"\n" + before proceeding.
"STEP 4] To start the migration, please run:\n" +
"\"husksync migrate legacy start\"\n"; STEP 4] To start the migration, please run:
"husksync migrate legacy start"
""".replaceAll(Pattern.quote("%source_host%"), obfuscateDataString(sourceHost))
.replaceAll(Pattern.quote("%source_port%"), Integer.toString(sourcePort))
.replaceAll(Pattern.quote("%source_username%"), obfuscateDataString(sourceUsername))
.replaceAll(Pattern.quote("%source_password%"), obfuscateDataString(sourcePassword))
.replaceAll(Pattern.quote("%source_database%"), sourceDatabase)
.replaceAll(Pattern.quote("%source_players_table%"), sourcePlayersTable)
.replaceAll(Pattern.quote("%source_data_table%"), sourceDataTable);
} }
@Value private record LegacyData(@NotNull User user,
private class LegacyData { @NotNull String serializedInventory, @NotNull String serializedEnderChest,
@NotNull User user; double health, double maxHealth, double healthScale, int hunger, float saturation,
@NotNull String serializedInventory; float saturationExhaustion, int selectedSlot, @NotNull String serializedPotionEffects,
@NotNull String serializedEnderChest; int totalExp, int expLevel, float expProgress,
double health; @NotNull String gameMode, @NotNull String serializedStatistics, boolean isFlying,
double maxHealth; @NotNull String serializedAdvancements, @NotNull String serializedLocation) {
double healthScale;
int hunger;
float saturation;
float saturationExhaustion;
int selectedSlot;
@NotNull String serializedPotionEffects;
int totalExp;
int expLevel;
float expProgress;
@NotNull String gameMode;
@NotNull String serializedStatistics;
boolean isFlying;
@NotNull String serializedAdvancements;
@NotNull String serializedLocation;
@NotNull @NotNull
public DataSnapshot.Packed toUserData(@NotNull HSLConverter converter, @NotNull HuskSync plugin) { public DataSnapshot.Packed toUserData(@NotNull HSLConverter converter, @NotNull HuskSync plugin) {
@ -337,7 +319,7 @@ public class LegacyMigrator extends Migrator {
.advancements(BukkitData.Advancements.from(converter .advancements(BukkitData.Advancements.from(converter
.deserializeAdvancementData(serializedAdvancements).stream() .deserializeAdvancementData(serializedAdvancements).stream()
.map(data -> Data.Advancements.Advancement.adapt(data.key(), data.criteriaMap())) .map(data -> Data.Advancements.Advancement.adapt(data.key(), data.criteriaMap()))
.collect(Collectors.toList()))) .toList()))
// Stats // Stats
.statistics(BukkitData.Statistics.from( .statistics(BukkitData.Statistics.from(

@ -21,7 +21,6 @@ package net.william278.husksync.migrator;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import lombok.Value;
import net.william278.husksync.BukkitHuskSync; import net.william278.husksync.BukkitHuskSync;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.data.BukkitData; import net.william278.husksync.data.BukkitData;
@ -105,14 +104,16 @@ public class MpdbMigrator extends Migrator {
plugin.log(Level.INFO, "Downloading raw data from the MySQLPlayerDataBridge database (this might take a while)..."); plugin.log(Level.INFO, "Downloading raw data from the MySQLPlayerDataBridge database (this might take a while)...");
final List<MpdbData> dataToMigrate = Lists.newArrayList(); final List<MpdbData> dataToMigrate = Lists.newArrayList();
try (final Connection connection = connectionPool.getConnection()) { try (final Connection connection = connectionPool.getConnection()) {
try (final PreparedStatement statement = connection.prepareStatement( try (final PreparedStatement statement = connection.prepareStatement("""
"SELECT `" + sourceInventoryTable + "`.`player_uuid`, `" + sourceInventoryTable + "`.`player_name`, `inventory`, `armor`, `enderchest`, `exp_lvl`, `exp`, `total_exp` " + SELECT `%source_inventory_table%`.`player_uuid`, `%source_inventory_table%`.`player_name`, `inventory`, `armor`, `enderchest`, `exp_lvl`, `exp`, `total_exp`
"FROM `" + sourceInventoryTable + "` " + FROM `%source_inventory_table%`
" INNER JOIN `" + sourceEnderChestTable + "` " + INNER JOIN `%source_ender_chest_table%`
" ON `" + sourceInventoryTable + "`.`player_uuid` = `" + sourceEnderChestTable + "`.`player_uuid` " + ON `%source_inventory_table%`.`player_uuid` = `%source_ender_chest_table%`.`player_uuid`
" INNER JOIN `" + sourceExperienceTable + "` " + INNER JOIN `%source_xp_table%`
" ON `" + sourceInventoryTable + "`.`player_uuid` = `" + sourceExperienceTable + "`.`player_uuid`;" ON `%source_inventory_table%`.`player_uuid` = `%source_xp_table%`.`player_uuid`;
)) { """.replaceAll(Pattern.quote("%source_inventory_table%"), sourceInventoryTable)
.replaceAll(Pattern.quote("%source_ender_chest_table%"), sourceEnderChestTable)
.replaceAll(Pattern.quote("%source_xp_table%"), sourceExperienceTable))) {
try (final ResultSet resultSet = statement.executeQuery()) { try (final ResultSet resultSet = statement.executeQuery()) {
int playersMigrated = 0; int playersMigrated = 0;
while (resultSet.next()) { while (resultSet.next()) {
@ -140,8 +141,8 @@ public class MpdbMigrator extends Migrator {
final AtomicInteger playersConverted = new AtomicInteger(); final AtomicInteger playersConverted = new AtomicInteger();
dataToMigrate.forEach(data -> { dataToMigrate.forEach(data -> {
final DataSnapshot.Packed convertedData = data.toUserData(mpdbConverter, plugin); final DataSnapshot.Packed convertedData = data.toUserData(mpdbConverter, plugin);
plugin.getDatabase().ensureUser(data.getUser()); plugin.getDatabase().ensureUser(data.user());
plugin.getDatabase().addSnapshot(data.getUser(), convertedData); plugin.getDatabase().addSnapshot(data.user(), convertedData);
playersConverted.getAndIncrement(); playersConverted.getAndIncrement();
if (playersConverted.get() % 50 == 0) { if (playersConverted.get() % 50 == 0) {
plugin.log(Level.INFO, "Converted MySQLPlayerDataBridge data for " + playersConverted + " players..."); plugin.log(Level.INFO, "Converted MySQLPlayerDataBridge data for " + playersConverted + " players...");
@ -159,57 +160,45 @@ public class MpdbMigrator extends Migrator {
@Override @Override
public void handleConfigurationCommand(@NotNull String[] args) { public void handleConfigurationCommand(@NotNull String[] args) {
if (args.length == 2) { if (args.length == 2) {
boolean $yield; if (switch (args[0].toLowerCase(Locale.ENGLISH)) {
switch (args[0].toLowerCase(Locale.ENGLISH)) { case "host" -> {
case "host": {
this.sourceHost = args[1]; this.sourceHost = args[1];
$yield = true; yield true;
break;
} }
case "port": { case "port" -> {
try { try {
this.sourcePort = Integer.parseInt(args[1]); this.sourcePort = Integer.parseInt(args[1]);
$yield = true; yield true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
$yield = false; yield false;
} }
break;
} }
case "username": { case "username" -> {
this.sourceUsername = args[1]; this.sourceUsername = args[1];
$yield = true; yield true;
break;
} }
case "password": { case "password" -> {
this.sourcePassword = args[1]; this.sourcePassword = args[1];
$yield = true; yield true;
break;
} }
case "database": { case "database" -> {
this.sourceDatabase = args[1]; this.sourceDatabase = args[1];
$yield = true; yield true;
break;
} }
case "inventory_table": { case "inventory_table" -> {
this.sourceInventoryTable = args[1]; this.sourceInventoryTable = args[1];
$yield = true; yield true;
break;
} }
case "ender_chest_table": { case "ender_chest_table" -> {
this.sourceEnderChestTable = args[1]; this.sourceEnderChestTable = args[1];
$yield = true; yield true;
break;
} }
case "experience_table": { case "experience_table" -> {
this.sourceExperienceTable = args[1]; this.sourceExperienceTable = args[1];
$yield = true; yield true;
break;
} }
default: { default -> false;
$yield = false; }) {
}
}
if ($yield) {
plugin.log(Level.INFO, getHelpMenu()); plugin.log(Level.INFO, getHelpMenu());
plugin.log(Level.INFO, "Successfully set " + args[0] + " to " + plugin.log(Level.INFO, "Successfully set " + args[0] + " to " +
obfuscateDataString(args[1])); obfuscateDataString(args[1]));
@ -237,81 +226,77 @@ public class MpdbMigrator extends Migrator {
@NotNull @NotNull
@Override @Override
public String getHelpMenu() { public String getHelpMenu() {
return "=== MySQLPlayerDataBridge Migration Wizard ==========\n" + return """
"NOTE: This migrator currently WORKS WITH MPDB version\n" + === MySQLPlayerDataBridge Migration Wizard ==========
"v4.9.2 and below!\n" + NOTE: This migrator currently WORKS WITH MPDB version
"\n" + v4.9.2 and below!
"This will migrate inventories, ender chests and XP\n" +
"from the MySQLPlayerDataBridge plugin to HuskSync.\n" + This will migrate inventories, ender chests and XP
"\n" + from the MySQLPlayerDataBridge plugin to HuskSync.
"To prevent excessive migration times, other non-vital\n" +
"data will not be transferred.\n" + To prevent excessive migration times, other non-vital
"\n" + data will not be transferred.
"[!] Existing data in the database will be wiped. [!]\n" +
"\n" + [!] Existing data in the database will be wiped. [!]
"STEP 1] Please ensure no players are on any servers.\n" +
"\n" + STEP 1] Please ensure no players are on any servers.
"STEP 2] HuskSync will need to connect to the database\n" +
"used to hold the source MySQLPlayerDataBridge data.\n" + STEP 2] HuskSync will need to connect to the database
"Please check these database parameters are OK:\n" + used to hold the source MySQLPlayerDataBridge data.
"- host: " + obfuscateDataString(sourceHost) + "\n" + Please check these database parameters are OK:
"- port: " + sourcePort + "\n" + - host: %source_host%
"- username: " + obfuscateDataString(sourceUsername) + "\n" + - port: %source_port%
"- password: " + obfuscateDataString(sourcePassword) + "\n" + - username: %source_username%
"- database: " + sourceDatabase + "\n" + - password: %source_password%
"- inventory_table: " + sourceInventoryTable + "\n" + - database: %source_database%
"- ender_chest_table: " + sourceEnderChestTable + "\n" + - inventory_table: %source_inventory_table%
"- experience_table: " + sourceExperienceTable + "\n" + - ender_chest_table: %source_ender_chest_table%
"If any of these are not correct, please correct them\n" + - experience_table: %source_xp_table%
"using the command:\n" + If any of these are not correct, please correct them
"\"husksync migrate mpdb set <parameter> <value>\"\n" + using the command:
"(e.g.: \"husksync migrate set mpdb host 1.2.3.4\")\n" + "husksync migrate mpdb set <parameter> <value>"
"\n" + (e.g.: "husksync migrate set mpdb host 1.2.3.4")
"STEP 3] HuskSync will migrate data into the database\n" +
"tables configures in the config.yml file of this\n" + STEP 3] HuskSync will migrate data into the database
"server. Please make sure you're happy with this\n" + tables configures in the config.yml file of this
"before proceeding.\n" + server. Please make sure you're happy with this
"\n" + before proceeding.
"STEP 4] To start the migration, please run:\n" +
"\"husksync migrate start mpdb\"\n" + STEP 4] To start the migration, please run:
"\n" + "husksync migrate start mpdb"
"NOTE: This migrator currently WORKS WITH MPDB version\n" +
"v4.9.2 and below!\n"; NOTE: This migrator currently WORKS WITH MPDB version
v4.9.2 and below!
""".replaceAll(Pattern.quote("%source_host%"), obfuscateDataString(sourceHost))
.replaceAll(Pattern.quote("%source_port%"), Integer.toString(sourcePort))
.replaceAll(Pattern.quote("%source_username%"), obfuscateDataString(sourceUsername))
.replaceAll(Pattern.quote("%source_password%"), obfuscateDataString(sourcePassword))
.replaceAll(Pattern.quote("%source_database%"), sourceDatabase)
.replaceAll(Pattern.quote("%source_inventory_table%"), sourceInventoryTable)
.replaceAll(Pattern.quote("%source_ender_chest_table%"), sourceEnderChestTable)
.replaceAll(Pattern.quote("%source_xp_table%"), sourceExperienceTable);
} }
/** /**
* Represents data exported from the MySQLPlayerDataBridge source database * Represents data exported from the MySQLPlayerDataBridge source database
*
* @param user The user whose data is being migrated
* @param serializedInventory The serialized inventory data
* @param serializedArmor The serialized armor data
* @param serializedEnderChest The serialized ender chest data
* @param expLevel The player's current XP level
* @param expProgress The player's current XP progress
* @param totalExp The player's total XP score
*/ */
@Value private record MpdbData(
private static class MpdbData { @NotNull User user,
/** @NotNull String serializedInventory,
* The user whose data is being migrated @NotNull String serializedArmor,
*/ @NotNull String serializedEnderChest,
@NotNull User user; int expLevel,
/** float expProgress,
* The serialized inventory data int totalExp
*/ ) {
@NotNull String serializedInventory;
/**
* The serialized armor data
*/
@NotNull String serializedArmor;
/**
* The serialized ender chest data
*/
@NotNull String serializedEnderChest;
/**
* The player's current XP level
*/
int expLevel;
/**
* The player's current XP progress
*/
float expProgress;
/**
* The player's total XP score
*/
int totalExp;
/** /**
* Converts exported MySQLPlayerDataBridge data into HuskSync's {@link DataSnapshot} object format * Converts exported MySQLPlayerDataBridge data into HuskSync's {@link DataSnapshot} object format

@ -62,7 +62,7 @@ public class BukkitUser extends OnlineUser implements BukkitUserDataHolder {
} }
@Override @Override
@Deprecated @Deprecated(since = "3.6.7")
public void sendToast(@NotNull MineDown title, @NotNull MineDown description, public void sendToast(@NotNull MineDown title, @NotNull MineDown description,
@NotNull String iconMaterial, @NotNull String backgroundType) { @NotNull String iconMaterial, @NotNull String backgroundType) {
plugin.log(Level.WARNING, "Toast notifications are deprecated. " + plugin.log(Level.WARNING, "Toast notifications are deprecated. " +

@ -77,7 +77,7 @@ public class BukkitLegacyConverter extends LegacyConverter {
@NotNull @NotNull
private Map<Identifier, Data> readStatusData(@NotNull JSONObject object) { private Map<Identifier, Data> readStatusData(@NotNull JSONObject object) {
if (!object.has("status_data")) { if (!object.has("status_data")) {
return Collections.emptyMap(); return Map.of();
} }
final JSONObject status = object.getJSONObject("status_data"); final JSONObject status = object.getJSONObject("status_data");

@ -69,7 +69,7 @@ public interface BukkitMapPersister {
if (!getPlugin().getSettings().getSynchronization().isPersistLockedMaps()) { if (!getPlugin().getSettings().getSynchronization().isPersistLockedMaps()) {
return items; return items;
} }
return private$forEachMap(items, map -> this.persistMapView(map, delegateRenderer)); return forEachMap(items, map -> this.persistMapView(map, delegateRenderer));
} }
/** /**
@ -83,26 +83,21 @@ public interface BukkitMapPersister {
if (!getPlugin().getSettings().getSynchronization().isPersistLockedMaps()) { if (!getPlugin().getSettings().getSynchronization().isPersistLockedMaps()) {
return items; return items;
} }
return private$forEachMap(items, this::private$applyMapView); return forEachMap(items, this::applyMapView);
} }
// Perform an operation on each map in an array of ItemStacks // Perform an operation on each map in an array of ItemStacks
@NotNull @NotNull
default ItemStack[] private$forEachMap(ItemStack[] items, @NotNull Function<ItemStack, ItemStack> function) { private ItemStack[] forEachMap(ItemStack[] items, @NotNull Function<ItemStack, ItemStack> function) {
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
final ItemStack item = items[i]; final ItemStack item = items[i];
if (item == null) { if (item == null) {
continue; continue;
} }
if (MaterialUtil.isFilledMap(item.getType()) && item.hasItemMeta()) { if (item.getType() == Material.FILLED_MAP && item.hasItemMeta()) {
items[i] = function.apply(item); items[i] = function.apply(item);
} else if (item.getItemMeta() instanceof BlockStateMeta && } else if (item.getItemMeta() instanceof BlockStateMeta b && b.getBlockState() instanceof ShulkerBox box) {
((BlockStateMeta) item.getItemMeta()).getBlockState() instanceof ShulkerBox forEachMap(box.getInventory().getContents(), function);
) {
BlockStateMeta b = (BlockStateMeta) item.getItemMeta();
ShulkerBox box = (ShulkerBox) b.getBlockState();
private$forEachMap(box.getInventory().getContents(), function);
b.setBlockState(box); b.setBlockState(box);
} }
} }
@ -110,7 +105,7 @@ public interface BukkitMapPersister {
} }
@NotNull @NotNull
default ItemStack persistMapView(@NotNull ItemStack map, @NotNull Player delegateRenderer) { private ItemStack persistMapView(@NotNull ItemStack map, @NotNull Player delegateRenderer) {
final MapMeta meta = Objects.requireNonNull((MapMeta) map.getItemMeta()); final MapMeta meta = Objects.requireNonNull((MapMeta) map.getItemMeta());
if (!meta.hasMapView()) { if (!meta.hasMapView()) {
return map; return map;
@ -144,7 +139,7 @@ public interface BukkitMapPersister {
} }
@NotNull @NotNull
default ItemStack private$applyMapView(@NotNull ItemStack map) { private ItemStack applyMapView(@NotNull ItemStack map) {
final MapMeta meta = Objects.requireNonNull((MapMeta) map.getItemMeta()); final MapMeta meta = Objects.requireNonNull((MapMeta) map.getItemMeta());
NBT.get(map, nbt -> { NBT.get(map, nbt -> {
if (!nbt.hasTag(MAP_DATA_KEY)) { if (!nbt.hasTag(MAP_DATA_KEY)) {
@ -191,8 +186,8 @@ public interface BukkitMapPersister {
} }
// Add a renderer to the map with the data and save to file // Add a renderer to the map with the data and save to file
final MapView view = private$generateRenderedMap(canvasData); final MapView view = generateRenderedMap(canvasData);
final String worldUid = private$getDefaultMapWorld().getUID().toString(); final String worldUid = getDefaultMapWorld().getUID().toString();
meta.setMapView(view); meta.setMapView(view);
map.setItemMeta(meta); map.setItemMeta(meta);
saveMapToFile(canvasData, view.getId()); saveMapToFile(canvasData, view.getId());
@ -209,7 +204,7 @@ public interface BukkitMapPersister {
} }
default void renderMapFromFile(@NotNull MapView view) { default void renderMapFromFile(@NotNull MapView view) {
final File mapFile = new File(private$getMapCacheFolder(), view.getId() + ".dat"); final File mapFile = new File(getMapCacheFolder(), view.getId() + ".dat");
if (!mapFile.exists()) { if (!mapFile.exists()) {
return; return;
} }
@ -237,7 +232,7 @@ public interface BukkitMapPersister {
default void saveMapToFile(@NotNull MapData data, int id) { default void saveMapToFile(@NotNull MapData data, int id) {
getPlugin().runAsync(() -> { getPlugin().runAsync(() -> {
final File mapFile = new File(private$getMapCacheFolder(), id + ".dat"); final File mapFile = new File(getMapCacheFolder(), id + ".dat");
if (mapFile.exists()) { if (mapFile.exists()) {
return; return;
} }
@ -253,7 +248,7 @@ public interface BukkitMapPersister {
} }
@NotNull @NotNull
default File private$getMapCacheFolder() { private File getMapCacheFolder() {
final File mapCache = new File(getPlugin().getDataFolder(), "maps"); final File mapCache = new File(getPlugin().getDataFolder(), "maps");
if (!mapCache.exists() && !mapCache.mkdirs()) { if (!mapCache.exists() && !mapCache.mkdirs()) {
getPlugin().log(Level.WARNING, "Failed to create maps folder"); getPlugin().log(Level.WARNING, "Failed to create maps folder");
@ -263,8 +258,8 @@ public interface BukkitMapPersister {
// Sets the renderer of a map, and returns the generated MapView // Sets the renderer of a map, and returns the generated MapView
@NotNull @NotNull
default MapView private$generateRenderedMap(@NotNull MapData canvasData) { private MapView generateRenderedMap(@NotNull MapData canvasData) {
final MapView view = Bukkit.createMap(private$getDefaultMapWorld()); final MapView view = Bukkit.createMap(getDefaultMapWorld());
view.getRenderers().clear(); view.getRenderers().clear();
// Create a new map view renderer with the map data color at each pixel // Create a new map view renderer with the map data color at each pixel
@ -280,7 +275,7 @@ public interface BukkitMapPersister {
} }
@NotNull @NotNull
static World private$getDefaultMapWorld() { private static World getDefaultMapWorld() {
final World world = Bukkit.getWorlds().get(0); final World world = Bukkit.getWorlds().get(0);
if (world == null) { if (world == null) {
throw new IllegalStateException("No worlds are loaded on the server!"); throw new IllegalStateException("No worlds are loaded on the server!");
@ -323,86 +318,35 @@ public interface BukkitMapPersister {
cursors.removeCursor(cursors.getCursor(0)); cursors.removeCursor(cursors.getCursor(0));
} }
canvasData.getBanners().forEach(banner -> cursors.addCursor(private$createBannerCursor(banner))); canvasData.getBanners().forEach(banner -> cursors.addCursor(createBannerCursor(banner)));
canvas.setCursors(cursors); canvas.setCursors(cursors);
} }
} }
@NotNull @NotNull
static MapCursor private$createBannerCursor(@NotNull MapBanner banner) { private static MapCursor createBannerCursor(@NotNull MapBanner banner) {
MapCursor.Type type;
switch (banner.getColor().toLowerCase(Locale.ENGLISH)) {
case "white": {
type = MapCursor.Type.BANNER_WHITE;
break;
}
case "orange": {
type = MapCursor.Type.BANNER_ORANGE;
break;
}
case "magenta": {
type = MapCursor.Type.BANNER_MAGENTA;
break;
}
case "light_blue": {
type = MapCursor.Type.BANNER_LIGHT_BLUE;
break;
}
case "yellow": {
type = MapCursor.Type.BANNER_YELLOW;
break;
}
case "lime": {
type = MapCursor.Type.BANNER_LIME;
break;
}
case "pink": {
type = MapCursor.Type.BANNER_PINK;
break;
}
case "gray": {
type = MapCursor.Type.BANNER_GRAY;
break;
}
case "light_gray": {
type = MapCursor.Type.BANNER_LIGHT_GRAY;
break;
}
case "cyan": {
type = MapCursor.Type.BANNER_CYAN;
break;
}
case "purple": {
type = MapCursor.Type.BANNER_PURPLE;
break;
}
case "blue": {
type = MapCursor.Type.BANNER_BLUE;
break;
}
case "brown": {
type = MapCursor.Type.BANNER_BROWN;
break;
}
case "green": {
type = MapCursor.Type.BANNER_GREEN;
break;
}
case "red": {
type = MapCursor.Type.BANNER_RED;
break;
}
default: {
type = MapCursor.Type.BANNER_BLACK;
break;
}
}
return new MapCursor( return new MapCursor(
(byte) banner.getPosition().getX(), (byte) banner.getPosition().getX(),
(byte) banner.getPosition().getZ(), (byte) banner.getPosition().getZ(),
(byte) 8, // Always rotate banners upright (byte) 8, // Always rotate banners upright
type, switch (banner.getColor().toLowerCase(Locale.ENGLISH)) {
case "white" -> MapCursor.Type.BANNER_WHITE;
case "orange" -> MapCursor.Type.BANNER_ORANGE;
case "magenta" -> MapCursor.Type.BANNER_MAGENTA;
case "light_blue" -> MapCursor.Type.BANNER_LIGHT_BLUE;
case "yellow" -> MapCursor.Type.BANNER_YELLOW;
case "lime" -> MapCursor.Type.BANNER_LIME;
case "pink" -> MapCursor.Type.BANNER_PINK;
case "gray" -> MapCursor.Type.BANNER_GRAY;
case "light_gray" -> MapCursor.Type.BANNER_LIGHT_GRAY;
case "cyan" -> MapCursor.Type.BANNER_CYAN;
case "purple" -> MapCursor.Type.BANNER_PURPLE;
case "blue" -> MapCursor.Type.BANNER_BLUE;
case "brown" -> MapCursor.Type.BANNER_BROWN;
case "green" -> MapCursor.Type.BANNER_GREEN;
case "red" -> MapCursor.Type.BANNER_RED;
default -> MapCursor.Type.BANNER_BLACK;
},
true, true,
banner.getText().isEmpty() ? null : banner.getText() banner.getText().isEmpty() ? null : banner.getText()
); );
@ -465,14 +409,11 @@ public interface BukkitMapPersister {
@NotNull @NotNull
private String getDimension() { private String getDimension() {
if (mapView.getWorld() == null) { return mapView.getWorld() != null ? switch (mapView.getWorld().getEnvironment()) {
return "minecraft:overworld"; case NETHER -> "minecraft:the_nether";
} case THE_END -> "minecraft:the_end";
switch (mapView.getWorld().getEnvironment()) { default -> "minecraft:overworld";
case NETHER: return "minecraft:the_nether"; } : "minecraft:overworld";
case THE_END: return "minecraft:the_end";
default: return "minecraft:overworld";
}
} }
/** /**
@ -501,7 +442,7 @@ public interface BukkitMapPersister {
} }
} catch (Throwable ignored) { } catch (Throwable ignored) {
} }
return MapData.fromPixels(pixels, getDimension(), (byte) 2, banners, Collections.emptyList()); return MapData.fromPixels(pixels, getDimension(), (byte) 2, banners, List.of());
} }
} }

@ -1,58 +0,0 @@
/*
* This file is part of HuskSync, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.husksync.util;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import net.william278.husksync.util.ref.RefUtil;
import org.bukkit.Material;
import java.lang.invoke.MethodHandle;
@UtilityClass
public class MaterialUtil {
private static final MethodHandle v$isAirMethod = RefUtil.bootstrapVirtualMethod("Lorg/bukkit/Material;isAir()Z");
@SneakyThrows
public static boolean isAir(Material $this) {
if (v$isAirMethod != null) {
return (boolean) v$isAirMethod.invoke($this);
}
switch ($this.name()) {
case "AIR":
case "CAVE_AIR":
case "VOID_AIR":
case "LEGACY_AIR":
return true;
default:
return false;
}
}
public static boolean isFilledMap(Material $this) {
switch ($this.name()) {
case "FILLED_MAP":
case "LEGACY_MAP":
return true;
default:
return false;
}
}
}

@ -1,220 +0,0 @@
/*
* This file is part of HuskSync, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.husksync.util.ref;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
public final class RefUtil {
private RefUtil() {
throw new UnsupportedOperationException("This class cannot be instantiated");
}
private static final MethodHandles.Lookup lookup = MethodHandles.lookup();
public static MethodHandle bootstrapStaticMethod(String methodDesc) {
String[] descParts = splitMethodDesc(methodDesc);
Class<?> owner;
try {
owner = Class.forName(descParts[0].replace('/', '.'));
} catch (ClassNotFoundException e) {
return null;
}
MethodType methodType;
try {
methodType = MethodType.fromMethodDescriptorString(descParts[2], owner.getClassLoader());
} catch (TypeNotPresentException e) {
return null;
}
try {
return lookup.findStatic(owner, descParts[1], methodType);
} catch (NoSuchMethodException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static MethodHandle bootstrapVirtualMethod(String methodDesc) {
String[] descParts = splitMethodDesc(methodDesc);
Class<?> owner;
try {
owner = Class.forName(descParts[0].replace('/', '.'));
} catch (ClassNotFoundException e) {
return null;
}
MethodType methodType;
try {
methodType = MethodType.fromMethodDescriptorString(descParts[2], owner.getClassLoader());
} catch (TypeNotPresentException e) {
return null;
}
try {
return lookup.findVirtual(owner, descParts[1], methodType);
} catch (NoSuchMethodException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static String[] splitMethodDesc(String methodDesc) {
if (methodDesc.length() < 5) { // L;()V
throw new IllegalArgumentException("Invalid method descriptor: " + methodDesc);
}
int descSplit = methodDesc.indexOf(';');
if (descSplit == -1) {
throw new IllegalArgumentException("Invalid method descriptor: " + methodDesc);
}
int argsStart = methodDesc.indexOf('(');
if (argsStart == -1) {
throw new IllegalArgumentException("Invalid method descriptor: " + methodDesc);
}
return new String[] {
methodDesc.substring(1, descSplit), // java/lang/Object
methodDesc.substring(descSplit + 1, argsStart), // method name
methodDesc.substring(argsStart) // (Ljava/lang/Object;)V
};
}
public static <T extends Throwable> RuntimeException sneakyThrow(Throwable t) throws T {
throw (T) t;
}
public static MethodHandle bootstrapStaticFieldGet(String fieldDesc) {
String[] descParts = splitFieldDesc(fieldDesc);
Class<?> owner;
try {
owner = Class.forName(descParts[0].replace('/', '.'));
} catch (ClassNotFoundException e) {
return null;
}
Class<?> fieldType;
try {
fieldType = MethodType.fromMethodDescriptorString("()" + descParts[2], owner.getClassLoader()).returnType();
} catch (TypeNotPresentException e) {
return null;
}
try {
return lookup.findStaticGetter(owner, descParts[1], fieldType);
} catch (NoSuchFieldException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static MethodHandle bootstrapStaticFieldSet(String fieldDesc) {
String[] descParts = splitFieldDesc(fieldDesc);
Class<?> owner;
try {
owner = Class.forName(descParts[0].replace('/', '.'));
} catch (ClassNotFoundException e) {
return null;
}
Class<?> fieldType;
try {
fieldType = MethodType.fromMethodDescriptorString("()" + descParts[2], owner.getClassLoader()).returnType();
} catch (TypeNotPresentException e) {
return null;
}
try {
return lookup.findStaticSetter(owner, descParts[1], fieldType);
} catch (NoSuchFieldException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static MethodHandle bootstrapVirtualFieldGet(String fieldDesc) {
String[] descParts = splitFieldDesc(fieldDesc);
Class<?> owner;
try {
owner = Class.forName(descParts[0].replace('/', '.'));
} catch (ClassNotFoundException e) {
return null;
}
Class<?> fieldType;
try {
fieldType = MethodType.fromMethodDescriptorString("()" + descParts[2], owner.getClassLoader()).returnType();
} catch (TypeNotPresentException e) {
return null;
}
try {
return lookup.findGetter(owner, descParts[1], fieldType);
} catch (NoSuchFieldException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static MethodHandle bootstrapVirtualFieldSet(String fieldDesc) {
String[] descParts = splitFieldDesc(fieldDesc);
Class<?> owner;
try {
owner = Class.forName(descParts[0].replace('/', '.'));
} catch (ClassNotFoundException e) {
return null;
}
Class<?> fieldType;
try {
fieldType = MethodType.fromMethodDescriptorString("()" + descParts[2], owner.getClassLoader()).returnType();
} catch (TypeNotPresentException e) {
return null;
}
try {
return lookup.findSetter(owner, descParts[1], fieldType);
} catch (NoSuchFieldException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static String[] splitFieldDesc(String fieldDesc) {
if (fieldDesc.length() < 3) { // L;:
throw new IllegalArgumentException("Invalid field descriptor: " + fieldDesc);
}
int descSplit = fieldDesc.indexOf(';');
if (descSplit == -1) {
throw new IllegalArgumentException("Invalid field descriptor: " + fieldDesc);
}
int argsStart = fieldDesc.indexOf(':');
if (argsStart == -1) {
throw new IllegalArgumentException("Invalid field descriptor: " + fieldDesc);
}
return new String[] {
fieldDesc.substring(1, descSplit), // java/lang/Object
fieldDesc.substring(descSplit + 1, argsStart), // field name
fieldDesc.substring(argsStart + 1) // Ljava/lang/Object;
};
}
}

@ -1,13 +1,20 @@
name: 'HuskSync' name: 'HuskSync'
version: '${version}' version: '${version}'
main: 'net.william278.husksync.BukkitHuskSync' main: 'net.william278.husksync.BukkitHuskSync'
api-version: 1.13 api-version: 1.17
author: 'William278, InkerBot' author: 'William278'
description: '${description}' description: '${description}'
website: 'https://git.inker.bot/HuskLegacy/HuskSync' website: 'https://william278.net'
folia-supported: true folia-supported: true
softdepend: softdepend:
- 'packetevents' - 'packetevents'
- 'ProtocolLib' - 'ProtocolLib'
- 'MysqlPlayerDataBridge' - 'MysqlPlayerDataBridge'
- 'Plan' - 'Plan'
libraries:
- 'redis.clients:jedis:${jedis_version}'
- 'com.mysql:mysql-connector-j:${mysql_driver_version}'
- 'org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}'
- 'org.postgresql:postgresql:${postgres_driver_version}'
- 'org.mongodb:mongodb-driver-sync:${mongodb_driver_version}'
- 'org.xerial.snappy:snappy-java:${snappy_version}'

@ -3,26 +3,26 @@ plugins {
} }
dependencies { dependencies {
api 'org.inksnow.cputil:logger:1.13'
api 'org.inksnow.cputil:database:1.13'
api 'commons-io:commons-io:2.16.1' api 'commons-io:commons-io:2.16.1'
api 'org.apache.commons:commons-text:1.12.0' api 'org.apache.commons:commons-text:1.12.0'
api 'de.themoep:minedown-adventure:1.7.3-SNAPSHOT' api 'net.william278:minedown:1.8.2'
api 'org.json:json:20240303' api 'org.json:json:20240303'
api 'com.google.code.gson:gson:2.11.0' api 'com.google.code.gson:gson:2.11.0'
api 'com.fatboyindustrial.gson-javatime-serialisers:gson-javatime-serialisers:1.1.2' api 'com.fatboyindustrial.gson-javatime-serialisers:gson-javatime-serialisers:1.1.2'
api 'org.inksnow.husk:configlib-yaml:4.5.4' api 'de.exlll:configlib-yaml:4.5.0'
api 'org.inksnow.husk:paginedown:1.1.3-ac18d11' api 'net.william278:paginedown:1.1.2'
api 'org.inksnow.husk:desertwell:2.0.5-9962d59:all' api 'net.william278:DesertWell:2.0.4'
api 'com.mojang:brigadier:1.1.8' api('com.zaxxer:HikariCP:5.1.0') {
exclude module: 'slf4j-api'
}
compileOnly 'org.inksnow.husk.uniform:uniform-common:1.2.1-ad25f16' compileOnly 'net.william278.uniform:uniform-common:1.2.1'
compileOnly 'com.mojang:brigadier:1.1.8'
compileOnly 'org.projectlombok:lombok:1.18.34' compileOnly 'org.projectlombok:lombok:1.18.34'
compileOnly 'org.jetbrains:annotations:24.1.0' compileOnly 'org.jetbrains:annotations:24.1.0'
compileOnly 'net.kyori:adventure-api:4.17.0' compileOnly 'net.kyori:adventure-api:4.17.0'
compileOnly 'net.kyori:adventure-platform-api:4.3.4' compileOnly 'net.kyori:adventure-platform-api:4.3.4'
compileOnly 'com.google.guava:guava:33.2.1-jre' compileOnly 'com.google.guava:guava:33.3.0-jre'
compileOnly 'com.github.plan-player-analytics:Plan:5.5.2272' compileOnly 'com.github.plan-player-analytics:Plan:5.5.2272'
compileOnly "redis.clients:jedis:$jedis_version" compileOnly "redis.clients:jedis:$jedis_version"
compileOnly "com.mysql:mysql-connector-j:$mysql_driver_version" compileOnly "com.mysql:mysql-connector-j:$mysql_driver_version"
@ -33,9 +33,9 @@ dependencies {
testImplementation "redis.clients:jedis:$jedis_version" testImplementation "redis.clients:jedis:$jedis_version"
testImplementation "org.xerial.snappy:snappy-java:$snappy_version" testImplementation "org.xerial.snappy:snappy-java:$snappy_version"
testImplementation 'com.google.guava:guava:33.2.1-jre' testImplementation 'com.google.guava:guava:33.3.0-jre'
testImplementation 'com.github.plan-player-analytics:Plan:5.5.2272' testImplementation 'com.github.plan-player-analytics:Plan:5.5.2272'
testCompileOnly 'org.inksnow.husk:configlib-yaml:4.5.4' testCompileOnly 'de.exlll:configlib-yaml:4.5.0'
testCompileOnly 'org.jetbrains:annotations:24.1.0' testCompileOnly 'org.jetbrains:annotations:24.1.0'
annotationProcessor 'org.projectlombok:lombok:1.18.34' annotationProcessor 'org.projectlombok:lombok:1.18.34'

@ -196,7 +196,7 @@ public interface HuskSync extends Task.Supplier, EventDispatcher, ConfigProvider
// Get the debug log message format // Get the debug log message format
@NotNull @NotNull
default String getDebugString(@NotNull String message) { private String getDebugString(@NotNull String message) {
return String.format("[DEBUG] [%s] %s", new SimpleDateFormat("mm:ss.SSS").format(new Date()), message); return String.format("[DEBUG] [%s] %s", new SimpleDateFormat("mm:ss.SSS").format(new Date()), message);
} }
@ -327,16 +327,16 @@ public interface HuskSync extends Task.Supplier, EventDispatcher, ConfigProvider
*/ */
final class FailedToLoadException extends IllegalStateException { final class FailedToLoadException extends IllegalStateException {
private static final String FORMAT = private static final String FORMAT = """
"HuskSync has failed to load! The plugin will not be enabled and no data will be synchronized.\n" + HuskSync has failed to load! The plugin will not be enabled and no data will be synchronized.
"Please make sure the plugin has been setup correctly (https://william278.net/docs/husksync/setup):\n" + Please make sure the plugin has been setup correctly (https://william278.net/docs/husksync/setup):
"\n" +
"1) Make sure you've entered your MySQL, MariaDB or MongoDB database details correctly in config.yml\n" + 1) Make sure you've entered your MySQL, MariaDB or MongoDB database details correctly in config.yml
"2) Make sure your Redis server details are also correct in config.yml\n" + 2) Make sure your Redis server details are also correct in config.yml
"3) Make sure your config is up-to-date (https://william278.net/docs/husksync/config-file)\n" + 3) Make sure your config is up-to-date (https://william278.net/docs/husksync/config-file)
"4) Check the error below for more details\n" + 4) Check the error below for more details
"\n" +
"Caused by: %s"; Caused by: %s""";
FailedToLoadException(@NotNull String message, @NotNull Throwable cause) { FailedToLoadException(@NotNull String message, @NotNull Throwable cause) {
super(String.format(FORMAT, message), cause); super(String.format(FORMAT, message), cause);

@ -29,19 +29,15 @@ import net.william278.husksync.data.Serializer;
import net.william278.husksync.sync.DataSyncer; import net.william278.husksync.sync.DataSyncer;
import net.william278.husksync.user.OnlineUser; import net.william278.husksync.user.OnlineUser;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.OptionalUtil;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Formatter;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* The common implementation of the HuskSync API, containing cross-platform API calls. * The common implementation of the HuskSync API, containing cross-platform API calls.
@ -142,7 +138,7 @@ public class HuskSyncAPI {
public CompletableFuture<Optional<DataSnapshot.Unpacked>> getCurrentData(@NotNull User user) { public CompletableFuture<Optional<DataSnapshot.Unpacked>> getCurrentData(@NotNull User user) {
return plugin.getRedisManager() return plugin.getRedisManager()
.getUserData(UUID.randomUUID(), user) .getUserData(UUID.randomUUID(), user)
.thenApply(data -> OptionalUtil.or(data, () -> plugin.getDatabase().getLatestSnapshot(user))) .thenApply(data -> data.or(() -> plugin.getDatabase().getLatestSnapshot(user)))
.thenApply(data -> data.map(snapshot -> snapshot.unpack(plugin))); .thenApply(data -> data.map(snapshot -> snapshot.unpack(plugin)));
} }
@ -158,8 +154,8 @@ public class HuskSyncAPI {
*/ */
public void setCurrentData(@NotNull User user, @NotNull DataSnapshot data) { public void setCurrentData(@NotNull User user, @NotNull DataSnapshot data) {
plugin.runAsync(() -> { plugin.runAsync(() -> {
final DataSnapshot.Packed packed = data instanceof DataSnapshot.Unpacked final DataSnapshot.Packed packed = data instanceof DataSnapshot.Unpacked unpacked
? ((DataSnapshot.Unpacked) data).pack(plugin) : (DataSnapshot.Packed) data; ? unpacked.pack(plugin) : (DataSnapshot.Packed) data;
addSnapshot(user, packed); addSnapshot(user, packed);
plugin.getRedisManager().sendUserDataUpdate(user, packed); plugin.getRedisManager().sendUserDataUpdate(user, packed);
}); });
@ -194,7 +190,7 @@ public class HuskSyncAPI {
return plugin.supplyAsync( return plugin.supplyAsync(
() -> plugin.getDatabase().getAllSnapshots(user).stream() () -> plugin.getDatabase().getAllSnapshots(user).stream()
.map(snapshot -> snapshot.unpack(plugin)) .map(snapshot -> snapshot.unpack(plugin))
.collect(Collectors.toList()) .toList()
); );
} }
@ -209,10 +205,9 @@ public class HuskSyncAPI {
*/ */
public CompletableFuture<List<DataSnapshot.Unpacked>> getSnapshot(@NotNull User user, @NotNull UUID versionId) { public CompletableFuture<List<DataSnapshot.Unpacked>> getSnapshot(@NotNull User user, @NotNull UUID versionId) {
return plugin.supplyAsync( return plugin.supplyAsync(
() -> plugin.getDatabase().getSnapshot(user, versionId) () -> plugin.getDatabase().getSnapshot(user, versionId).stream()
.map(Stream::of).orElseGet(Stream::empty)
.map(snapshot -> snapshot.unpack(plugin)) .map(snapshot -> snapshot.unpack(plugin))
.collect(Collectors.toList()) .toList()
); );
} }
@ -279,8 +274,8 @@ public class HuskSyncAPI {
@Nullable BiConsumer<User, DataSnapshot.Packed> callback) { @Nullable BiConsumer<User, DataSnapshot.Packed> callback) {
plugin.runAsync(() -> plugin.getDataSyncer().saveData( plugin.runAsync(() -> plugin.getDataSyncer().saveData(
user, user,
snapshot instanceof DataSnapshot.Unpacked snapshot instanceof DataSnapshot.Unpacked unpacked
? ((DataSnapshot.Unpacked) snapshot).pack(plugin) : (DataSnapshot.Packed) snapshot, ? unpacked.pack(plugin) : (DataSnapshot.Packed) snapshot,
callback callback
)); ));
} }
@ -309,8 +304,8 @@ public class HuskSyncAPI {
*/ */
public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot snapshot) { public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot snapshot) {
plugin.runAsync(() -> plugin.getDatabase().updateSnapshot( plugin.runAsync(() -> plugin.getDatabase().updateSnapshot(
user, snapshot instanceof DataSnapshot.Unpacked user, snapshot instanceof DataSnapshot.Unpacked unpacked
? ((DataSnapshot.Unpacked) snapshot).pack(plugin) : (DataSnapshot.Packed) snapshot ? unpacked.pack(plugin) : (DataSnapshot.Packed) snapshot
)); ));
} }
@ -444,8 +439,8 @@ public class HuskSyncAPI {
* @since 3.0 * @since 3.0
*/ */
public int getSnapshotFileSize(@NotNull DataSnapshot snapshot) { public int getSnapshotFileSize(@NotNull DataSnapshot snapshot) {
return (snapshot instanceof DataSnapshot.Packed) return (snapshot instanceof DataSnapshot.Packed packed)
? ((DataSnapshot.Packed) snapshot).getFileSize(plugin) ? packed.getFileSize(plugin)
: ((DataSnapshot.Unpacked) snapshot).pack(plugin).getFileSize(plugin); : ((DataSnapshot.Unpacked) snapshot).pack(plugin).getFileSize(plugin);
} }
@ -516,14 +511,15 @@ public class HuskSyncAPI {
*/ */
static final class NotRegisteredException extends IllegalStateException { static final class NotRegisteredException extends IllegalStateException {
private static final String REASONS = "This may be because:\n" + private static final String REASONS = """
"1) HuskSync has failed to enable successfully\n" + This may be because:
"2) Your plugin isn't set to load after HuskSync has\n" + 1) HuskSync has failed to enable successfully
" (Check if it set as a (soft)depend in plugin.yml or to load: BEFORE in paper-plugin.yml?)\n" + 2) Your plugin isn't set to load after HuskSync has
"3) You are attempting to access HuskSync on plugin construction/before your plugin has enabled."; (Check if it set as a (soft)depend in plugin.yml or to load: BEFORE in paper-plugin.yml?)
3) You are attempting to access HuskSync on plugin construction/before your plugin has enabled.""";
NotRegisteredException(@NotNull String reasons) { NotRegisteredException(@NotNull String reasons) {
super("Could not access the HuskSync API as it has not yet been registered. " + reasons); super("Could not access the HuskSync API as it has not yet been registered. %s".formatted(reasons));
} }
NotRegisteredException() { NotRegisteredException() {

@ -19,7 +19,6 @@
package net.william278.husksync.command; package net.william278.husksync.command;
import com.google.common.collect.ImmutableList;
import de.themoep.minedown.adventure.MineDown; import de.themoep.minedown.adventure.MineDown;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.data.Data; import net.william278.husksync.data.Data;
@ -38,14 +37,14 @@ import java.util.Optional;
public class EnderChestCommand extends ItemsCommand { public class EnderChestCommand extends ItemsCommand {
public EnderChestCommand(@NotNull HuskSync plugin) { public EnderChestCommand(@NotNull HuskSync plugin) {
super("enderchest", ImmutableList.of("echest", "openechest"), plugin); super("enderchest", List.of("echest", "openechest"), plugin);
} }
@Override @Override
protected void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot, protected void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot,
@NotNull User user, boolean allowEdit) { @NotNull User user, boolean allowEdit) {
final Optional<Data.Items.EnderChest> optionalEnderChest = snapshot.getEnderChest(); final Optional<Data.Items.EnderChest> optionalEnderChest = snapshot.getEnderChest();
if (!optionalEnderChest.isPresent()) { if (optionalEnderChest.isEmpty()) {
plugin.getLocales().getLocale("error_no_data_to_display") plugin.getLocales().getLocale("error_no_data_to_display")
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
return; return;
@ -77,7 +76,7 @@ public class EnderChestCommand extends ItemsCommand {
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
private void updateItems(@NotNull OnlineUser viewer, @NotNull Data.Items.Items items, @NotNull User holder) { private void updateItems(@NotNull OnlineUser viewer, @NotNull Data.Items.Items items, @NotNull User holder) {
final Optional<DataSnapshot.Packed> latestData = plugin.getDatabase().getLatestSnapshot(holder); final Optional<DataSnapshot.Packed> latestData = plugin.getDatabase().getLatestSnapshot(holder);
if (!latestData.isPresent()) { if (latestData.isEmpty()) {
plugin.getLocales().getLocale("error_no_data_to_display") plugin.getLocales().getLocale("error_no_data_to_display")
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
return; return;

@ -19,7 +19,6 @@
package net.william278.husksync.command; package net.william278.husksync.command;
import com.google.common.collect.ImmutableList;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException;
import de.themoep.minedown.adventure.MineDown; import de.themoep.minedown.adventure.MineDown;
@ -31,11 +30,9 @@ import net.kyori.adventure.text.format.TextColor;
import net.william278.desertwell.about.AboutMenu; import net.william278.desertwell.about.AboutMenu;
import net.william278.desertwell.util.UpdateChecker; import net.william278.desertwell.util.UpdateChecker;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.data.Identifier;
import net.william278.husksync.database.Database; import net.william278.husksync.database.Database;
import net.william278.husksync.migrator.Migrator; import net.william278.husksync.migrator.Migrator;
import net.william278.husksync.user.CommandUser; import net.william278.husksync.user.CommandUser;
import net.william278.husksync.util.StringUtil;
import net.william278.uniform.BaseCommand; import net.william278.uniform.BaseCommand;
import net.william278.uniform.CommandProvider; import net.william278.uniform.CommandProvider;
import net.william278.uniform.Permission; import net.william278.uniform.Permission;
@ -44,7 +41,7 @@ import org.apache.commons.text.WordUtils;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -55,7 +52,7 @@ public class HuskSyncCommand extends PluginCommand {
private final AboutMenu aboutMenu; private final AboutMenu aboutMenu;
public HuskSyncCommand(@NotNull HuskSync plugin) { public HuskSyncCommand(@NotNull HuskSync plugin) {
super("husksync", ImmutableList.of(), Permission.Default.TRUE, ExecutionScope.ALL, plugin); super("husksync", List.of(), Permission.Default.TRUE, ExecutionScope.ALL, plugin);
this.updateChecker = plugin.getUpdateChecker(); this.updateChecker = plugin.getUpdateChecker();
this.aboutMenu = AboutMenu.builder() this.aboutMenu = AboutMenu.builder()
.title(Component.text("HuskSync")) .title(Component.text("HuskSync"))
@ -113,8 +110,7 @@ public class HuskSyncCommand extends PluginCommand {
plugin.getLocales().getLocale("system_status_header").ifPresent(user::sendMessage); plugin.getLocales().getLocale("system_status_header").ifPresent(user::sendMessage);
user.sendMessage(Component.join( user.sendMessage(Component.join(
JoinConfiguration.newlines(), JoinConfiguration.newlines(),
Arrays.stream(StatusLine.values()).map(s -> s.get(plugin)) Arrays.stream(StatusLine.values()).map(s -> s.get(plugin)).toList()
.collect(Collectors.toList())
)); ));
}); });
} }
@ -206,7 +202,7 @@ public class HuskSyncCommand extends PluginCommand {
private enum StatusLine { private enum StatusLine {
PLUGIN_VERSION(plugin -> Component.text("v" + plugin.getPluginVersion().toStringWithoutMetadata()) PLUGIN_VERSION(plugin -> Component.text("v" + plugin.getPluginVersion().toStringWithoutMetadata())
.appendSpace().append(StringUtil.isBlank(plugin.getPluginVersion().getMetadata()) ? Component.empty() .appendSpace().append(plugin.getPluginVersion().getMetadata().isBlank() ? Component.empty()
: Component.text("(build " + plugin.getPluginVersion().getMetadata() + ")"))), : Component.text("(build " + plugin.getPluginVersion().getMetadata() + ")"))),
SERVER_VERSION(plugin -> Component.text(plugin.getServerVersion())), SERVER_VERSION(plugin -> Component.text(plugin.getServerVersion())),
LANGUAGE(plugin -> Component.text(plugin.getSettings().getLanguage())), LANGUAGE(plugin -> Component.text(plugin.getSettings().getLanguage())),
@ -214,7 +210,7 @@ public class HuskSyncCommand extends PluginCommand {
JAVA_VERSION(plugin -> Component.text(System.getProperty("java.version"))), JAVA_VERSION(plugin -> Component.text(System.getProperty("java.version"))),
JAVA_VENDOR(plugin -> Component.text(System.getProperty("java.vendor"))), JAVA_VENDOR(plugin -> Component.text(System.getProperty("java.vendor"))),
SERVER_NAME(plugin -> Component.text(plugin.getServerName())), SERVER_NAME(plugin -> Component.text(plugin.getServerName())),
CLUSTER_ID(plugin -> Component.text(StringUtil.isBlank(plugin.getSettings().getClusterId()) ? "None" : plugin.getSettings().getClusterId())), CLUSTER_ID(plugin -> Component.text(plugin.getSettings().getClusterId().isBlank() ? "None" : plugin.getSettings().getClusterId())),
SYNC_MODE(plugin -> Component.text(WordUtils.capitalizeFully( SYNC_MODE(plugin -> Component.text(WordUtils.capitalizeFully(
plugin.getSettings().getSynchronization().getMode().toString() plugin.getSettings().getSynchronization().getMode().toString()
))), ))),
@ -228,10 +224,10 @@ public class HuskSyncCommand extends PluginCommand {
), ),
IS_DATABASE_LOCAL(plugin -> getLocalhostBoolean(plugin.getSettings().getDatabase().getCredentials().getHost())), IS_DATABASE_LOCAL(plugin -> getLocalhostBoolean(plugin.getSettings().getDatabase().getCredentials().getHost())),
USING_REDIS_SENTINEL(plugin -> getBoolean( USING_REDIS_SENTINEL(plugin -> getBoolean(
!StringUtil.isBlank(plugin.getSettings().getRedis().getSentinel().getMaster()) !plugin.getSettings().getRedis().getSentinel().getMaster().isBlank()
)), )),
USING_REDIS_PASSWORD(plugin -> getBoolean( USING_REDIS_PASSWORD(plugin -> getBoolean(
!StringUtil.isBlank(plugin.getSettings().getRedis().getCredentials().getPassword()) !plugin.getSettings().getRedis().getCredentials().getPassword().isBlank()
)), )),
REDIS_USING_SSL(plugin -> getBoolean( REDIS_USING_SSL(plugin -> getBoolean(
plugin.getSettings().getRedis().getCredentials().isUseSsl() plugin.getSettings().getRedis().getCredentials().isUseSsl()
@ -247,13 +243,13 @@ public class HuskSyncCommand extends PluginCommand {
.hoverEvent(HoverEvent.showText( .hoverEvent(HoverEvent.showText(
Component.text(i.isEnabled() ? "Enabled" : "Disabled") Component.text(i.isEnabled() ? "Enabled" : "Disabled")
.append(Component.newline()) .append(Component.newline())
.append(i.getDependencies().isEmpty() .append(Component.text("Dependencies: %s".formatted(i.getDependencies()
? Component.text("Dependencies: None").color(NamedTextColor.GRAY) .isEmpty() ? "(None)" : i.getDependencies().stream()
: Component.text("Dependencies: " + i.getDependencies().stream() .map(d -> "%s (%s)".formatted(
.map(d -> d.getKey().value() + " (" + (d.isRequired() ? "Required" : "Optional") + ")") d.getKey().value(), d.isRequired() ? "Required" : "Optional"
.collect(Collectors.joining(", ")) )).collect(Collectors.joining(", ")))
).color(NamedTextColor.GRAY)) ).color(NamedTextColor.GRAY))
))).collect(Collectors.toList()) ))).toList()
)); ));
private final Function<HuskSync, Component> supplier; private final Function<HuskSync, Component> supplier;

@ -19,7 +19,6 @@
package net.william278.husksync.command; package net.william278.husksync.command;
import com.google.common.collect.ImmutableList;
import de.themoep.minedown.adventure.MineDown; import de.themoep.minedown.adventure.MineDown;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.data.Data; import net.william278.husksync.data.Data;
@ -38,14 +37,14 @@ import java.util.Optional;
public class InventoryCommand extends ItemsCommand { public class InventoryCommand extends ItemsCommand {
public InventoryCommand(@NotNull HuskSync plugin) { public InventoryCommand(@NotNull HuskSync plugin) {
super("inventory", ImmutableList.of("invsee", "openinv"), plugin); super("inventory", List.of("invsee", "openinv"), plugin);
} }
@Override @Override
protected void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot, protected void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot,
@NotNull User user, boolean allowEdit) { @NotNull User user, boolean allowEdit) {
final Optional<Data.Items.Inventory> optionalInventory = snapshot.getInventory(); final Optional<Data.Items.Inventory> optionalInventory = snapshot.getInventory();
if (!optionalInventory.isPresent()) { if (optionalInventory.isEmpty()) {
viewer.sendMessage(new MineDown("what the FUCK is happening")); viewer.sendMessage(new MineDown("what the FUCK is happening"));
plugin.getLocales().getLocale("error_no_data_to_display") plugin.getLocales().getLocale("error_no_data_to_display")
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
@ -78,7 +77,7 @@ public class InventoryCommand extends ItemsCommand {
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
private void updateItems(@NotNull OnlineUser viewer, @NotNull Data.Items.Items items, @NotNull User holder) { private void updateItems(@NotNull OnlineUser viewer, @NotNull Data.Items.Items items, @NotNull User holder) {
final Optional<DataSnapshot.Packed> latestData = plugin.getDatabase().getLatestSnapshot(holder); final Optional<DataSnapshot.Packed> latestData = plugin.getDatabase().getLatestSnapshot(holder);
if (!latestData.isPresent()) { if (latestData.isEmpty()) {
plugin.getLocales().getLocale("error_no_data_to_display") plugin.getLocales().getLocale("error_no_data_to_display")
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
return; return;

@ -24,7 +24,6 @@ import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.user.CommandUser; import net.william278.husksync.user.CommandUser;
import net.william278.husksync.user.OnlineUser; import net.william278.husksync.user.OnlineUser;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.OptionalUtil;
import net.william278.uniform.BaseCommand; import net.william278.uniform.BaseCommand;
import net.william278.uniform.Permission; import net.william278.uniform.Permission;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -45,32 +44,32 @@ public abstract class ItemsCommand extends PluginCommand {
final User user = ctx.getArgument("username", User.class); final User user = ctx.getArgument("username", User.class);
final UUID version = ctx.getArgument("version", UUID.class); final UUID version = ctx.getArgument("version", UUID.class);
final CommandUser executor = user(command, ctx); final CommandUser executor = user(command, ctx);
if (!(executor instanceof OnlineUser)) { if (!(executor instanceof OnlineUser online)) {
plugin.getLocales().getLocale("error_in_game_command_only") plugin.getLocales().getLocale("error_in_game_command_only")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
} }
this.showSnapshotItems((OnlineUser) executor, user, version); this.showSnapshotItems(online, user, version);
}, user("username"), uuid("version")); }, user("username"), uuid("version"));
command.addSyntax((ctx) -> { command.addSyntax((ctx) -> {
final User user = ctx.getArgument("username", User.class); final User user = ctx.getArgument("username", User.class);
final CommandUser executor = user(command, ctx); final CommandUser executor = user(command, ctx);
if (!(executor instanceof OnlineUser)) { if (!(executor instanceof OnlineUser online)) {
plugin.getLocales().getLocale("error_in_game_command_only") plugin.getLocales().getLocale("error_in_game_command_only")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
} }
this.showLatestItems((OnlineUser) executor, user); this.showLatestItems(online, user);
}, user("username")); }, user("username"));
} }
// View (and edit) the latest user data // View (and edit) the latest user data
private void showLatestItems(@NotNull OnlineUser viewer, @NotNull User user) { private void showLatestItems(@NotNull OnlineUser viewer, @NotNull User user) {
plugin.getRedisManager().getUserData(user.getUuid(), user).thenAccept(data -> OptionalUtil.or( plugin.getRedisManager().getUserData(user.getUuid(), user).thenAccept(data -> data
OptionalUtil.or(data, () -> .or(() -> plugin.getDatabase().getLatestSnapshot(user))
plugin.getDatabase().getLatestSnapshot(user)), .or(() -> {
() -> { plugin.getLocales().getLocale("error_no_data_to_display")
plugin.getLocales().getLocale("error_no_data_to_display").ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
return Optional.empty(); return Optional.empty();
}) })
.flatMap(packed -> { .flatMap(packed -> {
@ -88,8 +87,8 @@ public abstract class ItemsCommand extends PluginCommand {
// View a specific version of the user data // View a specific version of the user data
private void showSnapshotItems(@NotNull OnlineUser viewer, @NotNull User user, @NotNull UUID version) { private void showSnapshotItems(@NotNull OnlineUser viewer, @NotNull User user, @NotNull UUID version) {
OptionalUtil.or(plugin.getDatabase().getSnapshot(user, version), plugin.getDatabase().getSnapshot(user, version)
() -> { .or(() -> {
plugin.getLocales().getLocale("error_invalid_version_uuid") plugin.getLocales().getLocale("error_invalid_version_uuid")
.ifPresent(viewer::sendMessage); .ifPresent(viewer::sendMessage);
return Optional.empty(); return Optional.empty();

@ -46,7 +46,7 @@ public abstract class PluginCommand extends Command {
} }
private static String getDescription(@NotNull HuskSync plugin, @NotNull String name) { private static String getDescription(@NotNull HuskSync plugin, @NotNull String name) {
return plugin.getLocales().getRawLocale(name + "_command_description").orElse(""); return plugin.getLocales().getRawLocale("%s_command_description".formatted(name)).orElse("");
} }
@NotNull @NotNull
@ -72,10 +72,7 @@ public abstract class PluginCommand extends Command {
@NotNull @NotNull
protected CommandUser adapt(net.william278.uniform.CommandUser user) { protected CommandUser adapt(net.william278.uniform.CommandUser user) {
return user.getUuid() == null return user.getUuid() == null ? plugin.getConsole() : plugin.getOnlineUser(user.getUuid()).orElseThrow();
? plugin.getConsole()
: plugin.getOnlineUser(user.getUuid())
.orElseThrow(() -> new IllegalStateException("Online not found"));
} }
@NotNull @NotNull

@ -29,14 +29,12 @@ import net.william278.husksync.user.User;
import net.william278.husksync.util.DataDumper; import net.william278.husksync.util.DataDumper;
import net.william278.husksync.util.DataSnapshotList; import net.william278.husksync.util.DataSnapshotList;
import net.william278.husksync.util.DataSnapshotOverview; import net.william278.husksync.util.DataSnapshotOverview;
import net.william278.husksync.util.OptionalUtil;
import net.william278.uniform.BaseCommand; import net.william278.uniform.BaseCommand;
import net.william278.uniform.CommandProvider; import net.william278.uniform.CommandProvider;
import net.william278.uniform.Permission; import net.william278.uniform.Permission;
import net.william278.uniform.element.ArgumentElement; import net.william278.uniform.element.ArgumentElement;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Optional; import java.util.Optional;
@ -46,7 +44,7 @@ import java.util.logging.Level;
public class UserDataCommand extends PluginCommand { public class UserDataCommand extends PluginCommand {
public UserDataCommand(@NotNull HuskSync plugin) { public UserDataCommand(@NotNull HuskSync plugin) {
super("userdata", Collections.singletonList("playerdata"), Permission.Default.IF_OP, ExecutionScope.ALL, plugin); super("userdata", List.of("playerdata"), Permission.Default.IF_OP, ExecutionScope.ALL, plugin);
} }
@Override @Override
@ -61,37 +59,35 @@ public class UserDataCommand extends PluginCommand {
// Show the latest snapshot // Show the latest snapshot
private void viewLatestSnapshot(@NotNull CommandUser executor, @NotNull User user) { private void viewLatestSnapshot(@NotNull CommandUser executor, @NotNull User user) {
OptionalUtil.ifPresentOrElse( plugin.getDatabase().getLatestSnapshot(user).ifPresentOrElse(
plugin.getDatabase().getLatestSnapshot(user), data -> {
data -> { if (data.isInvalid()) {
if (data.isInvalid()) { plugin.getLocales().getLocale("error_invalid_data", data.getInvalidReason(plugin))
plugin.getLocales().getLocale("error_invalid_data", data.getInvalidReason(plugin)) .ifPresent(executor::sendMessage);
.ifPresent(executor::sendMessage); return;
return; }
} DataSnapshotOverview.of(data.unpack(plugin), data.getFileSize(plugin), user, plugin)
DataSnapshotOverview.of(data.unpack(plugin), data.getFileSize(plugin), user, plugin) .show(executor);
.show(executor); },
}, () -> plugin.getLocales().getLocale("error_no_data_to_display")
() -> plugin.getLocales().getLocale("error_no_data_to_display") .ifPresent(executor::sendMessage)
.ifPresent(executor::sendMessage)
); );
} }
// Show the specified snapshot // Show the specified snapshot
private void viewSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version) { private void viewSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version) {
OptionalUtil.ifPresentOrElse( plugin.getDatabase().getSnapshot(user, version).ifPresentOrElse(
plugin.getDatabase().getSnapshot(user, version), data -> {
data -> { if (data.isInvalid()) {
if (data.isInvalid()) { plugin.getLocales().getLocale("error_invalid_data", data.getInvalidReason(plugin))
plugin.getLocales().getLocale("error_invalid_data", data.getInvalidReason(plugin)) .ifPresent(executor::sendMessage);
.ifPresent(executor::sendMessage); return;
return; }
} DataSnapshotOverview.of(data.unpack(plugin), data.getFileSize(plugin), user, plugin)
DataSnapshotOverview.of(data.unpack(plugin), data.getFileSize(plugin), user, plugin) .show(executor);
.show(executor); },
}, () -> plugin.getLocales().getLocale("error_invalid_version_uuid")
() -> plugin.getLocales().getLocale("error_invalid_version_uuid") .ifPresent(executor::sendMessage)
.ifPresent(executor::sendMessage)
); );
} }
@ -125,7 +121,7 @@ public class UserDataCommand extends PluginCommand {
// Restore a snapshot // Restore a snapshot
private void restoreSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version) { private void restoreSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version) {
final Optional<DataSnapshot.Packed> optionalData = plugin.getDatabase().getSnapshot(user, version); final Optional<DataSnapshot.Packed> optionalData = plugin.getDatabase().getSnapshot(user, version);
if (!optionalData.isPresent()) { if (optionalData.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_version_uuid") plugin.getLocales().getLocale("error_invalid_version_uuid")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
@ -159,7 +155,7 @@ public class UserDataCommand extends PluginCommand {
// Pin a snapshot // Pin a snapshot
private void pinSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version) { private void pinSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version) {
final Optional<DataSnapshot.Packed> optionalData = plugin.getDatabase().getSnapshot(user, version); final Optional<DataSnapshot.Packed> optionalData = plugin.getDatabase().getSnapshot(user, version);
if (!optionalData.isPresent()) { if (optionalData.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_version_uuid") plugin.getLocales().getLocale("error_invalid_version_uuid")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
@ -181,7 +177,7 @@ public class UserDataCommand extends PluginCommand {
private void dumpSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version, private void dumpSnapshot(@NotNull CommandUser executor, @NotNull User user, @NotNull UUID version,
@NotNull DumpType type) { @NotNull DumpType type) {
final Optional<DataSnapshot.Packed> data = plugin.getDatabase().getSnapshot(user, version); final Optional<DataSnapshot.Packed> data = plugin.getDatabase().getSnapshot(user, version);
if (!data.isPresent()) { if (data.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_version_uuid") plugin.getLocales().getLocale("error_invalid_version_uuid")
.ifPresent(executor::sendMessage); .ifPresent(executor::sendMessage);
return; return;
@ -269,15 +265,12 @@ public class UserDataCommand extends PluginCommand {
private <S> ArgumentElement<S, DumpType> dumpType() { private <S> ArgumentElement<S, DumpType> dumpType() {
return new ArgumentElement<>("type", reader -> { return new ArgumentElement<>("type", reader -> {
final String type = reader.readString(); final String type = reader.readString();
switch (type.toLowerCase(Locale.ENGLISH)) { return switch (type.toLowerCase(Locale.ENGLISH)) {
case "web": case "web" -> DumpType.WEB;
return DumpType.WEB; case "file" -> DumpType.FILE;
case "file": default -> throw CommandSyntaxException.BUILT_IN_EXCEPTIONS
return DumpType.FILE; .dispatcherUnknownArgument().createWithContext(reader);
default: };
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS
.dispatcherUnknownArgument().createWithContext(reader);
}
}, (context, builder) -> { }, (context, builder) -> {
builder.suggest("web"); builder.suggest("web");
builder.suggest("file"); builder.suggest("file");

@ -42,14 +42,14 @@ import java.util.Optional;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Locales { public class Locales {
static final String CONFIG_HEADER = static final String CONFIG_HEADER = """
"┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n" +
"┃ HuskSync - Locales ┃\n" + HuskSync - Locales
"┃ Developed by William278 ┃\n" + Developed by William278
"┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n" +
"┣╸ See plugin about menu for international locale credits\n" + See plugin about menu for international locale credits
"┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown\n" + Formatted in MineDown: https://github.com/Phoenix616/MineDown
"┗╸ Translate HuskSync: https://william278.net/docs/husksync/translations"; Translate HuskSync: https://william278.net/docs/husksync/translations""";
protected static final String DEFAULT_LOCALE = "en-gb"; protected static final String DEFAULT_LOCALE = "en-gb";
@ -202,9 +202,9 @@ public class Locales {
/** /**
* Displays the notification in an Advancement Toast * Displays the notification in an Advancement Toast
* *
* @deprecated No longer supported, since 3.6.7 * @deprecated No longer supported
*/ */
@Deprecated @Deprecated(since = "3.6.7")
TOAST, TOAST,
/** /**

@ -27,7 +27,6 @@ import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
@Getter @Getter
@Configuration @Configuration
@ -35,13 +34,13 @@ import java.nio.file.Paths;
@AllArgsConstructor(access = AccessLevel.PRIVATE) @AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Server { public class Server {
static final String CONFIG_HEADER = static final String CONFIG_HEADER = """
"┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n" +
"┃ HuskSync - Server ID ┃\n" + HuskSync - Server ID
"┃ Developed by William278 ┃\n" + Developed by William278
"┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n" +
"┣╸ This file should contain the ID of this server as defined in your proxy config.\n" + This file should contain the ID of this server as defined in your proxy config.
"┗╸ If you join it using /server alpha, then set it to 'alpha' (case-sensitive)"; If you join it using /server alpha, then set it to 'alpha' (case-sensitive)""";
private String name = getDefault(); private String name = getDefault();
@ -56,14 +55,14 @@ public class Server {
@NotNull @NotNull
private static String getDefault() { private static String getDefault() {
final String serverFolder = System.getProperty("user.dir"); final String serverFolder = System.getProperty("user.dir");
return serverFolder == null ? "server" : Paths.get(serverFolder).getFileName().toString().trim(); return serverFolder == null ? "server" : Path.of(serverFolder).getFileName().toString().trim();
} }
@Override @Override
public boolean equals(@NotNull Object other) { public boolean equals(@NotNull Object other) {
// If the name of this server matches another, the servers are the same. // If the name of this server matches another, the servers are the same.
if (other instanceof Server) { if (other instanceof Server server) {
return ((Server) other).getName().equalsIgnoreCase(this.getName()); return server.getName().equalsIgnoreCase(this.getName());
} }
return super.equals(other); return super.equals(other);
} }

@ -19,7 +19,6 @@
package net.william278.husksync.config; package net.william278.husksync.config;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import de.exlll.configlib.Comment; import de.exlll.configlib.Comment;
import de.exlll.configlib.Configuration; import de.exlll.configlib.Configuration;
@ -48,14 +47,15 @@ import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Settings { public class Settings {
protected static final String CONFIG_HEADER = protected static final String CONFIG_HEADER = """
"┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n" +
"┃ HuskSync Config ┃\n" + HuskSync Config
"┃ Developed by William278 ┃\n" + Developed by William278
"┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n" +
"┣╸ Information: https://william278.net/project/husksync\n" + Information: https://william278.net/project/husksync
"┣╸ Config Help: https://william278.net/docs/husksync/config-file/\n" + Config Help: https://william278.net/docs/husksync/config-file/
"┗╸ Documentation: https://william278.net/docs/husksync"; Documentation: https://william278.net/docs/husksync""";
// Top-level settings // Top-level settings
@Comment({"Locale of the default language file to use.", "Docs: https://william278.net/docs/husksync/translations"}) @Comment({"Locale of the default language file to use.", "Docs: https://william278.net/docs/husksync/translations"})
private String language = Locales.DEFAULT_LOCALE; private String language = Locales.DEFAULT_LOCALE;
@ -207,7 +207,7 @@ public class Settings {
@Comment({"List of save cause IDs for which a snapshot will be automatically pinned (so it won't be rotated).", @Comment({"List of save cause IDs for which a snapshot will be automatically pinned (so it won't be rotated).",
"Docs: https://william278.net/docs/husksync/data-rotation#save-causes"}) "Docs: https://william278.net/docs/husksync/data-rotation#save-causes"})
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
private List<String> autoPinnedSaveCauses = ImmutableList.of( private List<String> autoPinnedSaveCauses = List.of(
DataSnapshot.SaveCause.INVENTORY_COMMAND.name(), DataSnapshot.SaveCause.INVENTORY_COMMAND.name(),
DataSnapshot.SaveCause.ENDERCHEST_COMMAND.name(), DataSnapshot.SaveCause.ENDERCHEST_COMMAND.name(),
DataSnapshot.SaveCause.BACKUP_RESTORE.name(), DataSnapshot.SaveCause.BACKUP_RESTORE.name(),
@ -265,7 +265,7 @@ public class Settings {
private Map<String, Boolean> features = Identifier.getConfigMap(); private Map<String, Boolean> features = Identifier.getConfigMap();
@Comment("Commands which should be blocked before a player has finished syncing (Use * to block all commands)") @Comment("Commands which should be blocked before a player has finished syncing (Use * to block all commands)")
private List<String> blacklistedCommandsWhileLocked = new ArrayList<>(ImmutableList.of("*")); private List<String> blacklistedCommandsWhileLocked = new ArrayList<>(List.of("*"));
@Comment("Configuration for how to sync attributes") @Comment("Configuration for how to sync attributes")
private AttributeSettings attributes = new AttributeSettings(); private AttributeSettings attributes = new AttributeSettings();
@ -278,21 +278,21 @@ public class Settings {
@Comment({"Which attributes should not be saved when syncing users. Supports wildcard matching.", @Comment({"Which attributes should not be saved when syncing users. Supports wildcard matching.",
"(e.g. ['minecraft:generic.max_health', 'minecraft:generic.*'])"}) "(e.g. ['minecraft:generic.max_health', 'minecraft:generic.*'])"})
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
private List<String> ignoredAttributes = new ArrayList<>(ImmutableList.of("")); private List<String> ignoredAttributes = new ArrayList<>(List.of(""));
@Comment({"Which modifiers should not be saved when syncing users. Supports wildcard matching.", @Comment({"Which modifiers should not be saved when syncing users. Supports wildcard matching.",
"(e.g. ['minecraft:effect.speed', 'minecraft:effect.*'])"}) "(e.g. ['minecraft:effect.speed', 'minecraft:effect.*'])"})
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
private List<String> ignoredModifiers = new ArrayList<>(ImmutableList.of( private List<String> ignoredModifiers = new ArrayList<>(List.of(
"minecraft:effect.*", "minecraft:creative_mode_*" "minecraft:effect.*", "minecraft:creative_mode_*"
)); ));
private boolean matchesWildcard(@NotNull String pat, @NotNull String value) { private boolean matchesWildcard(@NotNull String pat, @NotNull String value) {
if (!pat.contains(":")) { if (!pat.contains(":")) {
pat = "minecraft:" + pat; pat = "minecraft:%s".formatted(pat);
} }
if (!value.contains(":")) { if (!value.contains(":")) {
value = "minecraft:" + value; value = "minecraft:%s".formatted(value);
} }
return pat.contains("*") ? value.matches(pat.replace("*", ".*")) : pat.equals(value); return pat.contains("*") ? value.matches(pat.replace("*", ".*")) : pat.equals(value);
} }

@ -25,7 +25,6 @@ import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Value;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
@ -66,13 +65,9 @@ public interface Data {
return getStack().length; return getStack().length;
} }
@Value record Stack(@NotNull String material, int amount, @Nullable String name,
class Stack { @Nullable List<String> lore, @NotNull List<String> enchantments) {
@NotNull String material;
int amount;
@Nullable String name;
@Nullable List<String> lore;
@NotNull List<String> enchantments;
} }
default boolean isEmpty() { default boolean isEmpty() {
@ -134,32 +129,23 @@ public interface Data {
@NotNull @NotNull
List<Effect> getActiveEffects(); List<Effect> getActiveEffects();
@Value /**
class Effect { * Represents a potion effect
/** *
* The type of potion effect * @param type the type of potion effect
*/ * @param amplifier the amplifier of the potion effect
@SerializedName("type") @NotNull String type; * @param duration the duration of the potion effect
/** * @param isAmbient whether the potion effect is ambient
* The amplifier of the potion effect * @param showParticles whether the potion effect shows particles
*/ * @param hasIcon whether the potion effect displays a HUD icon
@SerializedName("amplifier") int amplifier; */
/** record Effect(@SerializedName("type") @NotNull String type,
* The duration of the potion effect @SerializedName("amplifier") int amplifier,
*/ @SerializedName("duration") int duration,
@SerializedName("duration") int duration; @SerializedName("is_ambient") boolean isAmbient,
/** @SerializedName("show_particles") boolean showParticles,
* Whether the potion effect is ambient @SerializedName("has_icon") boolean hasIcon) {
*/
@SerializedName("is_ambient") boolean isAmbient;
/**
* Whether the potion effect shows particles
*/
@SerializedName("show_particles") boolean showParticles;
/**
* Whether the potion effect displays a HUD icon
*/
@SerializedName("has_icon") boolean hasIcon;
} }
} }
@ -176,9 +162,7 @@ public interface Data {
@NotNull @NotNull
default List<Advancement> getCompletedExcludingRecipes() { default List<Advancement> getCompletedExcludingRecipes() {
return getCompleted().stream() return getCompleted().stream().filter(adv -> !adv.getKey().startsWith(RECIPE_ADVANCEMENT)).toList();
.filter(adv -> !adv.getKey().startsWith(RECIPE_ADVANCEMENT))
.collect(Collectors.toList());
} }
void setCompleted(@NotNull List<Advancement> completed); void setCompleted(@NotNull List<Advancement> completed);
@ -265,11 +249,11 @@ public interface Data {
void setWorld(@NotNull World world); void setWorld(@NotNull World world);
@Value record World(
class World { @SerializedName("name") @NotNull String name,
@SerializedName("name") @NotNull String name; @SerializedName("uuid") @NotNull UUID uuid,
@SerializedName("uuid") @NotNull UUID uuid; @SerializedName("environment") @NotNull String environment
@SerializedName("environment") @NotNull String environment; ) {
} }
} }
@ -311,17 +295,17 @@ public interface Data {
void setHealth(double health); void setHealth(double health);
/** /**
* @deprecated Use {@link Attributes#getMaxHealth()} instead, since 3.5 * @deprecated Use {@link Attributes#getMaxHealth()} instead
*/ */
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
default double getMaxHealth() { default double getMaxHealth() {
return getHealth(); return getHealth();
} }
/** /**
* @deprecated Use {@link Attributes#setMaxHealth(double)} instead, since 3.5 * @deprecated Use {@link Attributes#setMaxHealth(double)} instead
*/ */
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
default void setMaxHealth(double maxHealth) { default void setMaxHealth(double maxHealth) {
} }
@ -339,11 +323,11 @@ public interface Data {
List<Attribute> getAttributes(); List<Attribute> getAttributes();
@Value record Attribute(
class Attribute { @NotNull String name,
@NotNull String name; double baseValue,
double baseValue; @NotNull Set<Modifier> modifiers
@NotNull Set<Modifier> modifiers; ) {
public double getValue() { public double getValue() {
double value = baseValue; double value = baseValue;
@ -382,8 +366,7 @@ public interface Data {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof Modifier) { if (obj instanceof Modifier other) {
Modifier other = (Modifier) obj;
if (uuid == null || other.uuid == null) { if (uuid == null || other.uuid == null) {
return name.equals(other.name); return name.equals(other.name);
} }
@ -393,16 +376,12 @@ public interface Data {
} }
public double modify(double value) { public double modify(double value) {
switch (operationType) { return switch (operationType) {
case 0: case 0 -> value + amount;
return value + amount; case 1 -> value * amount;
case 1: case 2 -> value * (1 + amount);
return value * amount; default -> value;
case 2: };
return value * (1 + amount);
default:
return value;
}
} }
public boolean hasUuid() { public boolean hasUuid() {
@ -418,12 +397,12 @@ public interface Data {
default Optional<Attribute> getAttribute(@NotNull Key key) { default Optional<Attribute> getAttribute(@NotNull Key key) {
return getAttributes().stream() return getAttributes().stream()
.filter(attribute -> attribute.getName().equals(key.asString())) .filter(attribute -> attribute.name().equals(key.asString()))
.findFirst(); .findFirst();
} }
default void removeAttribute(@NotNull Key key) { default void removeAttribute(@NotNull Key key) {
getAttributes().removeIf(attribute -> attribute.getName().equals(key.asString())); getAttributes().removeIf(attribute -> attribute.name().equals(key.asString()));
} }
default double getMaxHealth() { default double getMaxHealth() {
@ -502,9 +481,9 @@ public interface Data {
* *
* @return {@code false} since v3.5 * @return {@code false} since v3.5
* @deprecated Moved to its own data type. This will always return {@code false}. * @deprecated Moved to its own data type. This will always return {@code false}.
* Use {@link FlightStatus#isAllowFlight()} instead, since 3.5 * Use {@link FlightStatus#isAllowFlight()} instead
*/ */
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
default boolean getAllowFlight() { default boolean getAllowFlight() {
return false; return false;
} }
@ -513,9 +492,9 @@ public interface Data {
* Set if the player can fly. * Set if the player can fly.
* *
* @deprecated Moved to its own data type. * @deprecated Moved to its own data type.
* Use {@link FlightStatus#setAllowFlight(boolean)} instead, since 3.5 * Use {@link FlightStatus#setAllowFlight(boolean)} instead
*/ */
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
default void setAllowFlight(boolean allowFlight) { default void setAllowFlight(boolean allowFlight) {
} }
@ -524,9 +503,9 @@ public interface Data {
* *
* @return {@code false} since v3.5 * @return {@code false} since v3.5
* @deprecated Moved to its own data type. This will always return {@code false}. * @deprecated Moved to its own data type. This will always return {@code false}.
* Use {@link FlightStatus#isFlying()} instead, since 3.5 * Use {@link FlightStatus#isFlying()} instead
*/ */
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
default boolean getIsFlying() { default boolean getIsFlying() {
return false; return false;
} }
@ -535,9 +514,9 @@ public interface Data {
* Set if the player is flying. * Set if the player is flying.
* *
* @deprecated Moved to its own data type. * @deprecated Moved to its own data type.
* Use {@link FlightStatus#setFlying(boolean)} instead, since 3.5 * Use {@link FlightStatus#setFlying(boolean)} instead
*/ */
@Deprecated @Deprecated(forRemoval = true, since = "3.5")
default void setIsFlying(boolean isFlying) { default void setIsFlying(boolean isFlying) {
} }

@ -383,7 +383,7 @@ public class DataSnapshot {
private Unpacked(@NotNull UUID id, boolean pinned, @NotNull OffsetDateTime timestamp, private Unpacked(@NotNull UUID id, boolean pinned, @NotNull OffsetDateTime timestamp,
@NotNull String saveCause, @NotNull String serverName, @NotNull TreeMap<Identifier, Data> data, @NotNull String saveCause, @NotNull String serverName, @NotNull TreeMap<Identifier, Data> data,
@NotNull Version minecraftVersion, @NotNull String platformType, int formatVersion) { @NotNull Version minecraftVersion, @NotNull String platformType, int formatVersion) {
super(id, pinned, timestamp, saveCause, serverName, Collections.emptyMap(), minecraftVersion, platformType, formatVersion); super(id, pinned, timestamp, saveCause, serverName, Map.of(), minecraftVersion, platformType, formatVersion);
this.deserialized = data; this.deserialized = data;
} }
@ -392,10 +392,7 @@ public class DataSnapshot {
private TreeMap<Identifier, Data> deserializeData(@NotNull HuskSync plugin) { private TreeMap<Identifier, Data> deserializeData(@NotNull HuskSync plugin) {
return data.entrySet().stream() return data.entrySet().stream()
.filter(e -> plugin.getIdentifier(e.getKey()).isPresent()) .filter(e -> plugin.getIdentifier(e.getKey()).isPresent())
.map(entry -> Maps.immutableEntry( .map(entry -> Map.entry(plugin.getIdentifier(entry.getKey()).orElseThrow(), entry.getValue()))
plugin.getIdentifier(entry.getKey()).orElseThrow(() -> new IllegalStateException("Invalid identifier")),
entry.getValue()
))
.collect(Collectors.toMap( .collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getKey,
entry -> plugin.deserializeData(entry.getKey(), entry.getValue(), getMinecraftVersion()), entry -> plugin.deserializeData(entry.getKey(), entry.getValue(), getMinecraftVersion()),
@ -942,7 +939,7 @@ public class DataSnapshot {
@NotNull @NotNull
public String getLocale(@NotNull HuskSync plugin) { public String getLocale(@NotNull HuskSync plugin) {
return plugin.getLocales() return plugin.getLocales()
.getRawLocale("save_cause_" + name().toLowerCase(Locale.ENGLISH)) .getRawLocale("save_cause_%s".formatted(name().toLowerCase(Locale.ENGLISH)))
.orElse(getDisplayName()); .orElse(getDisplayName());
} }

@ -19,9 +19,6 @@
package net.william278.husksync.data; package net.william278.husksync.data;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import lombok.*; import lombok.*;
import net.kyori.adventure.key.InvalidKeyException; import net.kyori.adventure.key.InvalidKeyException;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
@ -153,7 +150,7 @@ public class Identifier {
private static Identifier huskSync(@Subst("null") @NotNull String name, private static Identifier huskSync(@Subst("null") @NotNull String name,
@SuppressWarnings("SameParameterValue") boolean configDefault, @SuppressWarnings("SameParameterValue") boolean configDefault,
@NotNull Dependency... dependents) throws InvalidKeyException { @NotNull Dependency... dependents) throws InvalidKeyException {
return new Identifier(Key.key("husksync", name), configDefault, ImmutableSet.copyOf(dependents)); return new Identifier(Key.key("husksync", name), configDefault, Set.of(dependents));
} }
/** /**
@ -166,7 +163,7 @@ public class Identifier {
@ApiStatus.Internal @ApiStatus.Internal
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static Map<String, Boolean> getConfigMap() { public static Map<String, Boolean> getConfigMap() {
return ImmutableMap.ofEntries(Stream.of( return Map.ofEntries(Stream.of(
INVENTORY, ENDER_CHEST, POTION_EFFECTS, ADVANCEMENTS, LOCATION, STATISTICS, INVENTORY, ENDER_CHEST, POTION_EFFECTS, ADVANCEMENTS, LOCATION, STATISTICS,
HEALTH, HUNGER, ATTRIBUTES, EXPERIENCE, GAME_MODE, FLIGHT_STATUS, PERSISTENT_DATA HEALTH, HUNGER, ATTRIBUTES, EXPERIENCE, GAME_MODE, FLIGHT_STATUS, PERSISTENT_DATA
) )
@ -233,8 +230,7 @@ public class Identifier {
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof Identifier) { if (obj instanceof Identifier other) {
Identifier other = (Identifier) obj;
return key.equals(other.key); return key.equals(other.key);
} }
return false; return false;
@ -243,7 +239,7 @@ public class Identifier {
// Get the config entry for the identifier // Get the config entry for the identifier
@NotNull @NotNull
private Map.Entry<String, Boolean> getConfigEntry() { private Map.Entry<String, Boolean> getConfigEntry() {
return Maps.immutableEntry(getKeyValue(), enabledByDefault); return Map.entry(getKeyValue(), enabledByDefault);
} }
/** /**
@ -264,7 +260,7 @@ public class Identifier {
if (i1.dependsOn(i2)) { if (i1.dependsOn(i2)) {
if (i2.dependsOn(i1)) { if (i2.dependsOn(i1)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Found circular dependency between " + i1.getKey() + " and " + i2.getKey() "Found circular dependency between %s and %s".formatted(i1.getKey(), i2.getKey())
); );
} }
return 1; return 1;
@ -314,8 +310,7 @@ public class Identifier {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof Dependency) { if (obj instanceof Dependency other) {
Dependency other = (Dependency) obj;
return key.equals(other.key); return key.equals(other.key);
} }
return false; return false;

@ -26,7 +26,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors;
public interface SerializerRegistry { public interface SerializerRegistry {
@ -53,7 +52,7 @@ public interface SerializerRegistry {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default void registerSerializer(@NotNull Identifier id, @NotNull Serializer<? extends Data> serializer) { default void registerSerializer(@NotNull Identifier id, @NotNull Serializer<? extends Data> serializer) {
if (id.isCustom()) { if (id.isCustom()) {
getPlugin().log(Level.INFO, "Registered custom data type: " + id); getPlugin().log(Level.INFO, "Registered custom data type: %s".formatted(id));
} }
id.setEnabled(id.isCustom() || getPlugin().getSettings().getSynchronization().isFeatureEnabled(id)); id.setEnabled(id.isCustom() || getPlugin().getSettings().getSynchronization().isFeatureEnabled(id));
getSerializers().put(id, (Serializer<Data>) serializer); getSerializers().put(id, (Serializer<Data>) serializer);
@ -73,11 +72,11 @@ public interface SerializerRegistry {
final List<String> unmet = identifier.getDependencies().stream() final List<String> unmet = identifier.getDependencies().stream()
.filter(Identifier.Dependency::isRequired) .filter(Identifier.Dependency::isRequired)
.filter(dep -> !isDataTypeAvailable(dep.getKey().asString())) .filter(dep -> !isDataTypeAvailable(dep.getKey().asString()))
.map(dep -> dep.getKey().asString()) .map(dep -> dep.getKey().asString()).toList();
.collect(Collectors.toList());
if (!unmet.isEmpty()) { if (!unmet.isEmpty()) {
identifier.setEnabled(false); identifier.setEnabled(false);
getPlugin().log(Level.WARNING, "Disabled " + identifier + " syncing as the following types need to be on: " + String.join(", ", unmet)); getPlugin().log(Level.WARNING, "Disabled %s syncing as the following types need to be on: %s"
.formatted(identifier, String.join(", ", unmet)));
} }
}); });
} }
@ -117,7 +116,7 @@ public interface SerializerRegistry {
@NotNull @NotNull
default String serializeData(@NotNull Identifier identifier, @NotNull Data data) throws IllegalStateException { default String serializeData(@NotNull Identifier identifier, @NotNull Data data) throws IllegalStateException {
return getSerializer(identifier).map(serializer -> serializer.serialize(data)) return getSerializer(identifier).map(serializer -> serializer.serialize(data))
.orElseThrow(() -> new IllegalStateException("No serializer found for " + identifier)); .orElseThrow(() -> new IllegalStateException("No serializer found for %s".formatted(identifier)));
} }
/** /**
@ -134,7 +133,7 @@ public interface SerializerRegistry {
default Data deserializeData(@NotNull Identifier identifier, @NotNull String data, default Data deserializeData(@NotNull Identifier identifier, @NotNull String data,
@NotNull Version dataMcVersion) throws IllegalStateException { @NotNull Version dataMcVersion) throws IllegalStateException {
return getSerializer(identifier).map(serializer -> serializer.deserialize(data, dataMcVersion)).orElseThrow( return getSerializer(identifier).map(serializer -> serializer.deserialize(data, dataMcVersion)).orElseThrow(
() -> new IllegalStateException("No serializer found for " + identifier) () -> new IllegalStateException("No serializer found for %s".formatted(identifier))
); );
} }
@ -145,10 +144,10 @@ public interface SerializerRegistry {
* @param data the data to deserialize * @param data the data to deserialize
* @return the deserialized data * @return the deserialized data
* @since 3.5.4 * @since 3.5.4
* @deprecated Use {@link #deserializeData(Identifier, String, Version)} instead, since 3.6.5 * @deprecated Use {@link #deserializeData(Identifier, String, Version)} instead
*/ */
@NotNull @NotNull
@Deprecated @Deprecated(since = "3.6.5")
default Data deserializeData(@NotNull Identifier identifier, @NotNull String data) { default Data deserializeData(@NotNull Identifier identifier, @NotNull String data) {
return deserializeData(identifier, data, getPlugin().getMinecraftVersion()); return deserializeData(identifier, data, getPlugin().getMinecraftVersion());
} }
@ -165,7 +164,7 @@ public interface SerializerRegistry {
} }
// Returns if a data type is available and enabled in the config // Returns if a data type is available and enabled in the config
default boolean isDataTypeAvailable(@NotNull String key) { private boolean isDataTypeAvailable(@NotNull String key) {
return getIdentifier(key).map(Identifier::isEnabled).orElse(false); return getIdentifier(key).map(Identifier::isEnabled).orElse(false);
} }

@ -19,7 +19,6 @@
package net.william278.husksync.data; package net.william278.husksync.data;
import com.google.common.collect.Maps;
import net.william278.desertwell.util.ThrowingConsumer; import net.william278.desertwell.util.ThrowingConsumer;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@ -45,7 +44,7 @@ public interface UserDataHolder extends DataHolder {
default Map<Identifier, Data> getData() { default Map<Identifier, Data> getData() {
return getPlugin().getRegisteredDataTypes().stream() return getPlugin().getRegisteredDataTypes().stream()
.filter(Identifier::isEnabled) .filter(Identifier::isEnabled)
.map(id -> Maps.immutableEntry(id, getData(id))) .map(id -> Map.entry(id, getData(id)))
.filter(data -> data.getValue().isPresent()) .filter(data -> data.getValue().isPresent())
.collect(HashMap::new, (map, data) -> map.put(data.getKey(), data.getValue().get()), HashMap::putAll); .collect(HashMap::new, (map, data) -> map.put(data.getKey(), data.getValue().get()), HashMap::putAll);
} }

@ -19,14 +19,11 @@
package net.william278.husksync.database; package net.william278.husksync.database;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.Getter; import lombok.Getter;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.config.Settings; import net.william278.husksync.config.Settings;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.InputStreamUtil;
import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -59,10 +56,8 @@ public abstract class Database {
@SuppressWarnings("SameParameterValue") @SuppressWarnings("SameParameterValue")
@NotNull @NotNull
protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException { protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException {
return formatStatementTables(new String( return formatStatementTables(new String(Objects.requireNonNull(plugin.getResource(schemaFileName))
InputStreamUtil.readAllBytes(Objects.requireNonNull(plugin.getResource(schemaFileName))), .readAllBytes(), StandardCharsets.UTF_8)).split(";");
StandardCharsets.UTF_8
)).split(";");
} }
/** /**
@ -290,13 +285,13 @@ public abstract class Database {
@NotNull @NotNull
private Map.Entry<String, String> toEntry() { private Map.Entry<String, String> toEntry() {
return Maps.immutableEntry(name().toLowerCase(Locale.ENGLISH), defaultName); return Map.entry(name().toLowerCase(Locale.ENGLISH), defaultName);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@NotNull @NotNull
public static Map<String, String> getDefaults() { public static Map<String, String> getDefaults() {
return ImmutableMap.ofEntries(Arrays.stream(values()) return Map.ofEntries(Arrays.stream(values())
.map(TableName::toEntry) .map(TableName::toEntry)
.toArray(Map.Entry[]::new)); .toArray(Map.Entry[]::new));
} }

@ -30,7 +30,6 @@ import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.database.mongo.MongoCollectionHelper; import net.william278.husksync.database.mongo.MongoCollectionHelper;
import net.william278.husksync.database.mongo.MongoConnectionHandler; import net.william278.husksync.database.mongo.MongoConnectionHandler;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.OptionalUtil;
import org.bson.Document; import org.bson.Document;
import org.bson.conversions.Bson; import org.bson.conversions.Bson;
import org.bson.types.Binary; import org.bson.types.Binary;
@ -44,7 +43,6 @@ import java.util.Optional;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors;
public class MongoDbDatabase extends Database { public class MongoDbDatabase extends Database {
private MongoConnectionHandler mongoConnectionHandler; private MongoConnectionHandler mongoConnectionHandler;
@ -105,7 +103,7 @@ public class MongoDbDatabase extends Database {
@Override @Override
public void ensureUser(@NotNull User user) { public void ensureUser(@NotNull User user) {
try { try {
OptionalUtil.ifPresentOrElse(getUser(user.getUuid()), getUser(user.getUuid()).ifPresentOrElse(
existingUser -> { existingUser -> {
if (!existingUser.getUsername().equals(user.getUsername())) { if (!existingUser.getUsername().equals(user.getUsername())) {
// Update a user's name if it has changed in the database // Update a user's name if it has changed in the database
@ -279,8 +277,7 @@ public class MongoDbDatabase extends Database {
protected void rotateSnapshots(@NotNull User user) { protected void rotateSnapshots(@NotNull User user) {
try { try {
final List<DataSnapshot.Packed> unpinnedUserData = getAllSnapshots(user).stream() final List<DataSnapshot.Packed> unpinnedUserData = getAllSnapshots(user).stream()
.filter(dataSnapshot -> !dataSnapshot.isPinned()) .filter(dataSnapshot -> !dataSnapshot.isPinned()).toList();
.collect(Collectors.toList());
final int maxSnapshots = plugin.getSettings().getSynchronization().getMaxUserDataSnapshots(); final int maxSnapshots = plugin.getSettings().getSynchronization().getMaxUserDataSnapshots();
if (unpinnedUserData.size() > maxSnapshots) { if (unpinnedUserData.size() > maxSnapshots) {

@ -20,12 +20,11 @@
package net.william278.husksync.database; package net.william278.husksync.database;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.adapter.DataAdapter; import net.william278.husksync.adapter.DataAdapter;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.OptionalUtil;
import org.inksnow.cputil.db.AuroraDatabase;
import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -35,7 +34,6 @@ import java.sql.*;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors;
import static net.william278.husksync.config.Settings.DatabaseSettings; import static net.william278.husksync.config.Settings.DatabaseSettings;
@ -43,17 +41,15 @@ public class MySqlDatabase extends Database {
private static final String DATA_POOL_NAME = "HuskSyncHikariPool"; private static final String DATA_POOL_NAME = "HuskSyncHikariPool";
private final String flavor; private final String flavor;
private final org.inksnow.cputil.db.Database databaseType; private final String driverClass;
private AuroraDatabase dataSource; private HikariDataSource dataSource;
public MySqlDatabase(@NotNull HuskSync plugin) { public MySqlDatabase(@NotNull HuskSync plugin) {
super(plugin); super(plugin);
final Type type = plugin.getSettings().getDatabase().getType(); final Type type = plugin.getSettings().getDatabase().getType();
this.flavor = type.getProtocol(); this.flavor = type.getProtocol();
this.databaseType = type == Type.MARIADB this.driverClass = type == Type.MARIADB ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver";
? new org.inksnow.cputil.db.mariadb.MariadbDatabase()
: new org.inksnow.cputil.db.mysql.MysqlDatabase();
} }
/** /**
@ -76,44 +72,48 @@ public class MySqlDatabase extends Database {
public void initialize() throws IllegalStateException { public void initialize() throws IllegalStateException {
// Initialize the Hikari pooled connection // Initialize the Hikari pooled connection
final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials(); final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials();
dataSource = new HikariDataSource();
try { dataSource.setDriverClassName(driverClass);
dataSource = AuroraDatabase.builder() dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s",
.databaseType(databaseType) flavor,
.jdbcUrl(String.format("jdbc:%s://%s:%s/%s%s", credentials.getHost(),
flavor, credentials.getPort(),
credentials.getHost(), credentials.getDatabase(),
credentials.getPort(), credentials.getParameters()
credentials.getDatabase(), ));
credentials.getParameters()
)) // Authenticate with the database
.username(credentials.getUsername()) dataSource.setUsername(credentials.getUsername());
.password(credentials.getPassword()) dataSource.setPassword(credentials.getPassword());
.extension(dataSource -> {
final DatabaseSettings.PoolSettings pool = plugin.getSettings().getDatabase().getConnectionPool(); // Set connection pool options
dataSource.setMaximumPoolSize(pool.getMaximumPoolSize()); final DatabaseSettings.PoolSettings pool = plugin.getSettings().getDatabase().getConnectionPool();
dataSource.setMinimumIdle(pool.getMinimumIdle()); dataSource.setMaximumPoolSize(pool.getMaximumPoolSize());
dataSource.setMaxLifetime(pool.getMaximumLifetime()); dataSource.setMinimumIdle(pool.getMinimumIdle());
dataSource.setKeepaliveTime(pool.getKeepaliveTime()); dataSource.setMaxLifetime(pool.getMaximumLifetime());
dataSource.setConnectionTimeout(pool.getConnectionTimeout()); dataSource.setKeepaliveTime(pool.getKeepaliveTime());
dataSource.setPoolName(DATA_POOL_NAME); dataSource.setConnectionTimeout(pool.getConnectionTimeout());
}) dataSource.setPoolName(DATA_POOL_NAME);
.driverProperty("cachePrepStmts", "true")
.driverProperty("prepStmtCacheSize", "250") // Set additional connection pool properties
.driverProperty("prepStmtCacheSqlLimit", "2048") final Properties properties = new Properties();
.driverProperty("useServerPrepStmts", "true") properties.putAll(
.driverProperty("useLocalSessionState", "true") Map.of("cachePrepStmts", "true",
.driverProperty("useLocalTransactionState", "true") "prepStmtCacheSize", "250",
"prepStmtCacheSqlLimit", "2048",
.driverProperty("rewriteBatchedStatements", "true") "useServerPrepStmts", "true",
.driverProperty("cacheResultSetMetadata", "true") "useLocalSessionState", "true",
.driverProperty("cacheServerConfiguration", "true") "useLocalTransactionState", "true"
.driverProperty("elideSetAutoCommits", "true") ));
.driverProperty("maintainTimeStats", "false") properties.putAll(
.build(); Map.of(
} catch (IOException e) { "rewriteBatchedStatements", "true",
throw new IllegalStateException("Failed to initialize the Aurora database", e); "cacheResultSetMetadata", "true",
} "cacheServerConfiguration", "true",
"elideSetAutoCommits", "true",
"maintainTimeStats", "false")
);
dataSource.setDataSourceProperties(properties);
// Prepare database schema; make tables if they don't exist // Prepare database schema; make tables if they don't exist
try (Connection connection = dataSource.getConnection()) { try (Connection connection = dataSource.getConnection()) {
@ -135,14 +135,15 @@ public class MySqlDatabase extends Database {
@Blocking @Blocking
@Override @Override
public void ensureUser(@NotNull User user) { public void ensureUser(@NotNull User user) {
OptionalUtil.ifPresentOrElse(getUser(user.getUuid()), getUser(user.getUuid()).ifPresentOrElse(
existingUser -> { existingUser -> {
if (!existingUser.getUsername().equals(user.getUsername())) { if (!existingUser.getUsername().equals(user.getUsername())) {
// Update a user's name if it has changed in the database // Update a user's name if it has changed in the database
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"UPDATE `%users_table%` SET `username`=? WHERE `uuid`=?" UPDATE `%users_table%`
))) { SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUsername()); statement.setString(1, user.getUsername());
statement.setString(2, existingUser.getUuid().toString()); statement.setString(2, existingUser.getUuid().toString());
@ -157,9 +158,9 @@ public class MySqlDatabase extends Database {
() -> { () -> {
// Insert new player data into the database // Insert new player data into the database
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"INSERT INTO `%users_table%` (`uuid`,`username`) VALUES (?,?);" INSERT INTO `%users_table%` (`uuid`,`username`)
))) { VALUES (?,?);"""))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
statement.setString(2, user.getUsername()); statement.setString(2, user.getUsername());
@ -176,9 +177,10 @@ public class MySqlDatabase extends Database {
@Override @Override
public Optional<User> getUser(@NotNull UUID uuid) { public Optional<User> getUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT `uuid`, `username` FROM `%users_table%` WHERE `uuid`=?" SELECT `uuid`, `username`
))) { FROM `%users_table%`
WHERE `uuid`=?"""))) {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
@ -198,9 +200,10 @@ public class MySqlDatabase extends Database {
@Override @Override
public Optional<User> getUserByName(@NotNull String username) { public Optional<User> getUserByName(@NotNull String username) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT `uuid`, `username` FROM `%users_table%` WHERE `username`=?" SELECT `uuid`, `username`
))) { FROM `%users_table%`
WHERE `username`=?"""))) {
statement.setString(1, username); statement.setString(1, username);
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
@ -219,13 +222,12 @@ public class MySqlDatabase extends Database {
@Override @Override
public Optional<DataSnapshot.Packed> getLatestSnapshot(@NotNull User user) { public Optional<DataSnapshot.Packed> getLatestSnapshot(@NotNull User user) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT `version_uuid`, `timestamp`, `data` " + SELECT `version_uuid`, `timestamp`, `data`
"FROM `%user_data_table%` " + FROM `%user_data_table%`
"WHERE `player_uuid`=? " + WHERE `player_uuid`=?
"ORDER BY `timestamp` DESC " + ORDER BY `timestamp` DESC
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@ -251,12 +253,11 @@ public class MySqlDatabase extends Database {
public List<DataSnapshot.Packed> getAllSnapshots(@NotNull User user) { public List<DataSnapshot.Packed> getAllSnapshots(@NotNull User user) {
final List<DataSnapshot.Packed> retrievedData = Lists.newArrayList(); final List<DataSnapshot.Packed> retrievedData = Lists.newArrayList();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT `version_uuid`, `timestamp`, `data` " + SELECT `version_uuid`, `timestamp`, `data`
"FROM `%user_data_table%` " + FROM `%user_data_table%`
"WHERE `player_uuid`=? " + WHERE `player_uuid`=?
"ORDER BY `timestamp` DESC;" ORDER BY `timestamp` DESC;"""))) {
))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
@ -281,13 +282,12 @@ public class MySqlDatabase extends Database {
@Override @Override
public Optional<DataSnapshot.Packed> getSnapshot(@NotNull User user, @NotNull UUID versionUuid) { public Optional<DataSnapshot.Packed> getSnapshot(@NotNull User user, @NotNull UUID versionUuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT `version_uuid`, `timestamp`, `data` " + SELECT `version_uuid`, `timestamp`, `data`
"FROM `%user_data_table%` " + FROM `%user_data_table%`
"WHERE `player_uuid`=? AND `version_uuid`=? " + WHERE `player_uuid`=? AND `version_uuid`=?
"ORDER BY `timestamp` DESC " + ORDER BY `timestamp` DESC
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
statement.setString(2, versionUuid.toString()); statement.setString(2, versionUuid.toString());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
@ -311,17 +311,17 @@ public class MySqlDatabase extends Database {
@Override @Override
protected void rotateSnapshots(@NotNull User user) { protected void rotateSnapshots(@NotNull User user) {
final List<DataSnapshot.Packed> unpinnedUserData = getAllSnapshots(user).stream() final List<DataSnapshot.Packed> unpinnedUserData = getAllSnapshots(user).stream()
.filter(dataSnapshot -> !dataSnapshot.isPinned()) .filter(dataSnapshot -> !dataSnapshot.isPinned()).toList();
.collect(Collectors.toList());
final int maxSnapshots = plugin.getSettings().getSynchronization().getMaxUserDataSnapshots(); final int maxSnapshots = plugin.getSettings().getSynchronization().getMaxUserDataSnapshots();
if (unpinnedUserData.size() > maxSnapshots) { if (unpinnedUserData.size() > maxSnapshots) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"DELETE FROM `%user_data_table%` " + DELETE FROM `%user_data_table%`
"WHERE `player_uuid`=? " + WHERE `player_uuid`=?
"AND `pinned` IS FALSE " + AND `pinned` IS FALSE
"ORDER BY `timestamp` ASC " + ORDER BY `timestamp` ASC
"LIMIT " + (unpinnedUserData.size() - maxSnapshots) + ";"))) { LIMIT %entry_count%;""".replace("%entry_count%",
Integer.toString(unpinnedUserData.size() - maxSnapshots))))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
} }
@ -335,11 +335,10 @@ public class MySqlDatabase extends Database {
@Override @Override
public boolean deleteSnapshot(@NotNull User user, @NotNull UUID versionUuid) { public boolean deleteSnapshot(@NotNull User user, @NotNull UUID versionUuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"DELETE FROM `%user_data_table%` " + DELETE FROM `%user_data_table%`
"WHERE `player_uuid`=? AND `version_uuid`=? " + WHERE `player_uuid`=? AND `version_uuid`=?
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
statement.setString(2, versionUuid.toString()); statement.setString(2, versionUuid.toString());
return statement.executeUpdate() > 0; return statement.executeUpdate() > 0;
@ -354,12 +353,11 @@ public class MySqlDatabase extends Database {
@Override @Override
protected void rotateLatestSnapshot(@NotNull User user, @NotNull OffsetDateTime within) { protected void rotateLatestSnapshot(@NotNull User user, @NotNull OffsetDateTime within) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"DELETE FROM `%user_data_table%` " + DELETE FROM `%user_data_table%`
"WHERE `player_uuid`=? AND `timestamp`>? AND `pinned` IS FALSE " + WHERE `player_uuid`=? AND `timestamp`>? AND `pinned` IS FALSE
"ORDER BY `timestamp` ASC " + ORDER BY `timestamp` ASC
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
statement.setTimestamp(2, Timestamp.from(within.toInstant())); statement.setTimestamp(2, Timestamp.from(within.toInstant()));
statement.executeUpdate(); statement.executeUpdate();
@ -373,11 +371,10 @@ public class MySqlDatabase extends Database {
@Override @Override
protected void createSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) { protected void createSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"INSERT INTO `%user_data_table%` " + INSERT INTO `%user_data_table%`
"(`player_uuid`,`version_uuid`,`timestamp`,`save_cause`,`pinned`,`data`) " + (`player_uuid`,`version_uuid`,`timestamp`,`save_cause`,`pinned`,`data`)
"VALUES (?,?,?,?,?,?);" VALUES (?,?,?,?,?,?);"""))) {
))) {
statement.setString(1, user.getUuid().toString()); statement.setString(1, user.getUuid().toString());
statement.setString(2, data.getId().toString()); statement.setString(2, data.getId().toString());
statement.setTimestamp(3, Timestamp.from(data.getTimestamp().toInstant())); statement.setTimestamp(3, Timestamp.from(data.getTimestamp().toInstant()));
@ -395,12 +392,11 @@ public class MySqlDatabase extends Database {
@Override @Override
public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) { public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"UPDATE `%user_data_table%` " + UPDATE `%user_data_table%`
"SET `save_cause`=?,`pinned`=?,`data`=? " + SET `save_cause`=?,`pinned`=?,`data`=?
"WHERE `player_uuid`=? AND `version_uuid`=? " + WHERE `player_uuid`=? AND `version_uuid`=?
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setString(1, data.getSaveCause().name()); statement.setString(1, data.getSaveCause().name());
statement.setBoolean(2, data.isPinned()); statement.setBoolean(2, data.isPinned());
statement.setBlob(3, new ByteArrayInputStream(data.asBytes(plugin))); statement.setBlob(3, new ByteArrayInputStream(data.asBytes(plugin)));

@ -25,8 +25,6 @@ import net.william278.husksync.HuskSync;
import net.william278.husksync.adapter.DataAdapter; import net.william278.husksync.adapter.DataAdapter;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.OptionalUtil;
import org.inksnow.cputil.db.AuroraDatabase;
import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -35,7 +33,6 @@ import java.sql.*;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors;
import static net.william278.husksync.config.Settings.DatabaseSettings; import static net.william278.husksync.config.Settings.DatabaseSettings;
@ -43,7 +40,7 @@ public class PostgresDatabase extends Database {
private static final String DATA_POOL_NAME = "HuskSyncHikariPool"; private static final String DATA_POOL_NAME = "HuskSyncHikariPool";
private final String flavor; private final String flavor;
private final org.inksnow.cputil.db.Database databaseType; private final String driverClass;
private HikariDataSource dataSource; private HikariDataSource dataSource;
public PostgresDatabase(@NotNull HuskSync plugin) { public PostgresDatabase(@NotNull HuskSync plugin) {
@ -51,7 +48,7 @@ public class PostgresDatabase extends Database {
final Type type = plugin.getSettings().getDatabase().getType(); final Type type = plugin.getSettings().getDatabase().getType();
this.flavor = type.getProtocol(); this.flavor = type.getProtocol();
this.databaseType = new org.inksnow.cputil.db.postgres.PostgresqlDatabase(); this.driverClass = "org.postgresql.Driver";
} }
/** /**
@ -74,44 +71,48 @@ public class PostgresDatabase extends Database {
public void initialize() throws IllegalStateException { public void initialize() throws IllegalStateException {
// Initialize the Hikari pooled connection // Initialize the Hikari pooled connection
final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials(); final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials();
dataSource = new HikariDataSource();
try { dataSource.setDriverClassName(driverClass);
dataSource = AuroraDatabase.builder() dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s",
.databaseType(databaseType) flavor,
.jdbcUrl(String.format("jdbc:%s://%s:%s/%s%s", credentials.getHost(),
flavor, credentials.getPort(),
credentials.getHost(), credentials.getDatabase(),
credentials.getPort(), credentials.getParameters()
credentials.getDatabase(), ));
credentials.getParameters()
)) // Authenticate with the database
.extension(dataSource -> { dataSource.setUsername(credentials.getUsername());
final DatabaseSettings.PoolSettings pool = plugin.getSettings().getDatabase().getConnectionPool(); dataSource.setPassword(credentials.getPassword());
dataSource.setMaximumPoolSize(pool.getMaximumPoolSize());
dataSource.setMinimumIdle(pool.getMinimumIdle()); // Set connection pool options
dataSource.setMaxLifetime(pool.getMaximumLifetime()); final DatabaseSettings.PoolSettings pool = plugin.getSettings().getDatabase().getConnectionPool();
dataSource.setKeepaliveTime(pool.getKeepaliveTime()); dataSource.setMaximumPoolSize(pool.getMaximumPoolSize());
dataSource.setConnectionTimeout(pool.getConnectionTimeout()); dataSource.setMinimumIdle(pool.getMinimumIdle());
dataSource.setPoolName(DATA_POOL_NAME); dataSource.setMaxLifetime(pool.getMaximumLifetime());
}) dataSource.setKeepaliveTime(pool.getKeepaliveTime());
.username(credentials.getUsername()) dataSource.setConnectionTimeout(pool.getConnectionTimeout());
.password(credentials.getPassword()) dataSource.setPoolName(DATA_POOL_NAME);
.driverProperty("cachePrepStmts", "true")
.driverProperty("prepStmtCacheSize", "250") // Set additional connection pool properties
.driverProperty("prepStmtCacheSqlLimit", "2048") final Properties properties = new Properties();
.driverProperty("useServerPrepStmts", "true") properties.putAll(
.driverProperty("useLocalSessionState", "true") Map.of("cachePrepStmts", "true",
.driverProperty("useLocalTransactionState", "true") "prepStmtCacheSize", "250",
"prepStmtCacheSqlLimit", "2048",
.driverProperty("rewriteBatchedStatements", "true") "useServerPrepStmts", "true",
.driverProperty("cacheResultSetMetadata", "true") "useLocalSessionState", "true",
.driverProperty("cacheServerConfiguration", "true") "useLocalTransactionState", "true"
.driverProperty("elideSetAutoCommits", "true") ));
.driverProperty("maintainTimeStats", "false") properties.putAll(
.build(); Map.of(
} catch (IOException e) { "rewriteBatchedStatements", "true",
throw new IllegalStateException("Failed to initialize the Aurora database", e); "cacheResultSetMetadata", "true",
} "cacheServerConfiguration", "true",
"elideSetAutoCommits", "true",
"maintainTimeStats", "false")
);
dataSource.setDataSourceProperties(properties);
// Prepare database schema; make tables if they don't exist // Prepare database schema; make tables if they don't exist
try (Connection connection = dataSource.getConnection()) { try (Connection connection = dataSource.getConnection()) {
@ -133,16 +134,15 @@ public class PostgresDatabase extends Database {
@Blocking @Blocking
@Override @Override
public void ensureUser(@NotNull User user) { public void ensureUser(@NotNull User user) {
OptionalUtil.ifPresentOrElse(getUser(user.getUuid()), getUser(user.getUuid()).ifPresentOrElse(
existingUser -> { existingUser -> {
if (!existingUser.getUsername().equals(user.getUsername())) { if (!existingUser.getUsername().equals(user.getUsername())) {
// Update a user's name if it has changed in the database // Update a user's name if it has changed in the database
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"UPDATE \"%users_table%\" " + UPDATE "%users_table%"
"SET \"username\"=? " + SET "username"=?
"WHERE \"uuid\"=?" WHERE "uuid"=?"""))) {
))) {
statement.setString(1, user.getUsername()); statement.setString(1, user.getUsername());
statement.setObject(2, existingUser.getUuid()); statement.setObject(2, existingUser.getUuid());
@ -157,10 +157,9 @@ public class PostgresDatabase extends Database {
() -> { () -> {
// Insert new player data into the database // Insert new player data into the database
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"INSERT INTO \"%users_table%\" (\"uuid\",\"username\") " + INSERT INTO "%users_table%" ("uuid","username")
"VALUES (?,?);" VALUES (?,?);"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
statement.setString(2, user.getUsername()); statement.setString(2, user.getUsername());
@ -177,11 +176,10 @@ public class PostgresDatabase extends Database {
@Override @Override
public Optional<User> getUser(@NotNull UUID uuid) { public Optional<User> getUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT \"uuid\", \"username\" " + SELECT "uuid", "username"
"FROM \"%users_table%\" " + FROM "%users_table%"
"WHERE \"uuid\"=?" WHERE "uuid"=?"""))) {
))) {
statement.setObject(1, uuid); statement.setObject(1, uuid);
@ -201,11 +199,10 @@ public class PostgresDatabase extends Database {
@Override @Override
public Optional<User> getUserByName(@NotNull String username) { public Optional<User> getUserByName(@NotNull String username) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT \"uuid\", \"username\" " + SELECT "uuid", "username"
"FROM \"%users_table%\" " + FROM "%users_table%"
"WHERE \"username\"=?" WHERE "username"=?"""))) {
))) {
statement.setString(1, username); statement.setString(1, username);
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
@ -224,13 +221,12 @@ public class PostgresDatabase extends Database {
@Override @Override
public Optional<DataSnapshot.Packed> getLatestSnapshot(@NotNull User user) { public Optional<DataSnapshot.Packed> getLatestSnapshot(@NotNull User user) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT \"version_uuid\", \"timestamp\", \"data\" " + SELECT "version_uuid", "timestamp", "data"
"FROM \"%user_data_table%\" " + FROM "%user_data_table%"
"WHERE \"player_uuid\"=? " + WHERE "player_uuid"=?
"ORDER BY \"timestamp\" DESC " + ORDER BY "timestamp" DESC
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@ -254,12 +250,11 @@ public class PostgresDatabase extends Database {
public List<DataSnapshot.Packed> getAllSnapshots(@NotNull User user) { public List<DataSnapshot.Packed> getAllSnapshots(@NotNull User user) {
final List<DataSnapshot.Packed> retrievedData = Lists.newArrayList(); final List<DataSnapshot.Packed> retrievedData = Lists.newArrayList();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT \"version_uuid\", \"timestamp\", \"data\" " + SELECT "version_uuid", "timestamp", "data"
"FROM \"%user_data_table%\" " + FROM "%user_data_table%"
"WHERE \"player_uuid\"=? " + WHERE "player_uuid"=?
"ORDER BY \"timestamp\" DESC;" ORDER BY "timestamp" DESC;"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
@ -282,13 +277,12 @@ public class PostgresDatabase extends Database {
@Override @Override
public Optional<DataSnapshot.Packed> getSnapshot(@NotNull User user, @NotNull UUID versionUuid) { public Optional<DataSnapshot.Packed> getSnapshot(@NotNull User user, @NotNull UUID versionUuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"SELECT \"version_uuid\", \"timestamp\", \"data\" " + SELECT "version_uuid", "timestamp", "data"
"FROM \"%user_data_table%\" " + FROM "%user_data_table%"
"WHERE \"player_uuid\"=? AND \"version_uuid\"=? " + WHERE "player_uuid"=? AND "version_uuid"=?
"ORDER BY \"timestamp\" DESC " + ORDER BY "timestamp" DESC
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
statement.setObject(2, versionUuid); statement.setObject(2, versionUuid);
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
@ -310,18 +304,17 @@ public class PostgresDatabase extends Database {
@Override @Override
protected void rotateSnapshots(@NotNull User user) { protected void rotateSnapshots(@NotNull User user) {
final List<DataSnapshot.Packed> unpinnedUserData = getAllSnapshots(user).stream() final List<DataSnapshot.Packed> unpinnedUserData = getAllSnapshots(user).stream()
.filter(dataSnapshot -> !dataSnapshot.isPinned()) .filter(dataSnapshot -> !dataSnapshot.isPinned()).toList();
.collect(Collectors.toList());
final int maxSnapshots = plugin.getSettings().getSynchronization().getMaxUserDataSnapshots(); final int maxSnapshots = plugin.getSettings().getSynchronization().getMaxUserDataSnapshots();
if (unpinnedUserData.size() > maxSnapshots) { if (unpinnedUserData.size() > maxSnapshots) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"DELETE FROM \"%user_data_table%\"\n" + DELETE FROM "%user_data_table%"
"WHERE \"player_uuid\"=?\n" + WHERE "player_uuid"=?
"AND \"pinned\" = FALSE\n" + AND "pinned" = FALSE
"ORDER BY \"timestamp\" ASC\n" + ORDER BY "timestamp" ASC
"LIMIT " + (unpinnedUserData.size() - maxSnapshots) + ";" LIMIT %entry_count%;""".replace("%entry_count%",
))) { Integer.toString(unpinnedUserData.size() - maxSnapshots))))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
statement.executeUpdate(); statement.executeUpdate();
} }
@ -335,11 +328,10 @@ public class PostgresDatabase extends Database {
@Override @Override
public boolean deleteSnapshot(@NotNull User user, @NotNull UUID versionUuid) { public boolean deleteSnapshot(@NotNull User user, @NotNull UUID versionUuid) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"DELETE FROM \"%user_data_table%\" " + DELETE FROM "%user_data_table%"
"WHERE \"player_uuid\"=? AND \"version_uuid\"=? " + WHERE "player_uuid"=? AND "version_uuid"=?
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
statement.setString(2, versionUuid.toString()); statement.setString(2, versionUuid.toString());
return statement.executeUpdate() > 0; return statement.executeUpdate() > 0;
@ -354,16 +346,15 @@ public class PostgresDatabase extends Database {
@Override @Override
protected void rotateLatestSnapshot(@NotNull User user, @NotNull OffsetDateTime within) { protected void rotateLatestSnapshot(@NotNull User user, @NotNull OffsetDateTime within) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"DELETE FROM \"%user_data_table%\" " + DELETE FROM "%user_data_table%"
"WHERE \"player_uuid\"=? AND \"timestamp\" = ( " + WHERE "player_uuid"=? AND "timestamp" = (
" SELECT \"timestamp\" " + SELECT "timestamp"
" FROM \"%user_data_table%\" " + FROM "%user_data_table%"
" WHERE \"player_uuid\"=? AND \"timestamp\" > ? AND \"pinned\" = FALSE " + WHERE "player_uuid"=? AND "timestamp" > ? AND "pinned" = FALSE
" ORDER BY \"timestamp\" ASC " + ORDER BY "timestamp" ASC
" LIMIT 1 " + LIMIT 1
");" );"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
statement.setObject(2, user.getUuid()); statement.setObject(2, user.getUuid());
statement.setTimestamp(3, Timestamp.from(within.toInstant())); statement.setTimestamp(3, Timestamp.from(within.toInstant()));
@ -378,11 +369,10 @@ public class PostgresDatabase extends Database {
@Override @Override
protected void createSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) { protected void createSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"INSERT INTO \"%user_data_table%\" " + INSERT INTO "%user_data_table%"
"(\"player_uuid\",\"version_uuid\",\"timestamp\",\"save_cause\",\"pinned\",\"data\") " + ("player_uuid","version_uuid","timestamp","save_cause","pinned","data")
"VALUES (?,?,?,?,?,?);" VALUES (?,?,?,?,?,?);"""))) {
))) {
statement.setObject(1, user.getUuid()); statement.setObject(1, user.getUuid());
statement.setObject(2, data.getId()); statement.setObject(2, data.getId());
statement.setTimestamp(3, Timestamp.from(data.getTimestamp().toInstant())); statement.setTimestamp(3, Timestamp.from(data.getTimestamp().toInstant()));
@ -400,12 +390,11 @@ public class PostgresDatabase extends Database {
@Override @Override
public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) { public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables( try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
"UPDATE \"%user_data_table%\" " + UPDATE "%user_data_table%"
"SET \"save_cause\"=?,\"pinned\"=?,\"data\"=? " + SET "save_cause"=?,"pinned"=?,"data"=?
"WHERE \"player_uuid\"=? AND \"version_uuid\"=? " + WHERE "player_uuid"=? AND "version_uuid"=?
"LIMIT 1;" LIMIT 1;"""))) {
))) {
statement.setString(1, data.getSaveCause().name()); statement.setString(1, data.getSaveCause().name());
statement.setBoolean(2, data.isPinned()); statement.setBoolean(2, data.isPinned());
statement.setBytes(3, data.asBytes(plugin)); statement.setBytes(3, data.asBytes(plugin));

@ -34,7 +34,6 @@ import net.william278.husksync.data.DataSnapshot;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
@ -249,8 +248,7 @@ public class PlanHook {
return getLatestSnapshot(playerUUID) return getLatestSnapshot(playerUUID)
.flatMap(DataHolder::getAdvancements) .flatMap(DataHolder::getAdvancements)
.map(Data.Advancements::getCompleted) .map(Data.Advancements::getCompleted)
.map(List::size) .stream().count();
.orElse(0);
} }
@Conditional("hasSynced") @Conditional("hasSynced")

@ -19,8 +19,6 @@
package net.william278.husksync.listener; package net.william278.husksync.listener;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.data.Data; import net.william278.husksync.data.Data;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
@ -161,13 +159,13 @@ public abstract class EventListener {
@NotNull @NotNull
private Map.Entry<String, String> toEntry() { private Map.Entry<String, String> toEntry() {
return Maps.immutableEntry(name().toLowerCase(), defaultPriority.name()); return Map.entry(name().toLowerCase(), defaultPriority.name());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@NotNull @NotNull
public static Map<String, String> getDefaults() { public static Map<String, String> getDefaults() {
return ImmutableMap.ofEntries(Arrays.stream(values()) return Map.ofEntries(Arrays.stream(values())
.map(ListenerType::toEntry) .map(ListenerType::toEntry)
.toArray(Map.Entry[]::new)); .toArray(Map.Entry[]::new));
} }

@ -19,7 +19,6 @@
package net.william278.husksync.migrator; package net.william278.husksync.migrator;
import com.google.common.base.Strings;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -57,9 +56,7 @@ public abstract class Migrator {
* @return The data string obfuscated with stars (*) * @return The data string obfuscated with stars (*)
*/ */
protected final String obfuscateDataString(@NotNull String dataString) { protected final String obfuscateDataString(@NotNull String dataString) {
return (dataString.length() > 1 return (dataString.length() > 1 ? dataString.charAt(0) + "*".repeat(dataString.length() - 1) : "");
? dataString.charAt(0) + Strings.repeat("*", dataString.length() - 1)
: "");
} }
@NotNull @NotNull

@ -23,7 +23,6 @@ import net.william278.husksync.HuskSync;
import net.william278.husksync.config.Settings; import net.william278.husksync.config.Settings;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.CompletableFutureUtil;
import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.*; import redis.clients.jedis.*;
@ -128,7 +127,8 @@ public class RedisManager extends JedisPubSub {
} }
if (reconnected) { if (reconnected) {
plugin.log(Level.WARNING, "Redis Server connection lost. Attempting reconnect in " + (RECONNECTION_TIME / 1000) + "s...", t); plugin.log(Level.WARNING, "Redis Server connection lost. Attempting reconnect in %ss..."
.formatted(RECONNECTION_TIME / 1000), t);
} }
try { try {
this.unsubscribe(); this.unsubscribe();
@ -157,8 +157,7 @@ public class RedisManager extends JedisPubSub {
final RedisMessage redisMessage = RedisMessage.fromJson(plugin, message); final RedisMessage redisMessage = RedisMessage.fromJson(plugin, message);
switch (messageType) { switch (messageType) {
case UPDATE_USER_DATA: { case UPDATE_USER_DATA -> plugin.getOnlineUser(redisMessage.getTargetUuid()).ifPresent(
plugin.getOnlineUser(redisMessage.getTargetUuid()).ifPresent(
user -> { user -> {
try { try {
final DataSnapshot.Packed data = DataSnapshot.deserialize(plugin, redisMessage.getPayload()); final DataSnapshot.Packed data = DataSnapshot.deserialize(plugin, redisMessage.getPayload());
@ -168,19 +167,14 @@ public class RedisManager extends JedisPubSub {
user.completeSync(false, DataSnapshot.UpdateCause.UPDATED, plugin); user.completeSync(false, DataSnapshot.UpdateCause.UPDATED, plugin);
} }
} }
); );
break; case REQUEST_USER_DATA -> plugin.getOnlineUser(redisMessage.getTargetUuid()).ifPresent(
}
case REQUEST_USER_DATA: {
plugin.getOnlineUser(redisMessage.getTargetUuid()).ifPresent(
user -> RedisMessage.create( user -> RedisMessage.create(
UUID.fromString(new String(redisMessage.getPayload(), StandardCharsets.UTF_8)), UUID.fromString(new String(redisMessage.getPayload(), StandardCharsets.UTF_8)),
user.createSnapshot(DataSnapshot.SaveCause.INVENTORY_COMMAND).asBytes(plugin) user.createSnapshot(DataSnapshot.SaveCause.INVENTORY_COMMAND).asBytes(plugin)
).dispatch(plugin, RedisMessage.Type.RETURN_USER_DATA) ).dispatch(plugin, RedisMessage.Type.RETURN_USER_DATA)
); );
break; case RETURN_USER_DATA -> {
}
case RETURN_USER_DATA: {
final CompletableFuture<Optional<DataSnapshot.Packed>> future = pendingRequests.get( final CompletableFuture<Optional<DataSnapshot.Packed>> future = pendingRequests.get(
redisMessage.getTargetUuid() redisMessage.getTargetUuid()
); );
@ -194,10 +188,6 @@ public class RedisManager extends JedisPubSub {
} }
pendingRequests.remove(redisMessage.getTargetUuid()); pendingRequests.remove(redisMessage.getTargetUuid());
} }
break;
}
default: {
// Do nothing
} }
} }
} }
@ -244,7 +234,8 @@ public class RedisManager extends JedisPubSub {
); );
redisMessage.dispatch(plugin, RedisMessage.Type.REQUEST_USER_DATA); redisMessage.dispatch(plugin, RedisMessage.Type.REQUEST_USER_DATA);
}); });
return CompletableFutureUtil.orTimeout(future, return future
.orTimeout(
plugin.getSettings().getSynchronization().getNetworkLatencyMilliseconds(), plugin.getSettings().getSynchronization().getNetworkLatencyMilliseconds(),
TimeUnit.MILLISECONDS TimeUnit.MILLISECONDS
) )

@ -26,7 +26,6 @@ import net.william278.husksync.database.Database;
import net.william278.husksync.redis.RedisManager; import net.william278.husksync.redis.RedisManager;
import net.william278.husksync.user.OnlineUser; import net.william278.husksync.user.OnlineUser;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
import net.william278.husksync.util.OptionalUtil;
import net.william278.husksync.util.Task; import net.william278.husksync.util.Task;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.Blocking;
@ -159,12 +158,12 @@ public abstract class DataSyncer {
@ApiStatus.Internal @ApiStatus.Internal
protected void setUserFromDatabase(@NotNull OnlineUser user) { protected void setUserFromDatabase(@NotNull OnlineUser user) {
try { try {
OptionalUtil.ifPresentOrElse(getDatabase().getLatestSnapshot(user), getDatabase().getLatestSnapshot(user).ifPresentOrElse(
snapshot -> user.applySnapshot(snapshot, DataSnapshot.UpdateCause.SYNCHRONIZED), snapshot -> user.applySnapshot(snapshot, DataSnapshot.UpdateCause.SYNCHRONIZED),
() -> user.completeSync(true, DataSnapshot.UpdateCause.NEW_USER, plugin) () -> user.completeSync(true, DataSnapshot.UpdateCause.NEW_USER, plugin)
); );
} catch (Throwable e) { } catch (Throwable e) {
plugin.log(Level.WARNING, "Failed to set " + user.getUsername() + "'s data from the database", e); plugin.log(Level.WARNING, "Failed to set %s's data from the database".formatted(user.getUsername()), e);
user.completeSync(false, DataSnapshot.UpdateCause.SYNCHRONIZED, plugin); user.completeSync(false, DataSnapshot.UpdateCause.SYNCHRONIZED, plugin);
} }
} }

@ -23,7 +23,6 @@ import net.william278.husksync.HuskSync;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.redis.RedisKeyType; import net.william278.husksync.redis.RedisKeyType;
import net.william278.husksync.user.OnlineUser; import net.william278.husksync.user.OnlineUser;
import net.william278.husksync.util.OptionalUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class LockstepDataSyncer extends DataSyncer { public class LockstepDataSyncer extends DataSyncer {
@ -50,7 +49,7 @@ public class LockstepDataSyncer extends DataSyncer {
return false; return false;
} }
getRedis().setUserCheckedOut(user, true); getRedis().setUserCheckedOut(user, true);
OptionalUtil.ifPresentOrElse(getRedis().getUserData(user), getRedis().getUserData(user).ifPresentOrElse(
data -> user.applySnapshot(data, DataSnapshot.UpdateCause.SYNCHRONIZED), data -> user.applySnapshot(data, DataSnapshot.UpdateCause.SYNCHRONIZED),
() -> this.setUserFromDatabase(user) () -> this.setUserFromDatabase(user)
); );

@ -89,9 +89,9 @@ public abstract class OnlineUser extends User implements CommandUser, UserDataHo
* @param description the description of the toast * @param description the description of the toast
* @param iconMaterial the namespace-keyed material to use as an hasIcon of the toast * @param iconMaterial the namespace-keyed material to use as an hasIcon of the toast
* @param backgroundType the background ("ToastType") of the toast * @param backgroundType the background ("ToastType") of the toast
* @deprecated No longer supported, since 3.6.7 * @deprecated No longer supported
*/ */
@Deprecated @Deprecated(since = "3.6.7")
public abstract void sendToast(@NotNull MineDown title, @NotNull MineDown description, public abstract void sendToast(@NotNull MineDown title, @NotNull MineDown description,
@NotNull String iconMaterial, @NotNull String backgroundType); @NotNull String iconMaterial, @NotNull String backgroundType);
@ -145,17 +145,8 @@ public abstract class OnlineUser extends User implements CommandUser, UserDataHo
public void completeSync(boolean succeeded, @NotNull DataSnapshot.UpdateCause cause, @NotNull HuskSync plugin) { public void completeSync(boolean succeeded, @NotNull DataSnapshot.UpdateCause cause, @NotNull HuskSync plugin) {
if (succeeded) { if (succeeded) {
switch (plugin.getSettings().getSynchronization().getNotificationDisplaySlot()) { switch (plugin.getSettings().getSynchronization().getNotificationDisplaySlot()) {
case CHAT: { case CHAT -> cause.getCompletedLocale(plugin).ifPresent(this::sendMessage);
cause.getCompletedLocale(plugin).ifPresent(this::sendMessage); case ACTION_BAR -> cause.getCompletedLocale(plugin).ifPresent(this::sendActionBar);
break;
}
case ACTION_BAR:{
cause.getCompletedLocale(plugin).ifPresent(this::sendActionBar);
break;
}
default: {
// do nothing
}
} }
plugin.fireEvent( plugin.fireEvent(
plugin.getSyncCompleteEvent(this), plugin.getSyncCompleteEvent(this),

@ -55,8 +55,7 @@ public class User {
@Override @Override
public boolean equals(Object object) { public boolean equals(Object object) {
if (object instanceof User) { if (object instanceof User other) {
User other = (User) object;
return this.getUuid().equals(other.getUuid()); return this.getUuid().equals(other.getUuid());
} }
return super.equals(object); return super.equals(object);

@ -1,86 +0,0 @@
/*
* This file is part of HuskSync, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.husksync.util;
import lombok.experimental.UtilityClass;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
@UtilityClass
public class CompletableFutureUtil {
public static <T>CompletableFuture<T> orTimeout(CompletableFuture<T> $this, long timeout, TimeUnit unit) {
if (unit == null)
throw new NullPointerException();
if (!$this.isDone()) {
$this.whenComplete(new Canceller(Delayer.delay(new Timeout($this),
timeout, unit)));
}
return $this;
}
static final class Canceller implements BiConsumer<Object, Throwable> {
final Future<?> f;
Canceller(Future<?> f) { this.f = f; }
public void accept(Object ignore, Throwable ex) {
if (ex == null && f != null && !f.isDone())
f.cancel(false);
}
}
static final class Delayer {
static ScheduledFuture<?> delay(Runnable command, long delay,
TimeUnit unit) {
return delayer.schedule(command, delay, unit);
}
static final class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("CompletableFutureDelayScheduler");
return t;
}
}
static final ScheduledThreadPoolExecutor delayer;
static {
(delayer = new ScheduledThreadPoolExecutor(
1, new Delayer.DaemonThreadFactory())).
setRemoveOnCancelPolicy(true);
}
}
static final class Timeout implements Runnable {
final CompletableFuture<?> f;
Timeout(CompletableFuture<?> f) { this.f = f; }
public void run() {
if (f != null && !f.isDone())
f.completeExceptionally(new TimeoutException());
}
}
}

@ -21,7 +21,6 @@ package net.william278.husksync.util;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import lombok.SneakyThrows;
import net.william278.husksync.HuskSync; import net.william278.husksync.HuskSync;
import net.william278.husksync.data.DataSnapshot; import net.william278.husksync.data.DataSnapshot;
import net.william278.husksync.user.User; import net.william278.husksync.user.User;
@ -125,9 +124,8 @@ public class DataDumper {
} }
@NotNull @NotNull
@SneakyThrows
private String getWebContentField() { private String getWebContentField() {
return "content=" + URLEncoder.encode(toString(), "UTF-8"); return "content=" + URLEncoder.encode(toString(), StandardCharsets.UTF_8);
} }
/** /**
@ -138,7 +136,7 @@ public class DataDumper {
@NotNull @NotNull
public String toFile() throws IOException { public String toFile() throws IOException {
final Path filePath = getFilePath(); final Path filePath = getFilePath();
try (final Writer writer = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8)) { try (final FileWriter writer = new FileWriter(filePath.toFile(), StandardCharsets.UTF_8, false)) {
writer.write(toString()); // Write the data from #getString to the file using a writer writer.write(toString()); // Write the data from #getString to the file using a writer
return filePath.toString(); return filePath.toString();
} catch (IOException e) { } catch (IOException e) {

@ -30,7 +30,6 @@ import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle; import java.time.format.FormatStyle;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/** /**
* Represents a chat-viewable paginated list of {@link net.william278.husksync.data.DataSnapshot}s * Represents a chat-viewable paginated list of {@link net.william278.husksync.data.DataSnapshot}s
@ -61,8 +60,7 @@ public class DataSnapshotList {
snapshot.getSaveCause().getLocale(plugin), snapshot.getSaveCause().getLocale(plugin),
String.format("%.2fKiB", snapshot.getFileSize(plugin) / 1024f), String.format("%.2fKiB", snapshot.getFileSize(plugin) / 1024f),
snapshot.isInvalid() ? snapshot.getInvalidReason(plugin) : "") snapshot.isInvalid() ? snapshot.getInvalidReason(plugin) : "")
.orElse("• " + snapshot.getId())) .orElse("• " + snapshot.getId())).toList(),
.collect(Collectors.toList()),
plugin.getLocales().getBaseChatList(6) plugin.getLocales().getBaseChatList(6)
.setHeaderFormat(plugin.getLocales() .setHeaderFormat(plugin.getLocales()
.getRawLocale("data_list_title", dataOwner.getUsername(), .getRawLocale("data_list_title", dataOwner.getUsername(),

@ -1,108 +0,0 @@
/*
* This file is part of HuskSync, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.husksync.util;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@UtilityClass
public class InputStreamUtil {
// MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to
// use when skipping.
private static final int MAX_SKIP_BUFFER_SIZE = 2048;
private static final int DEFAULT_BUFFER_SIZE = 8192;
private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
public static byte[] readAllBytes(InputStream $this) throws IOException {
return readNBytes($this, Integer.MAX_VALUE);
}
public static byte[] readNBytes(InputStream $this, int len) throws IOException {
if (len < 0) {
throw new IllegalArgumentException("len < 0");
}
List<byte[]> bufs = null;
byte[] result = null;
int total = 0;
int remaining = len;
int n;
do {
byte[] buf = new byte[Math.min(remaining, DEFAULT_BUFFER_SIZE)];
int nread = 0;
// read to EOF which may read more or less than buffer size
while ((n = $this.read(buf, nread,
Math.min(buf.length - nread, remaining))) > 0) {
nread += n;
remaining -= n;
}
if (nread > 0) {
if (MAX_BUFFER_SIZE - total < nread) {
throw new OutOfMemoryError("Required array size too large");
}
if (nread < buf.length) {
buf = Arrays.copyOfRange(buf, 0, nread);
}
total += nread;
if (result == null) {
result = buf;
} else {
if (bufs == null) {
bufs = new ArrayList<>();
bufs.add(result);
}
bufs.add(buf);
}
}
// if the last call to read returned -1 or the number of bytes
// requested have been read then break
} while (n >= 0 && remaining > 0);
if (bufs == null) {
if (result == null) {
return new byte[0];
}
return result.length == total ?
result : Arrays.copyOf(result, total);
}
result = new byte[total];
int offset = 0;
remaining = total;
for (byte[] b : bufs) {
int count = Math.min(b.length, remaining);
System.arraycopy(b, 0, result, offset, count);
offset += count;
remaining -= count;
}
return result;
}
}

@ -1,54 +0,0 @@
/*
* This file is part of HuskSync, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.husksync.util;
import lombok.experimental.UtilityClass;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
@UtilityClass
public class OptionalUtil {
public static <T> Optional<T> or(Optional<T> $this, Supplier<? extends Optional<? extends T>> supplier) {
Objects.requireNonNull(supplier);
if ($this.isPresent()) {
return $this;
} else {
@SuppressWarnings("unchecked")
Optional<T> r = (Optional<T>) supplier.get();
return Objects.requireNonNull(r);
}
}
public static <T> Stream<T> stream(Optional<T> $this) {
return $this.map(Stream::of).orElseGet(Stream::empty);
}
public static <T> void ifPresentOrElse(Optional<T> $this, Consumer<? super T> action, Runnable emptyAction) {
if ($this.isPresent()) {
action.accept($this.get());
} else {
emptyAction.run();
}
}
}

@ -1,38 +0,0 @@
/*
* This file is part of HuskSync, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.husksync.util;
import lombok.experimental.UtilityClass;
@UtilityClass
public class StringUtil {
public static boolean isBlank(String $this) {
final int strLen = $this.length();
if (strLen == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace($this.charAt(i))) {
return false;
}
}
return true;
}
}

@ -16,16 +16,10 @@ dependencies {
} }
shadowJar { shadowJar {
mergeServiceFiles()
dependencies { dependencies {
exclude(dependency('com.mojang:brigadier')) exclude(dependency('com.mojang:brigadier'))
} }
relocate 'org.inksnow.cputil', 'net.william278.husksync.libraries.cputil'
relocate 'org.slf4j', 'net.william278.husksync.libraries.slf4j'
relocate 'org.objectweb.asm', 'net.william278.husksync.libraries.asm'
relocate 'org.apache.commons.io', 'net.william278.husksync.libraries.commons.io' relocate 'org.apache.commons.io', 'net.william278.husksync.libraries.commons.io'
relocate 'org.apache.commons.text', 'net.william278.husksync.libraries.commons.text' relocate 'org.apache.commons.text', 'net.william278.husksync.libraries.commons.text'
relocate 'org.apache.commons.lang3', 'net.william278.husksync.libraries.commons.lang3' relocate 'org.apache.commons.lang3', 'net.william278.husksync.libraries.commons.lang3'
@ -49,6 +43,8 @@ shadowJar {
relocate 'dev.triumphteam.gui', 'net.william278.husksync.libraries.triumphgui' relocate 'dev.triumphteam.gui', 'net.william278.husksync.libraries.triumphgui'
relocate 'space.arim.morepaperlib', 'net.william278.husksync.libraries.paperlib' relocate 'space.arim.morepaperlib', 'net.william278.husksync.libraries.paperlib'
relocate 'de.tr7zw.changeme.nbtapi', 'net.william278.husksync.libraries.nbtapi' relocate 'de.tr7zw.changeme.nbtapi', 'net.william278.husksync.libraries.nbtapi'
minimize()
} }
tasks { tasks {

@ -32,7 +32,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.InputStream; import java.io.InputStream;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@ -64,7 +63,7 @@ public class PaperHuskSyncLoader implements PluginLoader {
} catch (Throwable e) { } catch (Throwable e) {
classpathBuilder.getContext().getLogger().error("Failed to resolve libraries", e); classpathBuilder.getContext().getLogger().error("Failed to resolve libraries", e);
} }
return Collections.emptyList(); return List.of();
} }
@Nullable @Nullable

@ -61,18 +61,10 @@ public class PaperEventListener extends BukkitEventListener {
// Paper - support saving the player's items to keep if enabled // Paper - support saving the player's items to keep if enabled
final int maxInventorySize = BukkitData.Items.Inventory.INVENTORY_SLOT_COUNT; final int maxInventorySize = BukkitData.Items.Inventory.INVENTORY_SLOT_COUNT;
final List<ItemStack> itemsToSave; final List<ItemStack> itemsToSave = switch (settings.getItemsToSave()) {
switch (settings.getItemsToSave()) { case DROPS -> event.getDrops();
case DROPS:{ case ITEMS_TO_KEEP -> preserveOrder(event.getEntity().getInventory(), event.getItemsToKeep());
itemsToSave = event.getDrops(); };
break;
}
case ITEMS_TO_KEEP: {
itemsToSave = preserveOrder(event.getEntity().getInventory(), event.getItemsToKeep());
break;
}
default: throw new IllegalStateException("Unexpected value: " + settings.getItemsToSave());
}
if (itemsToSave.size() > maxInventorySize) { if (itemsToSave.size() > maxInventorySize) {
itemsToSave.subList(maxInventorySize, itemsToSave.size()).clear(); itemsToSave.subList(maxInventorySize, itemsToSave.size()).clear();
} }

@ -10,5 +10,5 @@ include(
'common', 'common',
'bukkit', 'bukkit',
'paper', 'paper',
// 'fabric' 'fabric'
) )
Loading…
Cancel
Save