Compare commits

..

17 commits

Author SHA1 Message Date
58c11652c0 Bump org.apache.maven.plugins:maven-compiler-plugin from 3.11.0 to 3.12.1 (#103)
Some checks failed
Java 11 CI / build (push) Has been cancelled
Java 17 CI / build (push) Has been cancelled
Bumps [org.apache.maven.plugins:maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.11.0 to 3.12.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/apache/maven-compiler-plugin/releases">org.apache.maven.plugins:maven-compiler-plugin's releases</a>.</em></p>
<blockquote>
<h2>3.12.1</h2>
<!-- raw HTML omitted -->
<h2>🐛 Bug Fixes</h2>
<ul>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-567">[MCOMPILER-567]</a> - Fail to compile if the generated-sources/annotation… (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/218">#218</a>) <a href="https://github.com/jorsol"><code>@​jorsol</code></a></li>
</ul>
<h2>📦 Dependency updates</h2>
<ul>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-568">[MCOMPILER-568]</a> - Bump plexusCompilerVersion from 2.14.1 to 2.14.2 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/220">#220</a>) <a href="https://github.com/dependabot"><code>@​dependabot</code></a></li>
</ul>
<h2>3.12.0</h2>
<!-- raw HTML omitted -->
<h2>🚀 New features and improvements</h2>
<ul>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-562">[MCOMPILER-562]</a> - Add property maven.compiler.outputDirectory to CompilerMojo (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/213">#213</a>) <a href="https://github.com/jGauravGupta"><code>@​jGauravGupta</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-381">[MCOMPILER-381]</a> - Refactor incremental detection (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/181">#181</a>) <a href="https://github.com/jorsol"><code>@​jorsol</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-542">[MCOMPILER-542]</a> - Clean JDK patch version in module-info.class  (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/208">#208</a>) <a href="https://github.com/jorsol"><code>@​jorsol</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-558">[MCOMPILER-558]</a> - compileSourceRoots in testCompile should be writable (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/209">#209</a>) <a href="https://github.com/lorenzsimon"><code>@​lorenzsimon</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-559">[MCOMPILER-559]</a> - Warn if overwriting the project's artifact's file to a different value (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/211">#211</a>) <a href="https://github.com/gnodet"><code>@​gnodet</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-550">[MCOMPILER-550]</a> - make outputDirectory writable (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/202">#202</a>) <a href="https://github.com/bmarwell"><code>@​bmarwell</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-549">[MCOMPILER-549]</a> - Improve log message in case of recompilation - fix jenkins build (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/203">#203</a>) <a href="https://github.com/slawekjaranowski"><code>@​slawekjaranowski</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-549">[MCOMPILER-549]</a> - Improve log message in case of recompilation (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/201">#201</a>) <a href="https://github.com/BrowneMonke"><code>@​BrowneMonke</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-391">[MCOMPILER-391]</a> - Use dep mgmt when resolving annotation processors and their deps (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/180">#180</a>) <a href="https://github.com/psiroky"><code>@​psiroky</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-531">[MCOMPILER-531]</a> - Prepare for Java 20(-ea) (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/184">#184</a>) <a href="https://github.com/slachiewicz"><code>@​slachiewicz</code></a></li>
</ul>
<h2>🐛 Bug Fixes</h2>
<ul>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-333">[MCOMPILER-333]</a> - Cleanup generated source files (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/214">#214</a>) <a href="https://github.com/jorsol"><code>@​jorsol</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-544">[MCOMPILER-544]</a> - don't add items to classpath that are not used for that (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/198">#198</a>) <a href="https://github.com/laeubi"><code>@​laeubi</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-547">[MCOMPILER-547]</a> - : Initialize pathElements to empty (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/199">#199</a>) <a href="https://github.com/rovarga"><code>@​rovarga</code></a></li>
</ul>
<h2>📦 Dependency updates</h2>
<ul>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-564">[MCOMPILER-564]</a> - Bump plexusCompilerVersion from 2.13.0 to 2.14.1 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/216">#216</a>) <a href="https://github.com/dependabot"><code>@​dependabot</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-557">[MCOMPILER-557]</a> - Upgrade maven-plugin parent to 41 - fix build (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/210">#210</a>) <a href="https://github.com/slawekjaranowski"><code>@​slawekjaranowski</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-554">[MCOMPILER-554]</a> - Update plexus-java to 1.2.0 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/207">#207</a>) <a href="https://github.com/jorsol"><code>@​jorsol</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-551">[MCOMPILER-551]</a> - Upgrade Parent to 40 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/205">#205</a>) <a href="https://github.com/slawekjaranowski"><code>@​slawekjaranowski</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-541">[MCOMPILER-541]</a> - update maven-shared-utils to 3.4.2 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/195">#195</a>) <a href="https://github.com/elharo"><code>@​elharo</code></a></li>
<li>Bump apache/maven-gh-actions-shared from 2 to 3 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/182">#182</a>) <a href="https://github.com/dependabot"><code>@​dependabot</code></a></li>
<li>Bump maven-invoker-plugin from 3.4.0 to 3.5.0 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/179">#179</a>) <a href="https://github.com/dependabot"><code>@​dependabot</code></a></li>
</ul>
<h2>👻 Maintenance</h2>
<ul>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-565">[MCOMPILER-565]</a> - Allow project build by Maven 4 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/217">#217</a>) <a href="https://github.com/slawekjaranowski"><code>@​slawekjaranowski</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MCOMPILER-552">[MCOMPILER-552]</a> - Refresh download page (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/204">#204</a>) <a href="https://github.com/slawekjaranowski"><code>@​slawekjaranowski</code></a></li>
<li>Remove references to old Maven versions. (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/194">#194</a>) <a href="https://github.com/elharo"><code>@​elharo</code></a></li>
<li>(doc) Drop unused and vulnerable dependency to log4j (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/190">#190</a>) <a href="https://github.com/slachiewicz"><code>@​slachiewicz</code></a></li>
<li><a href="https://issues.apache.org/jira/browse/MNG-6829">[MNG-6829]</a> - Replace StringUtils#isEmpty(String) &amp; #isNotEmpty(String) (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/189">#189</a>) <a href="https://github.com/timtebeek"><code>@​timtebeek</code></a></li>
<li>Update plexus-utils to 3.0.24 - in its (<a href="https://redirect.github.com/apache/maven-compiler-plugin/pull/183">#183</a>) <a href="https://github.com/slachiewicz"><code>@​slachiewicz</code></a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="736da68adf"><code>736da68</code></a> [maven-release-plugin] prepare release maven-compiler-plugin-3.12.1</li>
<li><a href="ef93f3dbf4"><code>ef93f3d</code></a> [MCOMPILER-568] Bump plexusCompilerVersion from 2.14.1 to 2.14.2 (<a href="https://redirect.github.com/apache/maven-compiler-plugin/issues/220">#220</a>)</li>
<li><a href="eb7840cf9f"><code>eb7840c</code></a> [MCOMPILER-567] - Fail to compile if the &quot;generated-sources/annotations&quot; does...</li>
<li><a href="2a7a73b34b"><code>2a7a73b</code></a> [maven-release-plugin] prepare for next development iteration</li>
<li><a href="c08b0fda54"><code>c08b0fd</code></a> [maven-release-plugin] prepare release maven-compiler-plugin-3.12.0</li>
<li><a href="a1c5b133a1"><code>a1c5b13</code></a> [MCOMPILER-565] Allow project build by Maven 4</li>
<li><a href="4855773643"><code>4855773</code></a> Bump plexusCompilerVersion from 2.13.0 to 2.14.1</li>
<li><a href="1d053422bd"><code>1d05342</code></a> [MCOMPILER-562] Add property maven.compiler.outputDirectory to CompilerMojo (...</li>
<li><a href="ea74978da1"><code>ea74978</code></a> [MCOMPILER-381] - Refactor incremental detection (<a href="https://redirect.github.com/apache/maven-compiler-plugin/issues/181">#181</a>)</li>
<li><a href="fd37f0934f"><code>fd37f09</code></a> [MCOMPILER-333] Cleanup generated source files (<a href="https://redirect.github.com/apache/maven-compiler-plugin/issues/214">#214</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.11.0...maven-compiler-plugin-3.12.1">compare view</a></li>
</ul>
</details>
<br />

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=org.apache.maven.plugins:maven-compiler-plugin&package-manager=maven&previous-version=3.11.0&new-version=3.12.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

</details>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Reviewed-on: #103
2024-08-23 09:25:36 +00:00
5930c4c8dc Bump org.apache.maven.plugins:maven-shade-plugin from 3.5.1 to 3.5.2 (#105)
Some checks are pending
Java 11 CI / build (push) Waiting to run
Java 17 CI / build (push) Waiting to run
Bumps [org.apache.maven.plugins:maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.5.1 to 3.5.2.
<details>
<summary>Commits</summary>
<ul>
<li><a href="95e22b4868"><code>95e22b4</code></a> [maven-release-plugin] prepare release maven-shade-plugin-3.5.2</li>
<li><a href="d807fea075"><code>d807fea</code></a> Bump org.vafer:jdependency from 2.9.0 to 2.10</li>
<li><a href="6d6084179e"><code>6d60841</code></a> Bump org.apache.commons:commons-compress from 1.23.0 to 1.25.0</li>
<li><a href="68457e50bc"><code>68457e5</code></a> [MSHADE-468] add system requirements history</li>
<li><a href="631371bd10"><code>631371b</code></a> Add mshade-462 IT</li>
<li><a href="cb7b10d4b9"><code>cb7b10d</code></a> [MSHADE-462] 3.5.1 not compatible with 3.4.1: The version cannot be empty.</li>
<li><a href="bd982e7e4b"><code>bd982e7</code></a> [MSHADE-420] fix time when read from extra field</li>
<li><a href="3692f81aaa"><code>3692f81</code></a> [SHADE-420] create IT: 2 runs with different TZ give different jars</li>
<li><a href="a5315de8ce"><code>a5315de</code></a> [MSHADE-464] Maven 3.6.3 as minimum requirements</li>
<li><a href="e7077c628c"><code>e7077c6</code></a> [MSHADE-467] Improved concurrency problem fix</li>
<li>Additional commits viewable in <a href="https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.5.1...maven-shade-plugin-3.5.2">compare view</a></li>
</ul>
</details>
<br />

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=org.apache.maven.plugins:maven-shade-plugin&package-manager=maven&previous-version=3.5.1&new-version=3.5.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

</details>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Reviewed-on: #105
2024-08-23 09:25:30 +00:00
458c4fc6cb Bump com.sk89q.worldedit:worldedit-bukkit from 7.2.17 to 7.3.0 (#107)
Some checks are pending
Java 11 CI / build (push) Waiting to run
Java 17 CI / build (push) Waiting to run
Bumps com.sk89q.worldedit:worldedit-bukkit from 7.2.17 to 7.3.0.

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=com.sk89q.worldedit:worldedit-bukkit&package-manager=maven&previous-version=7.2.17&new-version=7.3.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

</details>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Reviewed-on: #107
2024-08-23 09:25:23 +00:00
Stijn Bannink
15eb04d525
Merge pull request #101 from SBDPlugins/dependabot/maven/org.apache.maven.plugins-maven-javadoc-plugin-3.6.3
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.6.0 to 3.6.3
2023-12-04 20:39:22 +01:00
dependabot[bot]
54c03d5c72
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.6.0 to 3.6.3
Bumps [org.apache.maven.plugins:maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.6.0 to 3.6.3.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.6.0...maven-javadoc-plugin-3.6.3)

---
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>
2023-12-04 19:34:22 +00:00
Stijn Bannink
750b6fff8d
Merge pull request #99 from SBDPlugins/dependabot/maven/com.zaxxer-HikariCP-5.1.0
Bump com.zaxxer:HikariCP from 5.0.1 to 5.1.0
2023-11-06 20:57:22 +01:00
dependabot[bot]
430730b4b2
Bump com.zaxxer:HikariCP from 5.0.1 to 5.1.0
Bumps [com.zaxxer:HikariCP](https://github.com/brettwooldridge/HikariCP) from 5.0.1 to 5.1.0.
- [Changelog](https://github.com/brettwooldridge/HikariCP/blob/dev/CHANGES)
- [Commits](https://github.com/brettwooldridge/HikariCP/compare/HikariCP-5.0.1...HikariCP-5.1.0)

---
updated-dependencies:
- dependency-name: com.zaxxer:HikariCP
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-06 19:55:46 +00:00
Stijn Bannink
a0d5129072
Merge pull request #97 from SBDPlugins/dependabot/maven/com.sk89q.worldedit-worldedit-bukkit-7.2.17
Bump com.sk89q.worldedit:worldedit-bukkit from 7.2.16 to 7.2.17
2023-10-29 10:15:05 +01:00
dependabot[bot]
ae20be40c0
Bump com.sk89q.worldedit:worldedit-bukkit from 7.2.16 to 7.2.17
Bumps com.sk89q.worldedit:worldedit-bukkit from 7.2.16 to 7.2.17.

---
updated-dependencies:
- dependency-name: com.sk89q.worldedit:worldedit-bukkit
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-16 19:18:40 +00:00
Stijn Bannink
cd6bcbc730
Merge pull request #96 from SBDPlugins/dependabot/maven/com.sk89q.worldedit-worldedit-bukkit-7.2.16
Bump com.sk89q.worldedit:worldedit-bukkit from 7.2.9 to 7.2.16
2023-10-04 11:31:32 +02:00
Stijn Bannink
775682115b
Merge pull request #94 from SBDPlugins/dependabot/maven/org.projectlombok-lombok-1.18.30
Bump org.projectlombok:lombok from 1.18.28 to 1.18.30
2023-10-04 11:30:48 +02:00
Stijn Bannink
5107277a7b
Merge pull request #93 from SBDPlugins/dependabot/maven/org.apache.maven.plugins-maven-shade-plugin-3.5.1
Bump org.apache.maven.plugins:maven-shade-plugin from 3.5.0 to 3.5.1
2023-10-04 11:30:06 +02:00
dependabot[bot]
28732b82ee
Bump com.sk89q.worldedit:worldedit-bukkit from 7.2.9 to 7.2.16
Bumps com.sk89q.worldedit:worldedit-bukkit from 7.2.9 to 7.2.16.

---
updated-dependencies:
- dependency-name: com.sk89q.worldedit:worldedit-bukkit
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-02 19:18:46 +00:00
dependabot[bot]
ae8bfa7627
Bump org.projectlombok:lombok from 1.18.28 to 1.18.30
Bumps [org.projectlombok:lombok](https://github.com/projectlombok/lombok) from 1.18.28 to 1.18.30.
- [Changelog](https://github.com/projectlombok/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/projectlombok/lombok/compare/v1.18.28...v1.18.30)

---
updated-dependencies:
- dependency-name: org.projectlombok:lombok
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-25 19:22:24 +00:00
dependabot[bot]
56ffebfcc6
Bump org.apache.maven.plugins:maven-shade-plugin from 3.5.0 to 3.5.1
Bumps [org.apache.maven.plugins:maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.5.0 to 3.5.1.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.5.0...maven-shade-plugin-3.5.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>
2023-09-25 19:22:13 +00:00
Stijn Bannink
bb72b7ac6e
Merge pull request #84 from SBDPlugins/dependabot/maven/org.apache.maven.plugins-maven-javadoc-plugin-3.6.0
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.5.0 to 3.6.0
2023-09-21 16:57:37 +02:00
dependabot[bot]
fa32ba7d3a
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.5.0 to 3.6.0
Bumps [org.apache.maven.plugins:maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.5.0 to 3.6.0.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.5.0...maven-javadoc-plugin-3.6.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-18 19:51:24 +00:00
28 changed files with 2272 additions and 1636 deletions

30
pom.xml
View file

@ -29,7 +29,7 @@
<!-- Shade JAR --> <!-- Shade JAR -->
<plugin> <plugin>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version> <version>3.5.2</version>
<configuration> <configuration>
<relocations> <relocations>
<relocation> <relocation>
@ -81,7 +81,7 @@
<!-- Compile JAR --> <!-- Compile JAR -->
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version> <version>3.12.1</version>
<configuration> <configuration>
<release>11</release> <release>11</release>
</configuration> </configuration>
@ -111,7 +111,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.5.0</version> <version>3.6.3</version>
<configuration> <configuration>
<release>11</release> <release>11</release>
<sourcepath>${maven.lombok.delombok-target}</sourcepath> <sourcepath>${maven.lombok.delombok-target}</sourcepath>
@ -150,10 +150,6 @@
<id>enginehub-maven</id> <id>enginehub-maven</id>
<url>https://maven.enginehub.org/repo/</url> <url>https://maven.enginehub.org/repo/</url>
</repository> </repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
</repositories> </repositories>
<dependencies> <dependencies>
@ -169,7 +165,7 @@
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.28</version> <version>1.18.30</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
@ -201,7 +197,7 @@
<dependency> <dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
<version>5.0.1</version> <version>5.1.0</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@ -209,22 +205,8 @@
<dependency> <dependency>
<groupId>com.sk89q.worldedit</groupId> <groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId> <artifactId>worldedit-bukkit</artifactId>
<version>7.2.9</version> <version>7.3.0</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- STORM, framework for HikariCP data storage -->
<dependency>
<groupId>com.github.jensjeflensje</groupId>
<artifactId>storm</artifactId>
<version>4e84a5205f</version>
</dependency>
<!-- Aikar command framework -->
<dependency>
<groupId>co.aikar</groupId>
<artifactId>acf-paper</artifactId>
<version>0.5.1-SNAPSHOT</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View file

@ -5,24 +5,24 @@ import org.bstats.bukkit.Metrics;
import org.bstats.charts.SingleLineChart; import org.bstats.charts.SingleLineChart;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import tech.sbdevelopment.v10lift.api.V10LiftAPI; import tech.sbdevelopment.v10lift.commands.V10LiftCommand;
import tech.sbdevelopment.v10lift.commands.V10LiftTabCompleter;
import tech.sbdevelopment.v10lift.listeners.BlockBreakListener; import tech.sbdevelopment.v10lift.listeners.BlockBreakListener;
import tech.sbdevelopment.v10lift.listeners.EntityDamageListener; import tech.sbdevelopment.v10lift.listeners.EntityDamageListener;
import tech.sbdevelopment.v10lift.listeners.PlayerInteractListener; import tech.sbdevelopment.v10lift.listeners.PlayerInteractListener;
import tech.sbdevelopment.v10lift.listeners.SignChangeListener; import tech.sbdevelopment.v10lift.listeners.SignChangeListener;
import tech.sbdevelopment.v10lift.managers.*; import tech.sbdevelopment.v10lift.managers.*;
import tech.sbdevelopment.v10lift.sbutils.ConfigUpdater;
import tech.sbdevelopment.v10lift.sbutils.UpdateManager; import tech.sbdevelopment.v10lift.sbutils.UpdateManager;
import tech.sbdevelopment.v10lift.sbutils.YamlFile; import tech.sbdevelopment.v10lift.sbutils.YamlFile;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.logging.Level; import java.util.Collections;
public class V10LiftPlugin extends JavaPlugin { public class V10LiftPlugin extends JavaPlugin {
@Getter @Getter
private static V10LiftPlugin instance; private static V10LiftPlugin instance;
@Getter
private static V10LiftAPI api;
private static YamlFile config; private static YamlFile config;
private static DBManager dbManager; private static DBManager dbManager;
@Getter @Getter
@ -36,20 +36,18 @@ public class V10LiftPlugin extends JavaPlugin {
public void onEnable() { public void onEnable() {
instance = this; instance = this;
getLogger().info("-------------------------------");
getLogger().info("V10Lift v" + getDescription().getVersion());
getLogger().info("Made by SBDeveloper");
getLogger().info(" ");
//Load the API
getLogger().info("Loading API...");
api = new V10LiftAPI();
//Load the config //Load the config
getLogger().info("Loading configs...");
config = new YamlFile("config"); config = new YamlFile("config");
config.loadDefaults(); config.loadDefaults();
//And update config
try {
ConfigUpdater.update(this, "config.yml", config.getJavaFile(), Collections.emptyList());
} catch (IOException e) {
Bukkit.getLogger().warning("[V10Lift] Couldn't update the config.yml. Please check the stacktrace below.");
e.printStackTrace();
}
//Load the messages //Load the messages
messages = new YamlFile("messages"); messages = new YamlFile("messages");
messages.loadDefaults(); messages.loadDefaults();
@ -61,101 +59,88 @@ public class V10LiftPlugin extends JavaPlugin {
ForbiddenBlockManager.init(); ForbiddenBlockManager.init();
//Load the database //Load the database
getLogger().info("Loading lifts from storage..."); dbManager = new DBManager("data");
dbManager = new DBManager(this, "data");
try { try {
dbManager.load(); dbManager.load();
} catch (Exception e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Couldn't load lifts from data storage.", e); Bukkit.getLogger().warning("[V10Lift] Couldn't connect to the SQLite database. Please check the stacktrace below.");
e.printStackTrace();
} }
//Load vault if found //Load vault if found
if (VaultManager.setupPermissions()) { if (VaultManager.setupPermissions()) {
getLogger().info("Loading Vault hook for group whitelist support."); Bukkit.getLogger().info("[V10Lift] Loading Vault hook for group whitelist support.");
vault = true; vault = true;
} }
//Load worldedit if found //Load worldedit if found
if (Bukkit.getPluginManager().getPlugin("WorldEdit") != null) { if (Bukkit.getPluginManager().getPlugin("WorldEdit") != null) {
getLogger().info("Loading WorldEdit hook for selection support."); Bukkit.getLogger().info("[V10Lift] Loading WorldEdit hook for selection support.");
worldEdit = true; worldEdit = true;
} }
//Load the command //Load the command
getLogger().info("Registering commands..."); getCommand("v10lift").setExecutor(new V10LiftCommand());
try { getCommand("v10lift").setTabCompleter(new V10LiftTabCompleter());
ACFHandler.init(this);
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Couldn't load commands.", e);
}
//Register the listeners //Register the listeners
getLogger().info("Registering events...");
Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(), this); Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(), this);
Bukkit.getPluginManager().registerEvents(new BlockBreakListener(), this); Bukkit.getPluginManager().registerEvents(new BlockBreakListener(), this);
Bukkit.getPluginManager().registerEvents(new SignChangeListener(), this); Bukkit.getPluginManager().registerEvents(new SignChangeListener(), this);
Bukkit.getPluginManager().registerEvents(new EntityDamageListener(), this); Bukkit.getPluginManager().registerEvents(new EntityDamageListener(), this);
//Load metrics //Load metrics
getLogger().info("Loading metrics. Can be disabled in the global bStats config."); Bukkit.getLogger().info("[V10Lift] Loading metrics. Can be disabled in the global bStats config.");
Metrics metrics = new Metrics(this, 6564); Metrics metrics = new Metrics(this, 6564);
metrics.addCustomChart(new SingleLineChart("lifts", () -> api.getLifts().size())); metrics.addCustomChart(new SingleLineChart("lifts", () -> DataManager.getLifts().size()));
//Load the update checker //Load the update checker
if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) { if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) {
UpdateManager updateManager = new UpdateManager(this, UpdateManager.CheckType.SPIGOT); UpdateManager updateManager = new UpdateManager(this, 72317);
updateManager.handleResponse((versionResponse, version) -> { updateManager.handleResponse((versionResponse, version) -> {
switch (versionResponse) { switch (versionResponse) {
case FOUND_NEW: case FOUND_NEW:
getLogger().warning("There is a new version available! Current: " + this.getDescription().getVersion() + " New: " + version.get()); Bukkit.getLogger().warning("[V10Lift] There is a new version available! Current: " + this.getDescription().getVersion() + " New: " + version.get());
if (getSConfig().getFile().getBoolean("UpdateChecker.DownloadOnUpdate")) { if (getSConfig().getFile().getBoolean("UpdateChecker.DownloadOnUpdate")) {
getLogger().info("Trying to download the update. This could take some time..."); Bukkit.getLogger().info("[V10Lift] Trying to download the update. This could take some time...");
updateManager.handleDownloadResponse((downloadResponse, fileName) -> { updateManager.handleDownloadResponse((downloadResponse, fileName) -> {
switch (downloadResponse) { switch (downloadResponse) {
case DONE: case DONE:
getLogger().info("Update downloaded! If you restart your server, it will be loaded. Filename: " + fileName); Bukkit.getLogger().info("[V10Lift] Update downloaded! If you restart your server, it will be loaded. Filename: " + fileName);
break; break;
case ERROR: case ERROR:
getLogger().severe("Something went wrong when trying downloading the latest version."); Bukkit.getLogger().severe("[V10Lift] Something went wrong when trying downloading the latest version.");
break; break;
case UNAVAILABLE: case UNAVAILABLE:
getLogger().warning("Unable to download the latest version."); Bukkit.getLogger().warning("[V10Lift] Unable to download the latest version.");
break; break;
} }
}).runUpdate(); }).runUpdate();
} }
break; break;
case LATEST: case LATEST:
getLogger().info("You are running the latest version [" + this.getDescription().getVersion() + "]!"); Bukkit.getLogger().info("[V10Lift] You are running the latest version [" + this.getDescription().getVersion() + "]!");
break; break;
case THIS_NEWER: case THIS_NEWER:
getLogger().info("You are running a newer version [" + this.getDescription().getVersion() + "]! This is probably fine."); Bukkit.getLogger().info("[V10Lift] You are running a newer version [" + this.getDescription().getVersion() + "]! This is probably fine.");
break; break;
case UNAVAILABLE: case UNAVAILABLE:
getLogger().severe("Unable to perform an update check."); Bukkit.getLogger().severe("[V10Lift] Unable to perform an update check.");
break; break;
} }
}).check(); }).check();
} }
getLogger().info("Plugin loaded successfully!"); Bukkit.getLogger().info("[V10Lift] Plugin loaded successfully!");
getLogger().info("-------------------------------");
} }
@Override @Override
public void onDisable() { public void onDisable() {
getLogger().info("Saving lifts...");
try {
dbManager.save(); dbManager.save();
} catch (SQLException e) {
//We can't do anything about it here, just inform the user
getLogger().log(Level.WARNING, "Couldn't save lifts to data storage.", e);
}
dbManager.closeConnection(); dbManager.closeConnection();
getLogger().info("Plugin disabled!");
instance = null; instance = null;
} }

View file

@ -1,57 +1,96 @@
package tech.sbdevelopment.v10lift.api; package tech.sbdevelopment.v10lift.api;
import lombok.Getter; import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit; import org.bukkit.*;
import org.bukkit.Location;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.*;
import tech.sbdevelopment.v10lift.api.objects.LiftSign; import tech.sbdevelopment.v10lift.api.runnables.DoorCloser;
import tech.sbdevelopment.v10lift.api.runnables.MoveLift;
import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.managers.DataManager;
import tech.sbdevelopment.v10lift.managers.ForbiddenBlockManager;
import tech.sbdevelopment.v10lift.sbutils.LocationSerializer;
import tech.sbdevelopment.v10lift.utils.ConfigUtil;
import tech.sbdevelopment.v10lift.utils.BlockStateUtil;
import tech.sbdevelopment.v10lift.utils.DoorUtil;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.sql.SQLException;
import java.util.*; import java.util.*;
/** /**
* The Main API class, for all the API methods * The Main API class, for all the API methods
*/ */
public class V10LiftAPI { public class V10LiftAPI {
@Getter private static V10LiftAPI instance;
private final List<Lift> lifts = new ArrayList<>();
private V10LiftAPI() {
}
public static V10LiftAPI getInstance() {
if (instance == null) instance = new V10LiftAPI();
return instance;
}
/* Private API methods */
private void sortFloors(@Nonnull Lift lift) {
ArrayList<Map.Entry<String, Floor>> as = new ArrayList<>(lift.getFloors().entrySet());
as.sort(Comparator.comparingInt(o -> o.getValue().getY()));
Iterator<Map.Entry<String, Floor>> iter = as.iterator();
lift.getFloors().clear();
Map.Entry<String, Floor> e;
while (iter.hasNext()) {
e = iter.next();
lift.getFloors().put(e.getKey(), e.getValue());
}
}
private void startLift(String liftName) {
if (!DataManager.containsMovingTask(liftName)) {
Lift lift = DataManager.getLift(liftName);
DataManager.addMovingTask(liftName, Bukkit.getScheduler().scheduleSyncRepeatingTask(V10LiftPlugin.getInstance(), new MoveLift(liftName, lift.getSpeed()), lift.getSpeed(), lift.getSpeed()));
}
}
/* API methods */
/*
@todo Fix creating lifts in adventure not working
*/
/** /**
* Create a new Lift * Create a new Lift
* *
* @param p The player [owner] of the lift * @param p The player [owner] of the lift
* @param liftName The name of the lift * @param liftName The name of the lift
* @return The lift object, or null if already exists * @return true if created, false if null or already exists
*/ */
@Nullable public boolean createLift(Player p, String liftName) {
public Lift createLift(@Nonnull Player p, @Nonnull String liftName) { if (p == null || liftName == null || DataManager.containsLift(liftName)) return false;
if (isLift(liftName)) return null;
Lift lift = new Lift(p.getUniqueId(), V10LiftPlugin.getSConfig().getFile().getInt("DefaultSpeed"), V10LiftPlugin.getSConfig().getFile().getBoolean("DefaultRealistic")); DataManager.addLift(liftName, new Lift(p.getUniqueId(), V10LiftPlugin.getSConfig().getFile().getInt("DefaultSpeed"), V10LiftPlugin.getSConfig().getFile().getBoolean("DefaultRealistic")));
lifts.add(lift); return true;
return lift;
} }
/** /**
* Remove a lift * Remove a lift
* *
* @param lift The lift * @param liftName The name of the lift
* @return true if removed, false if failure (check console) * @return true if removed, false if null or doesn't exists
*/ */
public boolean deleteLift(Lift lift) { public boolean removeLift(String liftName) {
if (liftName == null || !DataManager.containsLift(liftName)) return false;
Iterator<Map.Entry<UUID, String>> iter = DataManager.getEditors().entrySet().iterator(); Iterator<Map.Entry<UUID, String>> iter = DataManager.getEditors().entrySet().iterator();
HashSet<UUID> activeEdits = new HashSet<>(); HashSet<UUID> activeEdits = new HashSet<>();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<UUID, String> entry = iter.next(); Map.Entry<UUID, String> entry = iter.next();
if (entry.getValue().equals(lift.getName())) { if (entry.getValue().equals(liftName)) {
activeEdits.add(entry.getKey()); activeEdits.add(entry.getKey());
iter.remove(); iter.remove();
} }
@ -68,37 +107,32 @@ public class V10LiftAPI {
DataManager.removeDoorEditPlayer(puuid); DataManager.removeDoorEditPlayer(puuid);
} }
if (DataManager.containsMovingTask(lift.getName())) { if (DataManager.containsMovingTask(liftName)) {
Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift.getName())); Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(liftName));
DataManager.removeMovingTask(lift.getName()); DataManager.removeMovingTask(liftName);
} }
lifts.remove(lift); DataManager.removeLift(liftName);
try { V10LiftPlugin.getDBManager().remove(liftName);
V10LiftPlugin.getDBManager().remove(lift);
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true; return true;
} }
public boolean isLift(@Nonnull String name) {
return lifts.stream().anyMatch(lift -> lift.getName().equalsIgnoreCase(name));
}
public Optional<Lift> getLift(@Nonnull String name) {
return lifts.stream().filter(lift -> lift.getName().equalsIgnoreCase(name)).findFirst();
}
/** /**
* Get the name of a lift by a location (checking for cab blocks) * Get the name of a lift by a location (checking for cab blocks)
* *
* @param loc The location you want to check for * @param loc The location you want to check for
* @return The liftname * @return The liftname
*/ */
public Optional<Lift> getLift(@Nonnull Location loc) { public String getLiftByLocation(Location loc) {
return lifts.stream().filter(lift -> lift.getBlocks().stream().anyMatch(block -> block.getWorld().equals(loc.getWorld().getName()) && block.getX() == loc.getBlockX() && block.getZ() == loc.getBlockZ())).findFirst(); for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
for (LiftBlock block : entry.getValue().getBlocks()) {
//Check for world, x and z
if (block.getWorld().equals(Objects.requireNonNull(loc.getWorld(), "World is null at getLiftByLocation").getName()) && block.getX() == loc.getBlockX() && block.getZ() == loc.getBlockZ()) {
return entry.getKey();
}
}
}
return null;
} }
/** /**
@ -107,12 +141,13 @@ public class V10LiftAPI {
* @param liftName The name of the lift * @param liftName The name of the lift
* @param newName The new name of the lift * @param newName The new name of the lift
*/ */
public boolean renameLift(@Nonnull String liftName, @Nonnull String newName) { public void renameLift(String liftName, String newName) {
Optional<Lift> liftOpt = getLift(liftName); if (liftName == null || newName == null || !DataManager.containsLift(liftName)) return;
if (liftOpt.isEmpty() || isLift(newName)) return false;
liftOpt.get().setName(newName); Lift lift = DataManager.getLift(liftName);
for (LiftSign ls : liftOpt.get().getSigns()) { DataManager.removeLift(liftName);
DataManager.addLift(newName, lift);
for (LiftSign ls : lift.getSigns()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at renameLift").getBlockAt(ls.getX(), ls.getY(), ls.getZ()); Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at renameLift").getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState(); BlockState bs = block.getState();
if (!(bs instanceof Sign)) continue; if (!(bs instanceof Sign)) continue;
@ -120,9 +155,557 @@ public class V10LiftAPI {
si.setLine(1, newName); si.setLine(1, newName);
si.update(); si.update();
} }
}
/**
* Add a block to a lift
* Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after!
*
* @param liftName The name of the lift
* @param block The block
* @return 0 if added, -1 if null or doesn't exists, -2 if forbidden, -3 if already added
*/
public int addBlockToLift(String liftName, Block block) {
if (liftName == null || block == null || !DataManager.containsLift(liftName)) return -1;
Lift lift = DataManager.getLift(liftName);
return addBlockToLift(lift.getBlocks(), block);
}
/**
* Add a block to a lift
* Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after!
*
* @param blocks The blockset
* @param block The block
* @return 0 if added, -1 if null or doesn't exists, -2 if forbidden, -3 if already added
*/
public int addBlockToLift(Set<LiftBlock> blocks, @Nonnull Block block) {
return addBlockToLift(blocks, new LiftBlock(block));
}
/**
* Add a block to a lift
* Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after!
*
* @param blocks The blockset
* @param block The LiftBlock
* @return 0 if added, -2 if forbidden, -3 if already added
*/
public int addBlockToLift(@Nonnull Set<LiftBlock> blocks, @Nonnull LiftBlock block) {
if (ForbiddenBlockManager.isForbidden(block.getMat())) return -2;
if (blocks.contains(block)) return -3;
blocks.add(block);
return 0;
}
/**
* Remove a block from a lift
* Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after!
*
* @param liftName The name of the lift
* @param block The block
* @return 0 if removed, -1 if null or doesn't exists, -2 if not added
*/
public int removeBlockFromLift(String liftName, Block block) {
if (liftName == null || block == null || !DataManager.containsLift(liftName)) return -1;
Lift lift = DataManager.getLift(liftName);
LiftBlock lb = new LiftBlock(block);
if (!lift.getBlocks().contains(lb)) return -2;
lift.getBlocks().remove(lb);
return 0;
}
/**
* Switch a block at a lift
* Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after!
*
* @param liftName The name of the lift
* @param block The block
* @return 0 if added, 1 if removed, -1 if null or doesn't exists, -2 if not added
*/
public int switchBlockAtLift(String liftName, Block block) {
if (liftName == null || block == null || !DataManager.containsLift(liftName)) return -1;
return switchBlockAtLift(DataManager.getLift(liftName).getBlocks(), block);
}
/**
* Switch a block at a lift
* Use {@link V10LiftAPI#sortLiftBlocks(String liftName)} after!
*
* @param blocks The blockset
* @param block The block
* @return 0 if added, 1 if removed, -1 if null or doesn't exists, -2 if not added
*/
public int switchBlockAtLift(TreeSet<LiftBlock> blocks, Block block) {
if (blocks == null || block == null) return -1;
if (ForbiddenBlockManager.isForbidden(block.getType())) return -2;
LiftBlock lb = new LiftBlock(block);
if (blocks.contains(lb)) {
blocks.remove(lb);
return 1;
}
blocks.add(lb);
return 0;
}
/**
* Sort the blocks of a lift.
* Use this after they have been modified.
*
* @param liftName The name of the lift
*/
public void sortLiftBlocks(String liftName) {
if (liftName != null && DataManager.containsLift(liftName)) {
Lift lift = DataManager.getLift(liftName);
if (lift.getWorldName() == null) lift.setWorldName(lift.getBlocks().first().getWorld());
World world = Bukkit.getWorld(lift.getWorldName());
if (world == null) return;
lift.setY(world.getMaxHeight());
for (LiftBlock lb : lift.getBlocks()) {
if (lb.getY() < lift.getY()) {
lift.setY(lb.getY());
lift.setWorldName(lb.getWorld());
}
}
}
}
/**
* Open the door
*
* @param liftName The name of the lift
* @return true/false
*/
public boolean openDoor(String liftName) {
if (liftName == null || !DataManager.containsLift(liftName)) return false;
Lift lift = DataManager.getLift(liftName);
if (lift.getQueue() != null) return false;
Floor f = null;
for (Floor fl : lift.getFloors().values()) {
if (fl.getY() == lift.getY() && fl.getWorld().equals(lift.getWorldName())) {
f = fl;
break;
}
}
if (f == null) return false;
if (lift.getDoorOpen() != null && !closeDoor(liftName)) return false;
for (LiftBlock lb : f.getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
block.setType(Material.AIR);
}
for (LiftBlock lb : f.getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
DoorUtil.openDoor(block);
}
lift.setDoorOpen(f);
if (lift.isRealistic()) lift.setDoorCloser(new DoorCloser(liftName));
return true; return true;
} }
/**
* Open the door
*
* @param lift The lift
* @param liftName The name of the lift
* @param f The floor
* @return true/false
*/
public boolean openDoor(Lift lift, String liftName, Floor f) {
if (lift == null || liftName == null || f == null) return false;
if (lift.getDoorOpen() != null && !closeDoor(liftName)) return false;
for (LiftBlock lb : f.getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
block.setType(Material.AIR);
}
for (LiftBlock lb : f.getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
DoorUtil.openDoor(block);
}
lift.setDoorOpen(f);
if (lift.isRealistic()) lift.setDoorCloser(new DoorCloser(liftName));
return true;
}
/**
* Close a lift door
*
* @param liftName The name of the lift
* @return true if door was closed, false if else.
*/
public boolean closeDoor(String liftName) {
if (liftName == null || !DataManager.containsLift(liftName)) return false;
Lift lift = DataManager.getLift(liftName);
boolean blocked = false;
if (lift.getDoorOpen() == null) {
return true;
}
if (lift.isRealistic()) {
for (LiftBlock lb : lift.getDoorOpen().getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
for (Entity ent : block.getChunk().getEntities()) {
Location loc = ent.getLocation();
if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) {
blocked = true;
break;
}
}
if (blocked) break;
}
for (LiftBlock lb : lift.getDoorOpen().getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
for (Entity ent : block.getChunk().getEntities()) {
Location loc = ent.getLocation();
if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) {
blocked = true;
break;
}
}
if (blocked) break;
}
}
if (!blocked) {
for (LiftBlock lb : lift.getDoorOpen().getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
BlockState state = block.getState();
state.setType(lb.getMat());
state.update(true);
}
for (LiftBlock lb : lift.getDoorOpen().getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
DoorUtil.closeDoor(block);
}
lift.setDoorOpen(null);
if (lift.getDoorCloser() != null) lift.getDoorCloser().stop();
}
return !blocked;
}
/**
* To check if a lift has an open door.
*
* @param liftName The name of the lift
* @return true if open, false if else
*/
public boolean hasDoorOpen(String liftName) {
return (liftName != null && DataManager.containsLift(liftName)) && DataManager.getLift(liftName).getDoorOpen() != null;
}
/**
* Adds a new floor to a lift
*
* @param liftName The name of the lift
* @param floorName The name of the floor
* @param floor The floor object
* @return 0 if added, -1 if null or doesn't exists, -2 if height is to high, -3 if floor already exists
*/
public int addFloor(String liftName, String floorName, Floor floor) {
if (liftName == null || floorName == null || floor == null || !DataManager.containsLift(liftName) || floor.getWorld() == null)
return -1;
if (floor.getY() > Objects.requireNonNull(Bukkit.getServer().getWorld(floor.getWorld()), "World is null at addNewFloor!").getMaxHeight())
return -2;
if (floorName.length() > 13) floorName = floorName.substring(0, 13).trim();
Lift lift = DataManager.getLift(liftName);
if (lift.getFloors().containsKey(floorName) || lift.getFloors().containsValue(floor)) return -3;
lift.getFloors().put(floorName, floor);
sortFloors(lift);
return 0;
}
/**
* Removes a floor from a lift
*
* @param liftName The name of the lift
* @param floorName The name of the floor
* @return true if removed, false if null or doesn't exists
*/
public boolean removeFloor(String liftName, String floorName) {
if (liftName == null || floorName == null || !DataManager.containsLift(liftName)) return false;
Lift lift = DataManager.getLift(liftName);
if (!lift.getFloors().containsKey(floorName)) return false;
lift.getFloors().remove(floorName);
lift.getInputs().removeIf(liftBlock -> liftBlock.getFloor().equals(floorName));
return true;
}
/**
* Rename a floor from a lift
*
* @param liftName The name of the lift
* @param oldName The old name of the floor
* @param newName The new name of the floor
* @return 0 if renamed, -1 if null or doesn't exists, -2 if floor doesn't exists, -3 if floor already exists
*/
public int renameFloor(String liftName, String oldName, String newName) {
if (liftName == null || oldName == null || newName == null || !DataManager.containsLift(liftName)) return -1;
Lift lift = DataManager.getLift(liftName);
if (!lift.getFloors().containsKey(oldName)) return -2;
if (newName.length() > 13) newName = newName.substring(0, 13).trim();
if (lift.getFloors().containsKey(newName)) return -3;
Floor f = lift.getFloors().get(oldName);
lift.getFloors().remove(oldName);
lift.getFloors().put(newName, f);
sortFloors(lift);
Iterator<LiftInput> liter = lift.getInputs().iterator();
LiftInput lb;
ArrayList<LiftInput> newBlocks = new ArrayList<>();
while (liter.hasNext()) {
lb = liter.next();
if (lb.getFloor().equals(oldName)) {
liter.remove();
newBlocks.add(new LiftInput(lb.getWorld(), lb.getX(), lb.getY(), lb.getZ(), newName));
}
}
newBlocks.forEach(nlb -> lift.getInputs().add(nlb));
return 0;
}
/**
* Check if a lift is defective
*
* @param liftName The name of the lift
* @return true/false
*/
public boolean isDefective(String liftName) {
if (liftName == null || !DataManager.containsLift(liftName)) return false;
return DataManager.getLift(liftName).isDefective();
}
/**
* Set a lift to (not) defective
*
* @param liftName The name of the lift
* @param state true/false
* @return 0 if set, -1 if null or doesn't exists, -2 if same state, -3 if no signs, -4 if wrong sign
*/
public int setDefective(String liftName, boolean state) {
if (liftName == null || !DataManager.containsLift(liftName)) return -1;
Lift lift = DataManager.getLift(liftName);
boolean oldState = lift.isDefective();
if (oldState == state) return -2;
lift.setDefective(state);
if (state) {
//SET DEFECTIVE
//Update sign
for (LiftSign ls : lift.getSigns()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation()));
return -4;
}
Sign s = (Sign) bs;
ls.setOldText(s.getLine(3));
s.setLine(3, ConfigUtil.getConfigText("DefectText"));
s.update();
}
//Update all cab signs
for (LiftBlock lb : lift.getBlocks()) {
BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
Sign s = (Sign) bs;
lift.setSignText(s.getLine(3));
s.setLine(3, ConfigUtil.getConfigText("DefectText"));
s.update();
}
} else {
//Update sign
for (LiftSign ls : lift.getSigns()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation()));
return -4;
}
Sign s = (Sign) bs;
s.setLine(3, ls.getOldText());
ls.setOldText(null);
s.update();
}
//Update all cab signs
for (LiftBlock lb : lift.getBlocks()) {
BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
Sign s = (Sign) bs;
s.setLine(3, lift.getSignText());
s.update();
}
lift.setSignText(null);
}
return 0;
}
/**
* Get the userWhitelist of a lift
*
* @param liftName The name of the lift
* @param floorName The name of the floor
* @return list with UUIDs of the players
*/
public HashSet<UUID> getUserWhitelist(String liftName, String floorName) {
HashSet<UUID> ret = new HashSet<>();
if (liftName != null && floorName != null && DataManager.containsLift(liftName)) {
Lift lift = DataManager.getLift(liftName);
if (lift.getFloors().containsKey(floorName)) {
ret = lift.getFloors().get(floorName).getUserWhitelist();
}
}
return ret;
}
/**
* Get the groupWhitelist of a lift
*
* @param liftName The name of the lift
* @param floorName The name of the floor
* @return list with groupnames
*/
public HashSet<String> getGroupWhitelist(String liftName, String floorName) {
HashSet<String> ret = new HashSet<>();
if (liftName != null && floorName != null && DataManager.containsLift(liftName)) {
Lift lift = DataManager.getLift(liftName);
if (lift.getFloors().containsKey(floorName)) {
ret = lift.getFloors().get(floorName).getGroupWhitelist();
}
}
return ret;
}
/**
* Check if a lift is offline
*
* @param liftName The name of the lift
* @return true/false
*/
public boolean isOffline(String liftName) {
if (liftName == null || !DataManager.containsLift(liftName)) return false;
return DataManager.getLift(liftName).isOffline();
}
/**
* Set a lift to (not) offline
*
* @param liftName The name of the lift
* @param state true/false
* @return 0 if set, -1 if null or doesn't exists, -2 if same state
*/
public int setOffline(String liftName, boolean state) {
if (liftName == null || !DataManager.containsLift(liftName)) return -1;
Lift lift = DataManager.getLift(liftName);
boolean oldState = lift.isOffline();
if (oldState == state) return -2;
lift.setOffline(state);
Iterator<LiftSign> liter = lift.getSigns().iterator();
BlockState bs;
Sign sign;
if (state) {
for (LiftBlock lb : lift.getBlocks()) {
bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue;
sign.setLine(3, ConfigUtil.getConfigText("DisabledText"));
sign.update();
}
while (liter.hasNext()) {
LiftSign ls = liter.next();
bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation()));
liter.remove();
continue;
}
sign = (Sign) bs;
ls.setOldText(sign.getLine(3));
sign.setLine(3, ConfigUtil.getConfigText("DisabledText"));
sign.update();
}
} else {
for (LiftBlock lb : lift.getBlocks()) {
bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue;
sign.setLine(3, "");
sign.update();
}
while (liter.hasNext()) {
LiftSign ls = liter.next();
bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation()));
liter.remove();
continue;
}
sign = (Sign) bs;
sign.setLine(3, ls.getOldText());
sign.update();
ls.setOldText(null);
}
}
return 0;
}
/**
* Check if a lift contains the block as rope
*
* @param liftName The name of the lift
* @param block The block
* @return true/false
*/
public boolean containsRope(String liftName, Block block) {
if (liftName == null || block == null || !DataManager.containsLift(liftName)) return false;
Lift lift = DataManager.getLift(liftName);
if (lift.getRopes().isEmpty()) return false;
String world = block.getWorld().getName();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
for (LiftRope rope : lift.getRopes()) {
if (x != rope.getX() || z != rope.getZ()) continue;
if (y >= rope.getMinY() && y <= rope.getMaxY()) {
return true;
}
}
return false;
}
/** /**
* Check if a block is a rope * Check if a block is a rope
* *
@ -130,6 +713,218 @@ public class V10LiftAPI {
* @return true/false * @return true/false
*/ */
public boolean isRope(Block b) { public boolean isRope(Block b) {
return getLifts().stream().anyMatch(lift -> lift.containsRope(b)); for (String lift : DataManager.getLifts().keySet()) {
if (containsRope(lift, b)) return true;
}
return false;
}
/**
* Send info about a lift to a player
*
* @param sender Where you want to send it to
* @param liftName The name of the lift
*/
public void sendLiftInfo(CommandSender sender, String liftName) {
sendLiftInfo(sender, liftName, DataManager.getLift(liftName));
}
/**
* Send info about a lift to a player
*
* @param ent Where you want to send it to
* @param liftName The name of the lift
* @param lift The lift
*/
public void sendLiftInfo(@Nonnull CommandSender ent, String liftName, @Nonnull Lift lift) {
ent.sendMessage(ChatColor.GOLD + "Elevator: " + ChatColor.YELLOW + liftName);
ent.sendMessage(ChatColor.GOLD + "Settings:");
ent.sendMessage(ChatColor.GREEN + " Speed: " + ChatColor.YELLOW + lift.getSpeed());
ent.sendMessage(ChatColor.GREEN + " Realistic Mode: " + ChatColor.YELLOW + lift.isRealistic());
ent.sendMessage(ChatColor.GREEN + " Malfunction: " + ChatColor.YELLOW + lift.isDefective());
ent.sendMessage(ChatColor.GOLD + "Floors:");
if (lift.getFloors().isEmpty()) {
ent.sendMessage(ChatColor.RED + "None.");
} else {
for (Map.Entry<String, Floor> entry : lift.getFloors().entrySet()) {
ent.sendMessage(ChatColor.GREEN + " " + entry.getKey() + ":");
Floor f = entry.getValue();
ent.sendMessage(ChatColor.YELLOW + " World: " + ChatColor.GREEN + f.getWorld());
ent.sendMessage(ChatColor.YELLOW + " Height: " + ChatColor.GREEN + f.getY());
ent.sendMessage(ChatColor.YELLOW + " Whitelist:");
if (f.getUserWhitelist().isEmpty() && f.getGroupWhitelist().isEmpty()) {
ent.sendMessage(ChatColor.GOLD + " None.");
} else {
ChatColor color = ChatColor.DARK_PURPLE;
Iterator<UUID> iter = f.getUserWhitelist().iterator();
Iterator<String> iter2 = f.getGroupWhitelist().iterator();
StringBuilder sb = new StringBuilder();
sb.append(" ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName());
while (iter.hasNext()) {
if (color == ChatColor.DARK_PURPLE) {
color = ChatColor.LIGHT_PURPLE;
} else {
color = ChatColor.DARK_PURPLE;
}
sb.append(ChatColor.AQUA).append(", ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName());
}
while (iter2.hasNext()) {
if (color == ChatColor.DARK_PURPLE) {
color = ChatColor.LIGHT_PURPLE;
} else {
color = ChatColor.DARK_PURPLE;
}
sb.append(ChatColor.AQUA).append(", ").append(color).append("Group: ").append(iter2.next());
}
ent.sendMessage(sb.toString());
}
}
}
}
/**
* Add a rope to a lift
*
* @param lift The name of the lift
* @param world The world
* @param x The x-pos
* @param minY The min y-pos
* @param maxY The max y-pos
* @param z The z-pos
* @return 0 if added, -1 if null or doesn't exists, -2 if not same mat, -3 if already a rope, -4 if forbidden material
*/
public int addRope(String lift, World world, int x, int minY, int maxY, int z) {
if (lift == null || !DataManager.containsLift(lift) || world == null) return -1;
//minY = maxY, so reverse
if (minY > maxY) {
int tempY = minY;
minY = maxY;
maxY = tempY;
}
Block block = world.getBlockAt(x, minY, z);
if (isRope(block)) return -3;
Material mat = block.getType();
if (ForbiddenBlockManager.isForbidden(mat)) return -4;
for (int i = minY + 1; i <= maxY; i++) {
block = world.getBlockAt(x, i, z);
if (isRope(block)) return -3;
if (block.getType() != mat) return -2;
}
LiftRope rope = new LiftRope(block, minY, maxY);
DataManager.getLift(lift).getRopes().add(rope);
return 0;
}
/**
* Remove a rope from a lift
*
* @param lift The name of the lift
* @param block The block
* @return true/false
*/
public boolean removeRope(String lift, Block block) {
if (lift == null || block == null || !DataManager.containsLift(lift) || !containsRope(lift, block))
return false;
String world = block.getWorld().getName();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
Iterator<LiftRope> riter = DataManager.getLift(lift).getRopes().iterator();
while (riter.hasNext()) {
LiftRope rope = riter.next();
if (x != rope.getX() || z != rope.getZ()) continue;
if (world.equals(rope.getWorld())) {
if (y >= rope.getMinY() && y <= rope.getMaxY()) {
riter.remove();
return true;
}
}
}
return false;
}
/**
* Set the queue of a lift
*
* @param liftName The name of the lift
* @param queue The queue
* @return true/false
*/
public boolean setQueue(String liftName, LinkedHashMap<String, Floor> queue) {
if (liftName == null || queue == null || !DataManager.containsLift(liftName)) return false;
Lift lift = DataManager.getLift(liftName);
lift.setQueue(new LinkedHashMap<>());
for (Map.Entry<String, Floor> e : queue.entrySet()) {
addToQueue(liftName, e.getValue(), e.getKey());
}
return true;
}
/**
* Add a location to the queue
*
* @param lift The name of the lift
* @param y The y-pos
* @param world The world
* @return true/false
*/
public boolean addToQueue(String lift, int y, World world) {
return addToQueue(lift, y, world, null);
}
/**
* Add a location to the queue
*
* @param lift The name of the lift
* @param y The y-pos
* @param world The world
* @param floorName The name of the flor
* @return true/false
*/
public boolean addToQueue(String lift, int y, @Nonnull World world, String floorName) {
return addToQueue(lift, new Floor(y, world.getName()), floorName);
}
/**
* Add a location to the queue
*
* @param lift The name of the lift
* @param floor The {@link Floor}
* @param floorName The name of the flor
* @return true/false
*/
public boolean addToQueue(String lift, Floor floor, String floorName) {
if (lift == null || floor == null || !DataManager.containsLift(lift)) return false;
Lift l = DataManager.getLift(lift);
if (l.getQueue() == null) {
l.setQueue(new LinkedHashMap<>());
}
if (!l.getQueue().containsValue(floor)) {
if (floorName == null) {
floorName = ChatColor.MAGIC + "-----";
for (Map.Entry<String, Floor> e : l.getFloors().entrySet()) {
if (e.getValue().equals(floor)) {
floorName = e.getKey();
floor = e.getValue();
break;
}
}
}
l.getQueue().put(floorName, floor);
startLift(lift);
return true;
}
return false;
} }
} }

View file

@ -1,54 +0,0 @@
package tech.sbdevelopment.v10lift.api.lists;
import lombok.Setter;
import tech.sbdevelopment.v10lift.api.objects.Floor;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class LiftQueue {
private final LinkedHashMap<String, Floor> queue = new LinkedHashMap<>();
@Setter
private LiftQueueListener listener;
public void empty() {
queue.clear();
}
public interface LiftQueueListener {
void onQueueChange();
}
public void requestFloor(String floorName, Floor floor) {
if (!queue.containsKey(floorName)) {
queue.put(floorName, floor);
if (listener != null) {
listener.onQueueChange();
}
}
}
public Iterator<Map.Entry<String, Floor>> iterator() {
return queue.entrySet().iterator();
}
public boolean hasRequests() {
return !queue.isEmpty();
}
public String getNextFloor(String currentFloor, boolean movingUp) {
if (!hasRequests()) return null;
String nextFloor = currentFloor;
for (Map.Entry<String, Floor> entry : queue.entrySet()) {
if ((movingUp && entry.getValue().getY() > entry.getValue().getY()) || (!movingUp && entry.getValue().getY() < entry.getValue().getY())) {
nextFloor = entry.getKey();
}
}
return nextFloor;
}
}

View file

@ -5,7 +5,6 @@ import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import javax.annotation.Nonnull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
@ -18,7 +17,6 @@ import java.util.UUID;
@NoArgsConstructor @NoArgsConstructor
@ToString @ToString
public class Floor { public class Floor {
@Nonnull
private String world; private String world;
private int y; private int y;
private ArrayList<LiftBlock> doorBlocks = new ArrayList<>(); private ArrayList<LiftBlock> doorBlocks = new ArrayList<>();

View file

@ -1,27 +1,11 @@
package tech.sbdevelopment.v10lift.api.objects; package tech.sbdevelopment.v10lift.api.objects;
import com.craftmend.storm.api.StormModel;
import com.craftmend.storm.api.markers.Column;
import com.craftmend.storm.api.markers.Table;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.lists.LiftQueue;
import tech.sbdevelopment.v10lift.api.runnables.DoorCloser; import tech.sbdevelopment.v10lift.api.runnables.DoorCloser;
import tech.sbdevelopment.v10lift.managers.ForbiddenBlockManager;
import tech.sbdevelopment.v10lift.sbutils.LocationSerializer;
import tech.sbdevelopment.v10lift.utils.ConfigUtil;
import tech.sbdevelopment.v10lift.utils.DoorUtil;
import javax.annotation.Nonnull;
import java.util.*; import java.util.*;
/** /**
@ -30,56 +14,36 @@ import java.util.*;
@Getter @Getter
@NoArgsConstructor @NoArgsConstructor
@ToString @ToString
@Table(name = "lifts") public class Lift {
public class Lift extends StormModel {
@Column
@Setter
private String name;
@Column
@Setter @Setter
private String worldName; private String worldName;
@Column
@Setter @Setter
private int y; private int y;
@Column
private HashSet<UUID> owners; private HashSet<UUID> owners;
@Column
private final TreeSet<LiftBlock> blocks = new TreeSet<>(); private final TreeSet<LiftBlock> blocks = new TreeSet<>();
@Column
private final LinkedHashMap<String, Floor> floors = new LinkedHashMap<>(); private final LinkedHashMap<String, Floor> floors = new LinkedHashMap<>();
@Column
private final HashSet<LiftSign> signs = new HashSet<>(); private final HashSet<LiftSign> signs = new HashSet<>();
@Column
private final HashSet<LiftInput> inputs = new HashSet<>(); private final HashSet<LiftInput> inputs = new HashSet<>();
@Column
private final HashSet<LiftInput> offlineInputs = new HashSet<>(); private final HashSet<LiftInput> offlineInputs = new HashSet<>();
//transient @Setter
private final LiftQueue queue = new LiftQueue(); private LinkedHashMap<String, Floor> queue = null;
@Column
private final HashSet<LiftRope> ropes = new HashSet<>(); private final HashSet<LiftRope> ropes = new HashSet<>();
@Column
@Setter @Setter
private int speed; private int speed;
@Column
@Setter @Setter
private boolean realistic; private boolean realistic;
@Column @Setter
private boolean offline = false; private boolean offline = false;
@Column
@Setter @Setter
private boolean sound = true; private boolean sound = true;
@Column @Setter
private boolean defective = false; private boolean defective = false;
@Column
@Setter @Setter
private String signText = null; private String signText = null;
//transient
@Setter @Setter
private int counter = 0; private int counter = 0;
//transient
@Setter @Setter
private Floor doorOpen = null; private Floor doorOpen = null;
//transient
@Setter @Setter
private DoorCloser doorCloser = null; private DoorCloser doorCloser = null;
@ -110,684 +74,4 @@ public class Lift extends StormModel {
this.speed = speed; this.speed = speed;
this.realistic = realistic; this.realistic = realistic;
} }
/**
* Add a block to a lift
* Use {@link Lift#sortLiftBlocks()} after!
*
* @param block The block
* @return 0 if added, -2 if forbidden, -3 if already added
*/
public int addBlock(@Nonnull Block block) {
return addBlock(getBlocks(), block);
}
/**
* Add a block to a lift
* Use {@link Lift#sortLiftBlocks()} after!
*
* @param blocks The blockset
* @param block The block
* @return 0 if added, -2 if forbidden, -3 if already added
*/
public int addBlock(@Nonnull Set<LiftBlock> blocks, @Nonnull Block block) {
return addBlock(blocks, new LiftBlock(block));
}
/**
* Add a block to a lift
* Use {@link Lift#sortLiftBlocks()} after!
*
* @param blocks The blockset
* @param block The LiftBlock
* @return 0 if added, -2 if forbidden, -3 if already added
*/
public int addBlock(@Nonnull Set<LiftBlock> blocks, @Nonnull LiftBlock block) {
if (ForbiddenBlockManager.isForbidden(block.getMat())) return -2;
if (blocks.contains(block)) return -3;
blocks.add(block);
return 0;
}
/**
* Remove a block from a lift
* Use {@link Lift#sortLiftBlocks()} after!
*
* @param block The block
* @return true if removed, false if doesn't exists
*/
public boolean removeBlock(@Nonnull Block block) {
LiftBlock lb = new LiftBlock(block);
if (!getBlocks().contains(lb)) return false;
getBlocks().remove(lb);
return true;
}
/**
* Switch a block at a lift
* Use {@link Lift#sortLiftBlocks()} after!
*
* @param block The block
* @return 0 if added, 1 if removed, -2 if not added
*/
public int switchBlock(@Nonnull Block block) {
return switchBlock(getBlocks(), block);
}
/**
* Switch a block at a lift
* Use {@link Lift#sortLiftBlocks()} after!
*
* @param blocks The blockset
* @param block The block
* @return 0 if added, 1 if removed, -2 if not added
*/
public int switchBlock(@Nonnull TreeSet<LiftBlock> blocks, @Nonnull Block block) {
if (ForbiddenBlockManager.isForbidden(block.getType())) return -2;
LiftBlock lb = new LiftBlock(block);
if (blocks.contains(lb)) {
blocks.remove(lb);
return 1;
}
blocks.add(lb);
return 0;
}
/**
* Sort the blocks of a lift.
* Use this after they have been modified.
*/
public void sortLiftBlocks() {
if (getWorldName() == null) setWorldName(getBlocks().first().getWorld());
World world = Bukkit.getWorld(getWorldName());
if (world == null) return;
setY(world.getMaxHeight());
for (LiftBlock lb : getBlocks()) {
if (lb.getY() < getY()) {
setY(lb.getY());
setWorldName(lb.getWorld());
}
}
}
/**
* Open the door
*
* @return true/false
*/
public boolean openDoor() {
if (getQueue() != null) return false;
Floor f = null;
for (Floor fl : getFloors().values()) {
if (fl.getY() == getY() && fl.getWorld().equals(getWorldName())) {
f = fl;
break;
}
}
if (f == null) return false;
if (getDoorOpen() != null && !closeDoor()) return false;
for (LiftBlock lb : f.getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
block.setType(Material.AIR);
}
for (LiftBlock lb : f.getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
DoorUtil.openDoor(block);
}
setDoorOpen(f);
if (isRealistic()) setDoorCloser(new DoorCloser(this));
return true;
}
/**
* Open the door
*
* @param f The floor
* @return true/false
*/
public boolean openDoor(@Nonnull Floor f) {
if (getDoorOpen() != null && !closeDoor()) return false;
for (LiftBlock lb : f.getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
block.setType(Material.AIR);
}
for (LiftBlock lb : f.getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at openDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
DoorUtil.openDoor(block);
}
setDoorOpen(f);
if (isRealistic()) setDoorCloser(new DoorCloser(this));
return true;
}
/**
* Close a lift door
*
* @return true if door was closed, false if else.
*/
public boolean closeDoor() {
boolean blocked = false;
if (getDoorOpen() == null) {
return true;
}
if (isRealistic()) {
for (LiftBlock lb : getDoorOpen().getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
for (Entity ent : block.getChunk().getEntities()) {
Location loc = ent.getLocation();
if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) {
blocked = true;
break;
}
}
if (blocked) break;
}
for (LiftBlock lb : getDoorOpen().getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
for (Entity ent : block.getChunk().getEntities()) {
Location loc = ent.getLocation();
if (loc.getBlockX() == lb.getX() && loc.getBlockY() == lb.getY() && loc.getBlockZ() == lb.getZ()) {
blocked = true;
break;
}
}
if (blocked) break;
}
}
if (!blocked) {
for (LiftBlock lb : getDoorOpen().getDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
BlockState state = block.getState();
state.setType(lb.getMat());
state.update(true);
}
for (LiftBlock lb : getDoorOpen().getRealDoorBlocks()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at closeDoor").getBlockAt(lb.getX(), lb.getY(), lb.getZ());
DoorUtil.closeDoor(block);
}
setDoorOpen(null);
if (getDoorCloser() != null) getDoorCloser().stop();
}
return !blocked;
}
/**
* To check if a lift has an open door.
*
* @return true if open, false if else
*/
public boolean hasDoorOpen() {
return getDoorOpen() != null;
}
private void sortFloors() {
ArrayList<Map.Entry<String, Floor>> as = new ArrayList<>(getFloors().entrySet());
as.sort(Comparator.comparingInt(o -> o.getValue().getY()));
Iterator<Map.Entry<String, Floor>> iter = as.iterator();
getFloors().clear();
Map.Entry<String, Floor> e;
while (iter.hasNext()) {
e = iter.next();
getFloors().put(e.getKey(), e.getValue());
}
}
/**
* Adds a new floor to a lift
*
* @param floorName The name of the floor
* @param floor The floor object
* @return 0 if added, -1 if world doesn't exist, -2 if height is too high, -3 if floor already exists
*/
public int addFloor(@Nonnull String floorName, @Nonnull Floor floor) {
if (Bukkit.getWorld(floor.getWorld()) == null) return -1;
if (floor.getY() > Bukkit.getServer().getWorld(floor.getWorld()).getMaxHeight())
return -2;
if (floorName.length() > 13) floorName = floorName.substring(0, 13).trim();
if (getFloors().containsKey(floorName) || getFloors().containsValue(floor)) return -3;
getFloors().put(floorName, floor);
sortFloors();
return 0;
}
/**
* Removes a floor from a lift
*
* @param floorName The name of the floor
* @return true if removed, false if null or doesn't exists
*/
public boolean removeFloor(@Nonnull String floorName) {
if (!getFloors().containsKey(floorName)) return false;
getFloors().remove(floorName);
getInputs().removeIf(liftBlock -> liftBlock.getFloor().equals(floorName));
return true;
}
/**
* Rename a floor from a lift
*
* @param oldName The old name of the floor
* @param newName The new name of the floor
* @return 0 if renamed, -2 if floor doesn't exists, -3 if floor already exists
*/
public int renameFloor(@Nonnull String oldName, @Nonnull String newName) {
if (!getFloors().containsKey(oldName)) return -2;
if (newName.length() > 13) newName = newName.substring(0, 13).trim();
if (getFloors().containsKey(newName)) return -3;
Floor f = getFloors().get(oldName);
getFloors().remove(oldName);
getFloors().put(newName, f);
sortFloors();
Iterator<LiftInput> liter = getInputs().iterator();
LiftInput lb;
ArrayList<LiftInput> newBlocks = new ArrayList<>();
while (liter.hasNext()) {
lb = liter.next();
if (lb.getFloor().equals(oldName)) {
liter.remove();
newBlocks.add(new LiftInput(lb.getWorld(), lb.getX(), lb.getY(), lb.getZ(), newName));
}
}
newBlocks.forEach(nlb -> getInputs().add(nlb));
return 0;
}
/**
* Set a lift to (not) defective
*
* @param state true/false
* @return 0 if set, -2 if same state, -3 if no signs, -4 if wrong sign
*/
public int setDefective(boolean state) {
if (defective == state) return -2;
defective = state;
if (state) {
//SET DEFECTIVE
//Update sign
for (LiftSign ls : getSigns()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation()));
return -4;
}
Sign s = (Sign) bs;
ls.setOldText(s.getLine(3));
s.setLine(3, ConfigUtil.getConfigText("DefectText"));
s.update();
}
//Update all cab signs
for (LiftBlock lb : getBlocks()) {
BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
Sign s = (Sign) bs;
setSignText(s.getLine(3));
s.setLine(3, ConfigUtil.getConfigText("DefectText"));
s.update();
}
} else {
//Update sign
for (LiftSign ls : getSigns()) {
Block block = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setDefective").getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation()));
return -4;
}
Sign s = (Sign) bs;
s.setLine(3, ls.getOldText());
ls.setOldText(null);
s.update();
}
//Update all cab signs
for (LiftBlock lb : getBlocks()) {
BlockState bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setDefective").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
Sign s = (Sign) bs;
s.setLine(3, getSignText());
s.update();
}
setSignText(null);
}
return 0;
}
/**
* Get the userWhitelist of a lift
*
* @param floorName The name of the floor
* @return set with UUIDs of the players
*/
public HashSet<UUID> getUserWhitelist(@Nonnull String floorName) {
HashSet<UUID> ret = new HashSet<>();
if (getFloors().containsKey(floorName)) {
ret = getFloors().get(floorName).getUserWhitelist();
}
return ret;
}
/**
* Get the groupWhitelist of a lift
*
* @param floorName The name of the floor
* @return set with groupnames
*/
public HashSet<String> getGroupWhitelist(@Nonnull String floorName) {
HashSet<String> ret = new HashSet<>();
if (getFloors().containsKey(floorName)) {
ret = getFloors().get(floorName).getGroupWhitelist();
}
return ret;
}
/**
* Set a lift to (not) offline
*
* @param state true/false
* @return 0 if set, -2 if same state
*/
public int setOffline(boolean state) {
if (offline == state) return -2;
offline = state;
Iterator<LiftSign> liter = getSigns().iterator();
BlockState bs;
Sign sign;
if (state) {
for (LiftBlock lb : getBlocks()) {
bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue;
sign.setLine(3, ConfigUtil.getConfigText("DisabledText"));
sign.update();
}
while (liter.hasNext()) {
LiftSign ls = liter.next();
bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation()));
liter.remove();
continue;
}
sign = (Sign) bs;
ls.setOldText(sign.getLine(3));
sign.setLine(3, ConfigUtil.getConfigText("DisabledText"));
sign.update();
}
} else {
for (LiftBlock lb : getBlocks()) {
bs = Objects.requireNonNull(Bukkit.getWorld(lb.getWorld()), "World is null at setOffline").getBlockAt(lb.getX(), lb.getY(), lb.getZ()).getState();
if (!(bs instanceof Sign)) continue;
sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue;
sign.setLine(3, "");
sign.update();
}
while (liter.hasNext()) {
LiftSign ls = liter.next();
bs = Objects.requireNonNull(Bukkit.getWorld(ls.getWorld()), "World is null at setOffline").getBlockAt(ls.getX(), ls.getY(), ls.getZ()).getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(bs.getBlock().getLocation()));
liter.remove();
continue;
}
sign = (Sign) bs;
sign.setLine(3, ls.getOldText());
sign.update();
ls.setOldText(null);
}
}
return 0;
}
/**
* Check if a lift contains the block as rope
*
* @param block The block
* @return true/false
*/
public boolean containsRope(@Nonnull Block block) {
if (getRopes().isEmpty()) return false;
int x = block.getX();
int y = block.getY();
int z = block.getZ();
for (LiftRope rope : getRopes()) {
if (x != rope.getX() || z != rope.getZ()) continue;
if (y >= rope.getMinY() && y <= rope.getMaxY()) {
return true;
}
}
return false;
}
/**
* Send info about a lift to a player
*
* @param ent Where you want to send it to
*/
public void sendInfo(@Nonnull CommandSender ent) {
ent.sendMessage(ChatColor.GOLD + "Elevator: " + ChatColor.YELLOW + name);
ent.sendMessage(ChatColor.GOLD + "Settings:");
ent.sendMessage(ChatColor.GREEN + " Speed: " + ChatColor.YELLOW + getSpeed());
ent.sendMessage(ChatColor.GREEN + " Realistic Mode: " + ChatColor.YELLOW + isRealistic());
ent.sendMessage(ChatColor.GREEN + " Malfunction: " + ChatColor.YELLOW + isDefective());
ent.sendMessage(ChatColor.GOLD + "Floors:");
if (getFloors().isEmpty()) {
ent.sendMessage(ChatColor.RED + "None.");
} else {
for (Map.Entry<String, Floor> entry : getFloors().entrySet()) {
ent.sendMessage(ChatColor.GREEN + " " + entry.getKey() + ":");
Floor f = entry.getValue();
ent.sendMessage(ChatColor.YELLOW + " World: " + ChatColor.GREEN + f.getWorld());
ent.sendMessage(ChatColor.YELLOW + " Height: " + ChatColor.GREEN + f.getY());
ent.sendMessage(ChatColor.YELLOW + " Whitelist:");
if (f.getUserWhitelist().isEmpty() && f.getGroupWhitelist().isEmpty()) {
ent.sendMessage(ChatColor.GOLD + " None.");
} else {
ChatColor color = ChatColor.DARK_PURPLE;
Iterator<UUID> iter = f.getUserWhitelist().iterator();
Iterator<String> iter2 = f.getGroupWhitelist().iterator();
StringBuilder sb = new StringBuilder();
sb.append(" ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName());
while (iter.hasNext()) {
if (color == ChatColor.DARK_PURPLE) {
color = ChatColor.LIGHT_PURPLE;
} else {
color = ChatColor.DARK_PURPLE;
}
sb.append(ChatColor.AQUA).append(", ").append(color).append(Bukkit.getOfflinePlayer(iter.next()).getName());
}
while (iter2.hasNext()) {
if (color == ChatColor.DARK_PURPLE) {
color = ChatColor.LIGHT_PURPLE;
} else {
color = ChatColor.DARK_PURPLE;
}
sb.append(ChatColor.AQUA).append(", ").append(color).append("Group: ").append(iter2.next());
}
ent.sendMessage(sb.toString());
}
}
}
}
/**
* Add a rope to a lift
*
* @param world The world
* @param x The x-pos
* @param minY The min y-pos
* @param maxY The max y-pos
* @param z The z-pos
* @return 0 if added, -2 if not same mat, -3 if already a rope, -4 if forbidden material
*/
public int addRope(@Nonnull World world, int x, int minY, int maxY, int z) {
//minY = maxY, so reverse
if (minY > maxY) {
int tempY = minY;
minY = maxY;
maxY = tempY;
}
Block block = world.getBlockAt(x, minY, z);
if (V10LiftPlugin.getApi().isRope(block)) return -3;
Material mat = block.getType();
if (ForbiddenBlockManager.isForbidden(mat)) return -4;
for (int i = minY + 1; i <= maxY; i++) {
block = world.getBlockAt(x, i, z);
if (V10LiftPlugin.getApi().isRope(block)) return -3;
if (block.getType() != mat) return -2;
}
LiftRope rope = new LiftRope(block, minY, maxY);
getRopes().add(rope);
return 0;
}
/**
* Remove a rope from a lift
*
* @param block The block
* @return true/false
*/
public boolean removeRope(@Nonnull Block block) {
if (!containsRope(block))
return false;
String world = block.getWorld().getName();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
Iterator<LiftRope> riter = getRopes().iterator();
while (riter.hasNext()) {
LiftRope rope = riter.next();
if (x != rope.getX() || z != rope.getZ()) continue;
if (world.equals(rope.getWorld())) {
if (y >= rope.getMinY() && y <= rope.getMaxY()) {
riter.remove();
return true;
}
}
}
return false;
}
// /**
// * Set the queue of a lift
// *
// * @param liftName The name of the lift
// * @param queue The queue
// * @return true/false
// */
// public boolean setQueue(String liftName, LinkedHashMap<String, Floor> queue) {
// if (liftName == null || queue == null || !DataManager.containsLift(liftName)) return false;
//
// Lift lift = DataManager.getLift(liftName);
// lift.setQueue(new LinkedHashMap<>());
// for (Map.Entry<String, Floor> e : queue.entrySet()) {
// addToQueue(liftName, e.getValue(), e.getKey());
// }
// return true;
// }
//
// /**
// * Add a location to the queue
// *
// * @param lift The name of the lift
// * @param y The y-pos
// * @param world The world
// * @return true/false
// */
// public boolean addToQueue(String lift, int y, World world) {
// return addToQueue(lift, y, world, null);
// }
//
// /**
// * Add a location to the queue
// *
// * @param lift The name of the lift
// * @param y The y-pos
// * @param world The world
// * @param floorName The name of the flor
// * @return true/false
// */
// public boolean addToQueue(String lift, int y, @Nonnull World world, String floorName) {
// return addToQueue(lift, new Floor(y, world.getName()), floorName);
// }
//
// /**
// * Add a location to the queue
// *
// * @param lift The name of the lift
// * @param floor The {@link Floor}
// * @param floorName The name of the flor
// * @return true/false
// */
// public boolean addToQueue(String lift, Floor floor, String floorName) {
// if (lift == null || floor == null || !DataManager.containsLift(lift)) return false;
//
// Lift l = DataManager.getLift(lift);
// if (l.getQueue() == null) {
// l.setQueue(new LinkedHashMap<>());
// }
//
// if (!l.getQueue().containsValue(floor)) {
// if (floorName == null) {
// floorName = ChatColor.MAGIC + "-----";
// for (Map.Entry<String, Floor> e : l.getFloors().entrySet()) {
// if (e.getValue().equals(floor)) {
// floorName = e.getKey();
// floor = e.getValue();
// break;
// }
// }
// }
//
// l.getQueue().put(floorName, floor);
// startLift(lift);
// return true;
// }
// return false;
// }
//
// private void start(String liftName) {
// if (!DataManager.containsMovingTask(liftName)) {
// Lift lift = DataManager.getLift(liftName);
// DataManager.addMovingTask(liftName, Bukkit.getScheduler().scheduleSyncRepeatingTask(V10LiftPlugin.getInstance(), new MoveLift(liftName, lift.getSpeed()), lift.getSpeed(), lift.getSpeed()));
// }
// }
} }

