1
mirror of https://github.com/CarmJos/MineConfiguration.git synced 2026-06-05 06:51:49 +08:00

Compare commits

...

34 Commits

Author SHA1 Message Date
carm 143e0c2283 chore(update): 适配上游版本更新。 2023-02-11 21:54:59 +08:00
carm 4b4f90ee38 chore(update): 适配上游版本更新。 2023-02-11 21:54:35 +08:00
dependabot[bot] 97d24c7027 chore(deps): bump annotations from 23.1.0 to 24.0.0 (#17)
Bumps [annotations](https://github.com/JetBrains/java-annotations) from 23.1.0 to 24.0.0.
- [Release notes](https://github.com/JetBrains/java-annotations/releases)
- [Changelog](https://github.com/JetBrains/java-annotations/blob/master/CHANGELOG.md)
- [Commits](https://github.com/JetBrains/java-annotations/compare/23.1.0...24.0.0)

---
updated-dependencies:
- dependency-name: org.jetbrains:annotations
  dependency-type: direct:production
  update-type: version-update:semver-major
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-12 22:15:52 +08:00
carm d1b01ffed5 build(scm): 修复错误的scm地址 2022-12-18 04:54:29 +08:00
carm 67931094e6 refactor(proj): 放弃spigot项目,将Bukkit子项目单独提出。 2022-12-16 16:09:50 +08:00
carm 02f59b99f0 feat(msg): 添加 sendToEach 方法支持 2022-12-16 04:31:43 +08:00
carm e781d54348 feat(color): 完善ColorParser支持渐变RGB颜色。 2022-12-16 04:13:49 +08:00
carm bbd2c9e5e7 Merge remote-tracking branch 'origin/master' 2022-12-12 22:46:18 +08:00
carm ccc8cc6b72 feat(deps): 适配上游版本更新。 2022-12-12 22:36:20 +08:00
dependabot[bot] 1612e49326 chore(deps): bump annotations from 23.0.0 to 23.1.0 (#16)
Bumps [annotations](https://github.com/JetBrains/java-annotations) from 23.0.0 to 23.1.0.
- [Release notes](https://github.com/JetBrains/java-annotations/releases)
- [Changelog](https://github.com/JetBrains/java-annotations/blob/master/CHANGELOG.md)
- [Commits](https://github.com/JetBrains/java-annotations/compare/23.0.0...23.1.0)

---
updated-dependencies:
- dependency-name: org.jetbrains:annotations
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-10 11:35:23 +08:00
carm 2754f12cd5 fix(parse): 修复Number类型转换错误的问题。 2022-12-06 22:06:27 +08:00
dependabot[bot] c0f5d32ba0 chore(deps): bump maven-shade-plugin from 3.4.0 to 3.4.1 (#14)
Bumps [maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.4.0 to 3.4.1.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.4.0...maven-shade-plugin-3.4.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-shade-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-02 18:31:09 +08:00
dependabot[bot] 6c355e0d89 chore(deps): bump maven-jar-plugin from 3.2.2 to 3.3.0 (#12)
Bumps [maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.2.2 to 3.3.0.
- [Release notes](https://github.com/apache/maven-jar-plugin/releases)
- [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.2.2...maven-jar-plugin-3.3.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-jar-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-22 00:22:14 +08:00
dependabot[bot] 6c7a5dd60a chore(deps): bump maven-shade-plugin from 3.3.0 to 3.4.0 (#11)
Bumps [maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.3.0 to 3.4.0.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.3.0...maven-shade-plugin-3.4.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-shade-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-15 22:01:36 +08:00
carm 425d61834b chore: 移除重复方法 2022-09-10 01:33:47 +08:00
carm c9a272d052 fix(repo): 添加sonatype-repo 2022-09-10 01:23:23 +08:00
carm 327484cd53 feat(source): 为 ConfigurationWrapper 添加 getSource() 方法以获取源实现内容。 2022-09-10 01:17:10 +08:00
carm 99090929dd feat(source): 为 ConfigurationWrapper 添加 getSource() 方法以获取源实现内容。 2022-09-10 01:04:14 +08:00
carm 8437c4c904 feat(source): 为 ConfigurationWrapper 添加 getSource() 方法以获取源实现内容。 2022-09-10 01:04:04 +08:00
dependabot[bot] 21f7742d78 chore(deps): bump maven-javadoc-plugin from 3.4.0 to 3.4.1 (#9)
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.4.0 to 3.4.1.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.4.0...maven-javadoc-plugin-3.4.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-16 21:04:11 +08:00
dependabot[bot] 68e6280c94 chore(deps): bump placeholderapi from 2.11.1 to 2.11.2 (#7)
Bumps placeholderapi from 2.11.1 to 2.11.2.

---
updated-dependencies:
- dependency-name: me.clip:placeholderapi
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-05 14:44:26 +08:00
carm 9a8e6395bb fix(text): 令 AbstractText#parse 返回值不得为null,避免在List类型循环parse时出现异常。 2022-06-21 05:03:16 +08:00
carm 7fa6fa1551 feat(item): 为ItemConfig添加 ItemFlag 与 enchant 相关配置 2022-06-18 06:10:17 +08:00
carm 346ae4c494 feat(item): 为ItemConfig添加 ItemFlag 与 enchant 相关配置 2022-06-18 06:00:39 +08:00
carm 2d8c1817a6 feat(item): 为ItemConfig添加 ItemFlag 与 enchant 相关配置 2022-06-18 05:56:58 +08:00
carm f67d0fae8d feat(item): 为ItemConfig添加 ItemFlag 与 enchant 相关配置 2022-06-18 05:56:43 +08:00
carm 8d723df7a6 chore(sound): 添加输入长度判断,适用于不想发送声音的情况。 2022-06-17 22:57:05 +08:00
carm d4c7124d9e chore(sound): 添加输入长度判断,适用于不想发送声音的情况。 2022-06-17 22:56:47 +08:00
carm 2804543419 test(bungee): 添加测试输出 2022-06-09 00:23:28 +08:00
carm f826014c09 refactor(all): 修改项目结构,为BungeeYAML支持注释。
项目结构修改,避免使用上的误解。同时为 Bungee(YAML) 支持了注释功能。

BREAKING CHANGE: 包名与入口类变更
  1. 项目结构与包名修改
  mineconfiguration-bukkit-general -> mineconfiguration-bukkit
  mineconfiguration-bukkit-native -> mineconfiguration-spigot
  2. MineConfiguration入口类变更,现移动到各自平台的包下。
2022-06-09 00:18:14 +08:00
carm 616d24d885 ci(javadoc): 添加debug消息 2022-05-28 12:48:08 +08:00
carm 8d58583a1e ci(javadoc): 添加debug消息 2022-05-28 12:43:32 +08:00
carm 4b594269bd ci(javadoc): 添加Javadoc自动部署到gh-pages 2022-05-28 12:30:04 +08:00
carm b629a7d96d fix(bukkit): 修复Title配置文件未初始化报错的问题 2022-05-28 12:15:54 +08:00
55 changed files with 999 additions and 641 deletions
+9
View File
@@ -0,0 +1,9 @@
# MineConfiguration Javadoc
基于 [Github Pages](https://pages.github.com/) 搭建,请访问 [JavaDoc](https://carmjos.github.io/MineConfiguration) 。
## 如何实现?
若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
自动部署项目的Javadoc到 [Github Pages](https://pages.github.com/)
可以参考我的文章 [《自动部署Javadoc到Github Pages》](https://pages.carm.cc/doc/javadoc-in-github.html) 。
+3 -3
View File
@@ -12,7 +12,7 @@ on:
jobs: jobs:
gh-deploy: gh-deploy:
name: "Publish Project (GitHub)" name: "Deploy Project (GitHub)"
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -37,7 +37,7 @@ jobs:
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
central-deploy: central-deploy:
name: "Deploy Project (Central Repository)" name: "Deploy Project (Central)"
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@@ -58,4 +58,4 @@ jobs:
env: env:
MAVEN_USERNAME: ${{ secrets.OSSRH_USER }} MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
MAVEN_PASSWORD: ${{ secrets.OSSRH_PASS }} MAVEN_PASSWORD: ${{ secrets.OSSRH_PASS }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
+74
View File
@@ -0,0 +1,74 @@
name: "Publish Javadoc"
on:
# 支持手动触发构建
workflow_dispatch:
release:
# 创建release的时候触发
types: [ published ]
jobs:
javadoc-deploy:
name: "Deploy Javadoc (Github Pages)"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: "Set up JDK"
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: maven
- name: "Generate Javadoc"
run: mvn -B javadoc:aggregate --file pom.xml -DskipTests
- name: "Copy Javadoc"
run: |
rm -rf docs
mkdir -vp docs
cp -vrf target/site/apidocs/* docs/
cp -vrf .doc/javadoc/JAVADOC-README.md docs/README.md
- name: "Generate Sitemap"
id: sitemap
uses: cicirello/generate-sitemap@v1
with:
base-url-path: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}
path-to-root: docs
- name: Output stats
run: |
echo "sitemap-path = ${{ steps.sitemap.outputs.sitemap-path }}"
echo "url-count = ${{ steps.sitemap.outputs.url-count }}"
echo "excluded-count = ${{ steps.sitemap.outputs.excluded-count }}"
ls -l docs
- name: Configure Git
env:
DEPLOY_PRI: ${{secrets.DEPLOY_PRI}}
run: |
sudo timedatectl set-timezone "Asia/Shanghai"
mkdir -p ~/.ssh/
echo "$DEPLOY_PRI" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.name '${{ github.repository_owner }}'
git config --global user.email '${{ github.repository_owner }}@users.noreply.github.com'
- name: Commit documentation changes
run: |
echo "Committing changes to git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git ..."
cd docs
git init
git remote add origin git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git
git checkout -b gh-pages
git add -A
git commit -m "API Document generated."
- name: Javadoc Website Push
run: |
cd docs
git push origin HEAD:gh-pages --force
+15 -26
View File
@@ -20,46 +20,35 @@ EasyConfiguration for MineCraft!
## 项目结构 ## 项目结构
### **MineConfiguration-Common** ### **MineConfiguration-Common** [`common`](common)
全部版本的共用部分,包括 全部版本的共用部分(均已被打包至下行包中),包括
- `ConfigMessage` (实现类为 `ConfiguredMessage<M>`) - `ConfigMessage` (实现类为 `ConfiguredMessage<M>`)
- `ConfigMessageList` (实现类为 `ConfiguredMessageList<M>`) - `ConfigMessageList` (实现类为 `ConfiguredMessageList<M>`)
如要使用,请访问对应实现类的builder() 方法来快速创建。 如要使用,请访问对应实现类的builder() 方法来快速创建。
### MineConfiguration-Bukkit ### **MineConfiguration-Bukkit** [`platform/bukkit`](platform/bukkit)
#### MineConfiguration-Bukkit-Base 适用于Bukkit的版本,同时支持其他以Bukkit为基础的服务端 *(如Spigot、Paper、CatServer)*
Bukkit系通用依赖,不包含实现部分,请使用 **MineConfiguration-Bukkit-General****MineConfiguration-Bukkit-Native**
相较于基础版本,额外提供了以下功能: 相较于基础版本,额外提供了以下功能:
- `ConfiguredSerializable<T extends ConfigurationSerializable>` - `ConfiguredSerializable<T extends ConfigurationSerializable>`
- `ConfiguredItem` (快捷读简单的物品配置文件) - `ConfiguredItem` (快捷读\写\使用简单的物品配置文件)
- `ConfiguredSound` (快捷读音效配置文件) - `ConfiguredSound` (快捷读\写\使用音效配置文件)
- `ConfiguredTitle` (快速读\写\使用标题文字配置文件)
以上类型可以通过 `CraftConfigValue.builder()` 来创建,部分类型提供了 `of(...);` 方法来快速创建。 以上类型可以通过 `CraftConfigValue.builder()` 来创建,部分类型提供了 `of(...);` 方法来快速创建。
#### **MineConfiguration-Bukkit-General** _(推荐)_ ### **MineConfiguration-Bungee** [`platform/bungee`](platform/bungee)
适用于Bukkit的版本,包含以Bukkit为基础的其他服务端 *(如Spigot、Paper、CatServer)* 适用于BungeeCord的版本,可用JSON与YAML格式。其中JSON格式**不支持配置文件注释**
#### **MineConfiguration-Bukkit-Native**
适用于 Spigot(1.18+) 的版本,适配了1.18及以后版本Spigot原生自带的配置文件注释功能,随Spigot更新而优化,安全稳定。
### **MineConfiguration-Bungee**
适用于BungeeCord的版本,可用JSON与YAML格式,但**不支持配置文件注释**。
如需使用配置文件注释,建议使用 [EasyConfiguration-YAML](https://github.com/CarmJos/EasyConfiguration) 。
## 开发 ## 开发
请详见 [EasyConfiguration](https://github.com/CarmJos/EasyConfiguration) 其他功能请详见 [EasyConfiguration](https://github.com/CarmJos/EasyConfiguration)
的 [开发介绍](https://github.com/CarmJos/EasyConfiguration/tree/master/.documentation) 。 的 [开发介绍](https://github.com/CarmJos/EasyConfiguration/tree/master/.documentation) 。
### 依赖方式 ### 依赖方式
@@ -111,14 +100,14 @@ Bukkit系通用依赖,不包含实现部分,请使用 **MineConfiguration-Bu
<dependency> <dependency>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>mineconfiguration-bukkit-general</artifactId> <artifactId>mineconfiguration-bukkit</artifactId>
<version>[LATEST RELEASE]</version> <version>[LATEST RELEASE]</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>mineconfiguration-bukkit-native</artifactId> <artifactId>mineconfiguration-spigot</artifactId>
<version>[LATEST RELEASE]</version> <version>[LATEST RELEASE]</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -164,9 +153,9 @@ repositories {
dependencies { dependencies {
api "cc.carm.lib:mineconfiguration-bukkit-general:[LATEST RELEASE]" api "cc.carm.lib:mineconfiguration-bukkit:[LATEST RELEASE]"
api "cc.carm.lib:mineconfiguration-bukkit-native:[LATEST RELEASE]" api "cc.carm.lib:mineconfiguration-spigot:[LATEST RELEASE]"
api "cc.carm.lib:mineconfiguration-bungee:[LATEST RELEASE]" api "cc.carm.lib:mineconfiguration-bungee:[LATEST RELEASE]"
+11 -25
View File
@@ -5,32 +5,30 @@
<parent> <parent>
<artifactId>mineconfiguration-parent</artifactId> <artifactId>mineconfiguration-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.2</version> <version>2.3.1</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
<artifactId>mineconfiguration-common</artifactId> <artifactId>mineconfiguration-common</artifactId>
<name>MineConfiguration-Common</name>
<description>轻松(做)配置,全部版本的共用部分。</description>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>${project.parent.groupId}</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easyconfiguration-core</artifactId> <artifactId>easyconfiguration-core</artifactId>
<version>${easyconfiguration.version}</version> <version>${deps.easyconfifuration.version}</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <!--suppress VulnerableLibrariesLocal -->
<groupId>de.themoep</groupId>
<artifactId>minedown</artifactId>
<version>1.7.1-SNAPSHOT</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>net.md-5</groupId> <groupId>net.md-5</groupId>
<artifactId>bungeecord-chat</artifactId> <artifactId>bungeecord-chat</artifactId>
@@ -43,18 +41,6 @@
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
@@ -28,16 +28,14 @@ public abstract class AbstractText<R> {
return this.message; return this.message;
} }
public <M> @Nullable M parse(@NotNull BiFunction<@Nullable R, @NotNull String, @NotNull M> parser, public <M> @NotNull M parse(@NotNull BiFunction<@Nullable R, @NotNull String, @NotNull M> parser,
@Nullable R receiver, @Nullable String[] params, @Nullable Object[] values) { @Nullable R receiver, @Nullable String[] params, @Nullable Object[] values) {
return parse(parser, receiver, ParamsUtils.buildParams(params, values)); return parse(parser, receiver, ParamsUtils.buildParams(params, values));
} }
public <M> @Nullable M parse(@NotNull BiFunction<@Nullable R, @NotNull String, @NotNull M> parser, public <M> @NotNull M parse(@NotNull BiFunction<@Nullable R, @NotNull String, @NotNull M> parser,
@Nullable R receiver, @NotNull Map<String, Object> placeholders) { @Nullable R receiver, @NotNull Map<String, Object> placeholders) {
String message = getMessage(); return parser.apply(receiver, ParamsUtils.setPlaceholders(message, placeholders));
if (message.isEmpty()) return null; // No further processing
else return parser.apply(receiver, ParamsUtils.setPlaceholders(message, placeholders));
} }
@@ -1,31 +1,93 @@
package cc.carm.lib.mineconfiguration.common.utils; package cc.carm.lib.mineconfiguration.common.utils;
import java.util.Arrays; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.List; import java.util.List;
import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* 颜色解析器,来自EasyPlugin项目。
* <br> 普通颜色 格式 {@code &+颜色代码 },如 {@literal &c} 、{@literal &a}
* <br> RGB颜色(版本需要≥1.14) 格式 {@code &(#XXXXXX) },如 {@literal &(#aaaaaa)}
* <br> 渐变RBG颜色(版本需要≥1.14) 格式 {@code &<#XXXXXX>FOOBAR&<#XXXXXX> }
* <p> 注意:当使用渐变RGB颜色时,普通颜色代码与RGB颜色代码将失效。
*
* @author CarmJos
* @since 1.4.18
*/
public class ColorParser { public class ColorParser {
public static Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([0-9a-fA-F]{6})\\)"); public static final Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([\\da-fA-F]{6})\\)");
public static final Pattern GRADIENT_PATTERN = Pattern.compile("&<&?#([\\da-fA-F]{6})>");
public static final Pattern COLOR_PATTERN = Pattern.compile("([&§][0-9a-fA-FrRxX])+"); // 会影响颜色的代码
public static final Pattern FORMAT_PATTERN = Pattern.compile("([&§][0-9a-fA-Fk-oK-OrRxX])+"); // MC可用的格式化代码
public static String parse(String text) { /**
return parseBaseColor(parseHexColor(text)); * 清除一条消息中的全部颜色代码 (包括RGB颜色代码与渐变颜色代码)
*
* @param text 源消息内容
* @return 清理颜色后的消息
*/
public static @NotNull String clear(@NotNull String text) {
text = HEX_PATTERN.matcher(text).replaceAll("");
text = GRADIENT_PATTERN.matcher(text).replaceAll("");
text = COLOR_PATTERN.matcher(text).replaceAll("");
return text;
} }
public static String[] parse(String... texts) { /**
* 对一条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param text 源消息内容
* @return 解析后的消息
*/
public static @NotNull String parse(@NotNull String text) {
return parseBaseColor(parseGradientColor(parseHexColor(text)));
}
/**
* 对多条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param texts 源消息内容
* @return 解析后的消息
*/
public static @NotNull String[] parse(@NotNull String... texts) {
return parse(Arrays.asList(texts)).toArray(new String[0]); return parse(Arrays.asList(texts)).toArray(new String[0]);
} }
public static List<String> parse(List<String> texts) { /**
* 对多条消息进行颜色解析,包括普通颜色代码、RGB颜色代码与RBG渐变代码。
*
* @param texts 源消息内容
* @return 解析后的消息
*/
public static @NotNull List<String> parse(@NotNull Collection<String> texts) {
return texts.stream().map(ColorParser::parse).collect(Collectors.toList()); return texts.stream().map(ColorParser::parse).collect(Collectors.toList());
} }
/**
* 解析消息中的基本颜色代码格式 {@code &+颜色代码 },如 {@literal &c} 、{@literal &a}
*
* @param text 消息内容
* @return RGB处理后的消息
* @see net.md_5.bungee.api.ChatColor
*/
public static String parseBaseColor(final String text) { public static String parseBaseColor(final String text) {
return text.replaceAll("&", "§").replace("§§", "&"); return text.replaceAll("&", "§").replace("§§", "&");
} }
/**
* 解析消息中的RGB颜色代码(版本需要≥1.14) 格式 {@code &(#XXXXXX) },如 {@literal &(#aaaaaa)}
*
* @param text 消息内容
* @return RGB处理后的消息
*/
public static String parseHexColor(String text) { public static String parseHexColor(String text) {
Matcher matcher = HEX_PATTERN.matcher(text); Matcher matcher = HEX_PATTERN.matcher(text);
while (matcher.find()) { while (matcher.find()) {
@@ -35,9 +97,114 @@ public class ColorParser {
return text; return text;
} }
private static String buildHexColor(String hexCode) { /**
return Arrays.stream(hexCode.split("")) * 对一条消息进行RGB渐变处理(版本需要≥1.14),格式 {@code &<#XXXXXX>FOOBAR&<#XXXXXX> }。
.map(s -> '§' + s) *
* @param text 消息内容
* @return RGB渐变处理后的消息
*/
public static @NotNull String parseGradientColor(@NotNull String text) {
List<String> colors = new ArrayList<>();
Matcher matcher = ColorParser.GRADIENT_PATTERN.matcher(text);
while (matcher.find()) colors.add(matcher.group(1));
if (colors.isEmpty()) return text; // 无渐变颜色,直接跳出
String[] parts = ColorParser.GRADIENT_PATTERN.split(text);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
String startHex = i - 1 >= 0 && colors.size() > i - 1 ? colors.get(i - 1) : null; // 本条消息的起始颜色
String endHex = colors.size() > i ? colors.get(i) : null; // 本条消息的结束颜色
builder.append(gradientText(parts[i], startHex, endHex));
}
return builder.toString();
}
public static @NotNull String gradientText(@NotNull String text,
@Nullable Color startColor, @Nullable Color endColor) {
Objects.requireNonNull(text, "Text to be gradient should not be null!");
if (startColor == null || endColor == null || text.isEmpty()) {
// 起始颜色有任一为空,则不进行渐变上色。
// 若有起始颜色,则代表其跟在某个渐变之后,应当添加"&r"阻断前面的渐变。
return (startColor != null ? "&r" : "") + text;
}
// 用于记录消息中特殊格式的位置
// 在渐变中,允许使用格式字符与颜色字符来改变其中某个字的颜色/格式,以支持更多形式内容。
LinkedHashMap<Integer, String> extraFormats = new LinkedHashMap<>();
Matcher matcher = ColorParser.FORMAT_PATTERN.matcher(text);
while (matcher.find()) {
extraFormats.put(matcher.start(), matcher.group());
text = matcher.replaceFirst("");
matcher.reset(text);
}
if (text.length() == 1) {
// 当只有一个实际字符时,无需进行渐变计算,直接返回 中间颜色+起始格式(如果有)+消息 即可。
return colorText(text, extraFormats.get(0), buildHexColor(mediumHex(startColor, endColor)));
}
String[] characters = text.split("");
int step = characters.length; // 变换次数
// 决定每种颜色变换的方向
int rDirection = startColor.getRed() < endColor.getRed() ? 1 : -1;
int gDirection = startColor.getGreen() < endColor.getGreen() ? 1 : -1;
int bDirection = startColor.getBlue() < endColor.getBlue() ? 1 : -1;
// 决定每种颜色每次变换的度
int rStep = Math.abs(startColor.getRed() - endColor.getRed()) / (step - 1);
int gStep = Math.abs(startColor.getGreen() - endColor.getGreen()) / (step - 1);
int bStep = Math.abs(startColor.getBlue() - endColor.getBlue()) / (step - 1);
String[] hexes = IntStream.range(0, step).mapToObj(i -> colorToHex(
startColor.getRed() + rStep * i * rDirection,
startColor.getGreen() + gStep * i * gDirection,
startColor.getBlue() + bStep * i * bDirection
)).toArray(String[]::new);
return IntStream.range(0, characters.length)
.mapToObj(i -> colorText(characters[i], extraFormats.get(i), buildHexColor(hexes[i])))
.collect(Collectors.joining());
}
protected static String gradientText(@NotNull String text, @Nullable String startHex, @Nullable String endHex) {
return gradientText(text,
startHex == null ? null : Color.decode("0x" + startHex),
endHex == null ? null : Color.decode("0x" + endHex)
);
}
private static String mediumHex(@NotNull Color start, @NotNull Color end) {
return colorToHex(
Math.abs(start.getRed() - end.getRed()) / 2,
Math.abs(start.getGreen() - end.getGreen()) / 2,
Math.abs(start.getBlue() - end.getBlue()) / 2
);
}
private static String colorText(String message, @Nullable String format, @Nullable String color) {
if (format != null && COLOR_PATTERN.matcher(format).find()) {
// format中存在影响颜色的内容,则当前消息的颜色会被覆盖。
// 为了减少最终消息的长度,故直接返回键入的FORMAT和对应消息的内容。
return format + message;
}
return (color == null ? "" : color) + (format == null ? "" : parseBaseColor(format)) + message;
}
protected static String colorToHex(Color color) {
return colorToHex(color.getRed(), color.getGreen(), color.getBlue());
}
protected static String colorToHex(int r, int g, int b) {
// 将R、G、B转换为16进制(若非2位则补0)输出
return String.format("%02X%02X%02X", r, g, b);
}
protected static String buildHexColor(String hexCode) {
return Arrays.stream(hexCode.split("")).map(s -> '§' + s)
.collect(Collectors.joining("", '§' + "x", "")); .collect(Collectors.joining("", '§' + "x", ""));
} }
@@ -0,0 +1,147 @@
package cc.carm.lib.mineconfiguration.common.value;
import cc.carm.lib.mineconfiguration.common.builder.message.MessageValueBuilder;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
public interface BaseMessage<R, M> {
/**
* 得到所有的接收者
*
* @return 全部可能的接收者
*/
@Unmodifiable
@NotNull Iterable<R> getAllReceivers();
/**
* 得到消息中的通过 {@link MessageValueBuilder#params(String...)}已定变量名(按定义顺序)
*
* @return 已定变量
*/
@NotNull String[] getParams();
/**
* 向接收者发送消息的根方法。
*
* @param receiver 接收者
* @param message 消息内容
*/
@ApiStatus.OverrideOnly
void apply(@NotNull R receiver, @NotNull M message);
/**
* 为某位接收者解析此消息。
*
* @param sender 接收者
* @param placeholders 消息中的变量与对应参数
* @return 解析变量后的消息内容
*/
@Nullable M parse(@Nullable R sender, @NotNull Map<String, Object> placeholders);
/**
* 为某位接收者解析此消息。
*
* @param sender 接收者
* @param values 已定变量的对应参数
* @return 解析变量后的消息内容
*/
default @Nullable M parse(@Nullable R sender, @Nullable Object... values) {
return parse(sender, ParamsUtils.buildParams(getParams(), values));
}
/**
* 向某位接收者发送消息
*
* @param receiver 消息的接收者
* @param values 已定变量的对应参数
*/
default void send(@Nullable R receiver, @Nullable Object... values) {
send(receiver, ParamsUtils.buildParams(getParams(), values));
}
/**
* 向某位接收者发送消息
*
* @param receiver 消息的接收者
* @param placeholders 消息中的变量与对应参数
*/
default void send(@Nullable R receiver, @NotNull Map<String, Object> placeholders) {
if (receiver == null) return;
M parsed = parse(receiver, placeholders);
if (parsed == null) return;
apply(receiver, parsed);
}
/**
* 向全部接收者(包括后台)发送不同参数的消息
*
* @param eachValues 每位接收者将收到已定变量的对应参数(按定义顺序)
*/
default void sendToEach(@NotNull Function<@NotNull R, Object[]> eachValues) {
sendToEach(null, eachValues);
}
/**
* 向特定接收者发送不同参数的消息
*
* @param limiter 接收者限定器,为空则不限定接收者。
* @param eachValues 每位接收者将收到已定变量的对应参数(按定义顺序)
*/
default void sendToEach(@Nullable Predicate<R> limiter,
@NotNull Function<@NotNull R, Object[]> eachValues) {
Predicate<R> predicate = Optional.ofNullable(limiter).orElse(r -> true);
for (R r : getAllReceivers()) {
if (predicate.test(r)) {
send(r, ParamsUtils.buildParams(getParams(), eachValues.apply(r)));
}
}
}
/**
* 广播此消息(包括后台)
*
* @param values 已定变量的对应参数(按定义顺序)
*/
default void sendToAll(@Nullable Object... values) {
broadcast(values);
}
/**
* 广播此消息(包括后台)
*
* @param placeholders 消息中的变量与对应参数
*/
default void sendToAll(@NotNull Map<String, Object> placeholders) {
broadcast(placeholders);
}
/**
* 广播此消息(包括后台)
*
* @param values 已定变量的对应参数(按定义顺序)
*/
default void broadcast(@Nullable Object... values) {
broadcast(ParamsUtils.buildParams(getParams(), values));
}
/**
* 广播此消息(包括后台)
*
* @param placeholders 消息中的变量与对应参数
*/
default void broadcast(@NotNull Map<String, Object> placeholders) {
getAllReceivers().forEach(r -> send(r, placeholders));
}
}
@@ -1,10 +1,9 @@
package cc.carm.lib.mineconfiguration.common.value; package cc.carm.lib.mineconfiguration.common.value;
import cc.carm.lib.mineconfiguration.common.data.AbstractText;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import cc.carm.lib.configuration.core.function.ConfigValueParser; import cc.carm.lib.configuration.core.function.ConfigValueParser;
import cc.carm.lib.configuration.core.source.ConfigurationProvider; import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.value.type.ConfiguredValue; import cc.carm.lib.configuration.core.value.type.ConfiguredValue;
import cc.carm.lib.mineconfiguration.common.data.AbstractText;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -15,11 +14,11 @@ import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
public abstract class ConfigMessage<M, T extends AbstractText<R>, R> public abstract class ConfigMessage<M, T extends AbstractText<R>, R>
extends ConfiguredValue<T> { extends ConfiguredValue<T> implements BaseMessage<R, M> {
protected final @NotNull String[] params; protected final @NotNull String[] params;
protected final @NotNull BiFunction<@Nullable R, @NotNull String, @Nullable M> messageParser; protected final @NotNull BiFunction<@Nullable R, @NotNull String, @Nullable M> messageParser;
protected final @NotNull BiConsumer<@NotNull R, @NotNull M> messageConsumer; protected final @NotNull BiConsumer<@NotNull R, @NotNull M> sendFunction;
protected final @NotNull Function<String, T> textBuilder; protected final @NotNull Function<String, T> textBuilder;
@@ -27,44 +26,35 @@ public abstract class ConfigMessage<M, T extends AbstractText<R>, R>
@Nullable List<String> headerComments, @Nullable String inlineComments, @Nullable List<String> headerComments, @Nullable String inlineComments,
@NotNull Class<T> textClazz, @NotNull T defaultMessage, @NotNull String[] params, @NotNull Class<T> textClazz, @NotNull T defaultMessage, @NotNull String[] params,
@NotNull BiFunction<@Nullable R, @NotNull String, @Nullable M> messageParser, @NotNull BiFunction<@Nullable R, @NotNull String, @Nullable M> messageParser,
@NotNull BiConsumer<@NotNull R, @NotNull M> messageConsumer, @NotNull BiConsumer<@NotNull R, @NotNull M> sendFunction,
@NotNull Function<String, T> textBuilder) { @NotNull Function<String, T> textBuilder) {
super(provider, sectionPath, headerComments, inlineComments, textClazz, defaultMessage, super(
provider, sectionPath, headerComments, inlineComments, textClazz, defaultMessage,
ConfigValueParser.castToString().andThen((s, d) -> textBuilder.apply(s)), AbstractText::getMessage ConfigValueParser.castToString().andThen((s, d) -> textBuilder.apply(s)), AbstractText::getMessage
); );
this.params = params; this.params = params;
this.messageParser = messageParser; this.messageParser = messageParser;
this.messageConsumer = messageConsumer; this.sendFunction = sendFunction;
this.textBuilder = textBuilder; this.textBuilder = textBuilder;
} }
public @Nullable M parse(@Nullable R sender, @Nullable Object... values) { @Override
return parse(sender, ParamsUtils.buildParams(params, values)); public String[] getParams() {
return params;
} }
@Override
public void apply(@NotNull R receiver, @NotNull M message) {
sendFunction.accept(receiver, message);
}
@Override
public @Nullable M parse(@Nullable R sender, @NotNull Map<String, Object> placeholders) { public @Nullable M parse(@Nullable R sender, @NotNull Map<String, Object> placeholders) {
T value = get(); T value = get();
if (value == null || value.getMessage().isEmpty()) return null; if (value == null || value.getMessage().isEmpty()) return null;
else return value.parse(this.messageParser, sender, placeholders); else return value.parse(this.messageParser, sender, placeholders);
} }
public void send(@Nullable R receiver, @Nullable Object... values) {
send(receiver, ParamsUtils.buildParams(params, values));
}
public void send(@Nullable R receiver, @NotNull Map<String, Object> placeholders) {
if (receiver == null) return;
M parsed = parse(receiver, placeholders);
if (parsed == null) return;
messageConsumer.accept(receiver, parsed);
}
public void broadcast(@Nullable Object... values) {
broadcast(ParamsUtils.buildParams(params, values));
}
public abstract void broadcast(@NotNull Map<String, Object> placeholders);
public void set(@Nullable String value) { public void set(@Nullable String value) {
this.set(value == null ? null : buildText(value)); this.set(value == null ? null : buildText(value));
} }
@@ -72,4 +62,5 @@ public abstract class ConfigMessage<M, T extends AbstractText<R>, R>
protected T buildText(String value) { protected T buildText(String value) {
return textBuilder.apply(value); return textBuilder.apply(value);
} }
} }
@@ -1,10 +1,9 @@
package cc.carm.lib.mineconfiguration.common.value; package cc.carm.lib.mineconfiguration.common.value;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import cc.carm.lib.mineconfiguration.common.data.AbstractText;
import cc.carm.lib.configuration.core.function.ConfigDataFunction; import cc.carm.lib.configuration.core.function.ConfigDataFunction;
import cc.carm.lib.configuration.core.source.ConfigurationProvider; import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.value.type.ConfiguredList; import cc.carm.lib.configuration.core.value.type.ConfiguredList;
import cc.carm.lib.mineconfiguration.common.data.AbstractText;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -16,7 +15,8 @@ import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public abstract class ConfigMessageList<M, T extends AbstractText<R>, R> extends ConfiguredList<T> { public abstract class ConfigMessageList<M, T extends AbstractText<R>, R>
extends ConfiguredList<T> implements BaseMessage<R, List<M>> {
protected final @NotNull String[] params; protected final @NotNull String[] params;
protected final @NotNull BiFunction<@Nullable R, @NotNull String, @Nullable M> messageParser; protected final @NotNull BiFunction<@Nullable R, @NotNull String, @Nullable M> messageParser;
@@ -24,7 +24,6 @@ public abstract class ConfigMessageList<M, T extends AbstractText<R>, R> extends
protected final @NotNull Function<String, T> textBuilder; protected final @NotNull Function<String, T> textBuilder;
@SuppressWarnings("NullableProblems")
public ConfigMessageList(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath, public ConfigMessageList(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments, @Nullable List<String> headerComments, @Nullable String inlineComments,
@NotNull Class<T> textClazz, @NotNull List<T> messages, @NotNull String[] params, @NotNull Class<T> textClazz, @NotNull List<T> messages, @NotNull String[] params,
@@ -41,38 +40,34 @@ public abstract class ConfigMessageList<M, T extends AbstractText<R>, R> extends
this.textBuilder = textBuilder; this.textBuilder = textBuilder;
} }
public @Nullable List<M> parse(@Nullable R sender, @Nullable Object... values) { @Override
return parse(sender, ParamsUtils.buildParams(params, values)); public String[] getParams() {
return params;
} }
public @Nullable List<M> parse(@Nullable R sender, @NotNull Map<String, Object> placeholders) { @Override
public void apply(@NotNull R receiver, @NotNull List<M> message) {
sendFunction.accept(receiver, message);
}
/**
* 为某位接收者解析消息
*
* @param receiver 消息的接收者
* @param placeholders 消息中的变量与对应参数
*/
@Override
public @Nullable List<M> parse(@Nullable R receiver, @NotNull Map<String, Object> placeholders) {
List<T> list = get(); List<T> list = get();
if (list.isEmpty()) return null; if (list.isEmpty()) return null;
List<String> messages = list.stream().map(T::getMessage).collect(Collectors.toList()); List<String> messages = list.stream().map(T::getMessage).collect(Collectors.toList());
if (String.join("", messages).isEmpty()) return null; if (String.join("", messages).isEmpty()) return null;
return list.stream().map(value -> value.parse(this.messageParser, sender, placeholders)) return list.stream().map(value -> value.parse(this.messageParser, receiver, placeholders))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public void send(@Nullable R receiver, @Nullable Object... values) {
send(receiver, ParamsUtils.buildParams(params, values));
}
public void send(@Nullable R receiver, @NotNull Map<String, Object> placeholders) {
if (receiver == null) return;
List<M> parsed = parse(receiver, placeholders);
if (parsed == null) return;
sendFunction.accept(receiver, parsed);
}
public void broadcast(@Nullable Object... values) {
broadcast(ParamsUtils.buildParams(params, values));
}
public abstract void broadcast(@NotNull Map<String, Object> placeholders);
public void setMessages(@NotNull String... values) { public void setMessages(@NotNull String... values) {
setMessages(values.length == 0 ? null : Arrays.asList(values)); setMessages(values.length == 0 ? null : Arrays.asList(values));
} }
@@ -83,7 +78,6 @@ public abstract class ConfigMessageList<M, T extends AbstractText<R>, R> extends
} else { } else {
set(buildText(values)); set(buildText(values));
} }
} }
protected List<T> buildText(List<String> values) { protected List<T> buildText(List<String> values) {
-57
View File
@@ -1,57 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mineconfiguration-bukkit</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<artifactId>mineconfiguration-bukkit-base</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easyconfiguration-core</artifactId>
<version>${easyconfiguration.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>mineconfiguration-common</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
-51
View File
@@ -1,51 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mineconfiguration-bukkit</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<artifactId>mineconfiguration-bukkit-general</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>mineconfiguration-bukkit-base</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
-59
View File
@@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mineconfiguration-bukkit</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<artifactId>mineconfiguration-bukkit-native</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>mineconfiguration-bukkit-base</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.18.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -1,42 +0,0 @@
package cc.carm.lib.mineconfiguration;
import cc.carm.lib.mineconfiguration.bukkit.source.SpigotConfigProvider;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
public class MineConfiguration {
public static SpigotConfigProvider from(File file, String source) {
SpigotConfigProvider provider = new SpigotConfigProvider(file);
try {
provider.initializeFile(source);
provider.initializeConfig();
} catch (IOException e) {
e.printStackTrace();
}
return provider;
}
public static SpigotConfigProvider from(File file) {
return from(file, file.getName());
}
public static SpigotConfigProvider from(String fileName) {
return from(fileName, fileName);
}
public static SpigotConfigProvider from(String fileName, String source) {
return from(new File(fileName), source);
}
public static SpigotConfigProvider from(Plugin plugin, String fileName) {
return from(plugin, fileName, fileName);
}
public static SpigotConfigProvider from(Plugin plugin, String fileName, String source) {
return from(new File(plugin.getDataFolder(), fileName), source);
}
}
@@ -1,53 +0,0 @@
package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.ConfigInitializer;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.io.File;
import java.util.Collections;
import java.util.List;
public class SpigotConfigProvider extends CraftConfigProvider {
public SpigotConfigProvider(@NotNull File file) {
super(file);
}
@Override
public void initializeConfig() {
this.configuration = YamlConfiguration.loadConfiguration(file);
this.initializer = new ConfigInitializer<>(this);
}
@Override
public void setHeaderComment(@Nullable String path, @Nullable List<String> comments) {
if (path == null) {
this.configuration.options().setHeader(comments);
} else {
this.configuration.setComments(path, comments);
}
}
@Override
public void setInlineComment(@NotNull String path, @Nullable String comment) {
if (comment == null) {
this.configuration.setInlineComments(path, null);
} else {
this.configuration.setComments(path, Collections.singletonList(comment));
}
}
@Override
public @Nullable @Unmodifiable List<String> getHeaderComment(@Nullable String path) {
if (path == null) return Collections.unmodifiableList(this.configuration.options().getHeader());
else return this.configuration.getComments(path);
}
@Override
public @Nullable String getInlineComment(@NotNull String path) {
return String.join(" ", this.configuration.getInlineComments(path));
}
}
+25 -11
View File
@@ -5,27 +5,32 @@
<parent> <parent>
<artifactId>mineconfiguration-parent</artifactId> <artifactId>mineconfiguration-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.2</version> <version>2.3.1</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
<artifactId>mineconfiguration-bukkit</artifactId> <artifactId>mineconfiguration-bukkit</artifactId>
<packaging>pom</packaging> <packaging>jar</packaging>
<modules>
<module>base</module>
<module>general</module>
<module>native</module>
</modules>
<name>MineConfiguration-Bukkit</name> <name>MineConfiguration-Bukkit</name>
<description>轻松(做)配置,适用于Bukkit系服务端的版本。</description>
<dependencies> <dependencies>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>mineconfiguration-common</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
<!--suppress VulnerableLibrariesLocal -->
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
@@ -37,7 +42,7 @@
<dependency> <dependency>
<groupId>me.clip</groupId> <groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId> <artifactId>placeholderapi</artifactId>
<version>2.11.1</version> <version>2.11.2</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
@@ -51,4 +56,13 @@
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> </project>
@@ -25,7 +25,7 @@ public abstract class CraftConfigValue<T> extends CachedConfigValue<T> {
public CraftConfigProvider getBukkitProvider() { public CraftConfigProvider getBukkitProvider() {
ConfigurationProvider<?> provider = getProvider(); ConfigurationProvider<?> provider = getProvider();
if (provider instanceof CraftConfigProvider) return (CraftConfigProvider) getProvider(); if (provider instanceof CraftConfigProvider) return (CraftConfigProvider) getProvider();
else throw new IllegalStateException("Provider is not a SpigotConfigProvider"); else throw new IllegalStateException("Provider is not a CraftConfigProvider");
} }
public CraftSectionWrapper getBukkitConfig() { public CraftSectionWrapper getBukkitConfig() {
@@ -1,4 +1,4 @@
package cc.carm.lib.mineconfiguration; package cc.carm.lib.mineconfiguration.bukkit;
import cc.carm.lib.mineconfiguration.bukkit.source.BukkitConfigProvider; import cc.carm.lib.mineconfiguration.bukkit.source.BukkitConfigProvider;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
@@ -38,4 +38,5 @@ public class MineConfiguration {
public static BukkitConfigProvider from(Plugin plugin, String fileName, String source) { public static BukkitConfigProvider from(Plugin plugin, String fileName, String source) {
return from(new File(plugin.getDataFolder(), fileName), source); return from(new File(plugin.getDataFolder(), fileName), source);
} }
} }
@@ -5,13 +5,12 @@ import cc.carm.lib.mineconfiguration.bukkit.data.ItemConfig;
import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredItem; import cc.carm.lib.mineconfiguration.bukkit.value.ConfiguredItem;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils; import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
public class ItemConfigBuilder extends AbstractCraftBuilder<ItemConfig, ItemConfigBuilder> { public class ItemConfigBuilder extends AbstractCraftBuilder<ItemConfig, ItemConfigBuilder> {
@@ -21,6 +20,9 @@ public class ItemConfigBuilder extends AbstractCraftBuilder<ItemConfig, ItemConf
protected String name = null; protected String name = null;
protected List<String> lore = new ArrayList<>(); 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 String[] params = new String[0];
protected @NotNull Function<@NotNull String, @NotNull String> paramFormatter = ParamsUtils.DEFAULT_PARAM_FORMATTER; protected @NotNull Function<@NotNull String, @NotNull String> paramFormatter = ParamsUtils.DEFAULT_PARAM_FORMATTER;
@@ -63,6 +65,24 @@ public class ItemConfigBuilder extends AbstractCraftBuilder<ItemConfig, ItemConf
return this; 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) { public ItemConfigBuilder formatParam(@NotNull Function<@NotNull String, @NotNull String> paramFormatter) {
this.paramFormatter = paramFormatter; this.paramFormatter = paramFormatter;
return getThis(); return getThis();
@@ -85,7 +105,7 @@ public class ItemConfigBuilder extends AbstractCraftBuilder<ItemConfig, ItemConf
protected @Nullable ItemConfig buildDefault() { protected @Nullable ItemConfig buildDefault() {
if (this.type == null) return null; if (this.type == null) return null;
else return new ItemConfig(type, data, name, lore); else return new ItemConfig(type, data, name, lore, enchants, flags);
} }
@Override @Override
@@ -28,7 +28,7 @@ public class TitleConfigBuilder extends AbstractCraftBuilder<TitleConfig, TitleC
} }
}; };
protected @NotNull String[] params; 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 fadeIn = 10;
protected @Range(from = 0L, to = Integer.MAX_VALUE) int stay = 60; protected @Range(from = 0L, to = Integer.MAX_VALUE) int stay = 60;
@@ -1,15 +1,20 @@
package cc.carm.lib.mineconfiguration.bukkit.data; package cc.carm.lib.mineconfiguration.bukkit.data;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper; 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 cc.carm.lib.mineconfiguration.bukkit.utils.TextParser;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
public class ItemConfig { public class ItemConfig {
@@ -18,12 +23,32 @@ public class ItemConfig {
protected @Nullable String name; protected @Nullable String name;
protected @NotNull List<String> lore; 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, public ItemConfig(@NotNull Material type, short damage,
@Nullable String name, @NotNull List<String> lore) { @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.type = type;
this.data = damage; this.data = damage;
this.name = name; this.name = name;
this.lore = lore; this.lore = lore;
this.enchants = enchants;
this.flags = flags;
} }
public @NotNull Material getType() { public @NotNull Material getType() {
@@ -75,6 +100,8 @@ public class ItemConfig {
if (meta == null) return item; if (meta == null) return item;
Optional.ofNullable(getName(player, placeholders)).ifPresent(meta::setDisplayName); Optional.ofNullable(getName(player, placeholders)).ifPresent(meta::setDisplayName);
Optional.ofNullable(getLore(player, placeholders)).ifPresent(meta::setLore); Optional.ofNullable(getLore(player, placeholders)).ifPresent(meta::setLore);
enchants.forEach((enchant, level) -> meta.addEnchant(enchant, level, true));
flags.forEach(meta::addItemFlags);
item.setItemMeta(meta); item.setItemMeta(meta);
return item; return item;
} }
@@ -86,20 +113,66 @@ public class ItemConfig {
if (name != null) map.put("name", name); if (name != null) map.put("name", name);
if (!lore.isEmpty()) map.put("lore", lore); 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; return map;
} }
public static @NotNull ItemConfig deserialize(@NotNull ConfigurationWrapper section) throws Exception { 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"); String typeName = section.getString("type");
if (typeName == null) throw new NullPointerException("Item type name is null"); if (typeName == null) throw new NullPointerException("Item type name is null");
Material type = Material.matchMaterial(typeName); Material type = Material.matchMaterial(typeName);
if (type == null) throw new Exception("Invalid material name: " + typeName); if (type == null) throw new Exception("Invalid material name: " + typeName);
else return new ItemConfig(
type, section.getShort("data", (short) 0), short data = section.getShort("data", (short) 0);
section.getString("name"), String name = section.getString("name");
section.getStringList("lore") 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;
} }
} }
@@ -85,7 +85,7 @@ public class SoundConfig {
@Contract("null -> null") @Contract("null -> null")
public static @Nullable SoundConfig deserialize(@Nullable String string) throws Exception { public static @Nullable SoundConfig deserialize(@Nullable String string) throws Exception {
if (string == null) return null; if (string == null || string.isEmpty()) return null;
String[] args = string.contains(":") ? string.split(":") : new String[]{string}; String[] args = string.contains(":") ? string.split(":") : new String[]{string};
if (args.length < 1) return null; if (args.length < 1) return null;
@@ -61,7 +61,7 @@ public class TitleConfig {
return map; return map;
} }
public static @NotNull TitleConfig deserialize(@NotNull ConfigurationWrapper section) { public static @NotNull TitleConfig deserialize(@NotNull ConfigurationWrapper<?> section) {
return of(section.getString("line1"), section.getString("line2")); return of(section.getString("line1"), section.getString("line2"));
} }
@@ -1,10 +1,10 @@
package cc.carm.lib.mineconfiguration.bukkit.source; package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.ConfigInitializer; import cc.carm.lib.configuration.core.ConfigInitializer;
import cc.carm.lib.configuration.core.source.ConfigurationComments;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
@@ -12,13 +12,12 @@ import java.io.StringWriter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List;
public class BukkitConfigProvider extends CraftConfigProvider { public class BukkitConfigProvider extends CraftConfigProvider {
protected static final char SEPARATOR = '.'; protected static final char SEPARATOR = '.';
protected BukkitYAMLComments bukkitComments = new BukkitYAMLComments(); protected @NotNull BukkitYAMLComments comments = new BukkitYAMLComments();
public BukkitConfigProvider(@NotNull File file) { public BukkitConfigProvider(@NotNull File file) {
super(file); super(file);
@@ -39,7 +38,7 @@ public class BukkitConfigProvider extends CraftConfigProvider {
configuration.save(getFile()); configuration.save(getFile());
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
this.bukkitComments.writeComments(configuration, new BufferedWriter(writer)); this.comments.writeComments(configuration, new BufferedWriter(writer));
String value = writer.toString(); // config contents String value = writer.toString(); // config contents
Path toUpdatePath = getFile().toPath(); Path toUpdatePath = getFile().toPath();
@@ -49,24 +48,8 @@ public class BukkitConfigProvider extends CraftConfigProvider {
} }
@Override @Override
public void setHeaderComment(@Nullable String path, @Nullable List<String> comments) { public @Nullable ConfigurationComments getComments() {
this.bukkitComments.setHeaderComments(path, comments); return this.comments;
} }
@Override
public void setInlineComment(@NotNull String path, @Nullable String comment) {
this.bukkitComments.setInlineComment(path, comment);
}
@Override
@Nullable
@Unmodifiable
public List<String> getHeaderComment(@Nullable String path) {
return this.bukkitComments.getHeaderComment(path);
}
@Override
public @Nullable String getInlineComment(@NotNull String path) {
return this.bukkitComments.getInlineComment(path);
}
} }
@@ -1,58 +1,20 @@
package cc.carm.lib.mineconfiguration.bukkit.source; package cc.carm.lib.mineconfiguration.bukkit.source;
import cc.carm.lib.configuration.core.source.ConfigurationComments;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
public class BukkitYAMLComments { public class BukkitYAMLComments extends ConfigurationComments {
protected final @NotNull Map<String, List<String>> headerComments = new HashMap<>();
protected final @NotNull Map<String, String> inlineComments = new HashMap<>();
protected @NotNull Map<String, List<String>> getHeaderComments() {
return headerComments;
}
protected @NotNull Map<String, String> getInlineComments() {
return inlineComments;
}
public void setHeaderComments(@Nullable String path, @Nullable List<String> comments) {
if (comments == null) {
getHeaderComments().remove(path);
} else {
getHeaderComments().put(path, comments);
}
}
public void setInlineComment(@NotNull String path, @Nullable String comment) {
if (comment == null) {
getInlineComments().remove(path);
} else {
getInlineComments().put(path, comment);
}
}
@Nullable
@Unmodifiable
public List<String> getHeaderComment(@Nullable String path) {
return Optional.ofNullable(getHeaderComments().get(path)).map(Collections::unmodifiableList).orElse(null);
}
public @Nullable String getInlineComment(@NotNull String path) {
return getInlineComments().get(path);
}
public @Nullable String buildHeaderComments(@Nullable String path, @NotNull String indents) { public @Nullable String buildHeaderComments(@Nullable String path, @NotNull String indents) {
List<String> comments = getHeaderComment(path); List<String> comments = getHeaderComment(path);
@@ -10,61 +10,62 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
public class CraftSectionWrapper implements ConfigurationWrapper { public class CraftSectionWrapper implements ConfigurationWrapper<ConfigurationSection> {
protected final ConfigurationSection section; protected final ConfigurationSection configuration;
protected CraftSectionWrapper(ConfigurationSection section) { protected CraftSectionWrapper(ConfigurationSection configuration) {
this.section = section; this.configuration = configuration;
} }
public ConfigurationSection getSourceSection() { @Override
return section; public @NotNull ConfigurationSection getSource() {
return this.configuration;
} }
@Override @Override
public @NotNull Set<String> getKeys(boolean deep) { public @NotNull Set<String> getKeys(boolean deep) {
return this.section.getKeys(deep); return this.configuration.getKeys(deep);
} }
@Override @Override
public @NotNull Map<String, Object> getValues(boolean deep) { public @NotNull Map<String, Object> getValues(boolean deep) {
return this.section.getValues(deep); return this.configuration.getValues(deep);
} }
@Override @Override
public void set(@NotNull String path, @Nullable Object value) { public void set(@NotNull String path, @Nullable Object value) {
this.section.set(path, value); this.configuration.set(path, value);
} }
@Override @Override
public boolean contains(@NotNull String path) { public boolean contains(@NotNull String path) {
return this.section.contains(path); return this.configuration.contains(path);
} }
@Override @Override
public @Nullable Object get(@NotNull String path) { public @Nullable Object get(@NotNull String path) {
return this.section.get(path); return this.configuration.get(path);
} }
@Override @Override
public boolean isList(@NotNull String path) { public boolean isList(@NotNull String path) {
return this.section.isList(path); return this.configuration.isList(path);
} }
@Override @Override
public @Nullable List<?> getList(@NotNull String path) { public @Nullable List<?> getList(@NotNull String path) {
return this.section.getList(path); return this.configuration.getList(path);
} }
@Override @Override
public boolean isConfigurationSection(@NotNull String path) { public boolean isConfigurationSection(@NotNull String path) {
return this.section.isConfigurationSection(path); return this.configuration.isConfigurationSection(path);
} }
@Override @Override
public @Nullable ConfigurationWrapper getConfigurationSection(@NotNull String path) { public @Nullable CraftSectionWrapper getConfigurationSection(@NotNull String path) {
return Optional.ofNullable(section.getConfigurationSection(path)) return Optional.ofNullable(configuration.getConfigurationSection(path))
.map(CraftSectionWrapper::of).orElse(null); .map(CraftSectionWrapper::of).orElse(null);
} }
@@ -7,11 +7,12 @@ import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers; import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.WrappedChatComponent; import com.comphenix.protocol.wrappers.WrappedChatComponent;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class ProtocolLibHelper { public class ProtocolLibHelper {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void sendTitle(Player player, long fadeIn, long stay, long fadeOut, String line1, String line2) throws Exception { public static void sendTitle(@NotNull Player player, long fadeIn, long stay, long fadeOut, String line1, String line2) throws Exception {
ProtocolManager pm = ProtocolLibrary.getProtocolManager(); ProtocolManager pm = ProtocolLibrary.getProtocolManager();
if (line1 != null) { if (line1 != null) {
@@ -35,7 +36,6 @@ public class ProtocolLibHelper {
.write(1, Math.toIntExact(stay)) .write(1, Math.toIntExact(stay))
.write(2, Math.toIntExact(fadeOut)); .write(2, Math.toIntExact(fadeOut));
pm.sendServerPacket(player, timePacket, false); pm.sendServerPacket(player, timePacket, false);
} }
} }
@@ -1,13 +1,13 @@
package cc.carm.lib.mineconfiguration.bukkit.value; package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.data.ItemConfig;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import cc.carm.lib.configuration.core.function.ConfigValueParser; 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.source.ConfigurationWrapper;
import cc.carm.lib.configuration.core.value.type.ConfiguredSection; 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.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.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -33,14 +33,17 @@ public class ConfiguredItem extends ConfiguredSection<ItemConfig> {
protected final @NotNull String[] params; protected final @NotNull String[] params;
public ConfiguredItem(@Nullable ConfigurationProvider<?> provider, @Nullable String sectionPath, public ConfiguredItem(@Nullable CraftConfigProvider provider, @Nullable String sectionPath,
@Nullable List<String> headerComments, @Nullable String inlineComments, @Nullable List<String> headerComments, @Nullable String inlineComments,
@Nullable ItemConfig defaultValue, @NotNull String[] params) { @Nullable ItemConfig defaultValue, @NotNull String[] params) {
super(provider, sectionPath, headerComments, inlineComments, ItemConfig.class, defaultValue, getItemParser(), ItemConfig::serialize); super(
provider, sectionPath, headerComments, inlineComments, ItemConfig.class, defaultValue,
getItemParser(), ItemConfig::serialize
);
this.params = params; this.params = params;
} }
public static ConfigValueParser<ConfigurationWrapper, ItemConfig> getItemParser() { public static ConfigValueParser<ConfigurationWrapper<?>, ItemConfig> getItemParser() {
return (s, d) -> ItemConfig.deserialize(s); return (s, d) -> ItemConfig.deserialize(s);
} }
@@ -1,17 +1,18 @@
package cc.carm.lib.mineconfiguration.bukkit.value; 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.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageValueBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig; import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.common.value.ConfigMessage; import cc.carm.lib.mineconfiguration.common.value.ConfigMessage;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageValueBuilder;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
@@ -43,10 +44,11 @@ public class ConfiguredMessage<M> extends ConfigMessage<M, TextConfig, CommandSe
} }
@Override @Override
public void broadcast(@NotNull Map<String, Object> placeholders) { public @NotNull Collection<CommandSender> getAllReceivers() {
Bukkit.getOnlinePlayers().forEach(pl -> send(pl, placeholders)); List<CommandSender> senders = new ArrayList<>();
send(Bukkit.getConsoleSender(), placeholders); senders.add(Bukkit.getConsoleSender());
senders.addAll(Bukkit.getOnlinePlayers());
return senders;
} }
} }
@@ -1,17 +1,18 @@
package cc.carm.lib.mineconfiguration.bukkit.value; 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.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageListBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig; import cc.carm.lib.mineconfiguration.bukkit.data.TextConfig;
import cc.carm.lib.mineconfiguration.common.value.ConfigMessageList; import cc.carm.lib.mineconfiguration.common.value.ConfigMessageList;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.mineconfiguration.bukkit.builder.message.CraftMessageListBuilder;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
@@ -38,9 +39,11 @@ public class ConfiguredMessageList<M> extends ConfigMessageList<M, TextConfig, C
super(provider, sectionPath, headerComments, inlineComments, TextConfig.class, messages, params, messageParser, sendFunction, TextConfig::of); super(provider, sectionPath, headerComments, inlineComments, TextConfig.class, messages, params, messageParser, sendFunction, TextConfig::of);
} }
public void broadcast(@NotNull Map<String, Object> placeholders) { @Override
Bukkit.getOnlinePlayers().forEach(pl -> send(pl, placeholders)); public @NotNull Collection<CommandSender> getAllReceivers() {
send(Bukkit.getConsoleSender(), placeholders); List<CommandSender> senders = new ArrayList<>();
senders.add(Bukkit.getConsoleSender());
senders.addAll(Bukkit.getOnlinePlayers());
return senders;
} }
} }
@@ -1,14 +1,14 @@
package cc.carm.lib.mineconfiguration.bukkit.value; package cc.carm.lib.mineconfiguration.bukkit.value;
import cc.carm.lib.mineconfiguration.bukkit.CraftConfigValue;
import cc.carm.lib.mineconfiguration.bukkit.data.TitleConfig;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import cc.carm.lib.configuration.core.function.ConfigValueParser; import cc.carm.lib.configuration.core.function.ConfigValueParser;
import cc.carm.lib.configuration.core.source.ConfigurationProvider; import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper; import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import cc.carm.lib.configuration.core.value.type.ConfiguredSection; 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.builder.title.TitleConfigBuilder;
import cc.carm.lib.mineconfiguration.bukkit.data.TitleConfig;
import cc.carm.lib.mineconfiguration.bukkit.function.TitleSendConsumer; import cc.carm.lib.mineconfiguration.bukkit.function.TitleSendConsumer;
import cc.carm.lib.mineconfiguration.common.utils.ParamsUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -87,15 +87,15 @@ public class ConfiguredTitle extends ConfiguredSection<TitleConfig> {
} }
} }
public void sendAll(Object... values) { public void sendToAll(Object... values) {
sendAll(this.params, values); sendToAll(this.params, values);
} }
public void sendAll(@NotNull String[] params, @NotNull Object[] values) { public void sendToAll(@NotNull String[] params, @NotNull Object[] values) {
sendAll(ParamsUtils.buildParams(params, values)); sendToAll(ParamsUtils.buildParams(params, values));
} }
public void sendAll(@NotNull Map<String, Object> placeholders) { public void sendToAll(@NotNull Map<String, Object> placeholders) {
TitleConfig config = get(); TitleConfig config = get();
if (config == null) return; if (config == null) return;
@@ -103,7 +103,7 @@ public class ConfiguredTitle extends ConfiguredSection<TitleConfig> {
} }
public static ConfigValueParser<ConfigurationWrapper, TitleConfig> getTitleParser() { public static ConfigValueParser<ConfigurationWrapper<?>, TitleConfig> getTitleParser() {
return (s, d) -> TitleConfig.deserialize(s); return (s, d) -> TitleConfig.deserialize(s);
} }
} }
+9 -25
View File
@@ -5,25 +5,28 @@
<parent> <parent>
<artifactId>mineconfiguration-parent</artifactId> <artifactId>mineconfiguration-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>1.4.2</version> <version>2.3.1</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
<artifactId>mineconfiguration-bungee</artifactId> <artifactId>mineconfiguration-bungee</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>MineConfiguration-Bungee</name> <name>MineConfiguration-Bungee</name>
<description>轻松(做)配置,适用于BungeeCord的版本,可用JSON与YAML格式。</description>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>${project.parent.groupId}</groupId> <groupId>${project.parent.groupId}</groupId>
<artifactId>easyconfiguration-core</artifactId> <artifactId>mineconfiguration-common</artifactId>
<version>${easyconfiguration.version}</version> <version>${project.parent.version}</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -43,29 +46,10 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>mineconfiguration-common</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
@@ -1,4 +1,4 @@
package cc.carm.lib.mineconfiguration; package cc.carm.lib.mineconfiguration.bungee;
import cc.carm.lib.mineconfiguration.bungee.source.BungeeConfigProvider; import cc.carm.lib.mineconfiguration.bungee.source.BungeeConfigProvider;
import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.Plugin;
@@ -9,6 +9,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.function.BiFunction; import java.util.function.BiFunction;
@SuppressWarnings("deprecation")
public class BungeeMessageBuilder extends MessageConfigBuilder<CommandSender, MessageText> { public class BungeeMessageBuilder extends MessageConfigBuilder<CommandSender, MessageText> {
@@ -1,28 +1,41 @@
package cc.carm.lib.mineconfiguration.bungee.source; package cc.carm.lib.mineconfiguration.bungee.source;
import cc.carm.lib.configuration.core.ConfigInitializer; import cc.carm.lib.configuration.core.ConfigInitializer;
import cc.carm.lib.configuration.core.source.ConfigurationComments;
import cc.carm.lib.configuration.core.source.impl.FileConfigProvider; import cc.carm.lib.configuration.core.source.impl.FileConfigProvider;
import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class BungeeConfigProvider extends FileConfigProvider<BungeeSectionWrapper> { public class BungeeConfigProvider extends FileConfigProvider<BungeeSectionWrapper> {
protected static final char SEPARATOR = '.';
protected ConfigurationProvider loader; protected ConfigurationProvider loader;
protected Configuration configuration; protected Configuration configuration;
protected ConfigInitializer<BungeeConfigProvider> initializer; protected ConfigInitializer<BungeeConfigProvider> initializer;
public BungeeConfigProvider(@NotNull File file, ConfigurationProvider loader) { protected BungeeYAMLComments comments = new BungeeYAMLComments();
public BungeeConfigProvider(@NotNull File file, @NotNull ConfigurationProvider loader) {
super(file); super(file);
this.loader = loader; this.loader = loader;
} }
public BungeeConfigProvider(@NotNull File file, @NotNull Class<? extends ConfigurationProvider> providerClass) {
this(file, ConfigurationProvider.getProvider(providerClass));
}
public void initializeConfig() throws IOException { public void initializeConfig() throws IOException {
this.configuration = getLoader().load(file); this.configuration = getLoader().load(file);
this.initializer = new ConfigInitializer<>(this); this.initializer = new ConfigInitializer<>(this);
@@ -38,29 +51,24 @@ public class BungeeConfigProvider extends FileConfigProvider<BungeeSectionWrappe
this.configuration = getLoader().load(file); this.configuration = getLoader().load(file);
} }
@Override
public @Nullable ConfigurationComments getComments() {
return this.comments;
}
@Override @Override
public void save() throws Exception { public void save() throws Exception {
getLoader().save(configuration, file); getLoader().save(configuration, file);
} if (getLoader() instanceof YamlConfiguration) {
StringWriter writer = new StringWriter();
this.comments.writeComments(configuration, new BufferedWriter(writer));
String value = writer.toString(); // config contents
@Override Path toUpdatePath = getFile().toPath();
public void setHeaderComment(@Nullable String path, @Nullable List<String> comments) { if (!value.equals(new String(Files.readAllBytes(toUpdatePath), StandardCharsets.UTF_8))) {
Files.write(toUpdatePath, value.getBytes(StandardCharsets.UTF_8));
} }
}
@Override
public void setInlineComment(@NotNull String path, @Nullable String comment) {
}
@Override
public @Nullable @Unmodifiable List<String> getHeaderComment(@Nullable String path) {
return null;
}
@Override
public @Nullable String getInlineComment(@NotNull String path) {
return null;
} }
@Override @Override
@@ -9,12 +9,14 @@ import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class BungeeSectionWrapper implements ConfigurationWrapper { import static cc.carm.lib.mineconfiguration.bungee.source.BungeeConfigProvider.SEPARATOR;
private final Configuration section; public class BungeeSectionWrapper implements ConfigurationWrapper<Configuration> {
private final Configuration configuration;
private BungeeSectionWrapper(@NotNull Configuration section) { private BungeeSectionWrapper(@NotNull Configuration section) {
this.section = section; this.configuration = section;
} }
@Contract("!null->!null") @Contract("!null->!null")
@@ -22,30 +24,52 @@ public class BungeeSectionWrapper implements ConfigurationWrapper {
return section == null ? null : new BungeeSectionWrapper(section); return section == null ? null : new BungeeSectionWrapper(section);
} }
protected static Set<String> getAllKeys(@NotNull Configuration config) {
Set<String> keys = new LinkedHashSet<>();
for (String key : config.getKeys()) {
keys.add(key);
Object value = config.get(key);
if (value instanceof Configuration) {
getAllKeys((Configuration) value).stream()
.map(subKey -> key + SEPARATOR + subKey).forEach(keys::add);
}
}
return keys;
}
@Override
public @NotNull Configuration getSource() {
return this.configuration;
}
@Override @Override
public @NotNull Set<String> getKeys(boolean deep) { public @NotNull Set<String> getKeys(boolean deep) {
return new LinkedHashSet<>(section.getKeys()); if (deep) {
return new LinkedHashSet<>(getAllKeys(configuration));
} else {
return new LinkedHashSet<>(configuration.getKeys());
}
} }
@Override @Override
public @NotNull Map<String, Object> getValues(boolean deep) { public @NotNull Map<String, Object> getValues(boolean deep) {
return section.getKeys().stream() return getKeys(deep).stream()
.collect(Collectors.toMap(key -> key, section::get, (a, b) -> b, LinkedHashMap::new)); .collect(Collectors.toMap(key -> key, configuration::get, (a, b) -> b, LinkedHashMap::new));
} }
@Override @Override
public void set(@NotNull String path, @Nullable Object value) { public void set(@NotNull String path, @Nullable Object value) {
this.section.set(path, value); this.configuration.set(path, value);
} }
@Override @Override
public boolean contains(@NotNull String path) { public boolean contains(@NotNull String path) {
return this.section.contains(path); return this.configuration.contains(path);
} }
@Override @Override
public @Nullable Object get(@NotNull String path) { public @Nullable Object get(@NotNull String path) {
return this.section.get(path); return this.configuration.get(path);
} }
@Override @Override
@@ -55,7 +79,7 @@ public class BungeeSectionWrapper implements ConfigurationWrapper {
@Override @Override
public @Nullable List<?> getList(@NotNull String path) { public @Nullable List<?> getList(@NotNull String path) {
return this.section.getList(path); return this.configuration.getList(path);
} }
@Override @Override
@@ -64,7 +88,7 @@ public class BungeeSectionWrapper implements ConfigurationWrapper {
} }
@Override @Override
public @Nullable ConfigurationWrapper getConfigurationSection(@NotNull String path) { public @Nullable BungeeSectionWrapper getConfigurationSection(@NotNull String path) {
return of(this.section.getSection(path)); return of(this.configuration.getSection(path));
} }
} }
@@ -0,0 +1,115 @@
package cc.carm.lib.mineconfiguration.bungee.source;
import cc.carm.lib.configuration.core.source.ConfigurationComments;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static cc.carm.lib.mineconfiguration.bungee.source.BungeeConfigProvider.SEPARATOR;
public class BungeeYAMLComments 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 Configuration source, @NotNull BufferedWriter writer) throws IOException {
ConfigurationProvider provider = ConfigurationProvider.getProvider(YamlConfiguration.class);
Configuration tmp = new Configuration();// 该对象用于临时记录配置内容
String configHeader = buildHeaderComments(null, "");
if (configHeader != null) writer.write(configHeader);
for (String fullKey : BungeeSectionWrapper.getAllKeys(source)) {
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("[" + SEPARATOR + "]");
String trailingKey = splitFullKey[splitFullKey.length - 1];
if (currentValue instanceof Configuration) {
Configuration section = (Configuration) currentValue;
writer.write(indents + trailingKey + ":");
if (inlineComment != null && inlineComment.length() > 0) {
writer.write(" # " + inlineComment);
}
if (!section.getKeys().isEmpty()) {
writer.write("\n");
} else {
writer.write(" {}\n");
if (indents.length() == 0) writer.write("\n");
}
continue;
}
tmp.set(trailingKey, currentValue);
StringWriter tmpStr = new StringWriter();
provider.save(tmp, tmpStr);
String yaml = tmpStr.toString();
tmpStr.close();
tmp.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(@NotNull String key) {
String[] splitKey = key.split("[" + SEPARATOR + "]");
return IntStream.range(1, splitKey.length).mapToObj(i -> " ").collect(Collectors.joining());
}
}
@@ -1,17 +1,18 @@
package cc.carm.lib.mineconfiguration.bungee.value; package cc.carm.lib.mineconfiguration.bungee.value;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.mineconfiguration.bungee.BungeeConfigValue; import cc.carm.lib.mineconfiguration.bungee.BungeeConfigValue;
import cc.carm.lib.mineconfiguration.bungee.builder.message.BungeeMessageValueBuilder; import cc.carm.lib.mineconfiguration.bungee.builder.message.BungeeMessageValueBuilder;
import cc.carm.lib.mineconfiguration.bungee.data.MessageText; import cc.carm.lib.mineconfiguration.bungee.data.MessageText;
import cc.carm.lib.mineconfiguration.common.value.ConfigMessage; import cc.carm.lib.mineconfiguration.common.value.ConfigMessage;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
@@ -43,9 +44,11 @@ public class ConfiguredMessage<M> extends ConfigMessage<M, MessageText, CommandS
} }
@Override @Override
public void broadcast(@NotNull Map<String, Object> placeholders) { public @NotNull Collection<CommandSender> getAllReceivers() {
ProxyServer.getInstance().getPlayers().forEach(pl -> send(pl, placeholders)); List<CommandSender> senders = new ArrayList<>();
send(ProxyServer.getInstance().getConsole(), placeholders); senders.add(ProxyServer.getInstance().getConsole());
senders.addAll(ProxyServer.getInstance().getPlayers());
return senders;
} }
@@ -10,6 +10,8 @@ import net.md_5.bungee.api.ProxyServer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@@ -38,9 +40,11 @@ public class ConfiguredMessageList<M> extends ConfigMessageList<M, MessageText,
super(provider, sectionPath, headerComments, inlineComments, MessageText.class, messages, params, messageParser, sendFunction, MessageText::of); super(provider, sectionPath, headerComments, inlineComments, MessageText.class, messages, params, messageParser, sendFunction, MessageText::of);
} }
public void broadcast(@NotNull Map<String, Object> placeholders) { @Override
ProxyServer.getInstance().getPlayers().forEach(pl -> send(pl, placeholders)); public @NotNull Collection<CommandSender> getAllReceivers() {
send(ProxyServer.getInstance().getConsole(), placeholders); List<CommandSender> senders = new ArrayList<>();
senders.add(ProxyServer.getInstance().getConsole());
senders.addAll(ProxyServer.getInstance().getPlayers());
return senders;
} }
} }
@@ -0,0 +1,62 @@
import cc.carm.lib.configuration.core.ConfigurationRoot;
import cc.carm.lib.configuration.core.annotation.HeaderComment;
import cc.carm.lib.configuration.core.annotation.InlineComment;
import cc.carm.lib.configuration.core.source.ConfigurationProvider;
import cc.carm.lib.configuration.core.value.ConfigValue;
import cc.carm.lib.configuration.core.value.type.ConfiguredList;
import cc.carm.lib.configuration.core.value.type.ConfiguredValue;
import cc.carm.lib.mineconfiguration.bungee.MineConfiguration;
import org.junit.Test;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
public class ConfigTest {
@Test
public void test() {
File file = new File("target/config.yml");
ConfigurationProvider<?> config = MineConfiguration.from(file);
config.initialize(Configuration.class);
try {
System.out.println("--------------------------------------------");
System.out.println(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
System.out.println("--------------------------------------------");
} catch (Exception exception) {
exception.printStackTrace();
}
}
@HeaderComment({
"MineConfiguration for BungeeCord",
"测试实例配置文件", ""
})
public static class Configuration extends ConfigurationRoot {
@InlineComment("是否显示DEBUG消息")
public static final ConfigValue<Boolean> DEBUG = ConfiguredValue.of(Boolean.class, false);
@HeaderComment("启动时执行的命令")
public static final class START_UP {
@HeaderComment("延迟执行的时间(单位:秒)")
public static final ConfigValue<Integer> DELAY = ConfiguredValue.of(Integer.class, 30);
@HeaderComment("循环执行的间隔(单位:秒)")
public static final ConfigValue<Integer> PERIOD = ConfiguredValue.of(Integer.class, 10);
@HeaderComment("执行的指令列表")
@InlineComment("建议以\"\"包裹")
public static final ConfigValue<List<String>> COMMANDS = ConfiguredList.builder(String.class)
.fromString().defaults("alert Commands here!").build();
}
}
}
+51 -49
View File
@@ -4,21 +4,20 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<java.version>1.8</java.version> <project.jdk.version>8</project.jdk.version>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<deps.easyconfifuration.version>3.3.3</deps.easyconfifuration.version>
<easyconfiguration.version>3.1.0</easyconfiguration.version>
</properties> </properties>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>mineconfiguration-parent</artifactId> <artifactId>mineconfiguration-parent</artifactId>
<version>1.4.2</version> <version>2.3.1</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<modules> <modules>
<module>common</module> <module>common</module>
<module>platform/bungee</module> <module>platform/bungee</module>
<module>platform/bukkit</module> <module>platform/bukkit</module>
</modules> </modules>
@@ -38,7 +37,7 @@
</developers> </developers>
<scm> <scm>
<connection>scm:git:git@github.com:CarmJos/Easy.MineConfiguration</connection> <connection>scm:git:git@github.com:CarmJos/MineConfiguration</connection>
<developerConnection>scm:git:git@github.com:CarmJos/MineConfiguration.git</developerConnection> <developerConnection>scm:git:git@github.com:CarmJos/MineConfiguration.git</developerConnection>
<url>https://github.com/CarmJos/MineConfiguration</url> <url>https://github.com/CarmJos/MineConfiguration</url>
<tag>HEAD</tag> <tag>HEAD</tag>
@@ -64,9 +63,13 @@
<repositories> <repositories>
<repository> <repository>
<id>carm-repo</id> <id>central</id>
<name>Carm's Repo</name> <url>https://repo1.maven.org/maven2/</url>
<url>https://repo.carm.cc/repository/maven-public/</url> </repository>
<repository>
<id>sonatype</id>
<url>https://s01.oss.sonatype.org/content/groups/public/</url>
</repository> </repository>
<repository> <repository>
@@ -75,13 +78,14 @@
</repository> </repository>
<repository> <repository>
<id>nexus</id> <id>lumine</id>
<url>https://mvn.lumine.io/repository/maven-public/</url> <url>https://mvn.lumine.io/repository/maven-public/</url>
</repository> </repository>
<repository> <repository>
<id>central</id> <id>carm-repo</id>
<url>https://repo1.maven.org/maven2/</url> <name>Carm's Repo</name>
<url>https://repo.carm.cc/repository/maven-public/</url>
</repository> </repository>
</repositories> </repositories>
@@ -102,7 +106,7 @@
<dependency> <dependency>
<groupId>org.jetbrains</groupId> <groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId> <artifactId>annotations</artifactId>
<version>23.0.0</version> <version>24.0.0</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
@@ -151,6 +155,36 @@
<goals>deploy</goals> <goals>deploy</goals>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>${project.jdk.version}</source>
<target>${project.jdk.version}</target>
<encoding>UTF-8</encoding>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins> </plugins>
<pluginManagement> <pluginManagement>
@@ -159,7 +193,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.0</version> <version>3.4.1</version>
<configuration> <configuration>
<classifier>javadoc</classifier> <classifier>javadoc</classifier>
<detectJavaApiLink>false</detectJavaApiLink> <detectJavaApiLink>false</detectJavaApiLink>
@@ -185,42 +219,10 @@
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version> <version>3.4.1</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>