1
mirror of https://github.com/CarmJos/MineConfiguration.git synced 2026-06-04 13:55:03 +08:00

refactor(proj): 放弃spigot项目,将Bukkit子项目单独提出。

This commit is contained in:
2022-12-16 16:09:50 +08:00
parent 02f59b99f0
commit 67931094e6
41 changed files with 72 additions and 308 deletions
@@ -0,0 +1,35 @@
package cc.carm.lib.mineconfiguration.bukkit;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.value.impl.CachedConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.CraftConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.source.CraftConfigProvider;
import cc.carm.lib.mineconfiguration.bukkit.source.CraftSectionWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public abstract class CraftConfigValue<T> extends CachedConfigValue<T> {
public static @NotNull CraftConfigBuilder builder() {
return new CraftConfigBuilder();
}
public CraftConfigValue(@Nullable CraftConfigProvider provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@Nullable T defaultValue) {
super(provider, sectionPath, headerComments, inlineComments, defaultValue);
}
public CraftConfigProvider getBukkitProvider() {
ConfigurationProvider<?> provider = getProvider();
if (provider instanceof CraftConfigProvider) return (CraftConfigProvider) getProvider();
else throw new IllegalStateException("Provider is not a CraftConfigProvider");
}
public CraftSectionWrapper getBukkitConfig() {
return getBukkitProvider().getConfiguration();
}
}
@@ -0,0 +1,42 @@
package cc.carm.lib.mineconfiguration.bukkit;
import cc.carm.lib.mineconfiguration.bukkit.source.BukkitConfigProvider;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
public class MineConfiguration {
public static BukkitConfigProvider from(File file, String source) {
BukkitConfigProvider provider = new BukkitConfigProvider(file);
try {
provider.initializeFile(source);
provider.initializeConfig();
} catch (IOException e) {
e.printStackTrace();
}
return provider;
}
public static BukkitConfigProvider from(File file) {
return from(file, file.getName());
}
public static BukkitConfigProvider from(String fileName) {
return from(fileName, fileName);
}
public static BukkitConfigProvider from(String fileName, String source) {
return from(new File(fileName), source);
}
public static BukkitConfigProvider from(Plugin plugin, String fileName) {
return from(plugin, fileName, fileName);
}
public static BukkitConfigProvider from(Plugin plugin, String fileName, String source) {
return from(new File(plugin.getDataFolder(), fileName), source);
}
}
@@ -0,0 +1,13 @@
package cc.carm.lib.mineconfiguration.bukkit.builder;
import cc.carm.lib.mineconfiguration.bukkit.source.CraftConfigProvider;
import cc.carm.lib.configuration.core.builder.AbstractConfigBuilder;
public abstract class AbstractCraftBuilder<T, B extends AbstractCraftBuilder<T, B>>
extends AbstractConfigBuilder<T, B, CraftConfigProvider> {
public AbstractCraftBuilder() {
super(CraftConfigProvider.class);
}
}
@@ -0,0 +1,45 @@
package cc.carm.lib.mineconfiguration.bukkit.builder;
import cc.carm.lib.configuration.core.builder.ConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.builder.item.ItemConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageBuilder;
import cc.carm.lib.mineconfiguration.bukkit.builder.serializable.SerializableBuilder;
import cc.carm.lib.mineconfiguration.bukkit.builder.sound.SoundConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.builder.title.TitleConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.ItemConfig;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredItem;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class CraftConfigBuilder extends ConfigBuilder {
public @NotNull SoundConfigBuilder createSound() {
return new SoundConfigBuilder();
}
public @NotNull ItemConfigBuilder createItem() {
return new ItemConfigBuilder();
}
public @NotNull CraftMessageBuilder createMessage() {
return new CraftMessageBuilder();
}
public @NotNull TitleConfigBuilder createTitle() {
return new TitleConfigBuilder();
}
public <V extends ConfigurationSerializable> @NotNull SerializableBuilder<V> ofSerializable(@NotNull Class<V> valueClass) {
return new SerializableBuilder<>(valueClass);
}
public @NotNull ConfiguredItem ofItem() {
return createItem().build();
}
public @NotNull ConfiguredItem ofItem(@Nullable ItemConfig defaultItem) {
return createItem().defaults(defaultItem).build();
}
}
@@ -0,0 +1,121 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.item;
import cc.carm.lib.mineconfiguration.bukkit.builder.AbstractCraftBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.ItemConfig;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredItem;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Function;
public class ItemConfigBuilder extends AbstractCraftBuilder<ItemConfig, ItemConfigBuilder> {
protected Material type;
protected short data = 0;
protected String name = null;
protected List<String> lore = new ArrayList<>();
protected Map<Enchantment, Integer> enchants = new LinkedHashMap<>();
protected Set<ItemFlag> flags = new LinkedHashSet<>();
protected @NotNull String[] params = new String[0];
protected @NotNull Function<@NotNull String, @NotNull String> paramFormatter = ParamsUtils.DEFAULT_PARAM_FORMATTER;
public ItemConfigBuilder defaults(@NotNull Material type,
@Nullable String name, @NotNull String... lore) {
return defaults(type, (short) 0, name, Arrays.asList(lore));
}
public ItemConfigBuilder defaults(@NotNull Material type, short data,
@Nullable String name, @NotNull String... lore) {
return defaults(type, data, name, Arrays.asList(lore));
}
public ItemConfigBuilder defaults(@NotNull Material type, short data,
@Nullable String name, @NotNull List<String> lore) {
return defaultType(type).defaultDataID(data).defaultName(name).defaultLore(lore);
}
public ItemConfigBuilder defaultType(@NotNull Material type) {
this.type = type;
return this;
}
public ItemConfigBuilder defaultName(@Nullable String name) {
this.name = name;
return this;
}
public ItemConfigBuilder defaultDataID(short dataID) {
this.data = dataID;
return this;
}
public ItemConfigBuilder defaultLore(@NotNull String... lore) {
return defaultLore(Arrays.asList(lore));
}
public ItemConfigBuilder defaultLore(@NotNull List<String> lore) {
this.lore = new ArrayList<>(lore);
return this;
}
public ItemConfigBuilder defaultEnchants(@NotNull Map<Enchantment, Integer> enchants) {
this.enchants = new LinkedHashMap<>(enchants);
return this;
}
public ItemConfigBuilder defaultEnchant(@NotNull Enchantment enchant, int level) {
return defaultEnchants(Collections.singletonMap(enchant, level));
}
public ItemConfigBuilder defaultFlags(@NotNull Set<ItemFlag> flags) {
this.flags = new LinkedHashSet<>(flags);
return this;
}
public ItemConfigBuilder defaultFlags(@NotNull ItemFlag... flags) {
return defaultFlags(new LinkedHashSet<>(Arrays.asList(flags)));
}
public ItemConfigBuilder formatParam(@NotNull Function<@NotNull String, @NotNull String> paramFormatter) {
this.paramFormatter = paramFormatter;
return getThis();
}
public ItemConfigBuilder params(@NotNull String... params) {
this.params = params;
return getThis();
}
public ItemConfigBuilder params(@NotNull List<String> params) {
this.params = params.toArray(new String[0]);
return getThis();
}
@Override
protected @NotNull ItemConfigBuilder getThis() {
return this;
}
protected @Nullable ItemConfig buildDefault() {
if (this.type == null) return null;
else return new ItemConfig(type, data, name, lore, enchants, flags);
}
@Override
public @NotNull ConfiguredItem build() {
ItemConfig defaultItem = Optional.ofNullable(this.defaultValue).orElse(buildDefault());
return new ConfiguredItem(this.provider, this.path, this.headerComments, this.inlineComment, defaultItem, buildParams());
}
protected final String[] buildParams() {
return Arrays.stream(params).map(param -> paramFormatter.apply(param)).toArray(String[]::new);
}
}
@@ -0,0 +1,44 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.message;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.bukkit.utils.TextParser;
import cc.carm.lib.mineconfiguration.common.builder.message.MessageConfigBuilder;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.function.BiFunction;
public class CraftMessageBuilder extends MessageConfigBuilder<CommandSender, TextConfig> {
public CraftMessageBuilder() {
super(CommandSender.class, TextConfig.class);
}
@Override
public @NotNull <M> CraftMessageValueBuilder<M> asValue(@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> parser) {
return new CraftMessageValueBuilder<>(parser);
}
@Override
public @NotNull <M> CraftMessageListBuilder<M> asList(@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> parser) {
return new CraftMessageListBuilder<>(parser);
}
public @NotNull
CraftMessageValueBuilder<String> asStringValue() {
return asValue(defaultParser()).whenSend(CommandSender::sendMessage);
}
public @NotNull
CraftMessageListBuilder<String> asStringList() {
return asList(defaultParser()).whenSend((r, m) -> m.forEach(r::sendMessage));
}
protected static @NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable String> defaultParser() {
return (receiver, message) -> TextParser.parseText(receiver, message, new HashMap<>());
}
}
@@ -0,0 +1,36 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.message;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredMessageList;
import cc.carm.lib.mineconfiguration.common.builder.message.MessageListBuilder;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Optional;
import java.util.function.BiFunction;
public class CraftMessageListBuilder<M>
extends MessageListBuilder<M, CommandSender, TextConfig, CraftMessageListBuilder<M>> {
public CraftMessageListBuilder(@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> parser) {
super(CommandSender.class, TextConfig::of, parser);
}
@Override
protected @NotNull CraftMessageListBuilder<M> getThis() {
return this;
}
@Override
public @NotNull ConfiguredMessageList<M> build() {
return new ConfiguredMessageList<>(
this.provider, this.path, this.headerComments, this.inlineComment,
Optional.ofNullable(this.defaultValue).orElse(TextConfig.of(new ArrayList<>())),
ParamsUtils.formatParams(this.paramFormatter, this.params),
this.messageParser, this.sendFunction
);
}
}
@@ -0,0 +1,37 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.message;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredMessage;
import cc.carm.lib.mineconfiguration.common.builder.message.MessageValueBuilder;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.function.BiFunction;
public class CraftMessageValueBuilder<M>
extends MessageValueBuilder<M, CommandSender, TextConfig, CraftMessageValueBuilder<M>> {
public CraftMessageValueBuilder(@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> parser) {
super(CommandSender.class, TextConfig::new, parser);
}
@Override
protected @NotNull CraftMessageValueBuilder<M> getThis() {
return this;
}
@Override
public @NotNull ConfiguredMessage<M> build() {
return new ConfiguredMessage<>(
this.provider, this.path, this.headerComments, this.inlineComment,
Optional.ofNullable(this.defaultValue).orElse(TextConfig.of("")),
ParamsUtils.formatParams(this.paramFormatter, this.params),
this.messageParser, this.sendHandler
);
}
}
@@ -0,0 +1,28 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.serializable;
import cc.carm.lib.mineconfiguration.bukkit.builder.AbstractCraftBuilder;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.jetbrains.annotations.NotNull;
public class SerializableBuilder<T extends ConfigurationSerializable>
extends AbstractCraftBuilder<T, SerializableBuilder<T>> {
protected final @NotNull Class<T> valueClass;
public SerializableBuilder(@NotNull Class<T> valueClass) {
this.valueClass = valueClass;
}
@Override
protected @NotNull SerializableBuilder<T> getThis() {
return this;
}
@Override
public @NotNull ConfiguredSerializable<T> build() {
return new ConfiguredSerializable<>(this.provider, this.path, this.headerComments, this.inlineComment, this.valueClass, this.defaultValue);
}
}
@@ -0,0 +1,46 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.sound;
import cc.carm.lib.mineconfiguration.bukkit.builder.AbstractCraftBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.SoundConfig;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredSound;
import org.bukkit.Sound;
import org.jetbrains.annotations.NotNull;
public class SoundConfigBuilder extends AbstractCraftBuilder<SoundConfig, SoundConfigBuilder> {
public @NotNull SoundConfigBuilder defaults(@NotNull Sound sound, float volume, float pitch) {
return defaults(new SoundConfig(sound.name(), sound, volume, pitch));
}
public @NotNull SoundConfigBuilder defaults(@NotNull Sound sound, float volume) {
return defaults(sound, volume, 1.0f);
}
public @NotNull SoundConfigBuilder defaults(@NotNull Sound sound) {
return defaults(sound, 1.0f);
}
public @NotNull SoundConfigBuilder defaults(@NotNull String soundName, float volume, float pitch) {
return defaults(new SoundConfig(soundName, volume, pitch));
}
public @NotNull SoundConfigBuilder defaults(@NotNull String soundName, float volume) {
return defaults(soundName, volume, 1.0f);
}
public @NotNull SoundConfigBuilder defaults(@NotNull String soundName) {
return defaults(soundName, 1.0f);
}
@Override
protected @NotNull SoundConfigBuilder getThis() {
return this;
}
@Override
public @NotNull ConfiguredSound build() {
return new ConfiguredSound(this.provider, this.path, this.headerComments, this.inlineComment, this.defaultValue);
}
}
@@ -0,0 +1,97 @@
package cc.carm.lib.mineconfiguration.bukkit.builder.title;
import cc.carm.lib.mineconfiguration.bukkit.builder.AbstractCraftBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TitleConfig;
import cc.carm.lib.mineconfiguration.bukkit.function.TitleSendConsumer;
import cc.carm.lib.mineconfiguration.bukkit.utils.ProtocolLibHelper;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredTitle;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Range;
import java.util.List;
import java.util.function.Function;
public class TitleConfigBuilder extends AbstractCraftBuilder<TitleConfig, TitleConfigBuilder> {
@SuppressWarnings("deprecation")
protected static @NotNull TitleSendConsumer DEFAULT_TITLE_CONSUMER = (player, fadeIn, stay, fadeOut, line1, line2) -> {
if (Bukkit.getPluginManager().isPluginEnabled("ProtocolLib")) {
try {
ProtocolLibHelper.sendTitle(player, fadeIn, stay, fadeOut, line1, line2);
} catch (Exception ignored) {
}
} else {
player.sendTitle(line1, line2);
}
};
protected @NotNull String[] params = new String[0];
protected @Range(from = 0L, to = Integer.MAX_VALUE) int fadeIn = 10;
protected @Range(from = 0L, to = Integer.MAX_VALUE) int stay = 60;
protected @Range(from = 0L, to = Integer.MAX_VALUE) int fadeOut = 10;
protected @NotNull TitleSendConsumer sendConsumer;
protected @NotNull Function<@NotNull String, @NotNull String> paramFormatter;
public TitleConfigBuilder() {
this.sendConsumer = TitleConfigBuilder.DEFAULT_TITLE_CONSUMER;
this.paramFormatter = ParamsUtils.DEFAULT_PARAM_FORMATTER;
}
public @NotNull TitleConfigBuilder defaults(@Nullable String line1,
@Nullable String line2) {
return defaults(TitleConfig.of(line1, line2));
}
public @NotNull TitleConfigBuilder whenSend(@NotNull TitleSendConsumer consumer) {
this.sendConsumer = consumer;
return this;
}
public TitleConfigBuilder params(String... params) {
this.params = params;
return this;
}
public TitleConfigBuilder params(@NotNull List<String> params) {
return params(params.toArray(new String[0]));
}
public TitleConfigBuilder fadeIn(@Range(from = 0L, to = Integer.MAX_VALUE) int fadeIn) {
this.fadeIn = fadeIn;
return this;
}
public TitleConfigBuilder stay(@Range(from = 0L, to = Integer.MAX_VALUE) int stay) {
this.stay = stay;
return this;
}
public TitleConfigBuilder fadeOut(@Range(from = 0L, to = Integer.MAX_VALUE) int fadeOut) {
this.fadeOut = fadeOut;
return this;
}
public TitleConfigBuilder formatParam(Function<String, String> paramFormatter) {
this.paramFormatter = paramFormatter;
return this;
}
@Override
protected @NotNull TitleConfigBuilder getThis() {
return this;
}
@Override
public @NotNull ConfiguredTitle build() {
return new ConfiguredTitle(
this.provider, this.path, this.headerComments, this.inlineComment,
this.defaultValue, ParamsUtils.formatParams(this.paramFormatter, this.params),
this.sendConsumer, this.fadeIn, this.stay, this.fadeOut
);
}
}
@@ -0,0 +1,178 @@
package cc.carm.lib.mineconfiguration.bukkit.data;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import cc.carm.lib.mineconfiguration.bukkit.source.CraftSectionWrapper;
import cc.carm.lib.mineconfiguration.bukkit.utils.TextParser;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
public class ItemConfig {
protected @NotNull Material type;
protected short data;
protected @Nullable String name;
protected @NotNull List<String> lore;
protected @NotNull Map<Enchantment, Integer> enchants;
protected @NotNull Set<ItemFlag> flags;
public ItemConfig(@NotNull Material type, @Nullable String name) {
this(type, name, Collections.emptyList());
}
public ItemConfig(@NotNull Material type, @Nullable String name, @NotNull List<String> lore) {
this(type, (short) 0, name, lore);
}
public ItemConfig(@NotNull Material type, short damage,
@Nullable String name, @NotNull List<String> lore) {
this(type, damage, name, lore, Collections.emptyMap(), Collections.emptySet());
}
public ItemConfig(@NotNull Material type, short damage,
@Nullable String name, @NotNull List<String> lore,
@NotNull Map<Enchantment, Integer> enchants,
@NotNull Set<ItemFlag> flags) {
this.type = type;
this.data = damage;
this.name = name;
this.lore = lore;
this.enchants = enchants;
this.flags = flags;
}
public @NotNull Material getType() {
return type;
}
public short getData() {
return data;
}
public @Nullable String getName() {
return name;
}
public @Nullable String getName(@Nullable Player player, @NotNull Map<String, Object> placeholders) {
return Optional.ofNullable(getName())
.map(name -> TextParser.parseText(player, name, placeholders))
.orElse(null);
}
public @NotNull List<String> getLore() {
return lore;
}
public @Nullable List<String> getLore(@Nullable Player player, @NotNull Map<String, Object> placeholders) {
if (getLore().isEmpty()) return null;
else return TextParser.parseList(player, getLore(), placeholders);
}
public final @NotNull ItemStack getItemStack() {
return getItemStack(1);
}
public @NotNull ItemStack getItemStack(int amount) {
return getItemStack(null, amount, new HashMap<>());
}
public @NotNull ItemStack getItemStack(@Nullable Player player) {
return getItemStack(player, new HashMap<>());
}
public @NotNull ItemStack getItemStack(@Nullable Player player, @NotNull Map<String, Object> placeholders) {
return getItemStack(player, 1, placeholders);
}
public @NotNull ItemStack getItemStack(@Nullable Player player, int amount, @NotNull Map<String, Object> placeholders) {
ItemStack item = new ItemStack(type, amount, data);
ItemMeta meta = item.getItemMeta();
if (meta == null) return item;
Optional.ofNullable(getName(player, placeholders)).ifPresent(meta::setDisplayName);
Optional.ofNullable(getLore(player, placeholders)).ifPresent(meta::setLore);
enchants.forEach((enchant, level) -> meta.addEnchant(enchant, level, true));
flags.forEach(meta::addItemFlags);
item.setItemMeta(meta);
return item;
}
public @NotNull Map<String, Object> serialize() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("type", type.name());
if (this.data != 0) map.put("data", data);
if (name != null) map.put("name", name);
if (!lore.isEmpty()) map.put("lore", lore);
Map<String, Integer> enchantments = new LinkedHashMap<>();
enchants.forEach((enchant, level) -> {
if (level > 0) enchantments.put(enchant.getName(), level);
});
if (!enchantments.isEmpty()) {
map.put("enchants", enchantments);
}
if (!flags.isEmpty()) {
map.put("flags", flags.stream().map(ItemFlag::name).collect(Collectors.toList()));
}
return map;
}
public static @NotNull ItemConfig deserialize(@NotNull ConfigurationSection section) throws Exception {
return deserialize(CraftSectionWrapper.of(section));
}
public static @NotNull ItemConfig deserialize(@NotNull ConfigurationWrapper<?> section) throws Exception {
String typeName = section.getString("type");
if (typeName == null) throw new NullPointerException("Item type name is null");
Material type = Material.matchMaterial(typeName);
if (type == null) throw new Exception("Invalid material name: " + typeName);
short data = section.getShort("data", (short) 0);
String name = section.getString("name");
List<String> lore = section.getStringList("lore");
Map<Enchantment, Integer> enchantments = readEnchantments(section.getConfigurationSection("enchants"));
Set<ItemFlag> flags = readFlags(section.getStringList("flags"));
return new ItemConfig(type, data, name, lore, enchantments, flags);
}
private static ItemFlag parseFlag(String flagName) {
return Arrays.stream(ItemFlag.values()).filter(flag -> flag.name().equalsIgnoreCase(flagName)).findFirst().orElse(null);
}
private static Set<ItemFlag> readFlags(List<String> flagConfig) {
Set<ItemFlag> flags = new LinkedHashSet<>();
for (String flagName : flagConfig) {
ItemFlag flag = parseFlag(flagName);
if (flag != null) flags.add(flag);
}
return flags;
}
private static Map<Enchantment, Integer> readEnchantments(ConfigurationWrapper<?> section) {
Map<Enchantment, Integer> enchantments = new LinkedHashMap<>();
if (section == null) return enchantments;
section.getKeys(false).forEach(key -> {
Enchantment enchantment = Enchantment.getByName(key);
int level = section.getInt(key, 0);
if (enchantment != null && level > 0) {
enchantments.put(enchantment, level);
}
});
return enchantments;
}
}
@@ -0,0 +1,106 @@
package cc.carm.lib.mineconfiguration.bukkit.data;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
public class SoundConfig {
protected @NotNull String typeName;
protected @Nullable Sound type;
protected float volume;
protected float pitch;
public SoundConfig(@NotNull String typeName) {
this(typeName, 1, 1);
}
public SoundConfig(@NotNull String typeName, float volume) {
this(typeName, volume, 1);
}
public SoundConfig(@NotNull String typeName, float volume, float pitch) {
this(typeName, Arrays.stream(Sound.values()).filter(s -> s.name().equalsIgnoreCase(typeName)).findFirst().orElse(null), volume, pitch);
}
public SoundConfig(@NotNull String typeName, @Nullable Sound type, float volume, float pitch) {
this.typeName = typeName;
this.type = type;
this.volume = volume;
this.pitch = pitch;
}
public void playTo(Player player) {
if (type == null) return;
player.playSound(player.getLocation(), type, volume, pitch);
}
public void playToAll() {
Bukkit.getOnlinePlayers().forEach(this::playTo);
}
public @NotNull String getTypeName() {
return typeName;
}
public @Nullable Sound getType() {
return type;
}
public float getPitch() {
return pitch;
}
public float getVolume() {
return volume;
}
public void setType(@NotNull Sound type) {
this.typeName = type.name();
this.type = type;
}
public void setVolume(float volume) {
this.volume = volume;
}
public void setPitch(float pitch) {
this.pitch = pitch;
}
public @NotNull String serialize() {
if (pitch != 1) {
return typeName + ":" + volume + ":" + pitch;
} else if (volume != 1) {
return typeName + ":" + volume;
} else {
return typeName;
}
}
@Contract("null -> null")
public static @Nullable SoundConfig deserialize(@Nullable String string) throws Exception {
if (string == null || string.isEmpty()) return null;
String[] args = string.contains(":") ? string.split(":") : new String[]{string};
if (args.length < 1) return null;
try {
return new SoundConfig(
args[0],
Sound.valueOf(args[0]),
(args.length >= 2) ? Float.parseFloat(args[1]) : 1,
(args.length >= 3) ? Float.parseFloat(args[2]) : 1
);
} catch (Exception exception) {
throw new Exception("Sound " + string + " wasn't configured correctly.", exception);
}
}
}
@@ -0,0 +1,35 @@
package cc.carm.lib.mineconfiguration.bukkit.data;
import cc.carm.lib.mineconfiguration.common.data.AbstractText;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class TextConfig extends AbstractText<CommandSender> {
public TextConfig(@NotNull String message) {
super(CommandSender.class, message);
}
@Contract("!null,-> !null")
public static @Nullable TextConfig of(@Nullable String message) {
if (message == null) return null;
else return new TextConfig(message);
}
public static @NotNull List<TextConfig> of(@Nullable List<String> messages) {
if (messages == null || messages.isEmpty()) return new ArrayList<>();
else return messages.stream().map(TextConfig::of).collect(Collectors.toList());
}
public static @NotNull List<TextConfig> of(@NotNull String... messages) {
return of(Arrays.asList(messages));
}
}
@@ -0,0 +1,68 @@
package cc.carm.lib.mineconfiguration.bukkit.data;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import cc.carm.lib.mineconfiguration.bukkit.function.TitleSendConsumer;
import cc.carm.lib.mineconfiguration.bukkit.utils.TextParser;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Range;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
public class TitleConfig {
public static @NotNull TitleConfig of(@Nullable String line1, @Nullable String line2) {
return of(
Optional.ofNullable(line1).map(TextConfig::of).orElse(null),
Optional.ofNullable(line2).map(TextConfig::of).orElse(null)
);
}
public static @NotNull TitleConfig of(@Nullable TextConfig line1, @Nullable TextConfig line2) {
return new TitleConfig(line1, line2);
}
protected @Nullable TextConfig line1;
protected @Nullable TextConfig line2;
protected TitleConfig(@Nullable TextConfig line1, @Nullable TextConfig line2) {
this.line1 = line1;
this.line2 = line2;
}
public void send(@NotNull Player player,
@Range(from = 0L, to = Long.MAX_VALUE) int fadeIn,
@Range(from = 0L, to = Long.MAX_VALUE) int stay,
@Range(from = 0L, to = Long.MAX_VALUE) int fadeOut,
@NotNull Map<String, Object> placeholders,
@Nullable TitleSendConsumer sendConsumer) {
if (this.line1 == null && this.line2 == null) return;
if (sendConsumer == null) return;
sendConsumer.send(
player, fadeIn, stay, fadeOut,
parseLine(this.line1, player, placeholders),
parseLine(this.line2, player, placeholders)
);
}
protected @NotNull String parseLine(@Nullable TextConfig text,
@NotNull Player player, @NotNull Map<String, Object> placeholders) {
if (text == null) return "";
else return TextParser.parseText(player, text.getMessage(), placeholders);
}
public @NotNull Map<String, Object> serialize() {
Map<String, Object> map = new LinkedHashMap<>();
if (this.line1 != null) map.put("line1", this.line1.getMessage());
if (this.line2 != null) map.put("line2", this.line2.getMessage());
return map;
}
public static @NotNull TitleConfig deserialize(@NotNull ConfigurationWrapper<?> section) {
return of(section.getString("line1"), section.getString("line2"));
}
}
@@ -0,0 +1,26 @@
package cc.carm.lib.mineconfiguration.bukkit.function;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;
@FunctionalInterface
public interface TitleSendConsumer {
/**
* 向目标玩家发送标题文字
*
* @param player 目标玩家
* @param fadeIn 淡入时间 (ticks)
* @param stay 保留时间 (ticks)
* @param fadeOut 淡出时间 (ticks)
* @param line1 第一行文字
* @param line2 第二行文字
*/
void send(@NotNull Player player,
@Range(from = 0L, to = Integer.MAX_VALUE) int fadeIn,
@Range(from = 0L, to = Integer.MAX_VALUE) int stay,
@Range(from = 0L, to = Integer.MAX_VALUE) int fadeOut,
@NotNull String line1, @NotNull String line2);
}
@@ -0,0 +1,55 @@
package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.ConfigInitializer;
import cc.carm.lib.configuration.core.source.ConfigurationComments;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class BukkitConfigProvider extends CraftConfigProvider {
protected static final char SEPARATOR = '.';
protected @NotNull BukkitYAMLComments comments = new BukkitYAMLComments();
public BukkitConfigProvider(@NotNull File file) {
super(file);
}
public void initializeConfig() {
this.configuration = YamlConfiguration.loadConfiguration(file);
this.initializer = new ConfigInitializer<>(this);
}
@Override
public @NotNull CraftSectionWrapper getConfiguration() {
return CraftSectionWrapper.of(this.configuration);
}
@Override
public void save() throws Exception {
configuration.save(getFile());
StringWriter writer = new StringWriter();
this.comments.writeComments(configuration, new BufferedWriter(writer));
String value = writer.toString(); // config contents
Path toUpdatePath = getFile().toPath();
if (!value.equals(new String(Files.readAllBytes(toUpdatePath), StandardCharsets.UTF_8))) {
Files.write(toUpdatePath, value.getBytes(StandardCharsets.UTF_8));
}
}
@Override
public @Nullable ConfigurationComments getComments() {
return this.comments;
}
}
@@ -0,0 +1,108 @@
package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.source.ConfigurationComments;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class BukkitYAMLComments extends ConfigurationComments {
public @Nullable String buildHeaderComments(@Nullable String path, @NotNull String indents) {
List<String> comments = getHeaderComment(path);
if (comments == null || comments.size() == 0) return null;
StringJoiner joiner = new StringJoiner("\n");
for (String comment : comments) {
if (comment.length() == 0) joiner.add(" ");
else joiner.add(indents + "# " + comment);
}
return joiner + "\n";
}
/**
* 从一个文件读取配置并写入注释到某个写入器中。
* 该方法的部分源代码借鉴自 tchristofferson/ConfigUpdater 项目。
*
* @param source 源配置文件
* @param writer 配置写入器
* @throws IOException 当写入发生错误时抛出
*/
public void writeComments(@NotNull YamlConfiguration source, @NotNull BufferedWriter writer) throws IOException {
FileConfiguration temp = new YamlConfiguration(); // 该对象用于临时记录配置内容
String configHeader = buildHeaderComments(null, "");
if (configHeader != null) writer.write(configHeader);
for (String fullKey : source.getKeys(true)) {
Object currentValue = source.get(fullKey);
String indents = getIndents(fullKey);
String headerComments = buildHeaderComments(fullKey, indents);
String inlineComment = getInlineComment(fullKey);
if (headerComments != null) writer.write(headerComments);
String[] splitFullKey = fullKey.split("[" + CraftConfigProvider.SEPARATOR + "]");
String trailingKey = splitFullKey[splitFullKey.length - 1];
if (currentValue instanceof ConfigurationSection) {
ConfigurationSection section = (ConfigurationSection) currentValue;
writer.write(indents + trailingKey + ":");
if (inlineComment != null && inlineComment.length() > 0) {
writer.write(" # " + inlineComment);
}
if (!section.getKeys(false).isEmpty()) {
writer.write("\n");
} else {
writer.write(" {}\n");
if (indents.length() == 0) writer.write("\n");
}
continue;
}
temp.set(trailingKey, currentValue);
String yaml = temp.saveToString();
temp.set(trailingKey, null);
yaml = yaml.substring(0, yaml.length() - 1);
if (inlineComment != null && inlineComment.length() > 0) {
if (yaml.contains("\n")) {
// section为多行内容,需要 InlineComment 加在首行末尾
String[] splitLine = yaml.split("\n", 2);
yaml = splitLine[0] + " # " + inlineComment + "\n" + splitLine[1];
} else {
// 其他情况下就直接加载后面就好。
yaml += " # " + inlineComment;
}
}
writer.write(indents + yaml.replace("\n", "\n" + indents) + "\n");
if (indents.length() == 0) writer.write("\n");
}
writer.close();
}
/**
* 得到一个键的缩进。
* 该方法的源代码来自 tchristofferson/ConfigUpdater 项目。
*
* @param key 键
* @return 该键的缩进文本
*/
protected static String getIndents(String key) {
String[] splitKey = key.split("[" + BukkitConfigProvider.SEPARATOR + "]");
return IntStream.range(1, splitKey.length).mapToObj(i -> " ").collect(Collectors.joining());
}
}
@@ -0,0 +1,43 @@
package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.ConfigInitializer;
import cc.carm.lib.configuration.core.source.impl.FileConfigProvider;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class CraftConfigProvider extends FileConfigProvider<CraftSectionWrapper> {
public static final char SEPARATOR = '.';
protected ConfigInitializer<? extends CraftConfigProvider> initializer;
protected YamlConfiguration configuration;
public CraftConfigProvider(@NotNull File file) {
super(file);
}
public abstract void initializeConfig();
@Override
public @NotNull CraftSectionWrapper getConfiguration() {
return CraftSectionWrapper.of(this.configuration);
}
@Override
protected void onReload() throws Exception {
configuration.load(getFile());
}
@Override
public void save() throws Exception {
configuration.save(getFile());
}
@Override
public @NotNull ConfigInitializer<? extends CraftConfigProvider> getInitializer() {
return this.initializer;
}
}
@@ -0,0 +1,75 @@
package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class CraftSectionWrapper implements ConfigurationWrapper<ConfigurationSection> {
protected final ConfigurationSection configuration;
protected CraftSectionWrapper(ConfigurationSection configuration) {
this.configuration = configuration;
}
@Override
public @NotNull ConfigurationSection getSource() {
return this.configuration;
}
@Override
public @NotNull Set<String> getKeys(boolean deep) {
return this.configuration.getKeys(deep);
}
@Override
public @NotNull Map<String, Object> getValues(boolean deep) {
return this.configuration.getValues(deep);
}
@Override
public void set(@NotNull String path, @Nullable Object value) {
this.configuration.set(path, value);
}
@Override
public boolean contains(@NotNull String path) {
return this.configuration.contains(path);
}
@Override
public @Nullable Object get(@NotNull String path) {
return this.configuration.get(path);
}
@Override
public boolean isList(@NotNull String path) {
return this.configuration.isList(path);
}
@Override
public @Nullable List<?> getList(@NotNull String path) {
return this.configuration.getList(path);
}
@Override
public boolean isConfigurationSection(@NotNull String path) {
return this.configuration.isConfigurationSection(path);
}
@Override
public @Nullable CraftSectionWrapper getConfigurationSection(@NotNull String path) {
return Optional.ofNullable(configuration.getConfigurationSection(path))
.map(CraftSectionWrapper::of).orElse(null);
}
public static CraftSectionWrapper of(ConfigurationSection section) {
return new CraftSectionWrapper(section);
}
}
@@ -0,0 +1,27 @@
package cc.carm.lib.mineconfiguration.bukkit.utils;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.entity.Player;
import java.util.List;
public class PlaceholderAPIHelper {
public static String parseMessages(Player player, String message) {
try {
return PlaceholderAPI.setPlaceholders(player, message);
} catch (Exception ignored) {
return message;
}
}
public static List<String> parseMessages(Player player, List<String> messages) {
try {
return PlaceholderAPI.setPlaceholders(player, messages);
} catch (Exception ignored) {
return messages;
}
}
}
@@ -0,0 +1,41 @@
package cc.carm.lib.mineconfiguration.bukkit.utils;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class ProtocolLibHelper {
@SuppressWarnings("deprecation")
public static void sendTitle(@NotNull Player player, long fadeIn, long stay, long fadeOut, String line1, String line2) throws Exception {
ProtocolManager pm = ProtocolLibrary.getProtocolManager();
if (line1 != null) {
PacketContainer packet = pm.createPacket(PacketType.Play.Server.TITLE);
packet.getTitleActions().write(0, EnumWrappers.TitleAction.TITLE);
packet.getChatComponents().write(0, WrappedChatComponent.fromText(line1));
pm.sendServerPacket(player, packet, false);
}
if (line2 != null) {
PacketContainer packet = pm.createPacket(PacketType.Play.Server.TITLE);
packet.getTitleActions().write(0, EnumWrappers.TitleAction.SUBTITLE);
packet.getChatComponents().write(0, WrappedChatComponent.fromText(line2));
pm.sendServerPacket(player, packet, false);
}
PacketContainer timePacket = pm.createPacket(PacketType.Play.Server.TITLE);
timePacket.getTitleActions().write(0, EnumWrappers.TitleAction.TIMES);
timePacket.getIntegers()
.write(0, Math.toIntExact(fadeIn))
.write(1, Math.toIntExact(stay))
.write(2, Math.toIntExact(fadeOut));
pm.sendServerPacket(player, timePacket, false);
}
}
@@ -0,0 +1,38 @@
package cc.carm.lib.mineconfiguration.bukkit.utils;
import cc.carm.lib.mineconfiguration.common.utils.ColorParser;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TextParser {
@Contract("_,!null,_->!null")
public static @Nullable String parseText(@Nullable CommandSender sender, @Nullable String message, @NotNull Map<String, Object> placeholders) {
if (message == null) return null;
if (sender instanceof Player && hasPlaceholderAPI()) {
message = PlaceholderAPIHelper.parseMessages((Player) sender, message);
}
return ColorParser.parse(ParamsUtils.setPlaceholders(message, placeholders));
}
public static @NotNull List<String> parseList(@Nullable CommandSender sender, List<String> messages, @NotNull Map<String, Object> placeholders) {
if (sender instanceof Player && hasPlaceholderAPI()) {
messages = PlaceholderAPIHelper.parseMessages((Player) sender, messages);
}
return ColorParser.parse(messages.stream().map(s -> ParamsUtils.setPlaceholders(s, placeholders)).collect(Collectors.toList()));
}
public static boolean hasPlaceholderAPI() {
return Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null;
}
}
@@ -0,0 +1,74 @@
package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.configuration.core.function.ConfigValueParser;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import cc.carm.lib.configuration.core.value.type.ConfiguredSection;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.item.ItemConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.ItemConfig;
import cc.carm.lib.mineconfiguration.bukkit.source.CraftConfigProvider;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConfiguredItem extends ConfiguredSection<ItemConfig> {
public static ItemConfigBuilder create() {
return CraftConfigValue.builder().createItem();
}
public static ConfiguredItem of() {
return CraftConfigValue.builder().ofItem();
}
public static ConfiguredItem of(@Nullable ItemConfig defaultItem) {
return CraftConfigValue.builder().ofItem(defaultItem);
}
protected final @NotNull String[] params;
public ConfiguredItem(@Nullable CraftConfigProvider provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@Nullable ItemConfig defaultValue, @NotNull String[] params) {
super(
provider, sectionPath, headerComments, inlineComments, ItemConfig.class, defaultValue,
getItemParser(), ItemConfig::serialize
);
this.params = params;
}
public static ConfigValueParser<ConfigurationWrapper<?>, ItemConfig> getItemParser() {
return (s, d) -> ItemConfig.deserialize(s);
}
public @NotNull String[] getParams() {
return params;
}
public @Nullable ItemStack getItem(@Nullable Player player) {
return getItem(player, 1);
}
public @Nullable ItemStack getItem(@Nullable Player player, int amount) {
return getItem(player, amount, new HashMap<>());
}
public @Nullable ItemStack getItem(@Nullable Player player, int amount, @NotNull Object... values) {
return getItem(player, amount, ParamsUtils.buildParams(params, values));
}
public @Nullable ItemStack getItem(@Nullable Player player, int amount, @NotNull String[] params, @NotNull Object[] values) {
return getItem(player, amount, ParamsUtils.buildParams(params, values));
}
public @Nullable ItemStack getItem(@Nullable Player player, int amount, @NotNull Map<String, Object> placeholders) {
return getOptional().map(item -> item.getItemStack(player, amount, placeholders)).orElse(null);
}
}
@@ -0,0 +1,54 @@
package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageValueBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.common.value.ConfigMessage;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
public class ConfiguredMessage<M> extends ConfigMessage<M, TextConfig, CommandSender> {
@NotNull
public static <M> CraftMessageValueBuilder<@Nullable M> create(@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> messageParser) {
return CraftConfigValue.builder().createMessage().asValue(messageParser);
}
public static CraftMessageValueBuilder<String> asString() {
return CraftConfigValue.builder().createMessage().asStringValue();
}
public static ConfiguredMessage<String> ofString() {
return asString().build();
}
public static ConfiguredMessage<String> ofString(@NotNull String defaultMessage) {
return asString().defaults(defaultMessage).build();
}
public ConfiguredMessage(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@NotNull TextConfig defaultMessage, @NotNull String[] params,
@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> messageParser,
@NotNull BiConsumer<@NotNull CommandSender, @NotNull M> sendFunction) {
super(provider, sectionPath, headerComments, inlineComments, TextConfig.class, defaultMessage, params, messageParser, sendFunction, TextConfig::of);
}
@Override
public @NotNull Collection<CommandSender> getAllReceivers() {
List<CommandSender> senders = new ArrayList<>();
senders.add(Bukkit.getConsoleSender());
senders.addAll(Bukkit.getOnlinePlayers());
return senders;
}
}
@@ -0,0 +1,49 @@
package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageListBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.common.value.ConfigMessageList;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
public class ConfiguredMessageList<M> extends ConfigMessageList<M, TextConfig, CommandSender> {
@NotNull
public static <M> CraftMessageListBuilder<M> create(@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> messageParser) {
return CraftConfigValue.builder().createMessage().asList(messageParser);
}
public static CraftMessageListBuilder<String> asStrings() {
return CraftConfigValue.builder().createMessage().asStringList();
}
public static ConfiguredMessageList<String> ofStrings(@NotNull String... defaultMessages) {
return asStrings().defaults(defaultMessages).build();
}
public ConfiguredMessageList(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@NotNull List<TextConfig> messages, @NotNull String[] params,
@NotNull BiFunction<@Nullable CommandSender, @NotNull String, @Nullable M> messageParser,
@NotNull BiConsumer<@NotNull CommandSender, @NotNull List<M>> sendFunction) {
super(provider, sectionPath, headerComments, inlineComments, TextConfig.class, messages, params, messageParser, sendFunction, TextConfig::of);
}
@Override
public @NotNull Collection<CommandSender> getAllReceivers() {
List<CommandSender> senders = new ArrayList<>();
senders.add(Bukkit.getConsoleSender());
senders.addAll(Bukkit.getOnlinePlayers());
return senders;
}
}
@@ -0,0 +1,53 @@
package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.source.CraftConfigProvider;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Optional;
public class ConfiguredSerializable<T extends ConfigurationSerializable> extends CraftConfigValue<T> {
public static <V extends ConfigurationSerializable> ConfiguredSerializable<V> of(@NotNull Class<V> valueClass) {
return of(valueClass, null);
}
public static <V extends ConfigurationSerializable> ConfiguredSerializable<V> of(@NotNull Class<V> valueClass,
@Nullable V defaultValue) {
return builder().ofSerializable(valueClass).defaults(defaultValue).build();
}
protected final @NotNull Class<T> valueClass;
public ConfiguredSerializable(@Nullable CraftConfigProvider provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@NotNull Class<T> valueClass, @Nullable T defaultValue) {
super(provider, sectionPath, headerComments, inlineComments, defaultValue);
this.valueClass = valueClass;
}
@Override
public @Nullable T get() {
if (isExpired()) { // 已过时的数据,需要重新解析一次。
try {
// 若未出现错误,则直接更新缓存并返回。
return updateCache(getBukkitConfig().get(getConfigPath(), getDefaultValue(), valueClass));
} catch (Exception e) {
// 出现了解析错误,提示并返回默认值。
e.printStackTrace();
return useDefault();
}
} else return Optional.ofNullable(getCachedValue()).orElse(defaultValue);
}
@Override
public void set(@Nullable T value) {
updateCache(value);
setValue(value);
}
}
@@ -0,0 +1,77 @@
package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.configuration.core.function.ConfigValueParser;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.value.type.ConfiguredValue;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.sound.SoundConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.SoundConfig;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Optional;
public class ConfiguredSound extends ConfiguredValue<SoundConfig> {
public static @NotNull SoundConfigBuilder create() {
return CraftConfigValue.builder().createSound();
}
public static @NotNull ConfiguredSound of(Sound sound) {
return CraftConfigValue.builder().createSound().defaults(sound).build();
}
public static @NotNull ConfiguredSound of(Sound sound, float volume) {
return CraftConfigValue.builder().createSound().defaults(sound, volume).build();
}
public static @NotNull ConfiguredSound of(Sound sound, float volume, float pitch) {
return CraftConfigValue.builder().createSound().defaults(sound, volume, pitch).build();
}
public static @NotNull ConfiguredSound of(String soundName) {
return CraftConfigValue.builder().createSound().defaults(soundName).build();
}
public static @NotNull ConfiguredSound of(String soundName, float volume) {
return CraftConfigValue.builder().createSound().defaults(soundName, volume).build();
}
public static @NotNull ConfiguredSound of(String soundName, float volume, float pitch) {
return CraftConfigValue.builder().createSound().defaults(soundName, volume, pitch).build();
}
public ConfiguredSound(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@Nullable SoundConfig defaultValue) {
super(provider, sectionPath, headerComments, inlineComments, SoundConfig.class, defaultValue, getSoundParser(), SoundConfig::serialize);
}
public void setSound(@NotNull Sound sound) {
setSound(sound, 1.0f);
}
public void setSound(@NotNull Sound sound, float volume) {
setSound(sound, volume, 1.0f);
}
public void setSound(@NotNull Sound sound, float volume, float pitch) {
set(new SoundConfig(sound.name(), sound, volume, pitch));
}
public void playTo(@NotNull Player player) {
Optional.ofNullable(get()).ifPresent(c -> c.playTo(player));
}
public void playToAll() {
Optional.ofNullable(get()).ifPresent(SoundConfig::playToAll);
}
public static ConfigValueParser<Object, SoundConfig> getSoundParser() {
return ConfigValueParser.castToString().andThen((s, d) -> SoundConfig.deserialize(s));
}
}
@@ -0,0 +1,109 @@
package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.configuration.core.function.ConfigValueParser;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import cc.carm.lib.configuration.core.value.type.ConfiguredSection;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.title.TitleConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TitleConfig;
import cc.carm.lib.mineconfiguration.bukkit.function.TitleSendConsumer;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Range;
import java.util.List;
import java.util.Map;
public class ConfiguredTitle extends ConfiguredSection<TitleConfig> {
public static TitleConfigBuilder create() {
return CraftConfigValue.builder().createTitle();
}
public static ConfiguredTitle of(@Nullable String line1, @Nullable String line2) {
return create().defaults(line1, line2).build();
}
public static ConfiguredTitle of(@Nullable String line1, @Nullable String line2,
int fadeIn, int stay, int fadeOut) {
return create().defaults(line1, line2).fadeIn(fadeIn).stay(stay).fadeOut(fadeOut).build();
}
protected final @NotNull TitleSendConsumer sendConsumer;
protected final @NotNull String[] params;
protected final int fadeIn;
protected final int stay;
protected final int fadeOut;
public ConfiguredTitle(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments,
@Nullable TitleConfig defaultValue, @NotNull String[] params,
@NotNull TitleSendConsumer sendConsumer,
int fadeIn, int stay, int fadeOut) {
super(provider, sectionPath, headerComments, inlineComments, TitleConfig.class, defaultValue, getTitleParser(), TitleConfig::serialize);
this.sendConsumer = sendConsumer;
this.params = params;
this.fadeIn = fadeIn;
this.stay = stay;
this.fadeOut = fadeOut;
}
@Range(from = 0L, to = Integer.MAX_VALUE)
public int getFadeInTicks() {
return fadeIn;
}
@Range(from = 0L, to = Integer.MAX_VALUE)
public int getStayTicks() {
return stay;
}
@Range(from = 0L, to = Integer.MAX_VALUE)
public int getFadeOutTicks() {
return fadeOut;
}
public @NotNull TitleSendConsumer getSendConsumer() {
return sendConsumer;
}
public void send(@NotNull Player player, Object... values) {
send(player, this.params, values);
}
public void send(@NotNull Player player, @NotNull String[] params, @NotNull Object[] values) {
send(player, ParamsUtils.buildParams(params, values));
}
public void send(@NotNull Player player, @NotNull Map<String, Object> placeholders) {
TitleConfig config = get();
if (config != null) {
config.send(player, fadeIn, stay, fadeOut, placeholders, sendConsumer);
}
}
public void sendToAll(Object... values) {
sendToAll(this.params, values);
}
public void sendToAll(@NotNull String[] params, @NotNull Object[] values) {
sendToAll(ParamsUtils.buildParams(params, values));
}
public void sendToAll(@NotNull Map<String, Object> placeholders) {
TitleConfig config = get();
if (config == null) return;
Bukkit.getOnlinePlayers().forEach(onlinePlayer -> send(onlinePlayer, placeholders));
}
public static ConfigValueParser<ConfigurationWrapper<?>, TitleConfig> getTitleParser() {
return (s, d) -> TitleConfig.deserialize(s);
}
}