View file

@ -3,18 +3,17 @@ package tech.sbdevelopment.v10lift.api.runnables;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.V10LiftAPI; import tech.sbdevelopment.v10lift.api.V10LiftAPI;
import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.managers.DataManager;
/** /**
* The DoorCloser runnable, used for checking if the door can be closed. * The DoorCloser runnable, used for checking if the door can be closed.
*/ */
public class DoorCloser implements Runnable { public class DoorCloser implements Runnable {
private final Lift lift; private final String liftName;
private final int taskID; private final int taskID;
public DoorCloser(Lift lift) { public DoorCloser(String liftName) {
this.lift = lift; this.liftName = liftName;
final long doorCloseTime = V10LiftPlugin.getSConfig().getFile().getLong("DoorCloseTime"); final long doorCloseTime = V10LiftPlugin.getSConfig().getFile().getLong("DoorCloseTime");
this.taskID = Bukkit.getScheduler().runTaskTimer(V10LiftPlugin.getInstance(), this, doorCloseTime, doorCloseTime).getTaskId(); this.taskID = Bukkit.getScheduler().runTaskTimer(V10LiftPlugin.getInstance(), this, doorCloseTime, doorCloseTime).getTaskId();
@ -22,11 +21,11 @@ public class DoorCloser implements Runnable {
@Override @Override
public void run() { public void run() {
if (lift.closeDoor()) stop(); if (V10LiftAPI.getInstance().closeDoor(liftName)) stop();
} }
public void stop() { public void stop() {
Bukkit.getScheduler().cancelTask(taskID); Bukkit.getScheduler().cancelTask(taskID);
lift.setDoorCloser(null); if (DataManager.containsLift(liftName)) DataManager.getLift(liftName).setDoorCloser(null);
} }
} }

View file

@ -1,5 +1,6 @@
package tech.sbdevelopment.v10lift.api.runnables; package tech.sbdevelopment.v10lift.api.runnables;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound; import com.cryptomorin.xseries.XSound;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -10,13 +11,14 @@ import org.bukkit.entity.Entity;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.V10LiftAPI;
import tech.sbdevelopment.v10lift.api.enums.LiftDirection; import tech.sbdevelopment.v10lift.api.enums.LiftDirection;
import tech.sbdevelopment.v10lift.api.objects.*; import tech.sbdevelopment.v10lift.api.objects.*;
import tech.sbdevelopment.v10lift.managers.AntiCopyBlockManager; import tech.sbdevelopment.v10lift.managers.AntiCopyBlockManager;
import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.managers.DataManager;
import tech.sbdevelopment.v10lift.sbutils.LocationSerializer; import tech.sbdevelopment.v10lift.sbutils.LocationSerializer;
import tech.sbdevelopment.v10lift.utils.BlockStateUtil;
import tech.sbdevelopment.v10lift.utils.ConfigUtil; import tech.sbdevelopment.v10lift.utils.ConfigUtil;
import tech.sbdevelopment.v10lift.utils.BlockStateUtil;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.*;
@ -65,16 +67,15 @@ public class MoveLift implements Runnable {
@Override @Override
public void run() { public void run() {
//Check if lift exists //Check if lift exists
Optional<Lift> liftOpt = V10LiftPlugin.getApi().getLift(liftName); Lift lift = DataManager.getLift(liftName);
if (liftOpt.isEmpty()) { if (lift == null) {
stop(); stop();
return; return;
} }
Lift lift = liftOpt.get();
//If the queue is NOT empty and the lift is offline //If the queue is NOT empty and the lift is NOT offline
if (lift.getQueue().hasRequests() || lift.isOffline()) { if (lift.getQueue().isEmpty() || lift.isOffline()) {
lift.getQueue().empty(); lift.setQueue(null);
stop(); stop();
return; return;
} }
@ -121,12 +122,12 @@ public class MoveLift implements Runnable {
if (changeOfDefect > 0.0D) { if (changeOfDefect > 0.0D) {
double chance = ThreadLocalRandom.current().nextDouble(100); double chance = ThreadLocalRandom.current().nextDouble(100);
if (chance < changeOfDefect) { if (chance < changeOfDefect) {
lift.setDefective(true); V10LiftAPI.getInstance().setDefective(liftName, true);
return; return;
} }
} }
Iterator<Map.Entry<String, Floor>> queueIterator = lift.getQueue().iterator(); Iterator<Map.Entry<String, Floor>> queueIterator = lift.getQueue().entrySet().iterator();
Map.Entry<String, Floor> floor = queueIterator.next(); Map.Entry<String, Floor> floor = queueIterator.next();
String floorName = floor.getKey(); String floorName = floor.getKey();
Floor floorTo = floor.getValue(); Floor floorTo = floor.getValue();
@ -143,7 +144,7 @@ public class MoveLift implements Runnable {
List<LiftBlock> antiCopyBlocks = new ArrayList<>(); List<LiftBlock> antiCopyBlocks = new ArrayList<>();
if (direction == LiftDirection.UP || direction == LiftDirection.DOWN) { if (direction == LiftDirection.UP || direction == LiftDirection.DOWN) {
if (!lift.closeDoor()) return; if (!V10LiftAPI.getInstance().closeDoor(liftName)) return;
if (direction == LiftDirection.UP) { if (direction == LiftDirection.UP) {
//MOVE ROPES //MOVE ROPES
@ -151,7 +152,7 @@ public class MoveLift implements Runnable {
if (rope.getCurrently() > rope.getMaxY()) { if (rope.getCurrently() > rope.getMaxY()) {
Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!"); Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!");
lift.setDefective(true); V10LiftAPI.getInstance().setDefective(liftName, true);
queueIterator.remove(); queueIterator.remove();
return; return;
} }
@ -304,7 +305,7 @@ public class MoveLift implements Runnable {
if (rope.getCurrently() < rope.getMinY()) { if (rope.getCurrently() < rope.getMinY()) {
Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!"); Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!");
lift.setDefective(true); V10LiftAPI.getInstance().setDefective(liftName, true);
queueIterator.remove(); queueIterator.remove();
stopAfter = true; stopAfter = true;
@ -387,7 +388,7 @@ public class MoveLift implements Runnable {
ls.setState((byte) 0); ls.setState((byte) 0);
} }
lift.openDoor(floorTo); V10LiftAPI.getInstance().openDoor(lift, liftName, floorTo);
if (lift.isRealistic()) lift.setCounter(ft); if (lift.isRealistic()) lift.setCounter(ft);

View file

@ -1,15 +1,15 @@
package tech.sbdevelopment.v10lift.commands; package tech.sbdevelopment.v10lift.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.CommandHelp;
import co.aikar.commands.annotation.*;
import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XMaterial;
import com.ibm.icu.impl.Pair;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Powerable; import org.bukkit.block.data.Powerable;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -25,102 +25,285 @@ import tech.sbdevelopment.v10lift.utils.ConfigUtil;
import tech.sbdevelopment.v10lift.utils.WorldEditUtil; import tech.sbdevelopment.v10lift.utils.WorldEditUtil;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Optional; import java.sql.SQLException;
import java.util.*; import java.util.*;
@CommandAlias("v10lift|v10l") public class V10LiftCommand implements CommandExecutor {
@Description("The main command for V10Lift")
public class V10LiftCommand extends BaseCommand { @Override
@HelpCommand public boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command cmd, @Nonnull String label, @Nonnull String[] args) {
@CatchUnknown if (args.length == 0) {
@Default //v10lift
public static void onHelp(CommandSender sender, CommandHelp help) { return helpCommand(sender);
help.showHelp(); } else if (args[0].equalsIgnoreCase("info") && args.length == 1) {
//v10lift info
return infoCommand(sender);
} else if (args[0].equalsIgnoreCase("list") && args.length == 1) {
//v10lift list
if (sender.hasPermission("v10lift.list") || sender.hasPermission("v10lift.admin")) {
return listCommand(sender);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("create") && (args.length == 1 || args.length == 2)) {
//v10lift create || v10lift create <Name>
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return createCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("delete") && args.length == 2) {
//v10lift delete <Name>
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return deleteCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("edit") && (args.length == 1 || args.length == 2)) {
//v10lift edit <Name>
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return editCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("floor") && (args.length == 3 || args.length == 4)) {
//v10lift floor add <Name> || v10lift floor del <Name> || v10lift floor rename <Old> <New>
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return floorCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("input") && (args.length == 2 || args.length == 3)) {
//v10lift input add <Floor name> || v10lift input del
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return inputCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("offline") && args.length == 2) {
//v10lift offline add || v10lift offline del
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return offlineCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("rename") && args.length == 2) {
//v10lift rename <New name>
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return renameCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("build") && args.length == 1) {
//v10lift build
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return buildCommand(sender);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("build") && args.length == 2 && args[1].equalsIgnoreCase("worldedit")) {
//v10lift build worldedit
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
if (!V10LiftPlugin.isWorldEditEnabled()) {
ConfigUtil.sendMessage(sender, "Build.WorldEditNotEnabled");
return true;
} }
@Subcommand("info") return buildWorldEditCommand(sender);
@Description("Get information about the plugin") } else {
public void infoCommand(CommandSender sender) { ConfigUtil.sendMessage(sender, "General.NoPermission");
sender.sendMessage(ChatColor.DARK_GREEN + "V10Lift v" + V10LiftPlugin.getInstance().getDescription().getVersion()); }
sender.sendMessage(ChatColor.GREEN + "Made by SBDeveloper"); } else if (args[0].equalsIgnoreCase("rope") && args.length == 2) {
sender.sendMessage(ChatColor.GREEN + " "); //v10lift rope add || v10lift rope del
sender.sendMessage(ChatColor.GREEN + "Type /v10lift help for more information!"); if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return ropeCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("door") && (args.length == 1 || args.length == 2)) {
//v10lift door <Name> || v10lift door
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return doorCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("whitelist") && (args.length == 3 || args.length == 4)) {
//v10lift whitelist add <Player> <Floor> || v10lift whitelist del <Player> <Floor>
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return whitelistCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("whois") && (args.length == 1 || args.length == 2)) {
//v10lift whois || v10lift whois <Name>
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return whoisCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("speed") && (args.length == 2 || args.length == 3)) {
//v10lift speed <Speed> [Name]
if (args.length == 2 && !(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return speedCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("sound") && args.length == 1) {
//v10lift sound
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return soundCommand(sender);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("realistic") && args.length == 1) {
//v10lift realistic
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return realisticCommand(sender);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("abort") && args.length == 1) {
//v10lift abort
if (!(sender instanceof Player)) {
ConfigUtil.sendMessage(sender, "General.PlayerOnly");
return true;
}
if (sender.hasPermission("v10lift.build") || sender.hasPermission("v10lift.admin")) {
return abortCommand(sender);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("reload") && args.length == 1) {
//v10lift reload
if (sender.hasPermission("v10lift.reload") || sender.hasPermission("v10lift.admin")) {
return reloadCommand(sender);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("repair") && args.length == 2) {
//v10lift repair <Name>
if (sender.hasPermission("v10lift.repair") || sender.hasPermission("v10lift.admin")) {
return repairCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("disable") && args.length == 2) {
//v10lift disable <Name>
if (sender.hasPermission("v10lift.disable") || sender.hasPermission("v10lift.admin")) {
return disableCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("setoffline") && args.length == 3) {
//v10lift setoffline <Name> <State>
if (sender.hasPermission("v10lift.setoffline") || sender.hasPermission("v10lift.admin")) {
return setOfflineCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("start")) {
//v10lift start <Name> <Floor>
if (sender.hasPermission("v10lift.start") || sender.hasPermission("v10lift.admin")) {
return startCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else if (args[0].equalsIgnoreCase("stop")) {
//v10lift stop <Name>
if (sender.hasPermission("v10lift.stop") || sender.hasPermission("v10lift.admin")) {
return stopCommand(sender, args);
} else {
ConfigUtil.sendMessage(sender, "General.NoPermission");
}
} else {
return helpCommand(sender);
}
return true;
} }
@Subcommand("list") private boolean listCommand(CommandSender sender) {
@Description("List all lifts")
@CommandPermission("v10lift.list")
public void listCommand(CommandSender sender) {
//Send list of all lifts //Send list of all lifts
List<Lift> lifts = V10LiftPlugin.getApi().getLifts(); Map<String, Lift> lifts = DataManager.getLifts();
if (lifts.isEmpty()) { if (lifts.isEmpty()) {
ConfigUtil.sendMessage(sender, "List.NoLifts"); ConfigUtil.sendMessage(sender, "List.NoLifts");
return; return true;
} }
ConfigUtil.sendMessage(sender, "List.Header"); ConfigUtil.sendMessage(sender, "List.Header");
for (Lift lift : lifts) { for (String liftName : lifts.keySet()) {
ConfigUtil.sendMessage(sender, "List.Lift", Map.of("%Name%", lift.getName())); ConfigUtil.sendMessage(sender, "List.Lift", Map.of("%Name%", liftName));
} }
} return true;
@Subcommand("create")
@Description("Create a lift")
@CommandPermission("v10lift.admin")
@CommandCompletion("@nothing")
public void createCommand(Player p, @co.aikar.commands.annotation.Optional String name) {
if (DataManager.containsPlayer(p.getUniqueId())) {
//Already building!!
if (name == null) {
ConfigUtil.sendMessage(p, "General.IncorrectUsage", Collections.singletonMap("%Command%", "/v10lift create <Name>"));
return;
}
TreeSet<LiftBlock> blocks = DataManager.getPlayer(p.getUniqueId());
if (blocks.isEmpty()) {
ConfigUtil.sendMessage(p, "Create.NoBlocks");
return;
}
Lift lift = V10LiftPlugin.getApi().createLift(p, name);
if (lift == null) {
ConfigUtil.sendMessage(p, "General.AlreadyExists");
return;
}
blocks.forEach(block -> lift.addBlock(lift.getBlocks(), block));
lift.sortLiftBlocks();
DataManager.removePlayer(p.getUniqueId());
ConfigUtil.sendMessage(p, "Create.Created", Collections.singletonMap("%Name%", name));
p.performCommand("v10lift edit " + name);
} else {
//Not building yet!!
DataManager.addPlayer(p.getUniqueId());
ConfigUtil.sendMessage(p, "Create.AddBlocks");
}
}
@Subcommand("delete")
@Description("Delete a lift")
@CommandPermission("v10lift.admin")
@CommandCompletion("@lifts")
public void deleteCommand(Player p, Lift lift) {
if (!V10LiftPlugin.getApi().deleteLift(lift)) {
ConfigUtil.sendMessage(p, "Delete.NotRemoved", Collections.singletonMap("%Name%", lift.getName()));
return;
}
ConfigUtil.sendMessage(p, "Delete.Removed", Collections.singletonMap("%Name%", lift.getName()));
} }
private boolean setOfflineCommand(CommandSender sender, @Nonnull String[] args) { private boolean setOfflineCommand(CommandSender sender, @Nonnull String[] args) {
String liftName = args[1]; String liftName = args[1];
boolean newState = Boolean.parseBoolean(args[2]); boolean newState = Boolean.parseBoolean(args[2]);
Optional<Lift> liftOpt = V10LiftPlugin.getApi().getLift(liftName); if (!DataManager.containsLift(liftName)) {
if (liftOpt.isEmpty()) {
ConfigUtil.sendMessage(sender, "General.DoesntExists"); ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true; return true;
} }
Lift lift = liftOpt.get();
Lift lift = DataManager.getLift(liftName);
lift.setOffline(newState); lift.setOffline(newState);
@ -143,73 +326,74 @@ public class V10LiftCommand extends BaseCommand {
private boolean disableCommand(CommandSender sender, @Nonnull String[] args) { private boolean disableCommand(CommandSender sender, @Nonnull String[] args) {
String liftName = args[1]; String liftName = args[1];
Optional<Lift> liftOpt = V10LiftPlugin.getApi().getLift(liftName); if (!DataManager.containsLift(liftName)) {
if (liftOpt.isEmpty()) {
ConfigUtil.sendMessage(sender, "General.DoesntExists"); ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true; return true;
} }
Lift lift = liftOpt.get();
Lift lift = DataManager.getLift(liftName);
if (lift.isDefective()) { if (lift.isDefective()) {
ConfigUtil.sendMessage(sender, "Disable.AlreadyDefective"); ConfigUtil.sendMessage(sender, "Disable.AlreadyDefective");
return true; return true;
} }
lift.setDefective(true); V10LiftAPI.getInstance().setDefective(liftName, true);
ConfigUtil.sendMessage(sender, "Disable.Disabled"); ConfigUtil.sendMessage(sender, "Disable.Disabled");
return true; return true;
} }
private boolean stopCommand(CommandSender sender, @Nonnull String[] args) { private boolean stopCommand(CommandSender sender, @Nonnull String[] args) {
Optional<Lift> liftOpt; String liftName;
if (args.length == 1 && sender instanceof Player) { if (args.length == 1 && sender instanceof Player) {
//v10lift stop -> Get liftName from loc and floorName from sign //v10lift stop -> Get liftName from loc and floorName from sign
Player p = (Player) sender; Player p = (Player) sender;
liftOpt = V10LiftPlugin.getApi().getLift(p.getLocation()); liftName = V10LiftAPI.getInstance().getLiftByLocation(p.getLocation());
} else if (args.length == 1) { } else if (args.length == 1) {
ConfigUtil.sendMessage(sender, "Stop.NonPlayer"); ConfigUtil.sendMessage(sender, "Stop.NonPlayer");
return true; return true;
} else { } else {
liftOpt = V10LiftPlugin.getApi().getLift(args[1]); liftName = args[1];
} }
if (liftOpt.isEmpty()) { if (liftName == null || !DataManager.containsLift(liftName)) {
ConfigUtil.sendMessage(sender, "General.DoesntExists"); ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true; return true;
} }
Lift lift = liftOpt.get();
if (lift.getQueue().hasRequests()) lift.getQueue().empty(); Lift lift = DataManager.getLift(liftName);
if (!lift.getQueue().isEmpty()) lift.getQueue().clear();
if (!DataManager.containsMovingTask(lift.getName())) { if (!DataManager.containsMovingTask(liftName)) {
ConfigUtil.sendMessage(sender, "Stop.NoMovingTasks", Collections.singletonMap("%Name%", lift.getName())); ConfigUtil.sendMessage(sender, "Stop.NoMovingTasks", Collections.singletonMap("%Name%", liftName));
return true; return true;
} }
Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift.getName())); Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(liftName));
DataManager.removeMovingTask(lift.getName()); DataManager.removeMovingTask(liftName);
ConfigUtil.sendMessage(sender, "Stop.Stopped", Collections.singletonMap("%Name%", lift.getName())); ConfigUtil.sendMessage(sender, "Stop.Stopped", Collections.singletonMap("%Name%", liftName));
return true; return true;
} }
private boolean startCommand(CommandSender sender, @Nonnull String[] args) { private boolean startCommand(CommandSender sender, @Nonnull String[] args) {
Optional<Lift> liftOpt; String liftName;
if (args.length == 1 && sender instanceof Player) { if (args.length == 1 && sender instanceof Player) {
//v10lift stop -> Get liftName from loc and floorName from sign //v10lift start -> Get liftName from loc and floorName from sign
Player p = (Player) sender; Player p = (Player) sender;
liftOpt = V10LiftPlugin.getApi().getLift(p.getLocation()); liftName = V10LiftAPI.getInstance().getLiftByLocation(p.getLocation());
} else if (args.length == 1) { } else if (args.length == 1) {
ConfigUtil.sendMessage(sender, "Start.NonPlayer"); ConfigUtil.sendMessage(sender, "Start.NonPlayer");
return true; return true;
} else { } else {
liftOpt = V10LiftPlugin.getApi().getLift(args[1]); liftName = args[1];
} }
if (liftOpt.isEmpty()) { if (liftName == null || !DataManager.containsLift(liftName)) {
ConfigUtil.sendMessage(sender, "General.DoesntExists"); ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true; return true;
} }
Lift lift = liftOpt.get();
Lift lift = DataManager.getLift(liftName);
String floorName = null; String floorName = null;
if (args.length == 1 || args.length == 2) { if (args.length == 1 || args.length == 2) {
@ -234,19 +418,20 @@ public class V10LiftCommand extends BaseCommand {
} }
Floor f = lift.getFloors().get(floorName); Floor f = lift.getFloors().get(floorName);
lift.getQueue().requestFloor(floorName, f); V10LiftAPI.getInstance().addToQueue(liftName, f, floorName);
ConfigUtil.sendMessage(sender, "Start.Started", Collections.singletonMap("%Name%", lift.getName())); ConfigUtil.sendMessage(sender, "Start.Started", Collections.singletonMap("%Name%", liftName));
return true; return true;
} }
private boolean reloadCommand(CommandSender sender) { private boolean reloadCommand(CommandSender sender) {
for (Lift lift : V10LiftPlugin.getApi().getLifts()) { for (Map.Entry<String, Lift> e : DataManager.getLifts().entrySet()) {
if (DataManager.containsMovingTask(lift.getName())) { String lift = e.getKey();
Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift.getName())); if (DataManager.containsMovingTask(lift)) {
Bukkit.getScheduler().cancelTask(DataManager.getMovingTask(lift));
} }
lift.getQueue().empty(); e.getValue().setQueue(null);
lift.sortLiftBlocks(); V10LiftAPI.getInstance().sortLiftBlocks(lift);
} }
DataManager.clearMovingTasks(); DataManager.clearMovingTasks();
@ -254,7 +439,7 @@ public class V10LiftCommand extends BaseCommand {
try { try {
V10LiftPlugin.getDBManager().save(); V10LiftPlugin.getDBManager().save();
V10LiftPlugin.getDBManager().load(); V10LiftPlugin.getDBManager().load();
} catch (Exception e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -301,7 +486,7 @@ public class V10LiftCommand extends BaseCommand {
if (DataManager.containsBuilderPlayer(p.getUniqueId())) { if (DataManager.containsBuilderPlayer(p.getUniqueId())) {
DataManager.removeBuilderPlayer(p.getUniqueId()); DataManager.removeBuilderPlayer(p.getUniqueId());
V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get().sortLiftBlocks(); V10LiftAPI.getInstance().sortLiftBlocks(DataManager.getEditPlayer(p.getUniqueId()));
abort = true; abort = true;
} }
@ -330,12 +515,12 @@ public class V10LiftCommand extends BaseCommand {
private boolean repairCommand(CommandSender sender, @Nonnull String[] args) { private boolean repairCommand(CommandSender sender, @Nonnull String[] args) {
String liftName = args[1]; String liftName = args[1];
Optional<Lift> liftOpt = V10LiftPlugin.getApi().getLift(liftName); if (!DataManager.containsLift(liftName)) {
if (liftOpt.isEmpty()) {
ConfigUtil.sendMessage(sender, "General.DoesntExists"); ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true; return true;
} }
Lift lift = liftOpt.get();
Lift lift = DataManager.getLift(liftName);
if (!lift.isDefective()) { if (!lift.isDefective()) {
ConfigUtil.sendMessage(sender, "Repair.NotDefective"); ConfigUtil.sendMessage(sender, "Repair.NotDefective");
@ -368,7 +553,7 @@ public class V10LiftCommand extends BaseCommand {
} }
} }
} }
lift.setDefective(false); V10LiftAPI.getInstance().setDefective(liftName, false);
ConfigUtil.sendMessage(sender, "Repair.Repaired"); ConfigUtil.sendMessage(sender, "Repair.Repaired");
return true; return true;
} }
@ -380,7 +565,7 @@ public class V10LiftCommand extends BaseCommand {
return true; return true;
} }
Lift lift = V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get(); Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
lift.setRealistic(!lift.isRealistic()); lift.setRealistic(!lift.isRealistic());
if (lift.isRealistic()) { if (lift.isRealistic()) {
ConfigUtil.sendMessage(sender, "Realistic.TurnedOn"); ConfigUtil.sendMessage(sender, "Realistic.TurnedOn");
@ -397,7 +582,7 @@ public class V10LiftCommand extends BaseCommand {
return true; return true;
} }
Lift lift = V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get(); Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
lift.setSound(!lift.isSound()); lift.setSound(!lift.isSound());
if (lift.isSound()) { if (lift.isSound()) {
ConfigUtil.sendMessage(sender, "Sound.TurnedOn"); ConfigUtil.sendMessage(sender, "Sound.TurnedOn");
@ -410,11 +595,11 @@ public class V10LiftCommand extends BaseCommand {
private boolean speedCommand(CommandSender sender, @Nonnull String[] args) { private boolean speedCommand(CommandSender sender, @Nonnull String[] args) {
Lift lift; Lift lift;
if (args.length == 3) { if (args.length == 3) {
if (!V10LiftPlugin.getApi().isLift(args[2])) { if (!DataManager.containsLift(args[2])) {
ConfigUtil.sendMessage(sender, "General.DoesntExists"); ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true; return true;
} }
lift = V10LiftPlugin.getApi().getLift(args[2]).get(); lift = DataManager.getLift(args[2]);
} else { } else {
Player p = (Player) sender; Player p = (Player) sender;
if (!DataManager.containsEditPlayer(p.getUniqueId())) { if (!DataManager.containsEditPlayer(p.getUniqueId())) {
@ -422,7 +607,7 @@ public class V10LiftCommand extends BaseCommand {
return true; return true;
} }
lift = V10LiftPlugin.getApi().getLift(DataManager.getEditPlayer(p.getUniqueId())).get(); lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
} }
try { try {
@ -449,10 +634,10 @@ public class V10LiftCommand extends BaseCommand {
ConfigUtil.sendMessage(sender, "Whois.WithoutName"); ConfigUtil.sendMessage(sender, "Whois.WithoutName");
} else { } else {
String liftName = args[1]; String liftName = args[1];
if (!V10LiftPlugin.getApi().isLift(liftName)) { if (!DataManager.containsLift(liftName)) {
ConfigUtil.sendMessage(sender, "Whois.DoesntExists"); ConfigUtil.sendMessage(sender, "Whois.DoesntExists");
} else { } else {
V10LiftPlugin.getApi().getLift(liftName).get().sendInfo(sender); V10LiftAPI.getInstance().sendLiftInfo(sender, liftName);
} }
} }
return true; return true;
@ -960,4 +1145,100 @@ public class V10LiftCommand extends BaseCommand {
} }
return true; return true;
} }
private boolean deleteCommand(@Nonnull CommandSender sender, @Nonnull String[] args) {
Player p = (Player) sender;
if (!DataManager.containsLift(args[1])) {
ConfigUtil.sendMessage(sender, "General.DoesntExists");
return true;
}
Lift lift = DataManager.getLift(args[1]);
if (!lift.getOwners().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(sender, "General.NoPermission");
return true;
}
if (!V10LiftAPI.getInstance().removeLift(args[1])) {
ConfigUtil.sendMessage(sender, "Delete.NotRemoved", Collections.singletonMap("%Name%", args[1]));
return true;
}
ConfigUtil.sendMessage(sender, "Delete.Removed", Collections.singletonMap("%Name%", args[1]));
return true;
}
private boolean createCommand(@Nonnull CommandSender sender, @Nonnull String[] args) {
Player p = (Player) sender;
if (DataManager.containsPlayer(p.getUniqueId())) {
//Already building!!
if (args.length < 2) {
ConfigUtil.sendMessage(sender, "General.IncorrectUsage", Collections.singletonMap("%Command%", "/v10lift create <Name>"));
return true;
}
TreeSet<LiftBlock> blocks = DataManager.getPlayer(p.getUniqueId());
if (blocks.isEmpty()) {
ConfigUtil.sendMessage(sender, "Create.NoBlocks");
return true;
}
if (!V10LiftAPI.getInstance().createLift(p, args[1])) {
ConfigUtil.sendMessage(sender, "General.AlreadyExists");
return true;
}
TreeSet<LiftBlock> blcks = DataManager.getLift(args[1]).getBlocks();
blocks.forEach(block -> V10LiftAPI.getInstance().addBlockToLift(blcks, block));
V10LiftAPI.getInstance().sortLiftBlocks(args[1]);
DataManager.removePlayer(p.getUniqueId());
ConfigUtil.sendMessage(p, "Create.Created", Collections.singletonMap("%Name%", args[1]));
p.performCommand("v10lift edit " + args[1]);
} else {
//Not building yet!!
DataManager.addPlayer(p.getUniqueId());
ConfigUtil.sendMessage(p, "Create.AddBlocks");
}
return true;
}
private boolean infoCommand(@Nonnull CommandSender sender) {
sender.sendMessage("§1==================================");
sender.sendMessage("§6V10Lift plugin made by §aSBDeveloper");
sender.sendMessage("§6Version: " + V10LiftPlugin.getInstance().getDescription().getVersion());
sender.sendMessage("§6Type /v10lift help for more information!");
sender.sendMessage("§1==================================");
return true;
}
private boolean helpCommand(@Nonnull CommandSender sender) {
sender.sendMessage("§8V10Lift commands:");
sender.sendMessage("§6/v10lift info§f: Gives you information about the plugin.");
sender.sendMessage("§6/v10lift help§f: Gives you this help page.");
sender.sendMessage("§6/v10lift reload§f: Reload the plugin.");
sender.sendMessage("§6/v10lift create [Name]§f: Create a lift.");
sender.sendMessage("§6/v10lift delete <Name>§f: Delete a lift.");
sender.sendMessage("§6/v10lift rename <New name>§f: Rename a lift.");
sender.sendMessage("§6/v10lift abort§f: Abort your action.");
sender.sendMessage("§6/v10lift whois [Name]§f: See information about a lift.");
sender.sendMessage("§6/v10lift edit [Name]§f: Edit a lift.");
sender.sendMessage("§6/v10lift floor <add/del/rename> <Name> [New name]§f: Add/remove/rename a floor.");
sender.sendMessage("§6/v10lift input <add/del> [Floorname]§f: Add/remove an input.");
sender.sendMessage("§6/v10lift offline <add/del>§f: Add/remove an offline input.");
sender.sendMessage("§6/v10lift build§f: Add/remove blocks to/from a cab.");
sender.sendMessage("§6/v10lift rope <add/del>§f: Add/remove a rope.");
sender.sendMessage("§6/v10lift door§f: Add doors to a lift.");
sender.sendMessage("§6/v10lift speed <New speed>§f: Change the speed of a lift.");
sender.sendMessage("§6/v10lift realistic§f: Toggle realistic mode.");
sender.sendMessage("§6/v10lift repair§f: Repair a lift.");
sender.sendMessage("§6/v10lift whitelist <add/del> <Player/Group> [Floorname]§f: Add/remove someone of the whitelist. Use g:<Groupname> for a group.");
sender.sendMessage("§6/v10lift start [Name] [Floor]§f: Start a lift to a floor.");
sender.sendMessage("§6/v10lift stop [Name]§f: Stop a lift.");
sender.sendMessage("§6/v10lift disable <Name>§f: Disable a lift.");
sender.sendMessage("§6/v10lift repair <Name>§f: Repair a lift.");
return true;
}
} }

View file

@ -0,0 +1,98 @@
package tech.sbdevelopment.v10lift.commands;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.managers.DataManager;
import tech.sbdevelopment.v10lift.managers.VaultManager;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class V10LiftTabCompleter implements TabCompleter {
private static final List<String> COMMANDS = Arrays.asList("create", "delete", "rename", "abort", "whois", "edit", "floor", "input", "build", "rope", "door", "speed", "realistic", "repair", "disable", "whitelist", "reload", "help", "start", "stop", "offline", "list", "setoffline");
private static final List<String> SUBRENAME = Arrays.asList("add", "del", "rename");
private static final List<String> SUB = Arrays.asList("add", "del");
private static final List<String> BOOL = Arrays.asList("true", "false");
@Override
public List<String> onTabComplete(@Nonnull CommandSender commandSender, @Nonnull Command cmd, @Nonnull String label, @Nonnull String[] args) {
if (label.equalsIgnoreCase("v10lift")) {
if (args.length == 1) {
return StringUtil.copyPartialMatches(args[0], COMMANDS, new ArrayList<>());
} else if (args.length == 2) {
//Command based sub-commands
if (args[0].equalsIgnoreCase("delete")
|| args[0].equalsIgnoreCase("edit")
|| args[0].equalsIgnoreCase("whois")
|| args[0].equalsIgnoreCase("repair")
|| args[0].equalsIgnoreCase("disable")
|| args[0].equalsIgnoreCase("start")
|| args[0].equalsIgnoreCase("stop")) {
return StringUtil.copyPartialMatches(args[1], DataManager.getLifts().keySet(), new ArrayList<>());
} else if (args[0].equalsIgnoreCase("floor")) {
return StringUtil.copyPartialMatches(args[1], SUBRENAME, new ArrayList<>());
} else if (args[0].equalsIgnoreCase("input")
|| args[0].equalsIgnoreCase("offline")
|| args[0].equalsIgnoreCase("whitelist")
|| args[0].equalsIgnoreCase("rope")) {
return StringUtil.copyPartialMatches(args[1], SUB, new ArrayList<>());
} else if (args[0].equalsIgnoreCase("setoffline")) {
return StringUtil.copyPartialMatches(args[1], BOOL, new ArrayList<>());
} else if (args[0].equalsIgnoreCase("build") && V10LiftPlugin.isWorldEditEnabled()) {
return StringUtil.copyPartialMatches(args[1], List.of("worldedit"), new ArrayList<>());
}
} else if (args.length == 3) {
//Command based arguments
if (args[0].equalsIgnoreCase("floor") && (args[1].equalsIgnoreCase("del") || args[1].equalsIgnoreCase("rename"))) {
if (commandSender instanceof Player) {
Player p = (Player) commandSender;
if (DataManager.containsEditPlayer(p.getUniqueId())) {
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
return StringUtil.copyPartialMatches(args[2], lift.getFloors().keySet(), new ArrayList<>());
}
}
} else if ((args[0].equalsIgnoreCase("input")
|| args[0].equalsIgnoreCase("offline")) && args[1].equalsIgnoreCase("del")) {
if (commandSender instanceof Player) {
Player p = (Player) commandSender;
if (DataManager.containsEditPlayer(p.getUniqueId())) {
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
return StringUtil.copyPartialMatches(args[2], lift.getFloors().keySet(), new ArrayList<>());
}
}
} else if (args[0].equalsIgnoreCase("whitelist")) {
ArrayList<String> playerOrGroupNames = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
playerOrGroupNames.add(p.getName());
}
if (V10LiftPlugin.isVaultEnabled()) {
playerOrGroupNames.addAll(VaultManager.getGroups());
}
return StringUtil.copyPartialMatches(args[2], playerOrGroupNames, new ArrayList<>());
}
} else if (args.length == 4) {
//Command based arguments
if (args[0].equalsIgnoreCase("whitelist")) {
if (commandSender instanceof Player) {
Player p = (Player) commandSender;
if (DataManager.containsEditPlayer(p.getUniqueId())) {
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
return StringUtil.copyPartialMatches(args[3], lift.getFloors().keySet(), new ArrayList<>());
}
}
}
}
}
return null;
}
}

View file

@ -7,27 +7,31 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.api.V10LiftAPI;
import tech.sbdevelopment.v10lift.api.objects.Floor; import tech.sbdevelopment.v10lift.api.objects.Floor;
import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.api.objects.LiftBlock; import tech.sbdevelopment.v10lift.api.objects.LiftBlock;
import tech.sbdevelopment.v10lift.api.objects.LiftInput;
import tech.sbdevelopment.v10lift.managers.DataManager;
import tech.sbdevelopment.v10lift.utils.ConfigUtil; import tech.sbdevelopment.v10lift.utils.ConfigUtil;
import tech.sbdevelopment.v10lift.utils.DoorUtil; import tech.sbdevelopment.v10lift.utils.DoorUtil;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
public class BlockBreakListener implements Listener { public class BlockBreakListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e) { public void onBlockBreak(BlockBreakEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if (V10LiftPlugin.getApi().isRope(b)) { if (V10LiftAPI.getInstance().isRope(b)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveRopeFirst"); ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveRopeFirst");
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
LiftBlock tlb = new LiftBlock(b); LiftBlock tlb = new LiftBlock(b);
for (Lift lift : V10LiftPlugin.getApi().getLifts()) { for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
Lift lift = entry.getValue();
if (lift.getBlocks().contains(tlb)) { if (lift.getBlocks().contains(tlb)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveLiftFirst"); ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveLiftFirst");
e.setCancelled(true); e.setCancelled(true);

View file

@ -7,8 +7,6 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.V10LiftAPI;
import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.api.objects.LiftBlock; import tech.sbdevelopment.v10lift.api.objects.LiftBlock;
import tech.sbdevelopment.v10lift.managers.DataManager; import tech.sbdevelopment.v10lift.managers.DataManager;
@ -33,7 +31,7 @@ public class EntityDamageListener implements Listener {
int y = loc.getBlockY(); int y = loc.getBlockY();
int z = loc.getBlockZ(); int z = loc.getBlockZ();
for (Lift lift : V10LiftPlugin.getApi().getLifts()) { for (Lift lift : DataManager.getLifts().values()) {
for (LiftBlock lb : lift.getBlocks()) { for (LiftBlock lb : lift.getBlocks()) {
if (world.equals(lb.getWorld()) && x == lb.getX() && y == lb.getY() && z == lb.getZ()) { if (world.equals(lb.getWorld()) && x == lb.getX() && y == lb.getY() && z == lb.getZ()) {
e.setCancelled(true); e.setCancelled(true);

View file

@ -7,13 +7,11 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.block.SignChangeEvent;
import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.api.objects.LiftSign; import tech.sbdevelopment.v10lift.api.objects.LiftSign;
import tech.sbdevelopment.v10lift.managers.DataManager;
import tech.sbdevelopment.v10lift.utils.ConfigUtil; import tech.sbdevelopment.v10lift.utils.ConfigUtil;
import java.util.Optional;
public class SignChangeListener implements Listener { public class SignChangeListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@ -27,13 +25,12 @@ public class SignChangeListener implements Listener {
return; return;
} }
Optional<Lift> liftOpt = V10LiftPlugin.getApi().getLift(lines[1]); if (!DataManager.containsLift(lines[1])) {
if (liftOpt.isEmpty()) {
ConfigUtil.sendMessage(e.getPlayer(), "General.DoesntExists"); ConfigUtil.sendMessage(e.getPlayer(), "General.DoesntExists");
return; return;
} }
Lift lift = liftOpt.get();
Lift lift = DataManager.getLift(lines[1]);
if (!lift.getOwners().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) { if (!lift.getOwners().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoPermission"); ConfigUtil.sendMessage(e.getPlayer(), "General.NoPermission");
e.setCancelled(true); e.setCancelled(true);

View file

@ -1,66 +0,0 @@
package tech.sbdevelopment.v10lift.locale;
import co.aikar.commands.MessageType;
import co.aikar.locales.MessageKey;
import net.md_5.bungee.api.ChatColor;
import tech.sbdevelopment.v10lift.managers.ACFHandler;
import java.util.Map;
public class Locale {
private Locale() {
}
/**
* Get a translated message
*
* @param key the key to the message
* @return the translated message string
*/
public static String getMessage(Message key) {
return getMessage(key.getMessageKey());
}
/**
* Get a translated message
*
* @param msg the key to the message
* @return the translated message string
*/
public static String getMessage(MessageKey msg) {
String message = ACFHandler.getManager().formatMessage(null, MessageType.INFO, msg);
return ChatColor.translateAlternateColorCodes('&', message);
}
/**
* Get a translated message
*
* @param key the key to the message
* @param args the arguments to the message
* @return the translated message string
*/
public static String getMessage(Message key, Map<String, String> args) {
return getMessage(key.getMessageKey(), args);
}
/**
* Get a translated message
*
* @param msg the key to the message
* @param args the arguments to the message
* @return the translated message string
*/
public static String getMessage(MessageKey msg, Map<String, String> args) {
//Turn map into array (key, value, key, value, etc.)
String[] argsArray = new String[args.size() * 2];
int i = 0;
for (Map.Entry<String, String> entry : args.entrySet()) {
argsArray[i] = entry.getKey();
argsArray[i + 1] = entry.getValue();
i += 2;
}
String message = ACFHandler.getManager().formatMessage(null, MessageType.INFO, msg, argsArray);
return ChatColor.translateAlternateColorCodes('&', message);
}
}

View file

@ -1,144 +0,0 @@
package tech.sbdevelopment.v10lift.locale;
import co.aikar.locales.MessageKey;
import co.aikar.locales.MessageKeyProvider;
public enum Message implements MessageKeyProvider {
GENERAL_NOPERMISSION,
GENERAL_PLAYERONLY,
GENERAL_INCORRECTUSAGE,
GENERAL_INTERNALERROR,
GENERAL_DOESNTEXISTS,
GENERAL_ALREADYEXISTS,
GENERAL_SWITCHONEDIT,
GENERAL_DETECTIONFAILED,
GENERAL_FLOORDOESNTEXISTS,
GENERAL_NOWHITELISTPERMISSION,
GENERAL_NOFLOORS,
GENERAL_REMOVELIFFTFIRST,
GENERAL_REMOVEROPEFIRST,
GENERAL_REMOVEDOORFIRST,
CREATE_ADDBLOCKS,
CREATE_NOBLOCKS,
CREATE_CREATED,
DELETE_NOTREMOVED,
DELETE_REMOVED,
RENAME_RENAMED,
EDIT_STILLINEDITMODE,
EDIT_TURNEDON,
EDIT_TURNEDOFF,
FLOOR_TOHIGH,
FLOOR_ALREADYEXISTS,
FLOOR_DOESNTEXISTS,
FLOOR_ADDED,
FLOOR_REMOVED,
FLOOR_RENAMED,
INPUT_STILLADJUSTING,
INPUT_NOTHINGTOREMOVE,
INPUT_ALREADYADDED,
INPUT_NOINPUT,
INPUT_RIGHTCLICK,
INPUT_CREATED,
INPUT_REMOVED,
OFFLINEINPUT_STILLADJUSTING,
OFFLINEINPUT_NOTHINGTOREMOVE,
OFFLINEINPUT_ALREADYADDED,
OFFLINEINPUT_NOINPUT,
OFFLINEINPUT_RIGHTCLICK,
OFFLINEINPUT_CREATED,
OFFLINEINPUT_REMOVED,
BUILD_DISABLED,
BUILD_ENABLED,
BUILD_BLOCKADDED,
BUILD_BLOCKREMOVED,
BUILD_BLACKLISTEDMATERIAL,
BUILD_NOSELECTION,
BUILD_UNSUPPORTEDSELECTION,
BUILD_BLOCKSADDED,
BUILD_BLOCKSFAILED,
BUILD_WORLDEDITNOTENABLED,
ROPE_STILLADJUSTING,
ROPE_ONLYUP,
ROPE_ONLYONEMATERIAL,
ROPE_ALREADYAROPE,
ROPE_NOTAROPE,
ROPE_BLACKLISTEDMATERIAL,
ROPE_ADD,
ROPE_DELETE,
ROPE_CLICKONEND,
ROPE_PARTREMOVED,
ROPE_CREATED,
ROPE_REMOVED,
DOOR_BLACKLISTEDMATERIAL,
DOOR_DISABLED,
DOOR_ENABLED,
DOOR_CREATED,
DOOR_REMOVED,
WHITELIST_GROUP_VAULTNOTFOUND,
WHITELIST_GROUP_NOTFOUND,
WHITELIST_GROUP_ALREADYCONTAINS,
WHITELIST_GROUP_DOESNTCONTAINS,
WHITELIST_GROUP_ADDED,
WHITELIST_GROUP_REMOVED,
WHITELIST_PLAYER_NOTFOUND,
WHITELIST_PLAYER_ALREADYCONTAINS,
WHITELIST_PLAYER_DOESNTCONTAINS,
WHITELIST_PLAYER_ADDED,
WHITELIST_PLAYER_REMOVED,
WHOIS_USEWITHOUTNAME,
WHOIS_NOTALIFT,
WHOIS_WITHOUTNAME,
SPEED_WRONGSPEED,
SPEED_CHANGED,
SOUND_TURNEDON,
SOUND_TURNEDOFF,
REALISTIC_TURNEDON,
REALISTIC_TURNEDOFF,
DISABLE_ALREADYDEFECTIVE,
DISABLE_DISABLED,
REPAIR_NOTDEFECTIVE,
REPAIR_ITEMSNEEDED,
REPAIR_REPAIRED,
ABORT_NOTHINGTOCANCEL,
ABORT_CANCELLED,
RELOAD_RELOADED,
START_NONPLAYER,
START_STARTED,
STOP_NONPLAYER,
STOP_NOMOVINGTASKS,
STOP_STOPPED,
LIFTSIGN_NONAME,
LIFTSIGN_CREATED,
LIFTSIGN_REMOVED,
LIST_NOLIFTS,
LIST_HEADER,
LIST_LIFT,
SETOFFLINE_DISABLED,
SETOFFLINE_ENABLED;
private final MessageKey key;
Message() {
this.key = MessageKey.of(convertConstantToLanguageKey("v10lift." + this.name()));
}
@Override
public MessageKey getMessageKey() {
return this.key;
}
private static String convertConstantToLanguageKey(String constant) {
StringBuilder languageKey = new StringBuilder();
String[] words = constant.split("_");
for (int i = 0; i < words.length; i++) {
String word = words[i].toLowerCase();
if (i > 0) {
languageKey.append(".");
}
languageKey.append(word);
}
return languageKey.toString();
}
}

View file

@ -1,4 +0,0 @@
/**
* All the event listeners of V10Lift
*/
package tech.sbdevelopment.v10lift.locale;

View file

@ -1,61 +0,0 @@
package tech.sbdevelopment.v10lift.managers;
import co.aikar.commands.PaperCommandManager;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.plugin.java.JavaPlugin;
import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.commands.V10LiftCommand;
import tech.sbdevelopment.v10lift.sbutils.YamlFile;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ACFHandler {
private static final String[] defaultLanguages = new String[]{"en"};
private static final Pattern pattern = Pattern.compile("^lang_([a-z]{2})\\.yml$");
private ACFHandler() {
}
private static PaperCommandManager manager;
public static void init(JavaPlugin plugin) throws IOException {
manager = new PaperCommandManager(plugin);
manager.getCommandContexts().registerContext(Lift.class, c -> V10LiftPlugin.getApi().getLift(c.popFirstArg().toLowerCase()).orElse(null));
manager.getCommandCompletions().registerCompletion("lifts", c -> V10LiftPlugin.getApi().getLifts().stream().map(Lift::getName).collect(Collectors.toList()));
manager.registerCommand(new V10LiftCommand());
manager.enableUnstableAPI("help");
manager.getLocales().setDefaultLocale(Locale.forLanguageTag(V10LiftPlugin.getSConfig().getFile().getString("Locale")));
File localeDir = new File(plugin.getDataFolder(), "locale");
localeDir.mkdirs();
for (String lang : defaultLanguages) {
YamlFile file = new YamlFile("locale/lang_" + lang);
file.loadDefaults();
}
for (File file : localeDir.listFiles((dir, name) -> name.startsWith("lang_") && name.endsWith(".yml"))) {
Matcher matcher = pattern.matcher(file.getName());
if (!matcher.matches()) continue;
try {
manager.getLocales().loadYamlLanguageFile(file, Locale.forLanguageTag(matcher.group(1)));
} catch (IOException | InvalidConfigurationException e) {
plugin.getLogger().severe("Couldn't load the language file " + file.getName() + "!");
}
}
}
public static PaperCommandManager getManager() {
return manager;
}
}

View file

@ -1,64 +1,147 @@
package tech.sbdevelopment.v10lift.managers; package tech.sbdevelopment.v10lift.managers;
import org.bukkit.plugin.java.JavaPlugin; import com.google.gson.Gson;
import org.bukkit.Bukkit;
import tech.sbdevelopment.v10lift.V10LiftPlugin; import tech.sbdevelopment.v10lift.V10LiftPlugin;
import tech.sbdevelopment.v10lift.api.objects.Lift; import tech.sbdevelopment.v10lift.api.objects.Lift;
import tech.sbdevelopment.v10lift.sbutils.StormSQLiteDB; import tech.sbdevelopment.v10lift.sbutils.SQLiteDB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Collection; import java.util.Map;
/** /**
* The DBManager manages the database * The DBManager manages the database
*/ */
public class DBManager { public class DBManager {
private final StormSQLiteDB data; private static final Gson gson = new Gson();
private static SQLiteDB data;
private static Connection con;
/** /**
* Construct the database manager * Construct the database manager
* *
* @param plugin The plugin instance * @param name The name of the sqlite database file
* @param dbName The name of the sqlite database file
*/ */
public DBManager(JavaPlugin plugin, String dbName) { public DBManager(String name) {
data = new SQLiteDB(name);
try { try {
data = new StormSQLiteDB(plugin, dbName); con = data.getConnection();
String query = "CREATE TABLE IF NOT EXISTS lifts (liftName varchar(255) NOT NULL, liftData blob NOT NULL, UNIQUE (liftName))";
PreparedStatement statement = con.prepareStatement(query);
statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException("Couldn't connect to the database!", e); e.printStackTrace();
} }
} }
/** /**
* Load the database from data * Load the database from data
* *
* @throws Exception If the data couldn't be loaded * @throws SQLException If the SQL SELECT fails
*/ */
public void load() throws Exception { public void load() throws SQLException {
Collection<Lift> lifts = data.getStorm().buildQuery(Lift.class) String query = "SELECT * FROM lifts";
.execute() PreparedStatement statement = con.prepareStatement(query);
.join(); ResultSet liftSet = statement.executeQuery();
V10LiftPlugin.getApi().getLifts().addAll(lifts); while (liftSet.next()) {
} //Loading a lift...
/** /*
* Save the data to the database * @todo Fix migrating from 1.12.2- to 1.13+
* * - byte to Facing for signs
* @throws SQLException If the data couldn't be saved * - Facing opposite for ropes
* - New materials
*/ */
public void save() throws SQLException {
for (Lift lift : V10LiftPlugin.getApi().getLifts()) { byte[] blob = liftSet.getBytes("liftData");
data.getStorm().save(lift); String json = new String(blob);
Lift lift = gson.fromJson(json, Lift.class);
DataManager.addLift(liftSet.getString("liftName"), lift);
Bukkit.getLogger().info("[V10Lift] Loading lift " + liftSet.getString("liftName") + " from data...");
} }
} }
/** /**
* Remove a lift from the database * Remove a lift from data
* *
* @param lift The lift to remove * @param liftName The name of the lift
* @throws SQLException If the lift couldn't be removed
*/ */
public void remove(Lift lift) throws SQLException { public void remove(String liftName) {
data.getStorm().delete(lift); if (!DataManager.containsLift(liftName)) {
Bukkit.getLogger().info("[V10Lift] Removing lift " + liftName + " to data...");
Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> {
try {
String query = "DELETE FROM lifts WHERE liftName = ?";
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, liftName);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
}
/**
* Save all lifts to data
*/
public void save() {
for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
saveLift(entry.getKey(), entry.getValue(), true);
}
}
/**
* Save a lift to data
*
* @param liftName The name of the lift
* @param lift The lift itself
*/
public void saveLift(String liftName, Lift lift, boolean sync) {
Bukkit.getLogger().info("[V10Lift] Saving lift " + liftName + " to data...");
byte[] blob = gson.toJson(lift).getBytes();
if (sync) {
updateLift(liftName, blob);
} else {
Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> updateLift(liftName, blob));
}
}
/**
* Update a lift in data
*
* @param liftName The name of the lift
* @param liftData The JSON blob of the lift object
*/
private void updateLift(String liftName, byte[] liftData) {
try {
String query = "INSERT INTO lifts (liftName, liftData) VALUES (?, ?)";
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, liftName);
statement.setBytes(2, liftData);
statement.executeUpdate();
} catch (SQLException ignored) {
}
try {
String query2 = "UPDATE lifts SET liftData = ? WHERE liftName = ?";
PreparedStatement statement2 = con.prepareStatement(query2);
statement2.setBytes(1, liftData);
statement2.setString(2, liftName);
statement2.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} }
/** /**

View file

@ -7,6 +7,8 @@ import tech.sbdevelopment.v10lift.api.objects.LiftBlock;
import java.util.*; import java.util.*;
public class DataManager { public class DataManager {
/* A manager for general HashMaps */
@Getter private static final Map<String, Lift> lifts = new LinkedHashMap<>();
private static final Map<UUID, TreeSet<LiftBlock>> builds = new LinkedHashMap<>(); private static final Map<UUID, TreeSet<LiftBlock>> builds = new LinkedHashMap<>();
@Getter private static final Map<UUID, String> editors = new LinkedHashMap<>(); @Getter private static final Map<UUID, String> editors = new LinkedHashMap<>();
private static final Map<UUID, String> inputEdits = new LinkedHashMap<>(); private static final Map<UUID, String> inputEdits = new LinkedHashMap<>();
@ -20,6 +22,26 @@ public class DataManager {
private static final List<UUID> whoisReq = new ArrayList<>(); private static final List<UUID> whoisReq = new ArrayList<>();
private static final Map<String, Integer> movingTasks = new HashMap<>(); private static final Map<String, Integer> movingTasks = new HashMap<>();
/* HashMap methods */
// //
public static void addLift(String liftName, Lift lift) {
lifts.put(liftName, lift);
}
public static void removeLift(String liftName) {
lifts.remove(liftName);
}
public static boolean containsLift(String liftName) {
return lifts.containsKey(liftName);
}
public static Lift getLift(String liftName) {
return lifts.get(liftName);
}
// //
public static boolean containsPlayer(UUID player) { public static boolean containsPlayer(UUID player) {
return builds.containsKey(player); return builds.containsKey(player);
} }

View file

@ -0,0 +1,335 @@
package tech.sbdevelopment.v10lift.sbutils;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
/**
* A class to update/add new sections/keys to your config while keeping your current values and keeping your comments
* Algorithm:
* Read the new file and scan for comments and ignored sections, if ignored section is found it is treated as a comment.
* Read and write each line of the new config, if the old config has value for the given key it writes that value in the new config.
* If a key has an attached comment above it, it is written first.
*
* @author tchristofferson
*/
public class ConfigUpdater {
/**
* Update a yaml file from a resource inside your plugin jar
*
* @param plugin You plugin
* @param resourceName The yaml file name to update from, typically config.yml
* @param toUpdate The yaml file to update
* @param ignoredSections List of sections to ignore and copy from the current config
* @throws IOException If an IOException occurs
*/
public static void update(Plugin plugin, String resourceName, File toUpdate, List<String> ignoredSections) throws IOException {
BufferedReader newReader = new BufferedReader(new InputStreamReader(plugin.getResource(resourceName), StandardCharsets.UTF_8));
List<String> newLines = newReader.lines().collect(Collectors.toList());
newReader.close();
FileConfiguration oldConfig = YamlConfiguration.loadConfiguration(toUpdate);
FileConfiguration newConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource(resourceName)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toUpdate), StandardCharsets.UTF_8));
List<String> ignoredSectionsArrayList = new ArrayList<>(ignoredSections);
//ignoredSections can ONLY contain configurations sections
ignoredSectionsArrayList.removeIf(ignoredSection -> !newConfig.isConfigurationSection(ignoredSection));
DumperOptions options = new DumperOptions();
options.setSplitLines(false);
Yaml yaml = new Yaml(options);
Map<String, String> comments = parseComments(newLines, ignoredSectionsArrayList, oldConfig, yaml);
write(newConfig, oldConfig, comments, ignoredSectionsArrayList, writer, yaml);
}
//Write method doing the work.
//It checks if key has a comment associated with it and writes comment then the key and value
private static void write(FileConfiguration newConfig, FileConfiguration oldConfig, Map<String, String> comments, List<String> ignoredSections, BufferedWriter writer, Yaml yaml) throws IOException {
outer:
for (String key : newConfig.getKeys(true)) {
String[] keys = key.split("\\.");
String actualKey = keys[keys.length - 1];
String comment = comments.remove(key);
StringBuilder prefixBuilder = new StringBuilder();
int indents = keys.length - 1;
appendPrefixSpaces(prefixBuilder, indents);
String prefixSpaces = prefixBuilder.toString();
if (comment != null) {
writer.write(comment);//No \n character necessary, new line is automatically at end of comment
}
for (String ignoredSection : ignoredSections) {
if (key.startsWith(ignoredSection)) {
continue outer;
}
}
Object newObj = newConfig.get(key);
Object oldObj = oldConfig.get(key);
if (newObj instanceof ConfigurationSection && oldObj instanceof ConfigurationSection) {
//write the old section
writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) oldObj);
} else if (newObj instanceof ConfigurationSection) {
//write the new section, old value is no more
writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) newObj);
} else if (oldObj != null) {
//write the old object
write(oldObj, actualKey, prefixSpaces, yaml, writer);
} else {
//write new object
write(newObj, actualKey, prefixSpaces, yaml, writer);
}
}
String danglingComments = comments.get(null);
if (danglingComments != null) {
writer.write(danglingComments);
}
writer.close();
}
//Doesn't work with configuration sections, must be an actual object
//Auto checks if it is serializable and writes to file
private static void write(Object obj, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException {
if (obj instanceof ConfigurationSerializable) {
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(((ConfigurationSerializable) obj).serialize()));
} else if (obj instanceof String || obj instanceof Character) {
if (obj instanceof String) {
String s = (String) obj;
obj = s.replace("\n", "\\n");
}
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj));
} else if (obj instanceof List) {
writeList((List<?>) obj, actualKey, prefixSpaces, yaml, writer);
} else {
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj));
}
}
//Writes a configuration section
private static void writeSection(BufferedWriter writer, String actualKey, String prefixSpaces, ConfigurationSection section) throws IOException {
if (section.getKeys(false).isEmpty()) {
writer.write(prefixSpaces + actualKey + ": {}");
} else {
writer.write(prefixSpaces + actualKey + ":");
}
writer.write("\n");
}
//Writes a list of any object
private static void writeList(List<?> list, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException {
writer.write(getListAsString(list, actualKey, prefixSpaces, yaml));
}
private static String getListAsString(List<?> list, String actualKey, String prefixSpaces, Yaml yaml) {
StringBuilder builder = new StringBuilder(prefixSpaces).append(actualKey).append(":");
if (list.isEmpty()) {
builder.append(" []\n");
return builder.toString();
}
builder.append("\n");
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if (o instanceof String || o instanceof Character) {
builder.append(prefixSpaces).append("- '").append(o).append("'");
} else if (o instanceof List) {
builder.append(prefixSpaces).append("- ").append(yaml.dump(o));
} else {
builder.append(prefixSpaces).append("- ").append(o);
}
if (i != list.size()) {
builder.append("\n");
}
}
return builder.toString();
}
//Key is the config key, value = comment and/or ignored sections
//Parses comments, blank lines, and ignored sections
private static Map<String, String> parseComments(List<String> lines, List<String> ignoredSections, FileConfiguration oldConfig, Yaml yaml) {
Map<String, String> comments = new HashMap<>();
StringBuilder builder = new StringBuilder();
StringBuilder keyBuilder = new StringBuilder();
int lastLineIndentCount = 0;
outer:
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line != null && line.trim().startsWith("-"))
continue;
if (line == null || line.trim().equals("") || line.trim().startsWith("#")) {
builder.append(line).append("\n");
} else {
lastLineIndentCount = setFullKey(keyBuilder, i, lines, lastLineIndentCount);
for (String ignoredSection : ignoredSections) {
if (keyBuilder.toString().equals(ignoredSection)) {
Object value = oldConfig.get(keyBuilder.toString());
if (value instanceof ConfigurationSection)
appendSection(builder, (ConfigurationSection) value, new StringBuilder(getPrefixSpaces(lastLineIndentCount)), yaml);
continue outer;
}
}
if (keyBuilder.length() > 0) {
comments.put(keyBuilder.toString(), builder.toString());
builder.setLength(0);
}
}
}
if (builder.length() > 0) {
comments.put(null, builder.toString());
}
return comments;
}
private static void appendSection(StringBuilder builder, ConfigurationSection section, StringBuilder prefixSpaces, Yaml yaml) {
builder.append(prefixSpaces).append(getKeyFromFullKey(section.getCurrentPath())).append(":");
Set<String> keys = section.getKeys(false);
if (keys.isEmpty()) {
builder.append(" {}\n");
return;
}
builder.append("\n");
prefixSpaces.append(" ");
for (String key : keys) {
Object value = section.get(key);
String actualKey = getKeyFromFullKey(key);
if (value instanceof ConfigurationSection) {
appendSection(builder, (ConfigurationSection) value, prefixSpaces, yaml);
prefixSpaces.setLength(prefixSpaces.length() - 2);
} else if (value instanceof List) {
builder.append(getListAsString((List<?>) value, actualKey, prefixSpaces.toString(), yaml));
} else {
builder.append(prefixSpaces).append(actualKey).append(": ").append(yaml.dump(value));
}
}
}
//Check how many times spaces make a jump of at least two
private static int countIndents(int index, List<String> lines) {
int currentSpaces = getSpaces(lines.get(index));
int indents = 0;
for (int i = index - 1; i >= 0; i--) {
String line = lines.get(i);
if (line == null || line.trim().equals("")) continue;
int newSpaces = getSpaces(lines.get(i));
// differs at least two
if (newSpaces < currentSpaces - 1) {
indents++;
currentSpaces = newSpaces;
}
if (currentSpaces <= 1) break;
}
return indents;
}
private static int getSpaces(String line) {
int spaces = 0;
for (char c : line.toCharArray()) {
if (c == ' ') {
spaces += 1;
} else {
break;
}
}
return spaces;
}
//Ex. keyBuilder = key1.key2.key3 --> key1.key2
private static void removeLastKey(StringBuilder keyBuilder) {
String temp = keyBuilder.toString();
String[] keys = temp.split("\\.");
if (keys.length == 1) {
keyBuilder.setLength(0);
return;
}
temp = temp.substring(0, temp.length() - keys[keys.length - 1].length() - 1);
keyBuilder.setLength(temp.length());
}
private static String getKeyFromFullKey(String fullKey) {
String[] keys = fullKey.split("\\.");
return keys[keys.length - 1];
}
//Updates the keyBuilder and returns configLines number of indents
private static int setFullKey(StringBuilder keyBuilder, int index, List<String> configLines, int lastLineIndentCount) {
int currentIndents = countIndents(index, configLines);
String key = configLines.get(index).trim().split(":")[0];
if (keyBuilder.length() == 0) {
keyBuilder.append(key);
} else if (currentIndents == lastLineIndentCount) {
//Replace the last part of the key with current key
removeLastKey(keyBuilder);
if (keyBuilder.length() > 0) {
keyBuilder.append(".");
}
keyBuilder.append(key);
} else if (currentIndents > lastLineIndentCount) {
//Append current key to the keyBuilder
keyBuilder.append(".").append(key);
} else {
int difference = lastLineIndentCount - currentIndents;
for (int i = 0; i < difference + 1; i++) {
removeLastKey(keyBuilder);
}
if (keyBuilder.length() > 0) {
keyBuilder.append(".");
}
keyBuilder.append(key);
}
return currentIndents;
}
private static String getPrefixSpaces(int indents) {
return new String(new char[Math.max(0, indents)]).replace("\0", " ");
}
private static void appendPrefixSpaces(StringBuilder builder, int indents) {
builder.append(getPrefixSpaces(indents));
}
}

View file

@ -0,0 +1,89 @@
package tech.sbdevelopment.v10lift.sbutils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.bukkit.Bukkit;
import tech.sbdevelopment.v10lift.V10LiftPlugin;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class SQLiteDB {
private final String dbName;
private HikariDataSource source;
private Connection con;
/**
* Initialize a new connection
*
* @param dbName The database name
*/
public SQLiteDB(String dbName) {
this.dbName = dbName;
File dbFile = new File(V10LiftPlugin.getInstance().getDataFolder(), dbName + ".db");
if (!dbFile.exists()) {
try {
Bukkit.getLogger().info("[V10Lift] Generating the " + dbName + ".db!");
if (!dbFile.createNewFile()) {
Bukkit.getLogger().severe("[V10Lift] Couldn't generate the " + dbName + ".db!");
return;
}
} catch (IOException e) {
Bukkit.getLogger().info("[V10Lift] Couldn't generate the " + dbName + ".db!");
return;
}
}
HikariConfig config = new HikariConfig();
config.setPoolName("V10Lift");
config.setUsername(null);
config.setPassword(null);
config.setDriverClassName("org.sqlite.JDBC");
config.setConnectionTestQuery("SELECT 1");
config.setMaximumPoolSize(1);
Properties prop = new Properties();
prop.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss");
config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath());
config.setDataSourceProperties(prop);
this.source = new HikariDataSource(config);
try {
this.con = this.source.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Get the connection, to execute queries
* <p>
* CREATE TABLE - execute()
* SELECT - executeQuery()
* UPDATE - executeUpdate()
*
* @return Connection
*/
public Connection getConnection() {
return this.con;
}
/**
* Close the connection
*/
public void closeSource() {
Bukkit.getLogger().info("[V10Lift] Closing the database connection for " + dbName + ".db!");
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
this.source.close();
}
}

View file

@ -1,72 +0,0 @@
package tech.sbdevelopment.v10lift.sbutils;
import com.craftmend.storm.Storm;
import com.craftmend.storm.connection.hikaricp.HikariDriver;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
public class StormSQLiteDB {
private final JavaPlugin plugin;
private final String dbName;
private final Storm storm;
/**
* Initialize a new database source
*
* @param dbName The database name
*/
public StormSQLiteDB(JavaPlugin plugin, String dbName) throws SQLException {
this.plugin = plugin;
this.dbName = dbName;
File dbFile = new File(plugin.getDataFolder(), dbName + ".db");
if (!dbFile.exists()) {
try {
plugin.getLogger().info("Generating the " + dbName + ".db...");
if (!dbFile.createNewFile()) {
throw new IOException("Couldn't generate the " + dbName + ".db!");
}
} catch (IOException e) {
throw new RuntimeException("Couldn't generate the " + dbName + ".db!", e);
}
}
HikariConfig config = new HikariConfig();
config.setPoolName(plugin.getName());
config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath());
config.setUsername(null);
config.setPassword(null);
config.setDriverClassName("org.sqlite.JDBC");
config.setConnectionTestQuery("SELECT 1");
config.setMaxLifetime(60000);
config.setIdleTimeout(45000);
config.setMinimumIdle(10);
config.setMaximumPoolSize(50);
this.storm = new Storm(new HikariDriver(config));
}
/**
* Close the connection
*/
public void closeSource() {
plugin.getLogger().info("Closing the database connection for " + dbName + ".db...");
this.storm.getDriver().close();
}
/**
* Get the database connection
*
* @return The database connection
*/
public Storm getStorm() {
return storm;
}
}

View file

@ -1,5 +1,6 @@
package tech.sbdevelopment.v10lift.sbutils; package tech.sbdevelopment.v10lift.sbutils;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -11,62 +12,68 @@ import java.net.URL;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
/** /**
* Update checker class * Update class for SBDevelopment
* *
* @author Stijn [SBDeveloper] * @author Stijn [SBDeveloper]
* @version 2.1 [19-11-2021] - This class supports both the v2 Spiget and v2 SBDUpdate API
*
* <p>&copy; Stijn Bannink [stijnbannink23@gmail.com] - All rights reserved.</p>
* @since 05-03-2020 * @since 05-03-2020
* @version 2.2 [17-04-2022] - Added Polymart support
*/ */
public class UpdateManager { public class UpdateManager {
private static final String SPIGOT_API = "https://api.spigotmc.org/legacy/update.php?resource=%d"; private static final JsonParser parser = new JsonParser();
private static final String SPIGOT_API = "https://api.spiget.org/v2/resources/%s/versions/latest";
private static final String SPIGOT_DOWNLOAD = "https://api.spiget.org/v2/resources/%s/download"; private static final String SPIGOT_DOWNLOAD = "https://api.spiget.org/v2/resources/%s/download";
private static final String POLYMART_API = "https://api.polymart.org/v1/getResourceInfoSimple/?resource_id=%d&key=version"; private static final String SBDPLUGINS_API = "https://updates.sbdplugins.nl/api/v2/plugins/%d";
private static final String POLYMART_DOWNLOAD = "https://api.polymart.org/v1/requestUpdateURL/?inject_version=%d&resource_id=%d&user_id=%d&nonce=%d&download_agent=%d&download_time=%d&download_token=%s"; private static final String SBDPLUGINS_DOWNLOAD = "https://updates.sbdplugins.nl/api/v2/download/%d";
private final Plugin plugin; private final Plugin plugin;
private final Version currentVersion; private final Version currentVersion;
private final CheckType type;
//Spigot & Polymart
private final int resourceID; private final int resourceID;
private final CheckType type;
//Polymart only private final String license;
private int injector_version;
private int user_id;
private int nonce;
private int download_agent;
private int download_time;
private String download_token;
private BiConsumer<VersionResponse, Version> versionResponse; private BiConsumer<VersionResponse, Version> versionResponse;
private BiConsumer<DownloadResponse, String> downloadResponse; private BiConsumer<DownloadResponse, String> downloadResponse;
/** /**
* Construct a new UpdateManager * Construct a new UpdateManager for Spigot
* *
* @param plugin The plugin instance * @param plugin The javaplugin (Main class)
* @param resourceID The resourceID on spigot/sbdplugins
*/ */
public UpdateManager(Plugin plugin, CheckType type) { public UpdateManager(Plugin plugin, int resourceID) {
this.plugin = plugin; this.plugin = plugin;
this.currentVersion = new Version(plugin.getDescription().getVersion()); this.currentVersion = new Version(plugin.getDescription().getVersion());
this.type = type; this.resourceID = resourceID;
this.resourceID = Integer.parseInt("%%__RESOURCE__%%"); this.type = CheckType.SPIGOT;
if (type == CheckType.POLYMART_PAID) { this.license = null;
this.injector_version = Integer.parseInt("%%__INJECT_VER__%%");
this.user_id = Integer.parseInt("%%__USER__%%");
this.nonce = Integer.parseInt("%%__NONCE__%%");
this.download_agent = Integer.parseInt("%%__AGENT__%%");
this.download_time = Integer.parseInt("%%__TIMESTAMP__%%");
this.download_token = "%%__VERIFY_TOKEN__%%";
} }
/**
* Construct a new UpdateManager for SBDPlugins
*
* @param plugin The javaplugin (Main class)
* @param resourceID The resourceID on spigot/sbdplugins
* @param license The license for the download
*/
public UpdateManager(Plugin plugin, int resourceID, String license) {
this.plugin = plugin;
this.currentVersion = new Version(plugin.getDescription().getVersion());
this.resourceID = resourceID;
this.type = CheckType.SBDPLUGINS;
this.license = license;
} }
/** /**
* Handle the response given by check(); * Handle the response given by check();
*
* @param versionResponse The response * @param versionResponse The response
* @return The updatemanager * @return The updatemanager
*/ */
@ -86,16 +93,23 @@ public class UpdateManager {
public void check() { public void check() {
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
try { try {
HttpsURLConnection con; BufferedReader in = null;
if (type == CheckType.POLYMART_PAID) { if (type == CheckType.SPIGOT) {
con = (HttpsURLConnection) new URL(String.format(POLYMART_API, this.resourceID)).openConnection(); HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection();
} else {
con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection();
}
con.setRequestMethod("GET"); con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "SBDChecker/2.1"); con.setRequestProperty("User-Agent", "Mozilla/5.0");
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else if (type == CheckType.SBDPLUGINS) {
HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_API, this.resourceID)).openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
}
if (in == null) return;
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine; String inputLine;
StringBuilder response = new StringBuilder(); StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) { while ((inputLine = in.readLine()) != null) {
@ -103,7 +117,10 @@ public class UpdateManager {
} }
in.close(); in.close();
Version onlineVersion = new Version(response.toString()); String version = parser.parse(response.toString()).getAsJsonObject().get(type == CheckType.SPIGOT ? "name" : "version").getAsString();
if (version == null) return;
Version onlineVersion = new Version(version);
VersionResponse verRes = this.currentVersion.check(onlineVersion); VersionResponse verRes = this.currentVersion.check(onlineVersion);
@ -136,16 +153,35 @@ public class UpdateManager {
ReadableByteChannel channel; ReadableByteChannel channel;
try { try {
//https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java //https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java
int response;
InputStream stream;
HttpsURLConnection connection; HttpsURLConnection connection;
if (type == CheckType.POLYMART_PAID) { if (type == CheckType.SBDPLUGINS) {
connection = (HttpsURLConnection) new URL(String.format(POLYMART_DOWNLOAD, this.injector_version, this.resourceID, this.user_id, this.nonce, this.download_agent, this.download_time, this.download_token)).openConnection(); connection = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_DOWNLOAD, this.resourceID)).openConnection();
String urlParameters = "license=" + license + "&port=" + Bukkit.getPort();
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postData);
wr.close();
} else { } else {
connection = (HttpsURLConnection) new URL(String.format(SPIGOT_DOWNLOAD, this.resourceID)).openConnection(); connection = (HttpsURLConnection) new URL(String.format(SPIGOT_DOWNLOAD, this.resourceID)).openConnection();
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("User-Agent", "Mozilla/5.0");
}
InputStream stream = connection.getInputStream(); response = connection.getResponseCode();
if (connection.getResponseCode() != 200) { stream = connection.getInputStream();
if (response != 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(stream)); BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine; String inputLine;
@ -155,7 +191,7 @@ public class UpdateManager {
} }
in.close(); in.close();
throw new RuntimeException("Download returned status #" + connection.getResponseCode(), new Throwable(responsestr.toString())); throw new RuntimeException("Download returned status #" + response, new Throwable(responsestr.toString()));
} }
channel = Channels.newChannel(stream); channel = Channels.newChannel(stream);
@ -198,7 +234,9 @@ public class UpdateManager {
} }
private File getPluginFile() { private File getPluginFile() {
if (!(this.plugin instanceof JavaPlugin)) { return null; } if (!(this.plugin instanceof JavaPlugin)) {
return null;
}
try { try {
Method method = JavaPlugin.class.getDeclaredMethod("getFile"); Method method = JavaPlugin.class.getDeclaredMethod("getFile");
method.setAccessible(true); method.setAccessible(true);
@ -208,8 +246,8 @@ public class UpdateManager {
} }
} }
public enum CheckType { private enum CheckType {
SPIGOT, POLYMART_PAID SPIGOT, SBDPLUGINS
} }
public enum VersionResponse { public enum VersionResponse {
@ -227,18 +265,18 @@ public class UpdateManager {
private final String version; private final String version;
public final String get() {
return this.version;
}
private Version(String version) { private Version(String version) {
if(version == null) if (version == null)
throw new IllegalArgumentException("Version can not be null"); throw new IllegalArgumentException("Version can not be null");
if(!version.matches("[0-9]+(\\.[0-9]+)*")) if (!version.matches("[0-9]+(\\.[0-9]+)*"))
throw new IllegalArgumentException("Invalid version format"); throw new IllegalArgumentException("Invalid version format");
this.version = version; this.version = version;
} }
public final String get() {
return this.version;
}
private VersionResponse check(Version that) { private VersionResponse check(Version that) {
String[] thisParts = this.get().split("\\."); String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\."); String[] thatParts = that.get().split("\\.");
@ -247,9 +285,9 @@ public class UpdateManager {
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0;
if(thisPart < thatPart) if (thisPart < thatPart)
return VersionResponse.FOUND_NEW; return VersionResponse.FOUND_NEW;
if(thisPart > thatPart) if (thisPart > thatPart)
return VersionResponse.THIS_NEWER; return VersionResponse.THIS_NEWER;
} }
return VersionResponse.LATEST; return VersionResponse.LATEST;

View file

@ -26,14 +26,14 @@ public class ConfigUtil {
} }
/** /**
* Send a message from the lang_en.yml without variables * Send a message from the messages.yml without variables
* *
* @param p The commandsender to send it to * @param p The commandsender to send it to
* @param path The path to look for * @param path The path to look for
*/ */
public static void sendMessage(CommandSender p, @Nonnull String path) { public static void sendMessage(CommandSender p, @Nonnull String path) {
if (V10LiftPlugin.getMessages().getFile().get(path) == null) { if (V10LiftPlugin.getMessages().getFile().get(path) == null) {
throw new NullPointerException("Message " + path + " not found in lang_en.yml!"); throw new NullPointerException("Message " + path + " not found in messages.yml!");
} }
if (V10LiftPlugin.getMessages().getFile().isList(path)) { if (V10LiftPlugin.getMessages().getFile().isList(path)) {
@ -48,7 +48,7 @@ public class ConfigUtil {
} }
/** /**
* Get a message from the lang_en.yml with variables * Get a message from the messages.yml with variables
* *
* @param p The commandsender to send it to * @param p The commandsender to send it to
* @param path The path to look for * @param path The path to look for
@ -56,7 +56,7 @@ public class ConfigUtil {
*/ */
public static void sendMessage(CommandSender p, @Nonnull String path, Map<String, String> replacement) { public static void sendMessage(CommandSender p, @Nonnull String path, Map<String, String> replacement) {
if (V10LiftPlugin.getMessages().getFile().get(path) == null) { if (V10LiftPlugin.getMessages().getFile().get(path) == null) {
throw new NullPointerException("Message " + path + " not found in lang_en.yml!"); throw new NullPointerException("Message " + path + " not found in messages.yml!");
} }
if (V10LiftPlugin.getMessages().getFile().isList(path)) { if (V10LiftPlugin.getMessages().getFile().isList(path)) {

View file

@ -1,6 +1,3 @@
# The language to use for the messages
Locale: en
# Generic sign texts # Generic sign texts
SignText: "[v10lift]" SignText: "[v10lift]"
DefectText: "&kDefect!" DefectText: "&kDefect!"

View file

@ -1,147 +0,0 @@
v10lift:
general:
nopermission: '&cYou don''t have the permission to do this.'
playeronly: '&cOnly players can do this.'
incorrectusage: '&cPlease use %Command% instead'
internalerror: '&cSomething went wrong internally.'
doesntexists: '&cThere are no lifts with that name.'
alreadyexists: '&cA lift with that name already exists.'
switchonedit: '&cEnable editor mode before doing this.'
detectionfailed: '&cAutomatic floor detection failed!'
floordoesntexists: '&cThe floor %Name% doesn''t exists!'
nowhitelistpermission: '&cYou can''t go to that floor!'
nofloors: '&cThis elevator has no floors!'
removeliftfirst: '&cYou can''t do this! Remove the lift first.'
removeropefirst: '&cYou can''t do this! Remove the rope first.'
removedoorfirst: '&cYou can''t do this! Remove the door first.'
create:
addblocks: >
&aOkay, now add all the blocks from the cab by right-clicking them.
&awhen finished, type: /v10lift create <Name>
noblocks: '&cYou must add blocks first.'
created: '&aSuccessfully created lift %Name%.'
delete:
notremoved: '&cThe lift %Name% couldn''t be removed.'
removed: '&aSuccessfully removed lift %Name%.'
rename:
renamed: '&aLift successfully renamed!'
edit:
stillineditmode: '&cYou are still in editor mode.'
turnedon: '&aEnabled editor.'
turnedoff: '&aDisabled editor.'
floor:
tohigh: '&cThat floor is too high!'
alreadyexists: '&cThat floor already exists!'
doesntexists: '&cThat floor doesn''t exists!'
added: '&aFloor successfully added!'
removed: '&aFloor successfully removed!'
renamed: '&aFloor successfully renamed!'
input:
stilladjusting: '&cYou are still adjusting an input!'
nothingtoremove: '&cThere is no input to remove!'
alreadyadded: '&cThis block has already been chosen as an input. Choose another block!'
noinput: '&cThis block is not an input. Choose another block!'
rightclick: '&aNow right click on the input block!'
created: '&aInput created!'
removed: '&aInput removed!'
offlineinput:
stilladjusting: '&cYou are still adjusting an offline input!'
nothingtoremove: '&cThere is no offline input to remove!'
alreadyadded: '&cThis block has already been chosen as an offline input. Choose another block!'
noinput: '&cThis block is not an offline input. Choose another block!'
rightclick: '&aNow right click on the offline input block!'
created: '&aOffline input created!'
removed: '&aOffline input removed!'
build:
disabled: '&aConstruction mode disabled!'
enabled: >
&aNow right-click on the elevator blocks!
&aThen do /v10lift build to save it!
blockadded: '&aBlock added to the elevator.'
blockremoved: '&6Block removed from the elevator.'
blacklistedmaterial: '&cThe material %Name% cannot be used!'
noselection: '&cYou must select a region with the WorldEdit wand first!'
unsupportedselection: '&cThe selection must be cuboid or polygonal!'
blocksadded: '&aBlocks added to the elevator.'
blocksfailed: '&cNot all blocks could be added to the elevator. Failure amount: %Failed%'
worldeditnotenabled: '&cWorldEdit is not enabled on this server!'
rope:
stilladjusting: '&cYou are still adjusting a rope.'
onlyup: '&cA rope can only go up!'
onlyonematerial: '&cThe rope must be of the same material!'
alreadyarope: '&cPart of the rope is already part of another rope!'
notarope: '&cThis block is not part of the rope.'
blacklistedmaterial: '&cThe rope is built of blacklisted blocks!'
add: '&aNow right-click on the beginning and the end of the rope.'
delete: '&aNow right-click on the rope.'
clickonend: '&6Now right-click on the end of the rope!'
partremoved: >
&6Start removed!
&6Now right-click on the end of the rope!
created: '&aRope created.'
removed: '&aRope removed.'
door:
blacklistedmaterial: '&cThe material %Name% is currently not supported!'
disabled: '&aDoor editor mode disabled!'
enabled: >
&aNow right-click on the door blocks! (If they are real doors, click on the bottom block)
&aThen do /v10lift door to save it.
created: '&aDoor created.'
removed: '&6Door removed.'
whitelist:
group:
vaultnotfound: '&cYou can''t add a group when Vault is not found.'
notfound: '&cThe group %Name% is not found.'
alreadycontains: '&cThe whitelist already contains this group!'
doesntcontains: '&cThe whitelist doesn''t contain this group!'
added: '&aGroup added to whitelist!'
removed: '&aGroup removed from whitelist!'
player:
notfound: '&cThe player %Name% could not be found.'
alreadycontains: '&cThis user is already on the whitelist'
doesntcontains: '&cThis user isn''t on the whitelist'
added: '&aUser added to whitelist!'
removed: '&aUser removed from whitelist!'
whois:
usewithoutname: '&cYou need to be a player to use this command without a name.'
notalift: '&cThis block is not part of a lift.'
withoutname: '&aNow right-click on the block you want to check.'
speed:
wrongspeed: '&cThe speed %Speed% is incorrect.'
changed: '&aUpdated lift speed!'
sound:
turnedon: '&aSounds are now turned on!'
turnedoff: '&aSounds are now turned off!'
realistic:
turnedon: '&aRealistic mode turned on!'
turnedoff: '&aRealistic mode turned off!'
disable:
alreadydefective: '&cThis lift is already defective!'
disabled: '&aLift disabled!'
repair:
notdefective: '&cThis lift isn''t defective!'
itemsneeded: '&cYou need %Amount%x %ItemName%!'
repaired: '&aYou successfully repaired the lift!'
abort:
nothingtocancel: '&cOops! You can''t cancel anything.'
cancelled: '&6Cancelled.'
reload:
reloaded: '&6Plugin reloaded successfully!'
start:
nonplayer: '&cPlease give a name as a non-player!'
started: '&aLift %Name% started.'
stop:
nonplayer: '&cPlease give a name as a non-player!'
nomovingtasks: '&cLift %Name% doesn''t contain any moving tasks!'
started: '&aLift %Name% stopped.'
liftsign:
noname: '&cNo lift name given!'
created: '&aLift sign created!'
removed: '&6Lift sign removed!'
list:
nolifts: '&cThere are no lifts!'
header: '&6Lifts:'
lift: '&6- %Name%'
setoffline:
disabled: '&aThe lift is now offline!'
enabled: '&aThe lift is now online!'

View file

@ -0,0 +1,175 @@
General:
NoPermission: '&cYou don''t have the permission to do this.'
PlayerOnly: '&cOnly players can do this.'
IncorrectUsage: '&cPlease use %Command% instead'
InternalError: '&cSomething went wrong internally.'
DoesntExists: '&cThere are no lifts with that name.'
AlreadyExists: '&cA lift with that name already exists.'
SwitchOnEdit: '&cEnable editor mode before doing this.'
DetectionFailed: '&cAutomatic floor detection failed!'
FloorDoesntExists: '&cThe floor %Name% doesn''t exists!'
NoWhitelistPermission: '&cYou can''t go to that floor!'
NoFloors: '&cThis elevator has no floors!'
RemoveLiftFirst: '&cYou can''t do this! Remove the lift first.'
RemoveRopeFirst: '&cYou can''t do this! Remove the rope first.'
RemoveDoorFirst: '&cYou can''t do this! Remove the door first.'
Create:
AddBlocks: |-
&aOkay, now add all the blocks from the cab by right-clicking them.
&awhen finished, type: /v10lift create <Name>
NoBlocks: '&cYou must add blocks first.'
Created: '&aSuccessfully created lift %Name%.'
Delete:
NotRemoved: '&cThe lift %Name% couldn''t be removed.'
Removed: '&aSuccessfully removed lift %Name%.'
Rename:
Renamed: '&aLift successfully renamed!'
Edit:
StillInEditMode: '&cYou are still in editor mode.'
TurnedOn: '&aEnabled editor.'
TurnedOff: '&aDisabled editor.'
Floor:
ToHigh: '&cThat floor is too high!'
AlreadyExists: '&cThat floor already exists!'
DoesntExists: '&cThat floor doesn''t exists!'
Added: '&aFloor successfully added!'
Removed: '&aFloor successfully removed!'
Renamed: '&aFloor successfully renamed!'
Input:
StillAdjusting: '&cYou are still adjusting an input!'
NothingToRemove: '&cThere is no input to remove!'
AlreadyAdded: '&cThis block has already been chosen as an input. Choose another
block!'
NoInput: '&cThis block is not an input. Choose another block!'
RightClick: '&aNow right click on the input block!'
Created: '&aInput created!'
Removed: '&aInput removed!'
OfflineInput:
StillAdjusting: '&cYou are still adjusting an offline input!'
NothingToRemove: '&cThere is no offline input to remove!'
AlreadyAdded: '&cThis block has already been chosen as an offline input. Choose
another block!'
NoInput: '&cThis block is not an offline input. Choose another block!'
RightClick: '&aNow right click on the offline input block!'
Created: '&aOffline input created!'
Removed: '&aOffline input removed!'
Build:
Disabled: '&aConstruction mode disabled!'
Enabled: |-
&aNow right-click on the elevator blocks!
&aThen do /v10lift build to save it!
BlockAdded: '&aBlock added to the elevator.'
BlockRemoved: '&6Block removed from the elevator.'
BlacklistedMaterial: '&cThe material %Name% cannot be used!'
NoSelection: '&cYou must select a region with the WorldEdit wand first!'
UnsupportedSelection: '&cThe selection must be cuboid or polygonal!'
BlocksAdded: '&aBlocks added to the elevator.'
BlocksFailed: '&cNot all blocks could be added to the elevator. Failure amount: %Failed%'
WorldEditNotEnabled: '&cWorldEdit is not enabled on this server!'
Rope:
StillAdjusting: '&cYou are still adjusting a rope.'
OnlyUp: '&cA rope can only go up!'
OnlyOneMaterial: '&cThe rope must be of the same material!'
AlreadyARope: '&cPart of the rope is already part of another rope!'
NotARope: '&cThis block is not part of the rope.'
BlacklistedMaterial: '&cThe rope is build of blacklisted blocks!'
Add: '&aNow right-click on the beginning and the end of the rope.'
Delete: '&aNow right-click on the rope.'
ClickOnEnd: '&6Now right-click on the end of the rope!'
PartRemoved: |-
&6Start removed!
&6Now right-click on the end of the rope!
Created: '&aRope created.'
Removed: '&aRope removed.'
Door:
BlacklistedMaterial: '&cThe material %Name% is currently not supported!'
Disabled: '&aDoor editor mode disabled!'
Enabled: |-
&aNow right-click on the door blocks! (If it are real doors, click on the bottom block)
&aThen do /v10lift door to save it.
Created: '&aDoor created.'
Removed: '&6Door removed.'
Whitelist:
Group:
VaultNotFound: '&cYou can''t add a group when Vault is not found.'
NotFound: '&cThe group %Name% is not found.'
AlreadyContains: '&cThe whitelist already contains this group!'
DoesntContains: '&cThe whitelist doesn''t contain this group!'
Added: '&aGroup added to whitelist!'
Removed: '&aGroup removed from whitelist!'
Player:
NotFound: '&cThe player %Name% could not be found.'
AlreadyContains: '&cThis user is already on the whitelist'
DoesntContains: '&cThis user isn''t on the whitelist'
Added: '&aUser added to whitelist!'
Removed: '&aUser removed from whitelist!'
Whois:
UseWithoutName: '&cYou need to be a player to use this command without name.'
NotALift: '&cThis block is not part of a lift.'
WithoutName: '&aNow right-click on the block you want to check.'
Speed:
WrongSpeed: '&cThe speed %Speed% is incorrect.'
Changed: '&aUpdated lift speed!'
Sound:
TurnedOn: '&aSounds are now turned on!'
TurnedOff: '&aSounds are now turned off!'
Realistic:
TurnedOn: '&aRealistic mode turned on!'
TurnedOff: '&aRealistic mode turned off!'
Disable:
AlreadyDefective: '&cThis lift is already defective!'
Disabled: '&aLift disabled!'
Repair:
NotDefective: '&cThis lift isn''t defective!'
ItemsNeeded: '&cYou need %Amount%x %ItemName%!'
Repaired: '&aYou successfully repaired the lift!'
Abort:
NothingToCancel: '&cOops! You can''t cancel anything.'
Cancelled: '&6Cancelled.'
Reload:
Reloaded: '&6Plugin reloaded successfully!'
Start:
NonPlayer: '&cPlease give a name as non-player!'
Started: '&aLift %Name% started.'
Stop:
NonPlayer: '&cPlease give a name as non-player!'
NoMovingTasks: '&cLift %Name% doesn''t contain any movingtasks!'
Started: '&aLift %Name% stopped.'
LiftSign:
NoName: '&cNo lift name given!'
Created: '&aLift sign created!'
Removed: '&6Lift sign removed!'
List:
NoLifts: '&cThere are no lifts!'
Header: '&6Lifts:'
Lift: '&6- %Name%'
SetOffline:
Disabled: '&aThe lift is now offline!'
Enabled: '&aThe lift is now online!'

View file

@ -4,3 +4,26 @@ version: ${project.version}
api-version: "1.13" api-version: "1.13"
author: SBDeveloper author: SBDeveloper
softdepend: ["Vault", "WorldEdit"] softdepend: ["Vault", "WorldEdit"]
commands:
v10lift:
description: The V10Lift Command
permissions:
v10lift.admin:
description: The full power admin permission
default: op
v10lift.build:
description: The permission to build a lift
v10lift.reload:
description: Reload the plugin
v10lift.repair:
description: Repair a lift
v10lift.disable:
description: Disable a lift
v10lift.start:
description: Start a lift
v10lift.stop:
description: Stop a lift
v10lift.list:
description: List all lifts
v10lift.setoffline:
description: Set a lift offline / online