diff --git a/ansible/build.gradle.kts b/ansible/build.gradle.kts index 18a20dc42..f2d2bfbaf 100644 --- a/ansible/build.gradle.kts +++ b/ansible/build.gradle.kts @@ -4,6 +4,7 @@ val proxyPlugin by configurations.creating dependencies { paperPlugin(project(path = ":plugins:banstick-paper", configuration = "reobf")) paperPlugin(project(path = ":plugins:bastion-paper", configuration = "reobf")) + paperPlugin(project(path = ":plugins:castlegates-paper", configuration = "reobf")) paperPlugin(project(path = ":plugins:citadel-paper", configuration = "reobf")) paperPlugin(project(path = ":plugins:civchat2-paper", configuration = "reobf")) paperPlugin(project(path = ":plugins:civduties-paper", configuration = "reobf")) diff --git a/ansible/src/paper-plugins/castlegates-paper-2.0.2.jar b/ansible/src/paper-plugins/castlegates-paper-2.0.2.jar deleted file mode 100644 index f51c30441..000000000 Binary files a/ansible/src/paper-plugins/castlegates-paper-2.0.2.jar and /dev/null differ diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/LICENSE b/plugins/castlegates-paper/LICENSE similarity index 99% rename from plugins/castlegates-paper/plugins/castlegates-paper/LICENSE rename to plugins/castlegates-paper/LICENSE index 5e7128b4f..490b5c70e 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/LICENSE +++ b/plugins/castlegates-paper/LICENSE @@ -1,53 +1,53 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and -You must cause any modified files to carry prominent notices stating that You changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. - -You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/README.md b/plugins/castlegates-paper/README.md similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/README.md rename to plugins/castlegates-paper/README.md index fb97e279e..12c278832 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/README.md +++ b/plugins/castlegates-paper/README.md @@ -1,26 +1,26 @@ -# CastleGates: - -Allows to create retractable bridges and gates. -Supports Citadel, Bastion and Orebfuscator plugins. - -### Requirements: -- Java 1.6 / 1.7 / 1.8 -- Spigot/PaperSpigot and any other fork of CraftBukkit - -#### Copyright and License: - -Copyright 2016 Aleksey Terzi. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -See the LICENSE file. +# CastleGates: + +Allows to create retractable bridges and gates. +Supports Citadel, Bastion and Orebfuscator plugins. + +### Requirements: +- Java 1.6 / 1.7 / 1.8 +- Spigot/PaperSpigot and any other fork of CraftBukkit + +#### Copyright and License: + +Copyright 2016 Aleksey Terzi. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +See the LICENSE file. diff --git a/plugins/castlegates-paper/build.gradle.kts b/plugins/castlegates-paper/build.gradle.kts new file mode 100644 index 000000000..0039e305a --- /dev/null +++ b/plugins/castlegates-paper/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + id("io.papermc.paperweight.userdev") +} + +version = "2.0.2" + +dependencies { + paperweight { + paperDevBundle("1.20.4-R0.1-SNAPSHOT") + } + + compileOnly(project(":plugins:civmodcore-paper")) + compileOnly(project(":plugins:namelayer-paper")) + compileOnly(project(":plugins:citadel-paper")) + compileOnly(project(":plugins:bastion-paper")) + compileOnly(project(":plugins:jukealert-paper")) +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/.gitignore b/plugins/castlegates-paper/plugins/castlegates-paper/.gitignore deleted file mode 100644 index e28109765..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -/target/ -.classpath -.settings/** -.project -.idea -*.iml -/bin/ -.gradle -build diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/build.gradle.kts b/plugins/castlegates-paper/plugins/castlegates-paper/build.gradle.kts deleted file mode 100644 index 43da0c460..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/build.gradle.kts +++ /dev/null @@ -1,29 +0,0 @@ -import net.civmc.civgradle.CivGradleExtension - -plugins { - id("net.civmc.civgradle") version "2.+" apply false -} - -subprojects { - apply(plugin = "java-library") - apply(plugin = "maven-publish") - apply(plugin = "net.civmc.civgradle") - - configure { - pluginName = project.property("pluginName") as String - } - - repositories { - mavenCentral() - maven("https://repo.civmc.net/repository/maven-public") - maven("https://repo.codemc.io/repository/maven-public/") - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/CivMC/NameLayer") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } -} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/gradle.properties b/plugins/castlegates-paper/plugins/castlegates-paper/gradle.properties deleted file mode 100644 index 2d0208197..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/gradle.properties +++ /dev/null @@ -1,7 +0,0 @@ -# Gradle properties -group = com.aleksey.castlegates -version = 2.0.2 -description = CastleGates - -# Custom Properties -pluginName = CastleGates diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/gradle/wrapper/gradle-wrapper.jar b/plugins/castlegates-paper/plugins/castlegates-paper/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 7454180f2..000000000 Binary files a/plugins/castlegates-paper/plugins/castlegates-paper/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/gradle/wrapper/gradle-wrapper.properties b/plugins/castlegates-paper/plugins/castlegates-paper/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 84d1f85fd..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/gradlew b/plugins/castlegates-paper/plugins/castlegates-paper/gradlew deleted file mode 100644 index c53aefaa5..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/gradlew.bat b/plugins/castlegates-paper/plugins/castlegates-paper/gradlew.bat deleted file mode 100644 index 107acd32c..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/build.gradle.kts b/plugins/castlegates-paper/plugins/castlegates-paper/paper/build.gradle.kts deleted file mode 100644 index 386862ec4..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/build.gradle.kts +++ /dev/null @@ -1,19 +0,0 @@ -plugins { - id("io.papermc.paperweight.userdev") -} - -civGradle { - paper { - pluginName = "CastleGates" - } -} - -dependencies { - paperDevBundle("1.18.2-R0.1-SNAPSHOT") - - compileOnly("net.civmc.civmodcore:paper:2.0.0-SNAPSHOT:dev-all") - compileOnly("net.civmc.namelayer:paper:3.0.0-SNAPSHOT:dev") - compileOnly("net.civmc.citadel:paper:5.0.0-SNAPSHOT:dev") - compileOnly("net.civmc.bastion:paper:3.0.0-SNAPSHOT:dev") - compileOnly("net.civmc.jukealert:paper:3.0.0-SNAPSHOT:dev") -} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/settings.gradle.kts b/plugins/castlegates-paper/plugins/castlegates-paper/settings.gradle.kts deleted file mode 100644 index 85e384b57..000000000 --- a/plugins/castlegates-paper/plugins/castlegates-paper/settings.gradle.kts +++ /dev/null @@ -1,12 +0,0 @@ -pluginManagement { - repositories { - gradlePluginPortal() - maven("https://repo.civmc.net/repository/maven-public/") - maven("https://papermc.io/repo/repository/maven-public/") - } -} - -rootProject.name = "castlegates" - -include(":paper") -project(":paper").name = rootProject.name + "-paper" diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/CastleGates.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/CastleGates.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/CastleGates.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/CastleGates.java index 9893ce230..70b6d38b7 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/CastleGates.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/CastleGates.java @@ -1,154 +1,154 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.aleksey.castlegates.engine.CastleGatesManager; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.java.JavaPlugin; - -import com.aleksey.castlegates.plugins.bastion.BastionManager; -import com.aleksey.castlegates.plugins.bastion.IBastionManager; -import com.aleksey.castlegates.plugins.bastion.NoBastionManager; -import com.aleksey.castlegates.plugins.citadel.CitadelManager; -import com.aleksey.castlegates.plugins.citadel.ICitadelManager; -import com.aleksey.castlegates.plugins.citadel.NoCitadelManager; -import com.aleksey.castlegates.command.CastleGatesCommand; -import com.aleksey.castlegates.database.SqlDatabase; -import com.aleksey.castlegates.plugins.jukealert.IJukeAlertManager; -import com.aleksey.castlegates.plugins.jukealert.JukeAlertManager; -import com.aleksey.castlegates.plugins.jukealert.NoJukeAlertManager; -import com.aleksey.castlegates.listener.BlockListener; -import com.aleksey.castlegates.listener.EntityListener; -import com.aleksey.castlegates.config.ConfigManager; - -public class CastleGates extends JavaPlugin { - private static CastleGates _instance; - public static CastleGates getInstance() { - return _instance; - } - - private static CastleGatesManager _manager; - public static CastleGatesManager getManager() { - return _manager; - } - - private static ConfigManager _configManager; - public static ConfigManager getConfigManager() { - return _configManager; - } - - private static ICitadelManager _citadelManager; - public static ICitadelManager getCitadelManager() { - return _citadelManager; - } - - private static IBastionManager _bastionManager; - public static IBastionManager getBastionManager() { - return _bastionManager; - } - - private static IJukeAlertManager _jukeAlertManager; - public static IJukeAlertManager getJukeAlertManager() { - return _jukeAlertManager; - } - - public static Logger getPluginLogger() { - return _instance.getLogger(); - } - - @Override - public void onEnable() { - _instance = this; - _manager = new CastleGatesManager(); - _configManager = new ConfigManager(getLogger()); - - enableCivPlugins(); - - // Load configurations - _configManager.load(getConfig()); - saveConfig(); - - SqlDatabase db = initDatabase(); - - if(db == null) return; - - if(!_manager.init(db)) - return; - - _citadelManager.init(); - - // register events - getServer().getPluginManager().registerEvents(new EntityListener(), this); - getServer().getPluginManager().registerEvents(new BlockListener(), this); - } - - private void enableCivPlugins() { - if(getServer().getPluginManager().getPlugin("Citadel") != null) { - _citadelManager = new CitadelManager(); - getLogger().log(Level.INFO, "Citadel plugin found."); - } else { - _citadelManager = new NoCitadelManager(); - getLogger().log(Level.INFO, "Citadel plugin NOT found."); - } - - if(getServer().getPluginManager().getPlugin("JukeAlert") != null) { - _jukeAlertManager = new JukeAlertManager(); - getLogger().log(Level.INFO, "JukeAlert plugin found."); - } else { - _jukeAlertManager = new NoJukeAlertManager(); - getLogger().log(Level.INFO, "JukeAlert plugin NOT found."); - } - - if(getServer().getPluginManager().getPlugin("Bastion") != null) { - _bastionManager = new BastionManager(); - _bastionManager.init(); - getLogger().log(Level.INFO, "Bastion plugin found."); - } else { - _bastionManager = new NoBastionManager(); - getLogger().log(Level.INFO, "Bastion plugin NOT found."); - } - } - - private SqlDatabase initDatabase() { - SqlDatabase db = new SqlDatabase( - _configManager.getDatabase().host, - _configManager.getDatabase().port, - _configManager.getDatabase().db, - _configManager.getDatabase().user, - _configManager.getDatabase().password, - getLogger() - ); - - if(!db.connect()) return null; - - if(!db.initDb()) { - db.close(); - return null; - } - - return db; - } - - @Override - public void onDisable() { - _manager.close(); - _citadelManager.close(); - getServer().getScheduler().cancelTasks(this); - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - return CastleGatesCommand.onCommand(sender, command, label, args); - } - - public static void runTask(Runnable task) { - _instance.getServer().getScheduler().runTask(_instance, task); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.aleksey.castlegates.engine.CastleGatesManager; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.java.JavaPlugin; + +import com.aleksey.castlegates.plugins.bastion.BastionManager; +import com.aleksey.castlegates.plugins.bastion.IBastionManager; +import com.aleksey.castlegates.plugins.bastion.NoBastionManager; +import com.aleksey.castlegates.plugins.citadel.CitadelManager; +import com.aleksey.castlegates.plugins.citadel.ICitadelManager; +import com.aleksey.castlegates.plugins.citadel.NoCitadelManager; +import com.aleksey.castlegates.command.CastleGatesCommand; +import com.aleksey.castlegates.database.SqlDatabase; +import com.aleksey.castlegates.plugins.jukealert.IJukeAlertManager; +import com.aleksey.castlegates.plugins.jukealert.JukeAlertManager; +import com.aleksey.castlegates.plugins.jukealert.NoJukeAlertManager; +import com.aleksey.castlegates.listener.BlockListener; +import com.aleksey.castlegates.listener.EntityListener; +import com.aleksey.castlegates.config.ConfigManager; + +public class CastleGates extends JavaPlugin { + private static CastleGates _instance; + public static CastleGates getInstance() { + return _instance; + } + + private static CastleGatesManager _manager; + public static CastleGatesManager getManager() { + return _manager; + } + + private static ConfigManager _configManager; + public static ConfigManager getConfigManager() { + return _configManager; + } + + private static ICitadelManager _citadelManager; + public static ICitadelManager getCitadelManager() { + return _citadelManager; + } + + private static IBastionManager _bastionManager; + public static IBastionManager getBastionManager() { + return _bastionManager; + } + + private static IJukeAlertManager _jukeAlertManager; + public static IJukeAlertManager getJukeAlertManager() { + return _jukeAlertManager; + } + + public static Logger getPluginLogger() { + return _instance.getLogger(); + } + + @Override + public void onEnable() { + _instance = this; + _manager = new CastleGatesManager(); + _configManager = new ConfigManager(getLogger()); + + enableCivPlugins(); + + // Load configurations + _configManager.load(getConfig()); + saveConfig(); + + SqlDatabase db = initDatabase(); + + if(db == null) return; + + if(!_manager.init(db)) + return; + + _citadelManager.init(); + + // register events + getServer().getPluginManager().registerEvents(new EntityListener(), this); + getServer().getPluginManager().registerEvents(new BlockListener(), this); + } + + private void enableCivPlugins() { + if(getServer().getPluginManager().getPlugin("Citadel") != null) { + _citadelManager = new CitadelManager(); + getLogger().log(Level.INFO, "Citadel plugin found."); + } else { + _citadelManager = new NoCitadelManager(); + getLogger().log(Level.INFO, "Citadel plugin NOT found."); + } + + if(getServer().getPluginManager().getPlugin("JukeAlert") != null) { + _jukeAlertManager = new JukeAlertManager(); + getLogger().log(Level.INFO, "JukeAlert plugin found."); + } else { + _jukeAlertManager = new NoJukeAlertManager(); + getLogger().log(Level.INFO, "JukeAlert plugin NOT found."); + } + + if(getServer().getPluginManager().getPlugin("Bastion") != null) { + _bastionManager = new BastionManager(); + _bastionManager.init(); + getLogger().log(Level.INFO, "Bastion plugin found."); + } else { + _bastionManager = new NoBastionManager(); + getLogger().log(Level.INFO, "Bastion plugin NOT found."); + } + } + + private SqlDatabase initDatabase() { + SqlDatabase db = new SqlDatabase( + _configManager.getDatabase().host, + _configManager.getDatabase().port, + _configManager.getDatabase().db, + _configManager.getDatabase().user, + _configManager.getDatabase().password, + getLogger() + ); + + if(!db.connect()) return null; + + if(!db.initDb()) { + db.close(); + return null; + } + + return db; + } + + @Override + public void onDisable() { + _manager.close(); + _citadelManager.close(); + getServer().getScheduler().cancelTasks(this); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + return CastleGatesCommand.onCommand(sender, command, label, args); + } + + public static void runTask(Runnable task) { + _instance.getServer().getScheduler().runTask(_instance, task); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/command/CastleGatesCommand.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/command/CastleGatesCommand.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/command/CastleGatesCommand.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/command/CastleGatesCommand.java index b4a74dd8a..e03703af7 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/command/CastleGatesCommand.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/command/CastleGatesCommand.java @@ -1,141 +1,141 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.command; - -import com.aleksey.castlegates.types.TimerMode; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.types.CommandMode; -import com.aleksey.castlegates.types.TimerOperation; -import com.aleksey.castlegates.utils.Helper; - -public class CastleGatesCommand { - public static boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (!(sender instanceof Player player)) { - if(args.length != 1 || !args[0].equalsIgnoreCase("reload")) return false; - CastleGates.getManager().reinit(); - return true; - } - - CommandMode mode; - - if(command.getName().equalsIgnoreCase("gear")) { - mode = CommandMode.CREATE; - } else if(command.getName().equalsIgnoreCase("link")) { - mode = CommandMode.LINK; - } else if(args.length == 0){ - return false; - } else { - switch(args[0].toLowerCase()) { - case "timer": - return setTimeMode(player, args); - case "normal": - mode = CommandMode.NORMAL; - break; - case "create": - mode = CommandMode.CREATE; - break; - case "link": - mode = CommandMode.LINK; - break; - case "info": - mode = CommandMode.INFO; - break; - default: - return false; - } - - if (args.length != 1) return false; - } - - CastleGates.getManager().setPlayerMode(player, mode, null, null, null); - - return true; - } - - private static boolean setTimeMode(Player player, String[] args) { - if(args.length > 4) return false; - - Integer timer; - TimerOperation timerOperation; - TimerMode timerMode; - - if(args.length == 2 && args[1].equalsIgnoreCase("door")) { - timer = 1; - timerOperation = TimerOperation.UNDRAW; - timerMode = TimerMode.DOOR; - } else { - timer = args.length > 1 - ? parseTimerTimeout(args[1], player) - : (Integer) CastleGates.getConfigManager().getTimerDefault(); - - if (timer == null) return true; - - timerOperation = CastleGates.getConfigManager().getTimerDefaultOperation(); - timerMode = TimerMode.DEFAULT; - - if(args.length > 2) { - if(args.length == 4 || !args[2].equalsIgnoreCase("door")) { - timerOperation = Helper.parseTimerOperation(args[2]); - - if (timerOperation == null) { - player.sendMessage(ChatColor.RED + "Allowed timer operations are draw, undraw and revert."); - return true; - } - } - - if(args.length == 4 || args[2].equalsIgnoreCase("door")) { - if(args.length == 4) { - if(!args[3].equalsIgnoreCase("door")) { - player.sendMessage(ChatColor.RED + "Allowed timer mode is door."); - return true; - } - } else { - timerOperation = TimerOperation.UNDRAW; - } - - timerMode = TimerMode.DOOR; - } - } - } - - CastleGates.getManager().setPlayerMode(player, CommandMode.TIMER, timer, timerOperation, timerMode); - - return true; - } - - private static Integer parseTimerTimeout(String text, Player player) { - int timer; - - try { - timer = Integer.parseInt(text); - } - catch(NumberFormatException ex) { - return null; - } - - if(timer < CastleGates.getConfigManager().getTimerMin() - || timer > CastleGates.getConfigManager().getTimerMax() - ) - { - String errorMessage = "Timer interval is limited to the value between " - + CastleGates.getConfigManager().getTimerMin() - + " and " - + CastleGates.getConfigManager().getTimerMax() - + " sec"; - - player.sendMessage(ChatColor.RED + errorMessage); - - return null; - } - - return timer; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.command; + +import com.aleksey.castlegates.types.TimerMode; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.types.CommandMode; +import com.aleksey.castlegates.types.TimerOperation; +import com.aleksey.castlegates.utils.Helper; + +public class CastleGatesCommand { + public static boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (!(sender instanceof Player player)) { + if(args.length != 1 || !args[0].equalsIgnoreCase("reload")) return false; + CastleGates.getManager().reinit(); + return true; + } + + CommandMode mode; + + if(command.getName().equalsIgnoreCase("gear")) { + mode = CommandMode.CREATE; + } else if(command.getName().equalsIgnoreCase("link")) { + mode = CommandMode.LINK; + } else if(args.length == 0){ + return false; + } else { + switch(args[0].toLowerCase()) { + case "timer": + return setTimeMode(player, args); + case "normal": + mode = CommandMode.NORMAL; + break; + case "create": + mode = CommandMode.CREATE; + break; + case "link": + mode = CommandMode.LINK; + break; + case "info": + mode = CommandMode.INFO; + break; + default: + return false; + } + + if (args.length != 1) return false; + } + + CastleGates.getManager().setPlayerMode(player, mode, null, null, null); + + return true; + } + + private static boolean setTimeMode(Player player, String[] args) { + if(args.length > 4) return false; + + Integer timer; + TimerOperation timerOperation; + TimerMode timerMode; + + if(args.length == 2 && args[1].equalsIgnoreCase("door")) { + timer = 1; + timerOperation = TimerOperation.UNDRAW; + timerMode = TimerMode.DOOR; + } else { + timer = args.length > 1 + ? parseTimerTimeout(args[1], player) + : (Integer) CastleGates.getConfigManager().getTimerDefault(); + + if (timer == null) return true; + + timerOperation = CastleGates.getConfigManager().getTimerDefaultOperation(); + timerMode = TimerMode.DEFAULT; + + if(args.length > 2) { + if(args.length == 4 || !args[2].equalsIgnoreCase("door")) { + timerOperation = Helper.parseTimerOperation(args[2]); + + if (timerOperation == null) { + player.sendMessage(ChatColor.RED + "Allowed timer operations are draw, undraw and revert."); + return true; + } + } + + if(args.length == 4 || args[2].equalsIgnoreCase("door")) { + if(args.length == 4) { + if(!args[3].equalsIgnoreCase("door")) { + player.sendMessage(ChatColor.RED + "Allowed timer mode is door."); + return true; + } + } else { + timerOperation = TimerOperation.UNDRAW; + } + + timerMode = TimerMode.DOOR; + } + } + } + + CastleGates.getManager().setPlayerMode(player, CommandMode.TIMER, timer, timerOperation, timerMode); + + return true; + } + + private static Integer parseTimerTimeout(String text, Player player) { + int timer; + + try { + timer = Integer.parseInt(text); + } + catch(NumberFormatException ex) { + return null; + } + + if(timer < CastleGates.getConfigManager().getTimerMin() + || timer > CastleGates.getConfigManager().getTimerMax() + ) + { + String errorMessage = "Timer interval is limited to the value between " + + CastleGates.getConfigManager().getTimerMin() + + " and " + + CastleGates.getConfigManager().getTimerMax() + + " sec"; + + player.sendMessage(ChatColor.RED + errorMessage); + + return null; + } + + return timer; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/config/ConfigDefaults.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/config/ConfigDefaults.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/config/ConfigDefaults.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/config/ConfigDefaults.java index 925a9f8a1..c416c2ef9 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/config/ConfigDefaults.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/config/ConfigDefaults.java @@ -1,240 +1,240 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.config; - -import org.bukkit.Material; - -public class ConfigDefaults { - public static final String[] gearMaterials = new String[] { - Material.STONE.name(), - Material.GRASS.name(), - Material.DIRT.name(), - Material.COBBLESTONE.name(), - - Material.OAK_WOOD.name(), - Material.OAK_LOG.name(), - Material.OAK_PLANKS.name(), - Material.OAK_STAIRS.name(), - Material.OAK_FENCE.name(), - Material.OAK_SLAB.name(), - Material.STRIPPED_OAK_LOG.name(), - Material.STRIPPED_OAK_WOOD.name(), - - Material.SPRUCE_WOOD.name(), - Material.SPRUCE_LOG.name(), - Material.SPRUCE_PLANKS.name(), - Material.SPRUCE_STAIRS.name(), - Material.SPRUCE_FENCE.name(), - Material.SPRUCE_SLAB.name(), - Material.STRIPPED_SPRUCE_LOG.name(), - Material.STRIPPED_SPRUCE_WOOD.name(), - - Material.BIRCH_WOOD.name(), - Material.BIRCH_LOG.name(), - Material.BIRCH_PLANKS.name(), - Material.BIRCH_STAIRS.name(), - Material.BIRCH_FENCE.name(), - Material.BIRCH_SLAB.name(), - Material.STRIPPED_BIRCH_LOG.name(), - Material.STRIPPED_BIRCH_WOOD.name(), - - Material.JUNGLE_WOOD.name(), - Material.JUNGLE_LOG.name(), - Material.JUNGLE_PLANKS.name(), - Material.JUNGLE_STAIRS.name(), - Material.JUNGLE_FENCE.name(), - Material.JUNGLE_SLAB.name(), - Material.STRIPPED_JUNGLE_LOG.name(), - Material.STRIPPED_JUNGLE_WOOD.name(), - - Material.ACACIA_WOOD.name(), - Material.ACACIA_LOG.name(), - Material.ACACIA_PLANKS.name(), - Material.ACACIA_STAIRS.name(), - Material.ACACIA_FENCE.name(), - Material.ACACIA_SLAB.name(), - Material.STRIPPED_ACACIA_LOG.name(), - Material.STRIPPED_ACACIA_WOOD.name(), - - Material.DARK_OAK_WOOD.name(), - Material.DARK_OAK_LOG.name(), - Material.DARK_OAK_PLANKS.name(), - Material.DARK_OAK_STAIRS.name(), - Material.DARK_OAK_FENCE.name(), - Material.DARK_OAK_SLAB.name(), - Material.STRIPPED_DARK_OAK_LOG.name(), - Material.STRIPPED_DARK_OAK_WOOD.name(), - - Material.GLASS.name(), - Material.LAPIS_BLOCK.name(), - Material.SANDSTONE.name(), - - Material.WHITE_WOOL.name(), - Material.ORANGE_WOOL.name(), - Material.MAGENTA_WOOL.name(), - Material.LIGHT_BLUE_WOOL.name(), - Material.YELLOW_WOOL.name(), - Material.LIME_WOOL.name(), - Material.PINK_WOOL.name(), - Material.GRAY_WOOL.name(), - Material.LIGHT_GRAY_WOOL.name(), - Material.CYAN_WOOL.name(), - Material.PURPLE_WOOL.name(), - Material.BLUE_WOOL.name(), - Material.BROWN_WOOL.name(), - Material.GREEN_WOOL.name(), - Material.RED_WOOL.name(), - Material.BLACK_WOOL.name(), - - Material.GOLD_BLOCK.name(), - Material.IRON_BLOCK.name(), - Material.BRICK.name(), - Material.MOSSY_COBBLESTONE.name(), - Material.MOSSY_COBBLESTONE_SLAB.name(), - Material.OBSIDIAN.name(), - Material.DIAMOND_BLOCK.name(), - Material.COBBLESTONE_STAIRS.name(), - Material.COBBLESTONE_SLAB.name(), - Material.ICE.name(), - Material.SNOW_BLOCK.name(), - Material.CLAY.name(), - Material.NETHERRACK.name(), - Material.GLOWSTONE.name(), - Material.SMOOTH_STONE.name(), - Material.IRON_BARS.name(), - Material.BRICK_STAIRS.name(), - Material.NETHER_BRICK.name(), - Material.NETHER_BRICK_STAIRS.name(), - Material.SANDSTONE_STAIRS.name(), - Material.EMERALD_BLOCK.name(), - Material.REDSTONE_BLOCK.name(), - Material.QUARTZ_BLOCK.name(), - Material.QUARTZ_STAIRS.name(), - Material.ACACIA_STAIRS.name(), - Material.DARK_OAK_STAIRS.name(), - Material.HAY_BLOCK.name(), - Material.COAL_BLOCK.name(), - Material.PACKED_ICE.name(), - Material.RED_SANDSTONE.name(), - Material.RED_SANDSTONE_STAIRS.name(), - Material.SPRUCE_FENCE.name(), - Material.BIRCH_FENCE.name(), - Material.JUNGLE_FENCE.name(), - Material.DARK_OAK_FENCE.name(), - Material.ACACIA_FENCE.name(), - Material.PURPUR_BLOCK.name(), - Material.PURPUR_STAIRS.name(), - Material.PURPUR_SLAB.name(), - Material.MAGMA_BLOCK.name(), - Material.NETHER_WART_BLOCK.name(), - Material.RED_NETHER_BRICKS.name(), - Material.BONE_BLOCK.name() - }; - - public static final String[] bridgeMaterials = new String[] { - Material.STONE.name(), - Material.DIRT.name(), - Material.COBBLESTONE.name(), - - Material.OAK_WOOD.name(), - Material.OAK_LOG.name(), - Material.OAK_PLANKS.name(), - Material.OAK_FENCE.name(), - Material.STRIPPED_OAK_LOG.name(), - Material.STRIPPED_OAK_WOOD.name(), - - Material.SPRUCE_WOOD.name(), - Material.SPRUCE_LOG.name(), - Material.SPRUCE_PLANKS.name(), - Material.SPRUCE_FENCE.name(), - Material.STRIPPED_SPRUCE_LOG.name(), - Material.STRIPPED_SPRUCE_WOOD.name(), - - Material.BIRCH_WOOD.name(), - Material.BIRCH_LOG.name(), - Material.BIRCH_PLANKS.name(), - Material.BIRCH_FENCE.name(), - Material.STRIPPED_BIRCH_LOG.name(), - Material.STRIPPED_BIRCH_WOOD.name(), - - Material.JUNGLE_WOOD.name(), - Material.JUNGLE_LOG.name(), - Material.JUNGLE_PLANKS.name(), - Material.JUNGLE_FENCE.name(), - Material.STRIPPED_JUNGLE_LOG.name(), - Material.STRIPPED_JUNGLE_WOOD.name(), - - Material.ACACIA_WOOD.name(), - Material.ACACIA_LOG.name(), - Material.ACACIA_PLANKS.name(), - Material.ACACIA_FENCE.name(), - Material.STRIPPED_ACACIA_LOG.name(), - Material.STRIPPED_ACACIA_WOOD.name(), - - Material.DARK_OAK_WOOD.name(), - Material.DARK_OAK_LOG.name(), - Material.DARK_OAK_PLANKS.name(), - Material.DARK_OAK_FENCE.name(), - Material.STRIPPED_DARK_OAK_LOG.name(), - Material.STRIPPED_DARK_OAK_WOOD.name(), - - Material.GLASS.name(), - Material.LAPIS_BLOCK.name(), - Material.SANDSTONE.name(), - - Material.WHITE_WOOL.name(), - Material.ORANGE_WOOL.name(), - Material.MAGENTA_WOOL.name(), - Material.LIGHT_BLUE_WOOL.name(), - Material.YELLOW_WOOL.name(), - Material.LIME_WOOL.name(), - Material.PINK_WOOL.name(), - Material.GRAY_WOOL.name(), - Material.LIGHT_GRAY_WOOL.name(), - Material.CYAN_WOOL.name(), - Material.PURPLE_WOOL.name(), - Material.BLUE_WOOL.name(), - Material.BROWN_WOOL.name(), - Material.GREEN_WOOL.name(), - Material.RED_WOOL.name(), - Material.BLACK_WOOL.name(), - - Material.GOLD_BLOCK.name(), - Material.IRON_BLOCK.name(), - Material.BRICK.name(), - Material.MOSSY_COBBLESTONE.name(), - Material.DIAMOND_BLOCK.name(), - Material.COBBLESTONE_STAIRS.name(), - Material.ICE.name(), - Material.SNOW_BLOCK.name(), - Material.CLAY.name(), - Material.NETHERRACK.name(), - Material.GLOWSTONE.name(), - Material.BRICK_STAIRS.name(), - Material.NETHER_BRICK.name(), - Material.NETHER_BRICK_STAIRS.name(), - Material.SANDSTONE_STAIRS.name(), - Material.EMERALD_BLOCK.name(), - Material.REDSTONE_BLOCK.name(), - Material.QUARTZ_BLOCK.name(), - Material.QUARTZ_STAIRS.name(), - Material.ACACIA_STAIRS.name(), - Material.DARK_OAK_STAIRS.name(), - Material.HAY_BLOCK.name(), - Material.COAL_BLOCK.name(), - Material.PACKED_ICE.name(), - Material.RED_SANDSTONE.name(), - Material.RED_SANDSTONE_STAIRS.name(), - Material.SPRUCE_FENCE.name(), - Material.BIRCH_FENCE.name(), - Material.JUNGLE_FENCE.name(), - Material.DARK_OAK_FENCE.name(), - Material.ACACIA_FENCE.name(), - Material.PURPUR_BLOCK.name(), - Material.PURPUR_STAIRS.name(), - Material.PURPUR_SLAB.name(), - }; -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.config; + +import org.bukkit.Material; + +public class ConfigDefaults { + public static final String[] gearMaterials = new String[] { + Material.STONE.name(), + Material.GRASS_BLOCK.name(), + Material.DIRT.name(), + Material.COBBLESTONE.name(), + + Material.OAK_WOOD.name(), + Material.OAK_LOG.name(), + Material.OAK_PLANKS.name(), + Material.OAK_STAIRS.name(), + Material.OAK_FENCE.name(), + Material.OAK_SLAB.name(), + Material.STRIPPED_OAK_LOG.name(), + Material.STRIPPED_OAK_WOOD.name(), + + Material.SPRUCE_WOOD.name(), + Material.SPRUCE_LOG.name(), + Material.SPRUCE_PLANKS.name(), + Material.SPRUCE_STAIRS.name(), + Material.SPRUCE_FENCE.name(), + Material.SPRUCE_SLAB.name(), + Material.STRIPPED_SPRUCE_LOG.name(), + Material.STRIPPED_SPRUCE_WOOD.name(), + + Material.BIRCH_WOOD.name(), + Material.BIRCH_LOG.name(), + Material.BIRCH_PLANKS.name(), + Material.BIRCH_STAIRS.name(), + Material.BIRCH_FENCE.name(), + Material.BIRCH_SLAB.name(), + Material.STRIPPED_BIRCH_LOG.name(), + Material.STRIPPED_BIRCH_WOOD.name(), + + Material.JUNGLE_WOOD.name(), + Material.JUNGLE_LOG.name(), + Material.JUNGLE_PLANKS.name(), + Material.JUNGLE_STAIRS.name(), + Material.JUNGLE_FENCE.name(), + Material.JUNGLE_SLAB.name(), + Material.STRIPPED_JUNGLE_LOG.name(), + Material.STRIPPED_JUNGLE_WOOD.name(), + + Material.ACACIA_WOOD.name(), + Material.ACACIA_LOG.name(), + Material.ACACIA_PLANKS.name(), + Material.ACACIA_STAIRS.name(), + Material.ACACIA_FENCE.name(), + Material.ACACIA_SLAB.name(), + Material.STRIPPED_ACACIA_LOG.name(), + Material.STRIPPED_ACACIA_WOOD.name(), + + Material.DARK_OAK_WOOD.name(), + Material.DARK_OAK_LOG.name(), + Material.DARK_OAK_PLANKS.name(), + Material.DARK_OAK_STAIRS.name(), + Material.DARK_OAK_FENCE.name(), + Material.DARK_OAK_SLAB.name(), + Material.STRIPPED_DARK_OAK_LOG.name(), + Material.STRIPPED_DARK_OAK_WOOD.name(), + + Material.GLASS.name(), + Material.LAPIS_BLOCK.name(), + Material.SANDSTONE.name(), + + Material.WHITE_WOOL.name(), + Material.ORANGE_WOOL.name(), + Material.MAGENTA_WOOL.name(), + Material.LIGHT_BLUE_WOOL.name(), + Material.YELLOW_WOOL.name(), + Material.LIME_WOOL.name(), + Material.PINK_WOOL.name(), + Material.GRAY_WOOL.name(), + Material.LIGHT_GRAY_WOOL.name(), + Material.CYAN_WOOL.name(), + Material.PURPLE_WOOL.name(), + Material.BLUE_WOOL.name(), + Material.BROWN_WOOL.name(), + Material.GREEN_WOOL.name(), + Material.RED_WOOL.name(), + Material.BLACK_WOOL.name(), + + Material.GOLD_BLOCK.name(), + Material.IRON_BLOCK.name(), + Material.BRICK.name(), + Material.MOSSY_COBBLESTONE.name(), + Material.MOSSY_COBBLESTONE_SLAB.name(), + Material.OBSIDIAN.name(), + Material.DIAMOND_BLOCK.name(), + Material.COBBLESTONE_STAIRS.name(), + Material.COBBLESTONE_SLAB.name(), + Material.ICE.name(), + Material.SNOW_BLOCK.name(), + Material.CLAY.name(), + Material.NETHERRACK.name(), + Material.GLOWSTONE.name(), + Material.SMOOTH_STONE.name(), + Material.IRON_BARS.name(), + Material.BRICK_STAIRS.name(), + Material.NETHER_BRICK.name(), + Material.NETHER_BRICK_STAIRS.name(), + Material.SANDSTONE_STAIRS.name(), + Material.EMERALD_BLOCK.name(), + Material.REDSTONE_BLOCK.name(), + Material.QUARTZ_BLOCK.name(), + Material.QUARTZ_STAIRS.name(), + Material.ACACIA_STAIRS.name(), + Material.DARK_OAK_STAIRS.name(), + Material.HAY_BLOCK.name(), + Material.COAL_BLOCK.name(), + Material.PACKED_ICE.name(), + Material.RED_SANDSTONE.name(), + Material.RED_SANDSTONE_STAIRS.name(), + Material.SPRUCE_FENCE.name(), + Material.BIRCH_FENCE.name(), + Material.JUNGLE_FENCE.name(), + Material.DARK_OAK_FENCE.name(), + Material.ACACIA_FENCE.name(), + Material.PURPUR_BLOCK.name(), + Material.PURPUR_STAIRS.name(), + Material.PURPUR_SLAB.name(), + Material.MAGMA_BLOCK.name(), + Material.NETHER_WART_BLOCK.name(), + Material.RED_NETHER_BRICKS.name(), + Material.BONE_BLOCK.name() + }; + + public static final String[] bridgeMaterials = new String[] { + Material.STONE.name(), + Material.DIRT.name(), + Material.COBBLESTONE.name(), + + Material.OAK_WOOD.name(), + Material.OAK_LOG.name(), + Material.OAK_PLANKS.name(), + Material.OAK_FENCE.name(), + Material.STRIPPED_OAK_LOG.name(), + Material.STRIPPED_OAK_WOOD.name(), + + Material.SPRUCE_WOOD.name(), + Material.SPRUCE_LOG.name(), + Material.SPRUCE_PLANKS.name(), + Material.SPRUCE_FENCE.name(), + Material.STRIPPED_SPRUCE_LOG.name(), + Material.STRIPPED_SPRUCE_WOOD.name(), + + Material.BIRCH_WOOD.name(), + Material.BIRCH_LOG.name(), + Material.BIRCH_PLANKS.name(), + Material.BIRCH_FENCE.name(), + Material.STRIPPED_BIRCH_LOG.name(), + Material.STRIPPED_BIRCH_WOOD.name(), + + Material.JUNGLE_WOOD.name(), + Material.JUNGLE_LOG.name(), + Material.JUNGLE_PLANKS.name(), + Material.JUNGLE_FENCE.name(), + Material.STRIPPED_JUNGLE_LOG.name(), + Material.STRIPPED_JUNGLE_WOOD.name(), + + Material.ACACIA_WOOD.name(), + Material.ACACIA_LOG.name(), + Material.ACACIA_PLANKS.name(), + Material.ACACIA_FENCE.name(), + Material.STRIPPED_ACACIA_LOG.name(), + Material.STRIPPED_ACACIA_WOOD.name(), + + Material.DARK_OAK_WOOD.name(), + Material.DARK_OAK_LOG.name(), + Material.DARK_OAK_PLANKS.name(), + Material.DARK_OAK_FENCE.name(), + Material.STRIPPED_DARK_OAK_LOG.name(), + Material.STRIPPED_DARK_OAK_WOOD.name(), + + Material.GLASS.name(), + Material.LAPIS_BLOCK.name(), + Material.SANDSTONE.name(), + + Material.WHITE_WOOL.name(), + Material.ORANGE_WOOL.name(), + Material.MAGENTA_WOOL.name(), + Material.LIGHT_BLUE_WOOL.name(), + Material.YELLOW_WOOL.name(), + Material.LIME_WOOL.name(), + Material.PINK_WOOL.name(), + Material.GRAY_WOOL.name(), + Material.LIGHT_GRAY_WOOL.name(), + Material.CYAN_WOOL.name(), + Material.PURPLE_WOOL.name(), + Material.BLUE_WOOL.name(), + Material.BROWN_WOOL.name(), + Material.GREEN_WOOL.name(), + Material.RED_WOOL.name(), + Material.BLACK_WOOL.name(), + + Material.GOLD_BLOCK.name(), + Material.IRON_BLOCK.name(), + Material.BRICK.name(), + Material.MOSSY_COBBLESTONE.name(), + Material.DIAMOND_BLOCK.name(), + Material.COBBLESTONE_STAIRS.name(), + Material.ICE.name(), + Material.SNOW_BLOCK.name(), + Material.CLAY.name(), + Material.NETHERRACK.name(), + Material.GLOWSTONE.name(), + Material.BRICK_STAIRS.name(), + Material.NETHER_BRICK.name(), + Material.NETHER_BRICK_STAIRS.name(), + Material.SANDSTONE_STAIRS.name(), + Material.EMERALD_BLOCK.name(), + Material.REDSTONE_BLOCK.name(), + Material.QUARTZ_BLOCK.name(), + Material.QUARTZ_STAIRS.name(), + Material.ACACIA_STAIRS.name(), + Material.DARK_OAK_STAIRS.name(), + Material.HAY_BLOCK.name(), + Material.COAL_BLOCK.name(), + Material.PACKED_ICE.name(), + Material.RED_SANDSTONE.name(), + Material.RED_SANDSTONE_STAIRS.name(), + Material.SPRUCE_FENCE.name(), + Material.BIRCH_FENCE.name(), + Material.JUNGLE_FENCE.name(), + Material.DARK_OAK_FENCE.name(), + Material.ACACIA_FENCE.name(), + Material.PURPUR_BLOCK.name(), + Material.PURPUR_STAIRS.name(), + Material.PURPUR_SLAB.name(), + }; +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/config/ConfigManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/config/ConfigManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/config/ConfigManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/config/ConfigManager.java index a43305548..17f982b1c 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/config/ConfigManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/config/ConfigManager.java @@ -1,362 +1,362 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.config; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.ItemStack; - -import com.aleksey.castlegates.types.TimerOperation; -import com.aleksey.castlegates.utils.Helper; - -public class ConfigManager { - public static class Database { - public String host; - public int port; - public String db; - public String user; - public String password; - } - - private static class ItemMaterial { - public Material material; - public Short damage; - public Integer amount; - public String lore; - - public ItemMaterial(Material material, Short damage, Integer amount, String lore) { - this.material = material; - this.damage = damage; - this.amount = amount; - this.lore = lore; - - if(Objects.equals(this.lore, "")) { - this.lore = null; - } - } - } - - private final Logger _logger; - private FileConfiguration _file; - private Database _database; - private HashSet _gearMaterials; - private HashSet _bridgeMaterials; - private ItemMaterial _stickItem; - private ItemMaterial _creationConsumeItem; - private int _maxPowerTransfers; - private int _maxBridgeLength; - private int _playerStateResetInSeconds; - private int _switchTimeout; - private int _maxRedstoneDistance; - private boolean _allowAutoCreate; - private boolean _interactWithSnitches; - private boolean _timerEnabled; - private int _timerMin; - private int _timerMax; - private int _timerDefault; - private TimerOperation _timerDefaultOperation; - private boolean _gearblockMustBeReinforced; - private boolean _horizontalLinkDisabled; - - public ConfigManager(Logger logger) { - _logger = logger; - } - - public void load(FileConfiguration file) { - _file = file; - - _database = new Database(); - _database.host = getString("Database.Host", "localhost"); - _database.port = getInt("Database.Port", 3306); - _database.db = getString("Database.Schema", "castle_gates"); - _database.user = getString("Database.User", ""); - _database.password = getString("Database.Password", ""); - - _allowAutoCreate = getBoolean("Settings.AllowAutoCreate", true); - _interactWithSnitches = getBoolean("Settings.InteractWithSnitches", true); - _maxPowerTransfers = getInt("Settings.MaxPowerTransfers", 8, 0, 10); - _maxBridgeLength = getInt("Settings.MaxBridgeLength", 16, 1, 40); - _playerStateResetInSeconds = getInt("Settings.PlayerStateResetInSeconds", 5 * 60); - _switchTimeout = getInt("Settings.SwitchTimeout", 1000, 500, 100000); - _maxRedstoneDistance = getInt("Settings.MaxRedstoneDistance", 7); - _timerEnabled = getBoolean("Settings.Timer.Enabled", true); - _timerMin = getInt("Settings.Timer.Min", 1); - _timerMax = getInt("Settings.Timer.Max", 60); - _timerDefault = getInt("Settings.Timer.DefaultInterval", 5); - _timerDefaultOperation = getTimerOperation(); - _gearblockMustBeReinforced = getBoolean("Settings.GearblockMustBeReinforced", false); - _horizontalLinkDisabled = getBoolean("Settings.HorizontalLinkDisabled", false); - - _gearMaterials = getBlockMaterials("Blocks.GearMaterials", ConfigDefaults.gearMaterials); - _bridgeMaterials = getBlockMaterials("Blocks.BridgeMaterials", ConfigDefaults.bridgeMaterials); - - _stickItem = getItemMaterial("Items.Tool", Material.STICK, null); - - _creationConsumeItem = getItemMaterial("Items.CreationConsume", Material.GOLD_INGOT, 1); - - if(_creationConsumeItem.amount == null) { - _creationConsumeItem.amount = 1; - } - - if(_creationConsumeItem.damage == null) { - _creationConsumeItem.damage = 0; - } - } - - public boolean isTimerEnabled() { - return _timerEnabled; - } - - public int getTimerMin() { - return _timerMin; - } - - public int getTimerMax() { - return _timerMax; - } - - public int getTimerDefault() { - return _timerDefault; - } - - public TimerOperation getTimerDefaultOperation() { - return _timerDefaultOperation; - } - - public boolean isGearblockMustBeReinforced() { return _gearblockMustBeReinforced; } - - public boolean isHorizontalLinkDisabled() { return _horizontalLinkDisabled; } - - public Database getDatabase() { - return _database; - } - - public boolean isGearBlockType(Block block) { - return _gearMaterials.contains(block.getType()); - } - - public boolean isStickItem(ItemStack item) { - if(item == null - || item.getType() != _stickItem.material - || _stickItem.damage != null && Helper.getItemDamage(item) != _stickItem.damage - || _stickItem.amount != null && item.getAmount() != _stickItem.amount - ) - { - return false; - } - - String lore = Helper.getLore(item); - - if(Objects.equals(lore, "")) { - lore = null; - } - - return Objects.equals(lore, _stickItem.lore); - } - - public boolean isBridgeMaterial(Block block) { - return _bridgeMaterials.contains(block.getType()); - } - - public boolean isCreationConsumeItem(ItemStack item) { - if(item == null - || item.getType() != _creationConsumeItem.material - || _creationConsumeItem.damage != null && Helper.getItemDamage(item) != _creationConsumeItem.damage - ) - { - return false; - } - - String lore = Helper.getLore(item); - - if(Objects.equals(lore, "")) { - lore = null; - } - - return Objects.equals(lore, _creationConsumeItem.lore); - } - - public ItemStack getCreationConsumeItem() { - ItemStack item = new ItemStack(_creationConsumeItem.material, _creationConsumeItem.amount); - - if (_creationConsumeItem.damage != null) - ((Damageable)item.getItemMeta()).setDamage(_creationConsumeItem.damage); - - Helper.setLore(item, _creationConsumeItem.lore); - - return item; - } - - public int getDataWorkerRate() { - return 500; - } - - public int getTimerWorkerRate() { - return 500; - } - - public int getMaxPowerTransfers() { - return _maxPowerTransfers; - } - - public int getMaxBridgeLength() { - return _maxBridgeLength; - } - - public int getPlayerStateResetInSeconds() { - return _playerStateResetInSeconds; - } - - public int getSwitchTimeout() { - return _switchTimeout; - } - - public double getMaxRedstoneDistance() { - return _maxRedstoneDistance; - } - - public boolean getAllowAutoCreate() { - return _allowAutoCreate; - } - - public boolean getInteractWithSnitches() { - return _interactWithSnitches; - } - - private TimerOperation getTimerOperation() { - final String path = "Settings.Timer.DefaultOperation"; - final TimerOperation defaultData = TimerOperation.UNDRAW; - - if (_file.get(path) == null) - _file.set(path, defaultData.name()); - - String name = _file.getString(path, defaultData.name()); - TimerOperation result = Helper.parseTimerOperation(name); - - if(result == null) { - _logger.log(Level.WARNING, "'" + name + "' is an invalid timer operation, '" + defaultData.name() + "'" + " will be used instead."); - result = defaultData; - } - - return result; - } - - private String getString(String path, String defaultData) { - if (_file.get(path) == null) - _file.set(path, defaultData); - - return _file.getString(path, defaultData); - } - - private int getInt(String path, int defaultData) { - if (_file.get(path) == null) - _file.set(path, defaultData); - - return _file.getInt(path, defaultData); - } - - private int getInt(String path, int defaultData, int min, int max) { - if (_file.get(path) == null) - _file.set(path, defaultData); - - int value = _file.getInt(path, defaultData); - - if(value < min) { - value = min; - } - else if(value > max) { - value = max; - } - - return value; - } - - private boolean getBoolean(String path, boolean defaultData) { - if (_file.get(path) == null) - _file.set(path, defaultData); - - return _file.getBoolean(path, defaultData); - } - - private HashSet getBlockMaterials(String path, String[] materials) { - List list; - - if(_file.get(path) != null) { - list = _file.getStringList(path); - } else { - _file.set(path, materials); - list = Arrays.asList(materials); - } - - HashSet result = new HashSet<>(); - - for(String materialName : list) { - if(materialName != null && materialName.length() > 0) { - var material = Material.getMaterial(materialName.toUpperCase()); - - if (material == null) - throw new IllegalArgumentException("Material " + materialName + " is not found"); - - result.add(material); - } - } - - return result; - } - - private ItemMaterial getItemMaterial(String path, Material defaultMaterial, Integer defaultAmount) { - String material = _file.getString(path + ".material"); - Short damage; - Integer amount; - String lore; - - if(material == null) { - material = defaultMaterial.name(); - damage = null; - amount = defaultAmount; - lore = ""; - - _file.set(path + ".material", material); - _file.set(path + ".damage", damage); - _file.set(path + ".amount", amount); - _file.set(path + ".lore", lore); - } else { - if(_file.get(path + ".damage") != null) { - damage = (short)_file.getInt(path + ".damage"); - } else { - damage = null; - _file.set(path + ".damage", damage); - } - - if(_file.get(path + ".amount") != null) { - amount = _file.getInt(path + ".amount"); - } else { - amount = defaultAmount; - _file.set(path + ".amount", amount); - } - - if(_file.get(path + ".lore") != null) { - lore = _file.getString(path + ".lore"); - } else { - lore = ""; - _file.set(path + ".lore", lore); - } - } - - Material materialObj = Material.getMaterial(material); - - return new ItemMaterial(materialObj, damage, amount, lore); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.config; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.ItemStack; + +import com.aleksey.castlegates.types.TimerOperation; +import com.aleksey.castlegates.utils.Helper; + +public class ConfigManager { + public static class Database { + public String host; + public int port; + public String db; + public String user; + public String password; + } + + private static class ItemMaterial { + public Material material; + public Short damage; + public Integer amount; + public String lore; + + public ItemMaterial(Material material, Short damage, Integer amount, String lore) { + this.material = material; + this.damage = damage; + this.amount = amount; + this.lore = lore; + + if(Objects.equals(this.lore, "")) { + this.lore = null; + } + } + } + + private final Logger _logger; + private FileConfiguration _file; + private Database _database; + private HashSet _gearMaterials; + private HashSet _bridgeMaterials; + private ItemMaterial _stickItem; + private ItemMaterial _creationConsumeItem; + private int _maxPowerTransfers; + private int _maxBridgeLength; + private int _playerStateResetInSeconds; + private int _switchTimeout; + private int _maxRedstoneDistance; + private boolean _allowAutoCreate; + private boolean _interactWithSnitches; + private boolean _timerEnabled; + private int _timerMin; + private int _timerMax; + private int _timerDefault; + private TimerOperation _timerDefaultOperation; + private boolean _gearblockMustBeReinforced; + private boolean _horizontalLinkDisabled; + + public ConfigManager(Logger logger) { + _logger = logger; + } + + public void load(FileConfiguration file) { + _file = file; + + _database = new Database(); + _database.host = getString("Database.Host", "localhost"); + _database.port = getInt("Database.Port", 3306); + _database.db = getString("Database.Schema", "castle_gates"); + _database.user = getString("Database.User", ""); + _database.password = getString("Database.Password", ""); + + _allowAutoCreate = getBoolean("Settings.AllowAutoCreate", true); + _interactWithSnitches = getBoolean("Settings.InteractWithSnitches", true); + _maxPowerTransfers = getInt("Settings.MaxPowerTransfers", 8, 0, 10); + _maxBridgeLength = getInt("Settings.MaxBridgeLength", 16, 1, 40); + _playerStateResetInSeconds = getInt("Settings.PlayerStateResetInSeconds", 5 * 60); + _switchTimeout = getInt("Settings.SwitchTimeout", 1000, 500, 100000); + _maxRedstoneDistance = getInt("Settings.MaxRedstoneDistance", 7); + _timerEnabled = getBoolean("Settings.Timer.Enabled", true); + _timerMin = getInt("Settings.Timer.Min", 1); + _timerMax = getInt("Settings.Timer.Max", 60); + _timerDefault = getInt("Settings.Timer.DefaultInterval", 5); + _timerDefaultOperation = getTimerOperation(); + _gearblockMustBeReinforced = getBoolean("Settings.GearblockMustBeReinforced", false); + _horizontalLinkDisabled = getBoolean("Settings.HorizontalLinkDisabled", false); + + _gearMaterials = getBlockMaterials("Blocks.GearMaterials", ConfigDefaults.gearMaterials); + _bridgeMaterials = getBlockMaterials("Blocks.BridgeMaterials", ConfigDefaults.bridgeMaterials); + + _stickItem = getItemMaterial("Items.Tool", Material.STICK, null); + + _creationConsumeItem = getItemMaterial("Items.CreationConsume", Material.GOLD_INGOT, 1); + + if(_creationConsumeItem.amount == null) { + _creationConsumeItem.amount = 1; + } + + if(_creationConsumeItem.damage == null) { + _creationConsumeItem.damage = 0; + } + } + + public boolean isTimerEnabled() { + return _timerEnabled; + } + + public int getTimerMin() { + return _timerMin; + } + + public int getTimerMax() { + return _timerMax; + } + + public int getTimerDefault() { + return _timerDefault; + } + + public TimerOperation getTimerDefaultOperation() { + return _timerDefaultOperation; + } + + public boolean isGearblockMustBeReinforced() { return _gearblockMustBeReinforced; } + + public boolean isHorizontalLinkDisabled() { return _horizontalLinkDisabled; } + + public Database getDatabase() { + return _database; + } + + public boolean isGearBlockType(Block block) { + return _gearMaterials.contains(block.getType()); + } + + public boolean isStickItem(ItemStack item) { + if(item == null + || item.getType() != _stickItem.material + || _stickItem.damage != null && Helper.getItemDamage(item) != _stickItem.damage + || _stickItem.amount != null && item.getAmount() != _stickItem.amount + ) + { + return false; + } + + String lore = Helper.getLore(item); + + if(Objects.equals(lore, "")) { + lore = null; + } + + return Objects.equals(lore, _stickItem.lore); + } + + public boolean isBridgeMaterial(Block block) { + return _bridgeMaterials.contains(block.getType()); + } + + public boolean isCreationConsumeItem(ItemStack item) { + if(item == null + || item.getType() != _creationConsumeItem.material + || _creationConsumeItem.damage != null && Helper.getItemDamage(item) != _creationConsumeItem.damage + ) + { + return false; + } + + String lore = Helper.getLore(item); + + if(Objects.equals(lore, "")) { + lore = null; + } + + return Objects.equals(lore, _creationConsumeItem.lore); + } + + public ItemStack getCreationConsumeItem() { + ItemStack item = new ItemStack(_creationConsumeItem.material, _creationConsumeItem.amount); + + if (_creationConsumeItem.damage != null) + ((Damageable)item.getItemMeta()).setDamage(_creationConsumeItem.damage); + + Helper.setLore(item, _creationConsumeItem.lore); + + return item; + } + + public int getDataWorkerRate() { + return 500; + } + + public int getTimerWorkerRate() { + return 500; + } + + public int getMaxPowerTransfers() { + return _maxPowerTransfers; + } + + public int getMaxBridgeLength() { + return _maxBridgeLength; + } + + public int getPlayerStateResetInSeconds() { + return _playerStateResetInSeconds; + } + + public int getSwitchTimeout() { + return _switchTimeout; + } + + public double getMaxRedstoneDistance() { + return _maxRedstoneDistance; + } + + public boolean getAllowAutoCreate() { + return _allowAutoCreate; + } + + public boolean getInteractWithSnitches() { + return _interactWithSnitches; + } + + private TimerOperation getTimerOperation() { + final String path = "Settings.Timer.DefaultOperation"; + final TimerOperation defaultData = TimerOperation.UNDRAW; + + if (_file.get(path) == null) + _file.set(path, defaultData.name()); + + String name = _file.getString(path, defaultData.name()); + TimerOperation result = Helper.parseTimerOperation(name); + + if(result == null) { + _logger.log(Level.WARNING, "'" + name + "' is an invalid timer operation, '" + defaultData.name() + "'" + " will be used instead."); + result = defaultData; + } + + return result; + } + + private String getString(String path, String defaultData) { + if (_file.get(path) == null) + _file.set(path, defaultData); + + return _file.getString(path, defaultData); + } + + private int getInt(String path, int defaultData) { + if (_file.get(path) == null) + _file.set(path, defaultData); + + return _file.getInt(path, defaultData); + } + + private int getInt(String path, int defaultData, int min, int max) { + if (_file.get(path) == null) + _file.set(path, defaultData); + + int value = _file.getInt(path, defaultData); + + if(value < min) { + value = min; + } + else if(value > max) { + value = max; + } + + return value; + } + + private boolean getBoolean(String path, boolean defaultData) { + if (_file.get(path) == null) + _file.set(path, defaultData); + + return _file.getBoolean(path, defaultData); + } + + private HashSet getBlockMaterials(String path, String[] materials) { + List list; + + if(_file.get(path) != null) { + list = _file.getStringList(path); + } else { + _file.set(path, materials); + list = Arrays.asList(materials); + } + + HashSet result = new HashSet<>(); + + for(String materialName : list) { + if(materialName != null && materialName.length() > 0) { + var material = Material.getMaterial(materialName.toUpperCase()); + + if (material == null) + throw new IllegalArgumentException("Material " + materialName + " is not found"); + + result.add(material); + } + } + + return result; + } + + private ItemMaterial getItemMaterial(String path, Material defaultMaterial, Integer defaultAmount) { + String material = _file.getString(path + ".material"); + Short damage; + Integer amount; + String lore; + + if(material == null) { + material = defaultMaterial.name(); + damage = null; + amount = defaultAmount; + lore = ""; + + _file.set(path + ".material", material); + _file.set(path + ".damage", damage); + _file.set(path + ".amount", amount); + _file.set(path + ".lore", lore); + } else { + if(_file.get(path + ".damage") != null) { + damage = (short)_file.getInt(path + ".damage"); + } else { + damage = null; + _file.set(path + ".damage", damage); + } + + if(_file.get(path + ".amount") != null) { + amount = _file.getInt(path + ".amount"); + } else { + amount = defaultAmount; + _file.set(path + ".amount", amount); + } + + if(_file.get(path + ".lore") != null) { + lore = _file.getString(path + ".lore"); + } else { + lore = ""; + _file.set(path + ".lore", lore); + } + } + + Material materialObj = Material.getMaterial(material); + + return new ItemMaterial(materialObj, damage, amount, lore); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/GearblockInfo.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/GearblockInfo.java similarity index 94% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/GearblockInfo.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/GearblockInfo.java index 6774d54f8..54bf440ed 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/GearblockInfo.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/GearblockInfo.java @@ -1,16 +1,16 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -public class GearblockInfo { - public int GearblockId; - public String WorldId; - public int X; - public int Y; - public int Z; - public Integer Timer; - public Integer TimerOperation; -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +public class GearblockInfo { + public int GearblockId; + public String WorldId; + public int X; + public int Y; + public int Z; + public Integer Timer; + public Integer TimerOperation; +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/GearblockSource.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/GearblockSource.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/GearblockSource.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/GearblockSource.java index ce202c6dc..2c2ddfa80 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/GearblockSource.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/GearblockSource.java @@ -1,122 +1,122 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.List; - -public class GearblockSource { - private static final String countAllScript = "SELECT COUNT(*) FROM cg_gearblock"; - private static final String selectAllScript = "SELECT * FROM cg_gearblock ORDER BY GearblockId"; - private static final String insertScript = "INSERT INTO cg_gearblock (WorldId, X, Y, Z, Timer, TimerOperation) VALUES (?, ?, ?, ?, ?, ?)"; - private static final String updateScript = "UPDATE cg_gearblock SET WorldId = ?, X = ?, Y = ?, Z = ?, Timer = ?, TimerOperation = ? WHERE GearblockId = ?"; - private static final String deleteScript = "DELETE FROM cg_gearblock WHERE GearblockId = ?"; - - private final SqlDatabase _db; - - public GearblockSource(SqlDatabase db) { - _db = db; - } - - public int countAll() throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(countAllScript)) { - try (ResultSet rs = sql.executeQuery()) { - if (rs.next()) return rs.getInt(1); - } - } - - return 0; - } - - public List selectAll() throws SQLException { - ArrayList list = new ArrayList<>(); - - try (PreparedStatement sql = _db.prepareStatement(selectAllScript)) { - try (ResultSet rs = sql.executeQuery()) { - while (rs.next()) { - GearblockInfo info = new GearblockInfo(); - - info.GearblockId = rs.getInt("GearblockId"); - info.WorldId = rs.getString("WorldId"); - info.X = rs.getInt("X"); - info.Y = rs.getInt("Y"); - info.Z = rs.getInt("Z"); - - info.Timer = rs.getInt("Timer"); - if (rs.wasNull()) info.Timer = null; - - info.TimerOperation = rs.getInt("TimerOperation"); - if (rs.wasNull()) info.TimerOperation = null; - - list.add(info); - } - } - } - - return list; - } - - public void insert(GearblockInfo info) throws SQLException { - try (PreparedStatement sql = _db.prepareStatementWithReturn(insertScript)) { - sql.setString(1, info.WorldId); - sql.setInt(2, info.X); - sql.setInt(3, info.Y); - sql.setInt(4, info.Z); - - if (info.Timer != null) - sql.setInt(5, info.Timer); - else - sql.setNull(5, Types.INTEGER); - - if (info.TimerOperation != null) - sql.setInt(6, info.TimerOperation); - else - sql.setNull(6, Types.INTEGER); - - sql.executeUpdate(); - - try (ResultSet rs = sql.getGeneratedKeys()) { - rs.next(); - info.GearblockId = rs.getInt(1); - } - } - } - - public void update(GearblockInfo info) throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(updateScript)) { - sql.setString(1, info.WorldId); - sql.setInt(2, info.X); - sql.setInt(3, info.Y); - sql.setInt(4, info.Z); - - if (info.Timer != null) - sql.setInt(5, info.Timer); - else - sql.setNull(5, Types.INTEGER); - - if (info.TimerOperation != null) - sql.setInt(6, info.TimerOperation); - else - sql.setNull(6, Types.INTEGER); - - sql.setInt(7, info.GearblockId); - - sql.executeUpdate(); - } - } - - public void delete(int gear_id) throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(deleteScript)) { - sql.setInt(1, gear_id); - - sql.executeUpdate(); - } - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +public class GearblockSource { + private static final String countAllScript = "SELECT COUNT(*) FROM cg_gearblock"; + private static final String selectAllScript = "SELECT * FROM cg_gearblock ORDER BY GearblockId"; + private static final String insertScript = "INSERT INTO cg_gearblock (WorldId, X, Y, Z, Timer, TimerOperation) VALUES (?, ?, ?, ?, ?, ?)"; + private static final String updateScript = "UPDATE cg_gearblock SET WorldId = ?, X = ?, Y = ?, Z = ?, Timer = ?, TimerOperation = ? WHERE GearblockId = ?"; + private static final String deleteScript = "DELETE FROM cg_gearblock WHERE GearblockId = ?"; + + private final SqlDatabase _db; + + public GearblockSource(SqlDatabase db) { + _db = db; + } + + public int countAll() throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(countAllScript)) { + try (ResultSet rs = sql.executeQuery()) { + if (rs.next()) return rs.getInt(1); + } + } + + return 0; + } + + public List selectAll() throws SQLException { + ArrayList list = new ArrayList<>(); + + try (PreparedStatement sql = _db.prepareStatement(selectAllScript)) { + try (ResultSet rs = sql.executeQuery()) { + while (rs.next()) { + GearblockInfo info = new GearblockInfo(); + + info.GearblockId = rs.getInt("GearblockId"); + info.WorldId = rs.getString("WorldId"); + info.X = rs.getInt("X"); + info.Y = rs.getInt("Y"); + info.Z = rs.getInt("Z"); + + info.Timer = rs.getInt("Timer"); + if (rs.wasNull()) info.Timer = null; + + info.TimerOperation = rs.getInt("TimerOperation"); + if (rs.wasNull()) info.TimerOperation = null; + + list.add(info); + } + } + } + + return list; + } + + public void insert(GearblockInfo info) throws SQLException { + try (PreparedStatement sql = _db.prepareStatementWithReturn(insertScript)) { + sql.setString(1, info.WorldId); + sql.setInt(2, info.X); + sql.setInt(3, info.Y); + sql.setInt(4, info.Z); + + if (info.Timer != null) + sql.setInt(5, info.Timer); + else + sql.setNull(5, Types.INTEGER); + + if (info.TimerOperation != null) + sql.setInt(6, info.TimerOperation); + else + sql.setNull(6, Types.INTEGER); + + sql.executeUpdate(); + + try (ResultSet rs = sql.getGeneratedKeys()) { + rs.next(); + info.GearblockId = rs.getInt(1); + } + } + } + + public void update(GearblockInfo info) throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(updateScript)) { + sql.setString(1, info.WorldId); + sql.setInt(2, info.X); + sql.setInt(3, info.Y); + sql.setInt(4, info.Z); + + if (info.Timer != null) + sql.setInt(5, info.Timer); + else + sql.setNull(5, Types.INTEGER); + + if (info.TimerOperation != null) + sql.setInt(6, info.TimerOperation); + else + sql.setNull(6, Types.INTEGER); + + sql.setInt(7, info.GearblockId); + + sql.executeUpdate(); + } + } + + public void delete(int gear_id) throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(deleteScript)) { + sql.setInt(1, gear_id); + + sql.executeUpdate(); + } + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/LinkInfo.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/LinkInfo.java similarity index 94% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/LinkInfo.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/LinkInfo.java index 5dfb6e0b3..1b2cdd94a 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/LinkInfo.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/LinkInfo.java @@ -1,13 +1,13 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -public class LinkInfo { - public int LinkId; - public Integer StartGearblockId; - public Integer EndGearblockId; - public String Blocks; -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +public class LinkInfo { + public int LinkId; + public Integer StartGearblockId; + public Integer EndGearblockId; + public String Blocks; +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/LinkSource.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/LinkSource.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/LinkSource.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/LinkSource.java index fe91bd612..111624ea7 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/LinkSource.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/LinkSource.java @@ -1,125 +1,125 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.List; - -public class LinkSource { - private static final String countAllScript = "SELECT COUNT(*) FROM cg_link"; - private static final String selectAllScript = "SELECT * FROM cg_link ORDER BY LinkId"; - private static final String insertScript = "INSERT INTO cg_link (StartGearblockId, EndGearblockId, Blocks) VALUES (?, ?, ?)"; - private static final String updateScript = "UPDATE cg_link SET StartGearblockId = ?, EndGearblockId = ?, Blocks = ? WHERE LinkId = ?"; - private static final String deleteScript = "DELETE FROM cg_link WHERE LinkId = ?"; - - private final SqlDatabase _db; - - public LinkSource(SqlDatabase db) { - _db = db; - } - - public int countAll() throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(countAllScript)) { - try (ResultSet rs = sql.executeQuery()) { - if (rs.next()) return rs.getInt(1); - } - } - - return 0; - } - - public List selectAll() throws SQLException { - ArrayList list = new ArrayList<>(); - - try (PreparedStatement sql = _db.prepareStatement(selectAllScript)) { - try (ResultSet rs = sql.executeQuery()) { - while (rs.next()) { - LinkInfo info = new LinkInfo(); - info.LinkId = rs.getInt("LinkId"); - - info.StartGearblockId = rs.getInt("StartGearblockId"); - if (rs.wasNull()) info.StartGearblockId = null; - - info.EndGearblockId = rs.getInt("EndGearblockId"); - if (rs.wasNull()) info.EndGearblockId = null; - - info.Blocks = rs.getString("Blocks"); - - list.add(info); - } - } - } - - return list; - } - - public void insert(LinkInfo info) throws SQLException { - try (PreparedStatement sql = _db.prepareStatementWithReturn(insertScript)) { - if (info.StartGearblockId != null) { - sql.setInt(1, info.StartGearblockId); - } else { - sql.setNull(1, Types.INTEGER); - } - - if (info.EndGearblockId != null) { - sql.setInt(2, info.EndGearblockId); - } else { - sql.setNull(2, Types.INTEGER); - } - - if (info.Blocks != null) { - sql.setString(3, info.Blocks); - } else { - sql.setNull(3, Types.VARCHAR); - } - - sql.executeUpdate(); - - try (ResultSet rs = sql.getGeneratedKeys()) { - rs.next(); - info.LinkId = rs.getInt(1); - } - } - } - - public void update(LinkInfo info) throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(updateScript)) { - if (info.StartGearblockId != null) { - sql.setInt(1, info.StartGearblockId); - } else { - sql.setNull(1, Types.INTEGER); - } - - if (info.EndGearblockId != null) { - sql.setInt(2, info.EndGearblockId); - } else { - sql.setNull(2, Types.INTEGER); - } - - if (info.Blocks != null) { - sql.setString(3, info.Blocks); - } else { - sql.setNull(3, Types.VARCHAR); - } - - sql.setInt(4, info.LinkId); - - sql.executeUpdate(); - } - } - - public void delete(int link_id) throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(deleteScript)) { - sql.setInt(1, link_id); - - sql.executeUpdate(); - } - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +public class LinkSource { + private static final String countAllScript = "SELECT COUNT(*) FROM cg_link"; + private static final String selectAllScript = "SELECT * FROM cg_link ORDER BY LinkId"; + private static final String insertScript = "INSERT INTO cg_link (StartGearblockId, EndGearblockId, Blocks) VALUES (?, ?, ?)"; + private static final String updateScript = "UPDATE cg_link SET StartGearblockId = ?, EndGearblockId = ?, Blocks = ? WHERE LinkId = ?"; + private static final String deleteScript = "DELETE FROM cg_link WHERE LinkId = ?"; + + private final SqlDatabase _db; + + public LinkSource(SqlDatabase db) { + _db = db; + } + + public int countAll() throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(countAllScript)) { + try (ResultSet rs = sql.executeQuery()) { + if (rs.next()) return rs.getInt(1); + } + } + + return 0; + } + + public List selectAll() throws SQLException { + ArrayList list = new ArrayList<>(); + + try (PreparedStatement sql = _db.prepareStatement(selectAllScript)) { + try (ResultSet rs = sql.executeQuery()) { + while (rs.next()) { + LinkInfo info = new LinkInfo(); + info.LinkId = rs.getInt("LinkId"); + + info.StartGearblockId = rs.getInt("StartGearblockId"); + if (rs.wasNull()) info.StartGearblockId = null; + + info.EndGearblockId = rs.getInt("EndGearblockId"); + if (rs.wasNull()) info.EndGearblockId = null; + + info.Blocks = rs.getString("Blocks"); + + list.add(info); + } + } + } + + return list; + } + + public void insert(LinkInfo info) throws SQLException { + try (PreparedStatement sql = _db.prepareStatementWithReturn(insertScript)) { + if (info.StartGearblockId != null) { + sql.setInt(1, info.StartGearblockId); + } else { + sql.setNull(1, Types.INTEGER); + } + + if (info.EndGearblockId != null) { + sql.setInt(2, info.EndGearblockId); + } else { + sql.setNull(2, Types.INTEGER); + } + + if (info.Blocks != null) { + sql.setString(3, info.Blocks); + } else { + sql.setNull(3, Types.VARCHAR); + } + + sql.executeUpdate(); + + try (ResultSet rs = sql.getGeneratedKeys()) { + rs.next(); + info.LinkId = rs.getInt(1); + } + } + } + + public void update(LinkInfo info) throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(updateScript)) { + if (info.StartGearblockId != null) { + sql.setInt(1, info.StartGearblockId); + } else { + sql.setNull(1, Types.INTEGER); + } + + if (info.EndGearblockId != null) { + sql.setInt(2, info.EndGearblockId); + } else { + sql.setNull(2, Types.INTEGER); + } + + if (info.Blocks != null) { + sql.setString(3, info.Blocks); + } else { + sql.setNull(3, Types.VARCHAR); + } + + sql.setInt(4, info.LinkId); + + sql.executeUpdate(); + } + } + + public void delete(int link_id) throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(deleteScript)) { + sql.setInt(1, link_id); + + sql.executeUpdate(); + } + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/ReinforcementInfo.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/ReinforcementInfo.java similarity index 94% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/ReinforcementInfo.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/ReinforcementInfo.java index b839275cb..9935a5eb9 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/ReinforcementInfo.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/ReinforcementInfo.java @@ -1,16 +1,16 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -public class ReinforcementInfo { - public int LinkId; - public int BlockSequence; - public long CreationTime; - public short TypeId; - public float Health; - public int GroupId; - public boolean Insecure; -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +public class ReinforcementInfo { + public int LinkId; + public int BlockSequence; + public long CreationTime; + public short TypeId; + public float Health; + public int GroupId; + public boolean Insecure; +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/ReinforcementSource.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/ReinforcementSource.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/ReinforcementSource.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/ReinforcementSource.java index 3e32986d8..3eb30fbdc 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/ReinforcementSource.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/ReinforcementSource.java @@ -1,70 +1,70 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -public class ReinforcementSource { - private static final String selectAllScript = "SELECT * FROM cg_reinforcement ORDER BY LinkId, BlockSequence"; - private static final String insertScript = "INSERT INTO cg_reinforcement (LinkId, BlockSequence, CreationTime, TypeId, Health, GroupId, Insecure) VALUES (?, ?, ?, ?, ?, ?, ?)"; - private static final String deleteScript = "DELETE FROM cg_reinforcement WHERE LinkId = ?"; - - private final SqlDatabase _db; - - public ReinforcementSource(SqlDatabase db) { - _db = db; - } - - public List selectAll() throws SQLException { - ArrayList list = new ArrayList<>(); - - try (PreparedStatement sql = _db.prepareStatement(selectAllScript)) { - - try (ResultSet rs = sql.executeQuery()) { - while (rs.next()) { - ReinforcementInfo info = new ReinforcementInfo(); - info.LinkId = rs.getInt("LinkId"); - info.BlockSequence = rs.getInt("BlockSequence"); - info.CreationTime = rs.getLong("CreationTime"); - info.TypeId = rs.getShort("TypeId"); - info.Health = rs.getFloat("Health"); - info.GroupId = rs.getInt("GroupId"); - info.Insecure = rs.getBoolean("Insecure"); - - list.add(info); - } - } - } - - return list; - } - - public void insert(ReinforcementInfo info) throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(insertScript)) { - sql.setInt(1, info.LinkId); - sql.setInt(2, info.BlockSequence); - sql.setLong(3, info.CreationTime); - sql.setShort(4, info.TypeId); - sql.setFloat(5, info.Health); - sql.setInt(6, info.GroupId); - sql.setBoolean(7, info.Insecure); - - sql.executeUpdate(); - } - } - - public void deleteByLinkId(int link_id) throws SQLException { - try (PreparedStatement sql = _db.prepareStatement(deleteScript)) { - sql.setInt(1, link_id); - - sql.executeUpdate(); - } - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class ReinforcementSource { + private static final String selectAllScript = "SELECT * FROM cg_reinforcement ORDER BY LinkId, BlockSequence"; + private static final String insertScript = "INSERT INTO cg_reinforcement (LinkId, BlockSequence, CreationTime, TypeId, Health, GroupId, Insecure) VALUES (?, ?, ?, ?, ?, ?, ?)"; + private static final String deleteScript = "DELETE FROM cg_reinforcement WHERE LinkId = ?"; + + private final SqlDatabase _db; + + public ReinforcementSource(SqlDatabase db) { + _db = db; + } + + public List selectAll() throws SQLException { + ArrayList list = new ArrayList<>(); + + try (PreparedStatement sql = _db.prepareStatement(selectAllScript)) { + + try (ResultSet rs = sql.executeQuery()) { + while (rs.next()) { + ReinforcementInfo info = new ReinforcementInfo(); + info.LinkId = rs.getInt("LinkId"); + info.BlockSequence = rs.getInt("BlockSequence"); + info.CreationTime = rs.getLong("CreationTime"); + info.TypeId = rs.getShort("TypeId"); + info.Health = rs.getFloat("Health"); + info.GroupId = rs.getInt("GroupId"); + info.Insecure = rs.getBoolean("Insecure"); + + list.add(info); + } + } + } + + return list; + } + + public void insert(ReinforcementInfo info) throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(insertScript)) { + sql.setInt(1, info.LinkId); + sql.setInt(2, info.BlockSequence); + sql.setLong(3, info.CreationTime); + sql.setShort(4, info.TypeId); + sql.setFloat(5, info.Health); + sql.setInt(6, info.GroupId); + sql.setBoolean(7, info.Insecure); + + sql.executeUpdate(); + } + } + + public void deleteByLinkId(int link_id) throws SQLException { + try (PreparedStatement sql = _db.prepareStatement(deleteScript)) { + sql.setInt(1, link_id); + + sql.executeUpdate(); + } + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/SqlDatabase.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/SqlDatabase.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/SqlDatabase.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/SqlDatabase.java index 6d86cb972..f41f905a6 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/database/SqlDatabase.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/database/SqlDatabase.java @@ -1,115 +1,115 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.database; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.aleksey.castlegates.utils.ResourceHelper; - -public class SqlDatabase { - private final String _host; - private final int _port; - private final String _db; - private final String _user; - private final String _password; - private final Logger _logger; - private Connection _connection; - - public SqlDatabase(String host, int port, String db, String user, String password, Logger logger) { - _host = host; - _port = port; - _db = db; - _user = user; - _password = password; - _logger = logger; - } - - public boolean connect() { - String jdbc = "jdbc:mysql://" + _host + ":" + _port + "/" + _db + "?user=" + _user + "&password=" + _password; - - try { - Class.forName("com.mysql.jdbc.Driver").newInstance(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - try { - _connection = DriverManager.getConnection(jdbc); - - _logger.log(Level.INFO, "Connected to the database!"); - return true; - } catch (SQLException ex) { //Error handling below: - _logger.log(Level.SEVERE, "Could not connnect to the database! Connection string: " + jdbc, ex); - return false; - } - } - - public void close() { - try { - _connection.close(); - } catch (SQLException ex) { - _logger.log(Level.SEVERE, "An error occured while closing the connection.", ex); - } - } - - public boolean isConnected() { - try { - return _connection.isValid(5); - } catch (SQLException ex) { - _logger.log(Level.SEVERE, "isConnected error!", ex); - } - return false; - } - - public boolean checkConnection() { - if(isConnected()) return true; - - _logger.log(Level.INFO, "Database went away, reconnecting."); - - return connect(); - } - - public PreparedStatement prepareStatement(String sqlStatement) throws SQLException { - return _connection.prepareStatement(sqlStatement); - } - - public PreparedStatement prepareStatementWithReturn(String sqlStatement) throws SQLException { - return _connection.prepareStatement(sqlStatement, Statement.RETURN_GENERATED_KEYS); - } - - public boolean initDb() { - _logger.log(Level.INFO, "Database initialization started..."); - - ArrayList list = ResourceHelper.readScriptList("/create_db.txt"); - - if (list == null) { - _logger.log(Level.SEVERE, "Resource create_db.txt is not found."); - return false; - } - - for(String script : list) { - try (PreparedStatement statement = prepareStatement(script)) { - statement.execute(); - } catch (SQLException e) { - _logger.log(Level.SEVERE, "Database is NOT initialized."); - _logger.log(Level.SEVERE, "Failed script: \n" + script); - e.printStackTrace(); - return false; - } - } - - _logger.log(Level.INFO, "Database initialized."); - - return true; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.database; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.aleksey.castlegates.utils.ResourceHelper; + +public class SqlDatabase { + private final String _host; + private final int _port; + private final String _db; + private final String _user; + private final String _password; + private final Logger _logger; + private Connection _connection; + + public SqlDatabase(String host, int port, String db, String user, String password, Logger logger) { + _host = host; + _port = port; + _db = db; + _user = user; + _password = password; + _logger = logger; + } + + public boolean connect() { + String jdbc = "jdbc:mysql://" + _host + ":" + _port + "/" + _db + "?user=" + _user + "&password=" + _password; + + try { + Class.forName("com.mysql.jdbc.Driver").newInstance(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } + try { + _connection = DriverManager.getConnection(jdbc); + + _logger.log(Level.INFO, "Connected to the database!"); + return true; + } catch (SQLException ex) { //Error handling below: + _logger.log(Level.SEVERE, "Could not connnect to the database! Connection string: " + jdbc, ex); + return false; + } + } + + public void close() { + try { + _connection.close(); + } catch (SQLException ex) { + _logger.log(Level.SEVERE, "An error occured while closing the connection.", ex); + } + } + + public boolean isConnected() { + try { + return _connection.isValid(5); + } catch (SQLException ex) { + _logger.log(Level.SEVERE, "isConnected error!", ex); + } + return false; + } + + public boolean checkConnection() { + if(isConnected()) return true; + + _logger.log(Level.INFO, "Database went away, reconnecting."); + + return connect(); + } + + public PreparedStatement prepareStatement(String sqlStatement) throws SQLException { + return _connection.prepareStatement(sqlStatement); + } + + public PreparedStatement prepareStatementWithReturn(String sqlStatement) throws SQLException { + return _connection.prepareStatement(sqlStatement, Statement.RETURN_GENERATED_KEYS); + } + + public boolean initDb() { + _logger.log(Level.INFO, "Database initialization started..."); + + ArrayList list = ResourceHelper.readScriptList("/create_db.txt"); + + if (list == null) { + _logger.log(Level.SEVERE, "Resource create_db.txt is not found."); + return false; + } + + for(String script : list) { + try (PreparedStatement statement = prepareStatement(script)) { + statement.execute(); + } catch (SQLException e) { + _logger.log(Level.SEVERE, "Database is NOT initialized."); + _logger.log(Level.SEVERE, "Failed script: \n" + script); + e.printStackTrace(); + return false; + } + } + + _logger.log(Level.INFO, "Database initialized."); + + return true; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/CastleGatesManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/CastleGatesManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/CastleGatesManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/CastleGatesManager.java index 6e88cacd5..1a03a18cc 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/CastleGatesManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/CastleGatesManager.java @@ -1,131 +1,131 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.engine; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.database.SqlDatabase; -import com.aleksey.castlegates.engine.bridge.BridgeEventHandler; -import com.aleksey.castlegates.engine.bridge.BridgeManager; -import com.aleksey.castlegates.types.CommandMode; -import com.aleksey.castlegates.types.TimerMode; -import com.aleksey.castlegates.types.TimerOperation; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import java.sql.SQLException; -import java.util.List; -import java.util.logging.Level; - -public class CastleGatesManager { - private SqlDatabase _db; - private StorageManager _storage; - private BridgeManager _bridgeManager; - private BridgeEventHandler _bridgeEventHandler; - private PlayerStateManager _stateManager; - - public boolean init(SqlDatabase db) { - _db = db; - - try { - _storage = new StorageManager(); - _storage.init(db); - } catch (SQLException e) { - e.printStackTrace(); - return false; - } - - _bridgeManager = new BridgeManager(); - _bridgeManager.init(_storage); - - _bridgeEventHandler = new BridgeEventHandler(_storage, _bridgeManager); - - _stateManager = new PlayerStateManager(); - - return true; - } - - public void reinit() { - CastleGates.getPluginLogger().log(Level.INFO, "Start reload process..."); - - _bridgeManager.close(); - - try { - _storage.close(); - _storage.init(_db); - } catch (SQLException e) { - e.printStackTrace(); - return; - } - - _bridgeManager.init(_storage); - - CastleGates.getPluginLogger().log(Level.INFO, "Reload process completed."); - } - - public void close() { - if(_bridgeManager != null) { - _bridgeManager.close(); - } - - if(_storage != null) { - _storage.close(); - } - - if(_db != null) { - _db.close(); - } - } - - public void setPlayerMode(Player player, CommandMode mode, Integer timer, TimerOperation timerOperation, TimerMode timerMode) { - _stateManager.setPlayerMode(player, mode, timer, timerOperation, timerMode); - } - - public void handlePlayerJoin(PlayerJoinEvent event) { - _stateManager.clearPlayerMode(event.getPlayer()); - } - - public void handlePlayerQuit(PlayerQuitEvent event) { - _stateManager.clearPlayerMode(event.getPlayer()); - } - - public void handleBlockClicked(PlayerInteractEvent event) { - boolean interacted = _bridgeEventHandler.handleBlockClicked(event, _stateManager.getPlayerState(event.getPlayer())); - - if(interacted) { - _stateManager.interact(event.getPlayer()); - } - } - - public void handleBlockBreak(BlockBreakEvent event) { - _bridgeEventHandler.handleBlockBreak(event); - } - - public void handleBlockRedstone(BlockRedstoneEvent event) { - _bridgeEventHandler.handleBlockRedstone(event); - } - - public void handleBlockPhysics(BlockPhysicsEvent event) { - _bridgeEventHandler.handleBlockPhysics(event); - } - - public void handleEntityExplode(EntityExplodeEvent event) { - _bridgeEventHandler.handleEntityExplode(event); - } - - public void handleEntityChangeBlock(EntityChangeBlockEvent event) { _bridgeEventHandler.handleEntityChangeBlock(event); } - - public void handlePistonEvent(List blocks) { - _bridgeEventHandler.handlePistonEvent(blocks); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.engine; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.database.SqlDatabase; +import com.aleksey.castlegates.engine.bridge.BridgeEventHandler; +import com.aleksey.castlegates.engine.bridge.BridgeManager; +import com.aleksey.castlegates.types.CommandMode; +import com.aleksey.castlegates.types.TimerMode; +import com.aleksey.castlegates.types.TimerOperation; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.sql.SQLException; +import java.util.List; +import java.util.logging.Level; + +public class CastleGatesManager { + private SqlDatabase _db; + private StorageManager _storage; + private BridgeManager _bridgeManager; + private BridgeEventHandler _bridgeEventHandler; + private PlayerStateManager _stateManager; + + public boolean init(SqlDatabase db) { + _db = db; + + try { + _storage = new StorageManager(); + _storage.init(db); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + + _bridgeManager = new BridgeManager(); + _bridgeManager.init(_storage); + + _bridgeEventHandler = new BridgeEventHandler(_storage, _bridgeManager); + + _stateManager = new PlayerStateManager(); + + return true; + } + + public void reinit() { + CastleGates.getPluginLogger().log(Level.INFO, "Start reload process..."); + + _bridgeManager.close(); + + try { + _storage.close(); + _storage.init(_db); + } catch (SQLException e) { + e.printStackTrace(); + return; + } + + _bridgeManager.init(_storage); + + CastleGates.getPluginLogger().log(Level.INFO, "Reload process completed."); + } + + public void close() { + if(_bridgeManager != null) { + _bridgeManager.close(); + } + + if(_storage != null) { + _storage.close(); + } + + if(_db != null) { + _db.close(); + } + } + + public void setPlayerMode(Player player, CommandMode mode, Integer timer, TimerOperation timerOperation, TimerMode timerMode) { + _stateManager.setPlayerMode(player, mode, timer, timerOperation, timerMode); + } + + public void handlePlayerJoin(PlayerJoinEvent event) { + _stateManager.clearPlayerMode(event.getPlayer()); + } + + public void handlePlayerQuit(PlayerQuitEvent event) { + _stateManager.clearPlayerMode(event.getPlayer()); + } + + public void handleBlockClicked(PlayerInteractEvent event) { + boolean interacted = _bridgeEventHandler.handleBlockClicked(event, _stateManager.getPlayerState(event.getPlayer())); + + if(interacted) { + _stateManager.interact(event.getPlayer()); + } + } + + public void handleBlockBreak(BlockBreakEvent event) { + _bridgeEventHandler.handleBlockBreak(event); + } + + public void handleBlockRedstone(BlockRedstoneEvent event) { + _bridgeEventHandler.handleBlockRedstone(event); + } + + public void handleBlockPhysics(BlockPhysicsEvent event) { + _bridgeEventHandler.handleBlockPhysics(event); + } + + public void handleEntityExplode(EntityExplodeEvent event) { + _bridgeEventHandler.handleEntityExplode(event); + } + + public void handleEntityChangeBlock(EntityChangeBlockEvent event) { _bridgeEventHandler.handleEntityChangeBlock(event); } + + public void handlePistonEvent(List blocks) { + _bridgeEventHandler.handlePistonEvent(blocks); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/PlayerStateManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/PlayerStateManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/PlayerStateManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/PlayerStateManager.java index 4f9247610..5b5b513fb 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/PlayerStateManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/PlayerStateManager.java @@ -1,117 +1,117 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.engine; - -import java.util.Map; -import java.util.HashMap; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.types.TimerMode; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.types.CommandMode; -import com.aleksey.castlegates.types.TimerOperation; - -public class PlayerStateManager { - public static class PlayerState { - public CommandMode mode; - public Integer timer; - public TimerOperation timerOperation; - public TimerMode timerMode; - public long lastInteracted; - } - - private final Map _states = new HashMap<>(); - private final Map _tasks = new HashMap<>(); - - public void clearPlayerMode(Player player) { - Integer taskId = _tasks.get(player); - - if(taskId != null) { - Bukkit.getScheduler().cancelTask(taskId); - } - - PlayerState state = _states.get(player); - - if(state == null) return; - - _states.remove(player); - - if(player.isOnline()) { - player.sendMessage(ChatColor.YELLOW + "Castle Gates " + state.mode.name() + " mode off"); - } - } - - public PlayerState getPlayerState(Player player) { - return _states.get(player); - } - - public void setPlayerMode(Player player, CommandMode mode, Integer timer, TimerOperation timerOperation, TimerMode timerMode) { - if(mode == CommandMode.OFF) { - clearPlayerMode(player); - return; - } - - PlayerState state = _states.get(player); - - if(state == null) { - if(mode == CommandMode.NORMAL) { - player.sendMessage(ChatColor.GREEN + "Castle Gates " + mode.name() + " mode on"); - return; - } - - _states.put(player, state = new PlayerState()); - } - else if(state.mode == mode) { - clearPlayerMode(player); - return; - } - - state.mode = mode; - state.timer = timer; - state.timerOperation = timerOperation; - state.timerMode = timerMode; - state.lastInteracted = System.currentTimeMillis(); - - addTask(player); - - player.sendMessage(ChatColor.GREEN + "Castle Gates " + mode.name() + " mode on"); - } - - public void interact(Player player) { - PlayerState state = _states.get(player); - - if(state != null) { - state.lastInteracted = System.currentTimeMillis(); - } - } - - private void addTask(final Player player) { - if(_tasks.containsKey(player)) return; - - final PlayerStateManager stateManager = this; - - int taskId = Bukkit.getScheduler().runTaskTimer( - CastleGates.getInstance(), - () -> { - PlayerState state = stateManager._states.get(player); - if(state != null) { - long offTime = state.lastInteracted + 1000L * CastleGates.getConfigManager().getPlayerStateResetInSeconds(); - - if(offTime < System.currentTimeMillis()) { - clearPlayerMode(player); - } - } - }, - 20L * 30, - 20L * 30 - ).getTaskId(); - - _tasks.put(player, taskId); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.engine; + +import java.util.Map; +import java.util.HashMap; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.types.TimerMode; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.types.CommandMode; +import com.aleksey.castlegates.types.TimerOperation; + +public class PlayerStateManager { + public static class PlayerState { + public CommandMode mode; + public Integer timer; + public TimerOperation timerOperation; + public TimerMode timerMode; + public long lastInteracted; + } + + private final Map _states = new HashMap<>(); + private final Map _tasks = new HashMap<>(); + + public void clearPlayerMode(Player player) { + Integer taskId = _tasks.get(player); + + if(taskId != null) { + Bukkit.getScheduler().cancelTask(taskId); + } + + PlayerState state = _states.get(player); + + if(state == null) return; + + _states.remove(player); + + if(player.isOnline()) { + player.sendMessage(ChatColor.YELLOW + "Castle Gates " + state.mode.name() + " mode off"); + } + } + + public PlayerState getPlayerState(Player player) { + return _states.get(player); + } + + public void setPlayerMode(Player player, CommandMode mode, Integer timer, TimerOperation timerOperation, TimerMode timerMode) { + if(mode == CommandMode.OFF) { + clearPlayerMode(player); + return; + } + + PlayerState state = _states.get(player); + + if(state == null) { + if(mode == CommandMode.NORMAL) { + player.sendMessage(ChatColor.GREEN + "Castle Gates " + mode.name() + " mode on"); + return; + } + + _states.put(player, state = new PlayerState()); + } + else if(state.mode == mode) { + clearPlayerMode(player); + return; + } + + state.mode = mode; + state.timer = timer; + state.timerOperation = timerOperation; + state.timerMode = timerMode; + state.lastInteracted = System.currentTimeMillis(); + + addTask(player); + + player.sendMessage(ChatColor.GREEN + "Castle Gates " + mode.name() + " mode on"); + } + + public void interact(Player player) { + PlayerState state = _states.get(player); + + if(state != null) { + state.lastInteracted = System.currentTimeMillis(); + } + } + + private void addTask(final Player player) { + if(_tasks.containsKey(player)) return; + + final PlayerStateManager stateManager = this; + + int taskId = Bukkit.getScheduler().runTaskTimer( + CastleGates.getInstance(), + () -> { + PlayerState state = stateManager._states.get(player); + if(state != null) { + long offTime = state.lastInteracted + 1000L * CastleGates.getConfigManager().getPlayerStateResetInSeconds(); + + if(offTime < System.currentTimeMillis()) { + clearPlayerMode(player); + } + } + }, + 20L * 30, + 20L * 30 + ).getTaskId(); + + _tasks.put(player, taskId); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/StorageManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/StorageManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/StorageManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/StorageManager.java index 80dafc40a..67416ff22 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/StorageManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/StorageManager.java @@ -1,114 +1,114 @@ -/** - * Created by Aleksey Terzi - */ - -package com.aleksey.castlegates.engine; - -import com.aleksey.castlegates.database.SqlDatabase; -import com.aleksey.castlegates.types.*; -import com.aleksey.castlegates.utils.DataWorker; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -public class StorageManager { - private Map _gearblocks; - private DataWorker _dataWorker; - - public void init(SqlDatabase db) throws SQLException { - _dataWorker = new DataWorker(db); - - _gearblocks = _dataWorker.load(); - - _dataWorker.startThread(); - } - - public void close() { - if(_dataWorker != null) { - _dataWorker.close(); - _dataWorker = null; - } - } - - public Gearblock getGearblock(BlockCoord location) { - return _gearblocks.get(location); - } - - public boolean hasGearblock(BlockCoord location) { - return _gearblocks.containsKey(location); - } - - public void addGearblock(BlockCoord location) { - Gearblock gearblock = new Gearblock(location); - - _gearblocks.put(location, gearblock); - - _dataWorker.addChangedGearblock(gearblock); - } - - public void removeGearblock(Gearblock gearblock) { - _gearblocks.remove(gearblock.getCoord()); - - gearblock.setRemoved(); - - _dataWorker.addChangedGearblock(gearblock); - } - - public void addLink(Gearblock gearblock1, Gearblock gearblock2) { - GearblockLink link; - - if(gearblock1.getBrokenLink() != null) { - link = gearblock1.getBrokenLink(); - link.setRestored(gearblock2); - } - else if(gearblock2.getBrokenLink() != null) { - link = gearblock2.getBrokenLink(); - link.setRestored(gearblock1); - } - else { - link = new GearblockLink(gearblock1, gearblock2); - } - - gearblock1.setLink(link); - gearblock2.setLink(link); - - _dataWorker.addChangedLink(link); - } - - public void removeLink(GearblockLink link) { - link.setRemoved(); - - if(link.getGearblock1() != null) { - link.getGearblock1().setLink(null); - } - - if(link.getGearblock2() != null) { - link.getGearblock2().setLink(null); - } - - _dataWorker.addChangedLink(link); - } - - public void setLinkBlocks(GearblockLink link, List blocks) { - link.setBlocks(blocks); - _dataWorker.addChangedLink(link); - } - - public void setLinkBroken(Gearblock gearblock) { - gearblock.getLink().setBroken(gearblock); - _dataWorker.addChangedLink(gearblock.getBrokenLink()); - } - - public void setGearblockTimer(Gearblock gearblock, Integer timer, TimerOperation timerOperation, TimerMode timerMode) { - gearblock.setTimer(timer, timerOperation, timerMode); - - _dataWorker.addChangedGearblock(gearblock); - } - - public void clearGearblockTimer(Gearblock gearblock) { - gearblock.setTimer(null, null, null); - - _dataWorker.addChangedGearblock(gearblock); - } +/** + * Created by Aleksey Terzi + */ + +package com.aleksey.castlegates.engine; + +import com.aleksey.castlegates.database.SqlDatabase; +import com.aleksey.castlegates.types.*; +import com.aleksey.castlegates.utils.DataWorker; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +public class StorageManager { + private Map _gearblocks; + private DataWorker _dataWorker; + + public void init(SqlDatabase db) throws SQLException { + _dataWorker = new DataWorker(db); + + _gearblocks = _dataWorker.load(); + + _dataWorker.startThread(); + } + + public void close() { + if(_dataWorker != null) { + _dataWorker.close(); + _dataWorker = null; + } + } + + public Gearblock getGearblock(BlockCoord location) { + return _gearblocks.get(location); + } + + public boolean hasGearblock(BlockCoord location) { + return _gearblocks.containsKey(location); + } + + public void addGearblock(BlockCoord location) { + Gearblock gearblock = new Gearblock(location); + + _gearblocks.put(location, gearblock); + + _dataWorker.addChangedGearblock(gearblock); + } + + public void removeGearblock(Gearblock gearblock) { + _gearblocks.remove(gearblock.getCoord()); + + gearblock.setRemoved(); + + _dataWorker.addChangedGearblock(gearblock); + } + + public void addLink(Gearblock gearblock1, Gearblock gearblock2) { + GearblockLink link; + + if(gearblock1.getBrokenLink() != null) { + link = gearblock1.getBrokenLink(); + link.setRestored(gearblock2); + } + else if(gearblock2.getBrokenLink() != null) { + link = gearblock2.getBrokenLink(); + link.setRestored(gearblock1); + } + else { + link = new GearblockLink(gearblock1, gearblock2); + } + + gearblock1.setLink(link); + gearblock2.setLink(link); + + _dataWorker.addChangedLink(link); + } + + public void removeLink(GearblockLink link) { + link.setRemoved(); + + if(link.getGearblock1() != null) { + link.getGearblock1().setLink(null); + } + + if(link.getGearblock2() != null) { + link.getGearblock2().setLink(null); + } + + _dataWorker.addChangedLink(link); + } + + public void setLinkBlocks(GearblockLink link, List blocks) { + link.setBlocks(blocks); + _dataWorker.addChangedLink(link); + } + + public void setLinkBroken(Gearblock gearblock) { + gearblock.getLink().setBroken(gearblock); + _dataWorker.addChangedLink(gearblock.getBrokenLink()); + } + + public void setGearblockTimer(Gearblock gearblock, Integer timer, TimerOperation timerOperation, TimerMode timerMode) { + gearblock.setTimer(timer, timerOperation, timerMode); + + _dataWorker.addChangedGearblock(gearblock); + } + + public void clearGearblockTimer(Gearblock gearblock) { + gearblock.setTimer(null, null, null); + + _dataWorker.addChangedGearblock(gearblock); + } } \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeEventHandler.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeEventHandler.java similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeEventHandler.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeEventHandler.java index 1a8d3f651..69b1afd13 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeEventHandler.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeEventHandler.java @@ -1,524 +1,524 @@ -/** - * Created by Aleksey Terzi - */ - -package com.aleksey.castlegates.engine.bridge; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.config.ConfigManager; -import com.aleksey.castlegates.engine.PlayerStateManager; -import com.aleksey.castlegates.engine.StorageManager; -import com.aleksey.castlegates.types.*; -import com.aleksey.castlegates.utils.Helper; -import com.aleksey.castlegates.utils.ParticleHelper; -import com.aleksey.castlegates.utils.PowerResultHelper; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; - -import java.util.HashSet; -import java.util.List; -import java.util.UUID; - -public class BridgeEventHandler { - private static class FindGearResult { - public Gearblock gearblock; - public int distance; - - public FindGearResult(Gearblock gearblock, int distance) { - this.gearblock = gearblock; - this.distance = distance; - } - } - - private final StorageManager _storage; - private final BridgeManager _bridgeManager; - private final HashSet _waitingBlocks = new HashSet<>(); - private final HashSet _processingBlocks = new HashSet<>(); - - public BridgeEventHandler(StorageManager storage, BridgeManager bridgeManager) { - _storage = storage; - _bridgeManager = bridgeManager; - } - - public boolean handleBlockClicked(PlayerInteractEvent event, PlayerStateManager.PlayerState state) { - if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getHand() == EquipmentSlot.HAND) { - simpleActivate(event); - return false; - } - - if(event.getAction() != Action.LEFT_CLICK_BLOCK) - return false; - - boolean interacted = false; - ConfigManager configManager = CastleGates.getConfigManager(); - CommandMode mode = state != null ? state.mode: CommandMode.OFF; - - if(configManager.getAllowAutoCreate() && configManager.isCreationConsumeItem(event.getItem())) { - interacted = createGearblockAndLink(event); - } - else if(mode == CommandMode.INFO) { - showGearInfo(event); - interacted = true; - } - else if(mode == CommandMode.TIMER) { - interacted = setGearblockTimer(event, state); - } - else if(configManager.isStickItem(event.getItem())) { - interacted = switch(mode) { - case CREATE -> createGearblock(event); - case LINK -> linkGearblocks(event); - default -> false; - }; - } - - return interacted; - } - - public void handleBlockBreak(BlockBreakEvent event) { - Block block = event.getBlock(); - BridgeManager.RemoveResult result = _bridgeManager.removeGear(new BlockCoord(block)); - - if(result == BridgeManager.RemoveResult.Removed || result == BridgeManager.RemoveResult.RemovedWithLink) { - Helper.putItemToInventoryOrDrop(event.getPlayer(), block.getLocation(), CastleGates.getConfigManager().getCreationConsumeItem()); - } - } - - public void handleBlockRedstone(BlockRedstoneEvent event) { - if ((event.getOldCurrent() != 0) == (event.getNewCurrent() != 0)) return; - - Block block = event.getBlock(); - - for (BlockFace face : BridgeManager.faces) { - Block faceBlock = block.getRelative(face); - - if(_storage.getGearblock(new BlockCoord(faceBlock)) != null) { - _waitingBlocks.add(faceBlock); - } - } - } - - public void handleBlockPhysics(BlockPhysicsEvent event) { - Block block = event.getBlock(); - - if(_waitingBlocks.remove(block)) { - processBlock(block, block.isBlockPowered()); - } - } - - public void handleEntityExplode(EntityExplodeEvent event) { - for (Block block : event.blockList()) { - _bridgeManager.removeGear(new BlockCoord(block)); - } - } - - public void handleEntityChangeBlock(EntityChangeBlockEvent event) { - _bridgeManager.removeGear(new BlockCoord(event.getBlock())); - } - - public void handlePistonEvent(List blocks) { - ItemStack dropItem = CastleGates.getConfigManager().getCreationConsumeItem(); - - for (Block block : blocks) { - BridgeManager.RemoveResult result = _bridgeManager.removeGear(new BlockCoord(block)); - - if(result == BridgeManager.RemoveResult.Removed || result == BridgeManager.RemoveResult.RemovedWithLink) { - Helper.putItemToInventoryOrDrop(null, block.getLocation(), dropItem); - } - } - } - - private boolean createGearblockAndLink(PlayerInteractEvent event) { - if(event.getClickedBlock() == null - || CastleGates.getCitadelManager().isReinforcingStateActive(event.getPlayer()) - || !createGearblock(event) - ) { - return false; - } - - Block block = event.getClickedBlock(); - Gearblock gearblock1 = _storage.getGearblock(new BlockCoord(block)); - - if(gearblock1.getLink() != null) - return true; - - for(BlockFace face : BridgeManager.faces) { - FindGearResult result = findEndGear(block, face); - - if(result != null - && result.gearblock.getLink() == null - && linkGearblocks(event.getPlayer(), gearblock1, result, false) - ) - { - break; - } - } - - return true; - } - - private boolean createGearblock(PlayerInteractEvent event) { - Player player = event.getPlayer(); - Block block = event.getClickedBlock(); - - if (block == null) - return false; - - Location location = block.getLocation(); - - if(CastleGates.getConfigManager().isGearblockMustBeReinforced() - && !CastleGates.getCitadelManager().isReinforced(location)) - { - player.sendMessage(ChatColor.RED + "Block must be reinforced to create a gearblock."); - return false; - } - - if(!CastleGates.getCitadelManager().canBypass(player, location)) { - player.sendMessage(ChatColor.RED + "Citadel has prevented the creation of a gearblock."); - return false; - } - - ItemStack consumeItem = CastleGates.getConfigManager().getCreationConsumeItem(); - List consumeSlots = Helper.getConsumeSlots(player, consumeItem); - - if(consumeSlots == null && consumeItem != null) { - player.sendMessage(ChatColor.RED + "Not enough material left to create a gearblock."); - return false; - } - - BridgeManager.CreateResult result = _bridgeManager.createGear(block); - - if(result == BridgeManager.CreateResult.NotCreated) { - player.sendMessage(ChatColor.RED + block.getType().toString() + " cannot be used as a gearblock."); - return false; - } else if(result == BridgeManager.CreateResult.AlreadyExist) { - player.sendMessage(ChatColor.RED + "That block is already a gearblock."); - return true; - } - - Helper.consumeItem(player, consumeItem, consumeSlots); - - player.sendMessage(ChatColor.GREEN + "A gearblock has been created."); - - ParticleHelper.spawn(block, ParticleHelper.Type.Info); - - return true; - } - - private boolean linkGearblocks(PlayerInteractEvent event) { - Player player = event.getPlayer(); - Block block = event.getClickedBlock(); - - if (block == null) - return false; - - Gearblock gearblock1 = _storage.getGearblock(new BlockCoord(block)); - - if(gearblock1 == null) - return false; - - if(!CastleGates.getCitadelManager().canBypass(player, block.getLocation())) { - player.sendMessage(ChatColor.RED + "Citadel has prevented the creation of a link."); - return false; - } - - if(gearblock1.getLink() != null) { - if(gearblock1.getLink().isDrawn()) { - player.sendMessage(ChatColor.RED + "Cannot unlink gearblocks in a drawn bridge/gate."); - } else { - _bridgeManager.removeLink(gearblock1.getLink()); - player.sendMessage(ChatColor.GREEN + "The gearblocks have been unlinked."); - } - - return true; - } - - FindGearResult result = findEndGear(block, event.getBlockFace()); - - if(result == null) { - event.getPlayer().sendMessage(ChatColor.RED + "End gearblock not found. Link distance is limited to " + CastleGates.getConfigManager().getMaxBridgeLength() + " blocks."); - } else { - linkGearblocks(player, gearblock1, result, true); - } - - return true; - } - - private boolean linkGearblocks(Player player, Gearblock gearblock1, FindGearResult result, boolean showError) { - Location loc = new Location(player.getWorld(), result.gearblock.getCoord().getX(), result.gearblock.getCoord().getY(), result.gearblock.getCoord().getZ()); - - if(!CastleGates.getCitadelManager().canBypass(player, loc)) { - if(showError) { - player.sendMessage(ChatColor.RED + "Citadel has prevented the creation of a link."); - } - - return false; - } - - if(result.gearblock.getLink() != null) { - if(showError) { - player.sendMessage(ChatColor.RED + "The gearblock at [" + result.gearblock.getCoord().getX() + " " + result.gearblock.getCoord().getY() + " " + result.gearblock.getCoord().getZ() + "] already has a link. Remove it before creating a new one."); - ParticleHelper.spawn(player, result.gearblock, ParticleHelper.Type.Warning); - } - - return false; - } - - if(_bridgeManager.createLink(gearblock1, result.gearblock, result.distance)) { - player.sendMessage(ChatColor.GREEN + "The gearblock has been linked with the gearblock at [" + result.gearblock.getCoord().getX() + " " + result.gearblock.getCoord().getY() + " " + result.gearblock.getCoord().getZ() + "]."); - ParticleHelper.spawn(player, gearblock1, ParticleHelper.Type.Info); - ParticleHelper.spawn(player, result.gearblock, ParticleHelper.Type.Info); - return true; - } - - if(showError) { - player.sendMessage(ChatColor.RED + "The gearblock at [" + result.gearblock.getCoord().getX() + " " + result.gearblock.getCoord().getY() + " " + result.gearblock.getCoord().getZ() + "] has a broken link which cannot be restored by using the clicked block. Click the block where the other gearblock used to be."); - ParticleHelper.spawn(player, result.gearblock, ParticleHelper.Type.Warning); - } - - return false; - } - - private FindGearResult findEndGear(Block startGearBlock, BlockFace blockFace) { - UUID worldUID = startGearBlock.getWorld().getUID(); - int x = startGearBlock.getX(); - int y = startGearBlock.getY(); - int z = startGearBlock.getZ(); - int maxBridgeLength = CastleGates.getConfigManager().getMaxBridgeLength(); - - boolean isNonSimpleDisabled = CastleGates.getConfigManager().isHorizontalLinkDisabled() - && blockFace != BlockFace.UP - && blockFace != BlockFace.DOWN; - - for(int i = 0; i < maxBridgeLength; i++) { - x += blockFace.getModX(); - y += blockFace.getModY(); - z += blockFace.getModZ(); - - BlockCoord location = new BlockCoord(worldUID, x, y, z); - Gearblock gearblock = _storage.getGearblock(location); - - if(gearblock != null) { - if (i == 0 || i > 1 && isNonSimpleDisabled) - return null; - - if (isNonSimpleDisabled && ( - hasAdjacentGearblocks(worldUID, startGearBlock.getX(), startGearBlock.getY(), startGearBlock.getZ()) - || hasAdjacentGearblocks(worldUID, x, y, z) - ) - ) { - return null; - } - - return new FindGearResult(gearblock, i); - } - } - - return null; - } - - private boolean hasAdjacentGearblocks(UUID worldUID, int x, int y, int z) { - return _storage.hasGearblock(new BlockCoord(worldUID, x + 1, y, z)) - || _storage.hasGearblock(new BlockCoord(worldUID, x - 1, y, z)) - || _storage.hasGearblock(new BlockCoord(worldUID, x, y + 1, z)) - || _storage.hasGearblock(new BlockCoord(worldUID, x, y - 1, z)) - || _storage.hasGearblock(new BlockCoord(worldUID, x, y, z + 1)) - || _storage.hasGearblock(new BlockCoord(worldUID, x, y, z - 1)); - } - - private void showGearInfo(PlayerInteractEvent event) { - Player player = event.getPlayer(); - Block block = event.getClickedBlock(); - - if (block == null) - return; - - BlockCoord blockCoord = new BlockCoord(block); - Gearblock gearblock = _storage.getGearblock(blockCoord); - - if(gearblock == null) { - BridgeManager.SearchBridgeBlockResult searchResult = _bridgeManager.searchBridgeBlock(blockCoord); - - switch(searchResult) { - case Bridge -> player.sendMessage("Bridge block"); - case Gates -> player.sendMessage("Gate block"); - } - - return; - } - - if(!CastleGates.getCitadelManager().canViewInformation(player, block.getLocation())) { - player.sendMessage(ChatColor.RED + "Gearblock"); - } - else { - if(gearblock.getLink() == null) { - player.sendMessage(ChatColor.GREEN + "The gearblock is not linked."); - - if(gearblock.getBrokenLink() != null) { - player.sendMessage(ChatColor.GREEN + "But contains " + gearblock.getBrokenLink().getBlocks().size() + " drawn blocks."); - } - } - else { - Gearblock gearblock2 = gearblock.getLink().getGearblock1() == gearblock ? gearblock.getLink().getGearblock2(): gearblock.getLink().getGearblock1(); - player.sendMessage(ChatColor.GREEN + "The gearblock has been linked to the gearblock at [" + gearblock2.getCoord().getX() + " " + gearblock2.getCoord().getY() + " " + gearblock2.getCoord().getZ() + "]."); - - if(gearblock.getLink().isDrawn()) { - player.sendMessage(ChatColor.GREEN + "The bridge/gate is drawn."); - } - - ParticleHelper.spawn(player, gearblock2, ParticleHelper.Type.Info); - } - - if(gearblock.getTimer() != null) { - String message = "Timer: " + gearblock.getTimer() + " sec to process operation " + gearblock.getTimerOperation() + " in " + gearblock.getTimerMode() + " mode."; - player.sendMessage(ChatColor.GREEN + message); - } - - if(gearblock.getLockedGearblocks() != null || gearblock.getLockGearblock() != null) { - player.sendMessage(ChatColor.YELLOW + "Locked"); - } - } - } - - private void processBlock(Block block, boolean isPowered) { - if(_processingBlocks.contains(block)) - return; - - Gearblock gearblock = _storage.getGearblock(new BlockCoord(block)); - - if(gearblock == null || gearblock.isPowered() == isPowered) - return; - - _processingBlocks.add(block); - - try - { - List players = Helper.getNearbyPlayers(block.getLocation()); - - PowerResult result = _bridgeManager.processGearblock( - block.getWorld(), - gearblock, - isPowered, - players - ); - - if(result.status == PowerResult.Status.Locked && gearblock.getTimerMode() == TimerMode.DOOR) { - result = PowerResult.Unchanged; - } - - PowerResultHelper.showStatus(block.getLocation(), players, result); - } finally { - _processingBlocks.remove(block); - } - } - - private boolean setGearblockTimer(PlayerInteractEvent event, PlayerStateManager.PlayerState state) { - Player player = event.getPlayer(); - Block block = event.getClickedBlock(); - - if (block == null) - return true; - - if(!CastleGates.getConfigManager().isTimerEnabled()) { - player.sendMessage(ChatColor.RED + "The timer function is disabled on this server."); - return true; - } - - BlockCoord blockCoord = new BlockCoord(block); - Gearblock gearblock = _storage.getGearblock(blockCoord); - - if(gearblock == null) { - player.sendMessage(ChatColor.RED + "That block is not a gearblock."); - return true; - } - - if(!CastleGates.getCitadelManager().canBypass(player, block.getLocation())) { - player.sendMessage(ChatColor.RED + "Citadel has prevented that operation."); - return true; - } - - String message; - - if(gearblock.getTimer() == null) { - _storage.setGearblockTimer(gearblock, state.timer, state.timerOperation, state.timerMode); - String modeText = state.timerMode == TimerMode.DEFAULT ? "DEFAULT" : "DOOR"; - message = ChatColor.GREEN + "The gearblock's timer has been set to " + state.timer + " sec to process operation " + state.timerOperation + " in " + modeText + " mode."; - } else { - _storage.clearGearblockTimer(gearblock); - message = ChatColor.YELLOW + "The gearblock's timer has been removed."; - } - - player.sendMessage(message); - - ParticleHelper.spawn(player, gearblock, ParticleHelper.Type.Info); - - return true; - } - - private void simpleActivate(PlayerInteractEvent event) { - Block block = event.getClickedBlock(); - - if (block == null) - return; - - BlockCoord blockCoord = new BlockCoord(block); - Gearblock gearblock = _storage.getGearblock(blockCoord); - - if(gearblock != null) - return; - - GearblockLink link; - - if((link = getLink(blockCoord.getForward(), blockCoord.getBackward())) == null - && (link = getLink(blockCoord.getRight(), blockCoord.getLeft())) == null - && (link = getLink(blockCoord.getTop(), blockCoord.getBottom())) == null - ) - { - return; - } - - if(_bridgeManager.isNotSimpleGearblock(link.getGearblock1(), event.getPlayer()) - || _bridgeManager.isNotSimpleGearblock(link.getGearblock2(), event.getPlayer()) - ) - { - return; - } - - BlockCoord processCoord = link.getGearblock1().getCoord(); - Block processBlock = block.getWorld().getBlockAt(processCoord.getX(), processCoord.getY(), processCoord.getZ()); - - if(_waitingBlocks.contains(processBlock)) - return; - - processBlock(processBlock, true); - processBlock(processBlock, false); - } - - private GearblockLink getLink(BlockCoord start, BlockCoord end) { - Gearblock gearblock = _storage.getGearblock(start); - GearblockLink link = gearblock != null ? gearblock.getLink() : null; - - if(link != null && - ( - link.getGearblock1().getCoord().equals(start) && link.getGearblock2().getCoord().equals(end) - || link.getGearblock1().getCoord().equals(end) && link.getGearblock2().getCoord().equals(start) - ) - ) - { - return link; - } - - return null; - } +/** + * Created by Aleksey Terzi + */ + +package com.aleksey.castlegates.engine.bridge; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.config.ConfigManager; +import com.aleksey.castlegates.engine.PlayerStateManager; +import com.aleksey.castlegates.engine.StorageManager; +import com.aleksey.castlegates.types.*; +import com.aleksey.castlegates.utils.Helper; +import com.aleksey.castlegates.utils.ParticleHelper; +import com.aleksey.castlegates.utils.PowerResultHelper; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; + +import java.util.HashSet; +import java.util.List; +import java.util.UUID; + +public class BridgeEventHandler { + private static class FindGearResult { + public Gearblock gearblock; + public int distance; + + public FindGearResult(Gearblock gearblock, int distance) { + this.gearblock = gearblock; + this.distance = distance; + } + } + + private final StorageManager _storage; + private final BridgeManager _bridgeManager; + private final HashSet _waitingBlocks = new HashSet<>(); + private final HashSet _processingBlocks = new HashSet<>(); + + public BridgeEventHandler(StorageManager storage, BridgeManager bridgeManager) { + _storage = storage; + _bridgeManager = bridgeManager; + } + + public boolean handleBlockClicked(PlayerInteractEvent event, PlayerStateManager.PlayerState state) { + if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getHand() == EquipmentSlot.HAND) { + simpleActivate(event); + return false; + } + + if(event.getAction() != Action.LEFT_CLICK_BLOCK) + return false; + + boolean interacted = false; + ConfigManager configManager = CastleGates.getConfigManager(); + CommandMode mode = state != null ? state.mode: CommandMode.OFF; + + if(configManager.getAllowAutoCreate() && configManager.isCreationConsumeItem(event.getItem())) { + interacted = createGearblockAndLink(event); + } + else if(mode == CommandMode.INFO) { + showGearInfo(event); + interacted = true; + } + else if(mode == CommandMode.TIMER) { + interacted = setGearblockTimer(event, state); + } + else if(configManager.isStickItem(event.getItem())) { + interacted = switch(mode) { + case CREATE -> createGearblock(event); + case LINK -> linkGearblocks(event); + default -> false; + }; + } + + return interacted; + } + + public void handleBlockBreak(BlockBreakEvent event) { + Block block = event.getBlock(); + BridgeManager.RemoveResult result = _bridgeManager.removeGear(new BlockCoord(block)); + + if(result == BridgeManager.RemoveResult.Removed || result == BridgeManager.RemoveResult.RemovedWithLink) { + Helper.putItemToInventoryOrDrop(event.getPlayer(), block.getLocation(), CastleGates.getConfigManager().getCreationConsumeItem()); + } + } + + public void handleBlockRedstone(BlockRedstoneEvent event) { + if ((event.getOldCurrent() != 0) == (event.getNewCurrent() != 0)) return; + + Block block = event.getBlock(); + + for (BlockFace face : BridgeManager.faces) { + Block faceBlock = block.getRelative(face); + + if(_storage.getGearblock(new BlockCoord(faceBlock)) != null) { + _waitingBlocks.add(faceBlock); + } + } + } + + public void handleBlockPhysics(BlockPhysicsEvent event) { + Block block = event.getBlock(); + + if(_waitingBlocks.remove(block)) { + processBlock(block, block.isBlockPowered()); + } + } + + public void handleEntityExplode(EntityExplodeEvent event) { + for (Block block : event.blockList()) { + _bridgeManager.removeGear(new BlockCoord(block)); + } + } + + public void handleEntityChangeBlock(EntityChangeBlockEvent event) { + _bridgeManager.removeGear(new BlockCoord(event.getBlock())); + } + + public void handlePistonEvent(List blocks) { + ItemStack dropItem = CastleGates.getConfigManager().getCreationConsumeItem(); + + for (Block block : blocks) { + BridgeManager.RemoveResult result = _bridgeManager.removeGear(new BlockCoord(block)); + + if(result == BridgeManager.RemoveResult.Removed || result == BridgeManager.RemoveResult.RemovedWithLink) { + Helper.putItemToInventoryOrDrop(null, block.getLocation(), dropItem); + } + } + } + + private boolean createGearblockAndLink(PlayerInteractEvent event) { + if(event.getClickedBlock() == null + || CastleGates.getCitadelManager().isReinforcingStateActive(event.getPlayer()) + || !createGearblock(event) + ) { + return false; + } + + Block block = event.getClickedBlock(); + Gearblock gearblock1 = _storage.getGearblock(new BlockCoord(block)); + + if(gearblock1.getLink() != null) + return true; + + for(BlockFace face : BridgeManager.faces) { + FindGearResult result = findEndGear(block, face); + + if(result != null + && result.gearblock.getLink() == null + && linkGearblocks(event.getPlayer(), gearblock1, result, false) + ) + { + break; + } + } + + return true; + } + + private boolean createGearblock(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + + if (block == null) + return false; + + Location location = block.getLocation(); + + if(CastleGates.getConfigManager().isGearblockMustBeReinforced() + && !CastleGates.getCitadelManager().isReinforced(location)) + { + player.sendMessage(ChatColor.RED + "Block must be reinforced to create a gearblock."); + return false; + } + + if(!CastleGates.getCitadelManager().canBypass(player, location)) { + player.sendMessage(ChatColor.RED + "Citadel has prevented the creation of a gearblock."); + return false; + } + + ItemStack consumeItem = CastleGates.getConfigManager().getCreationConsumeItem(); + List consumeSlots = Helper.getConsumeSlots(player, consumeItem); + + if(consumeSlots == null && consumeItem != null) { + player.sendMessage(ChatColor.RED + "Not enough material left to create a gearblock."); + return false; + } + + BridgeManager.CreateResult result = _bridgeManager.createGear(block); + + if(result == BridgeManager.CreateResult.NotCreated) { + player.sendMessage(ChatColor.RED + block.getType().toString() + " cannot be used as a gearblock."); + return false; + } else if(result == BridgeManager.CreateResult.AlreadyExist) { + player.sendMessage(ChatColor.RED + "That block is already a gearblock."); + return true; + } + + Helper.consumeItem(player, consumeItem, consumeSlots); + + player.sendMessage(ChatColor.GREEN + "A gearblock has been created."); + + ParticleHelper.spawn(block, ParticleHelper.Type.Info); + + return true; + } + + private boolean linkGearblocks(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + + if (block == null) + return false; + + Gearblock gearblock1 = _storage.getGearblock(new BlockCoord(block)); + + if(gearblock1 == null) + return false; + + if(!CastleGates.getCitadelManager().canBypass(player, block.getLocation())) { + player.sendMessage(ChatColor.RED + "Citadel has prevented the creation of a link."); + return false; + } + + if(gearblock1.getLink() != null) { + if(gearblock1.getLink().isDrawn()) { + player.sendMessage(ChatColor.RED + "Cannot unlink gearblocks in a drawn bridge/gate."); + } else { + _bridgeManager.removeLink(gearblock1.getLink()); + player.sendMessage(ChatColor.GREEN + "The gearblocks have been unlinked."); + } + + return true; + } + + FindGearResult result = findEndGear(block, event.getBlockFace()); + + if(result == null) { + event.getPlayer().sendMessage(ChatColor.RED + "End gearblock not found. Link distance is limited to " + CastleGates.getConfigManager().getMaxBridgeLength() + " blocks."); + } else { + linkGearblocks(player, gearblock1, result, true); + } + + return true; + } + + private boolean linkGearblocks(Player player, Gearblock gearblock1, FindGearResult result, boolean showError) { + Location loc = new Location(player.getWorld(), result.gearblock.getCoord().getX(), result.gearblock.getCoord().getY(), result.gearblock.getCoord().getZ()); + + if(!CastleGates.getCitadelManager().canBypass(player, loc)) { + if(showError) { + player.sendMessage(ChatColor.RED + "Citadel has prevented the creation of a link."); + } + + return false; + } + + if(result.gearblock.getLink() != null) { + if(showError) { + player.sendMessage(ChatColor.RED + "The gearblock at [" + result.gearblock.getCoord().getX() + " " + result.gearblock.getCoord().getY() + " " + result.gearblock.getCoord().getZ() + "] already has a link. Remove it before creating a new one."); + ParticleHelper.spawn(player, result.gearblock, ParticleHelper.Type.Warning); + } + + return false; + } + + if(_bridgeManager.createLink(gearblock1, result.gearblock, result.distance)) { + player.sendMessage(ChatColor.GREEN + "The gearblock has been linked with the gearblock at [" + result.gearblock.getCoord().getX() + " " + result.gearblock.getCoord().getY() + " " + result.gearblock.getCoord().getZ() + "]."); + ParticleHelper.spawn(player, gearblock1, ParticleHelper.Type.Info); + ParticleHelper.spawn(player, result.gearblock, ParticleHelper.Type.Info); + return true; + } + + if(showError) { + player.sendMessage(ChatColor.RED + "The gearblock at [" + result.gearblock.getCoord().getX() + " " + result.gearblock.getCoord().getY() + " " + result.gearblock.getCoord().getZ() + "] has a broken link which cannot be restored by using the clicked block. Click the block where the other gearblock used to be."); + ParticleHelper.spawn(player, result.gearblock, ParticleHelper.Type.Warning); + } + + return false; + } + + private FindGearResult findEndGear(Block startGearBlock, BlockFace blockFace) { + UUID worldUID = startGearBlock.getWorld().getUID(); + int x = startGearBlock.getX(); + int y = startGearBlock.getY(); + int z = startGearBlock.getZ(); + int maxBridgeLength = CastleGates.getConfigManager().getMaxBridgeLength(); + + boolean isNonSimpleDisabled = CastleGates.getConfigManager().isHorizontalLinkDisabled() + && blockFace != BlockFace.UP + && blockFace != BlockFace.DOWN; + + for(int i = 0; i < maxBridgeLength; i++) { + x += blockFace.getModX(); + y += blockFace.getModY(); + z += blockFace.getModZ(); + + BlockCoord location = new BlockCoord(worldUID, x, y, z); + Gearblock gearblock = _storage.getGearblock(location); + + if(gearblock != null) { + if (i == 0 || i > 1 && isNonSimpleDisabled) + return null; + + if (isNonSimpleDisabled && ( + hasAdjacentGearblocks(worldUID, startGearBlock.getX(), startGearBlock.getY(), startGearBlock.getZ()) + || hasAdjacentGearblocks(worldUID, x, y, z) + ) + ) { + return null; + } + + return new FindGearResult(gearblock, i); + } + } + + return null; + } + + private boolean hasAdjacentGearblocks(UUID worldUID, int x, int y, int z) { + return _storage.hasGearblock(new BlockCoord(worldUID, x + 1, y, z)) + || _storage.hasGearblock(new BlockCoord(worldUID, x - 1, y, z)) + || _storage.hasGearblock(new BlockCoord(worldUID, x, y + 1, z)) + || _storage.hasGearblock(new BlockCoord(worldUID, x, y - 1, z)) + || _storage.hasGearblock(new BlockCoord(worldUID, x, y, z + 1)) + || _storage.hasGearblock(new BlockCoord(worldUID, x, y, z - 1)); + } + + private void showGearInfo(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + + if (block == null) + return; + + BlockCoord blockCoord = new BlockCoord(block); + Gearblock gearblock = _storage.getGearblock(blockCoord); + + if(gearblock == null) { + BridgeManager.SearchBridgeBlockResult searchResult = _bridgeManager.searchBridgeBlock(blockCoord); + + switch(searchResult) { + case Bridge -> player.sendMessage("Bridge block"); + case Gates -> player.sendMessage("Gate block"); + } + + return; + } + + if(!CastleGates.getCitadelManager().canViewInformation(player, block.getLocation())) { + player.sendMessage(ChatColor.RED + "Gearblock"); + } + else { + if(gearblock.getLink() == null) { + player.sendMessage(ChatColor.GREEN + "The gearblock is not linked."); + + if(gearblock.getBrokenLink() != null) { + player.sendMessage(ChatColor.GREEN + "But contains " + gearblock.getBrokenLink().getBlocks().size() + " drawn blocks."); + } + } + else { + Gearblock gearblock2 = gearblock.getLink().getGearblock1() == gearblock ? gearblock.getLink().getGearblock2(): gearblock.getLink().getGearblock1(); + player.sendMessage(ChatColor.GREEN + "The gearblock has been linked to the gearblock at [" + gearblock2.getCoord().getX() + " " + gearblock2.getCoord().getY() + " " + gearblock2.getCoord().getZ() + "]."); + + if(gearblock.getLink().isDrawn()) { + player.sendMessage(ChatColor.GREEN + "The bridge/gate is drawn."); + } + + ParticleHelper.spawn(player, gearblock2, ParticleHelper.Type.Info); + } + + if(gearblock.getTimer() != null) { + String message = "Timer: " + gearblock.getTimer() + " sec to process operation " + gearblock.getTimerOperation() + " in " + gearblock.getTimerMode() + " mode."; + player.sendMessage(ChatColor.GREEN + message); + } + + if(gearblock.getLockedGearblocks() != null || gearblock.getLockGearblock() != null) { + player.sendMessage(ChatColor.YELLOW + "Locked"); + } + } + } + + private void processBlock(Block block, boolean isPowered) { + if(_processingBlocks.contains(block)) + return; + + Gearblock gearblock = _storage.getGearblock(new BlockCoord(block)); + + if(gearblock == null || gearblock.isPowered() == isPowered) + return; + + _processingBlocks.add(block); + + try + { + List players = Helper.getNearbyPlayers(block.getLocation()); + + PowerResult result = _bridgeManager.processGearblock( + block.getWorld(), + gearblock, + isPowered, + players + ); + + if(result.status == PowerResult.Status.Locked && gearblock.getTimerMode() == TimerMode.DOOR) { + result = PowerResult.Unchanged; + } + + PowerResultHelper.showStatus(block.getLocation(), players, result); + } finally { + _processingBlocks.remove(block); + } + } + + private boolean setGearblockTimer(PlayerInteractEvent event, PlayerStateManager.PlayerState state) { + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + + if (block == null) + return true; + + if(!CastleGates.getConfigManager().isTimerEnabled()) { + player.sendMessage(ChatColor.RED + "The timer function is disabled on this server."); + return true; + } + + BlockCoord blockCoord = new BlockCoord(block); + Gearblock gearblock = _storage.getGearblock(blockCoord); + + if(gearblock == null) { + player.sendMessage(ChatColor.RED + "That block is not a gearblock."); + return true; + } + + if(!CastleGates.getCitadelManager().canBypass(player, block.getLocation())) { + player.sendMessage(ChatColor.RED + "Citadel has prevented that operation."); + return true; + } + + String message; + + if(gearblock.getTimer() == null) { + _storage.setGearblockTimer(gearblock, state.timer, state.timerOperation, state.timerMode); + String modeText = state.timerMode == TimerMode.DEFAULT ? "DEFAULT" : "DOOR"; + message = ChatColor.GREEN + "The gearblock's timer has been set to " + state.timer + " sec to process operation " + state.timerOperation + " in " + modeText + " mode."; + } else { + _storage.clearGearblockTimer(gearblock); + message = ChatColor.YELLOW + "The gearblock's timer has been removed."; + } + + player.sendMessage(message); + + ParticleHelper.spawn(player, gearblock, ParticleHelper.Type.Info); + + return true; + } + + private void simpleActivate(PlayerInteractEvent event) { + Block block = event.getClickedBlock(); + + if (block == null) + return; + + BlockCoord blockCoord = new BlockCoord(block); + Gearblock gearblock = _storage.getGearblock(blockCoord); + + if(gearblock != null) + return; + + GearblockLink link; + + if((link = getLink(blockCoord.getForward(), blockCoord.getBackward())) == null + && (link = getLink(blockCoord.getRight(), blockCoord.getLeft())) == null + && (link = getLink(blockCoord.getTop(), blockCoord.getBottom())) == null + ) + { + return; + } + + if(_bridgeManager.isNotSimpleGearblock(link.getGearblock1(), event.getPlayer()) + || _bridgeManager.isNotSimpleGearblock(link.getGearblock2(), event.getPlayer()) + ) + { + return; + } + + BlockCoord processCoord = link.getGearblock1().getCoord(); + Block processBlock = block.getWorld().getBlockAt(processCoord.getX(), processCoord.getY(), processCoord.getZ()); + + if(_waitingBlocks.contains(processBlock)) + return; + + processBlock(processBlock, true); + processBlock(processBlock, false); + } + + private GearblockLink getLink(BlockCoord start, BlockCoord end) { + Gearblock gearblock = _storage.getGearblock(start); + GearblockLink link = gearblock != null ? gearblock.getLink() : null; + + if(link != null && + ( + link.getGearblock1().getCoord().equals(start) && link.getGearblock2().getCoord().equals(end) + || link.getGearblock1().getCoord().equals(end) && link.getGearblock2().getCoord().equals(start) + ) + ) + { + return link; + } + + return null; + } } \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeManager.java index 194815185..65eebb185 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/engine/bridge/BridgeManager.java @@ -1,754 +1,754 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.engine.bridge; - -import java.util.*; -import java.util.logging.Level; - -import com.aleksey.castlegates.config.ConfigManager; -import com.aleksey.castlegates.database.ReinforcementInfo; -import com.aleksey.castlegates.engine.StorageManager; -import com.aleksey.castlegates.plugins.citadel.ICitadel; -import com.aleksey.castlegates.types.*; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.plugins.citadel.ICitadelManager; -import com.aleksey.castlegates.events.CastleGatesDrawGateEvent; -import com.aleksey.castlegates.events.CastleGatesUndrawGateEvent; -import com.aleksey.castlegates.utils.Helper; -import com.aleksey.castlegates.utils.TimerWorker; - -public class BridgeManager { - public static final BlockFace[] faces = new BlockFace[] { - BlockFace.EAST, - BlockFace.WEST, - BlockFace.UP, - BlockFace.DOWN, - BlockFace.SOUTH, - BlockFace.NORTH - }; - - public enum CreateResult { NotCreated, AlreadyExist, Created } - public enum RemoveResult { NotExist, Removed, RemovedWithLink } - public enum SearchBridgeBlockResult { NotFound, Bridge, Gates } - public enum DoorAccess { None, Partial, Full } - - private StorageManager _storage; - private Map _pendingTimerBatches; - private TimerWorker _timerWorker; - - public void init(StorageManager storage) { - _storage = storage; - _pendingTimerBatches = new HashMap<>(); - - _timerWorker = new TimerWorker(this); - _timerWorker.startThread(); - } - - public void close() { - if(_timerWorker != null) { - _timerWorker.terminateThread(); - _timerWorker = null; - } - } - - public SearchBridgeBlockResult searchBridgeBlock(BlockCoord coord) { - int maxLen = CastleGates.getConfigManager().getMaxBridgeLength(); - - for(BlockFace face : faces) { - BlockCoord current = coord.clone(); - - for(int i = 0; i < maxLen; i++) { - current.increment(face); - - Gearblock gearblock = _storage.getGearblock(current); - - if(gearblock != null) { - if(isBridgeBlock(gearblock, face)) { - return face == BlockFace.UP || face == BlockFace.DOWN - ? SearchBridgeBlockResult.Gates - : SearchBridgeBlockResult.Bridge; - } - - break; - } - } - } - - return SearchBridgeBlockResult.NotFound; - } - - private static boolean isBridgeBlock(Gearblock gearblock, BlockFace face) { - GearblockLink link = gearblock.getLink(); - - if(link == null || link.isDrawn()) return false; - - BlockCoord coord1 = link.getGearblock1().getCoord(); - BlockCoord coord2 = link.getGearblock2().getCoord(); - - return switch(face) { - case EAST -> coord1.getX() < gearblock.getCoord().getX() || coord2.getX() < gearblock.getCoord().getX(); - case WEST -> coord1.getX() > gearblock.getCoord().getX() || coord2.getX() > gearblock.getCoord().getX(); - case UP -> coord1.getY() < gearblock.getCoord().getY() || coord2.getY() < gearblock.getCoord().getY(); - case DOWN -> coord1.getY() > gearblock.getCoord().getY() || coord2.getY() > gearblock.getCoord().getY(); - case SOUTH -> coord1.getZ() < gearblock.getCoord().getZ() || coord2.getZ() < gearblock.getCoord().getZ(); - case NORTH -> coord1.getZ() > gearblock.getCoord().getZ() || coord2.getZ() > gearblock.getCoord().getZ(); - default -> false; - }; - } - - public CreateResult createGear(Block block) { - BlockCoord location = new BlockCoord(block); - - if(!CastleGates.getConfigManager().isGearBlockType(block)) return CreateResult.NotCreated; - if(_storage.hasGearblock(location)) return CreateResult.AlreadyExist; - - _storage.addGearblock(location); - - return CreateResult.Created; - } - - public RemoveResult removeGear(BlockCoord location) { - Gearblock gear = _storage.getGearblock(location); - - if(gear == null) return RemoveResult.NotExist; - - RemoveResult result = RemoveResult.Removed; - - if(gear.getLockGearblock() != null) { - unlock(gear.getLockGearblock()); - } else { - unlock(gear); - } - - if(gear.getBrokenLink() != null) { - removeLink(gear.getBrokenLink()); - result = RemoveResult.RemovedWithLink; - } - else if (gear.getLink() != null) { - if(gear.getLink().isDrawn()) { - _storage.setLinkBroken(gear); - } else { - removeLink(gear.getLink()); - result = RemoveResult.RemovedWithLink; - } - } - - _storage.removeGearblock(gear); - - return result; - } - - public void removeLink(GearblockLink link) { - if(link == null) - return; - - Gearblock gearblock1 = link.getGearblock1(); - - if(gearblock1 != null) { - if(gearblock1.getLockGearblock() != null) { - unlock(gearblock1.getLockGearblock()); - } else { - unlock(gearblock1); - } - } - - Gearblock gearblock2 = link.getGearblock2(); - - if(gearblock2 != null) { - if(gearblock2.getLockGearblock() != null) { - unlock(gearblock2.getLockGearblock()); - } else { - unlock(gearblock2); - } - } - - _storage.removeLink(link); - } - - public boolean createLink(Gearblock gearblock1, Gearblock gearblock2, int distance) { - if(!removeGearblocksLinks(gearblock1, gearblock2, distance)) return false; - - if(gearblock1.getLink() != null) return true; - - _storage.addLink(gearblock1, gearblock2); - - return true; - } - - private boolean removeGearblocksLinks(Gearblock gearblock1, Gearblock gearblock2, int distance) { - if(gearblock1.getBrokenLink() != null && gearblock2.getBrokenLink() != null - || gearblock1.getBrokenLink() != null && distance != gearblock1.getBrokenLink().getBlocks().size() - || gearblock2.getBrokenLink() != null && distance != gearblock2.getBrokenLink().getBlocks().size() - ) - { - return false; - } - - GearblockLink link1 = gearblock1.getLink(); - GearblockLink link2 = gearblock2.getLink(); - - if(link1 != null && link1.equals(link2)) return true; - - if(link1 != null && link1.isDrawn() || link2 != null && link2.isDrawn()) return false; - - if(link1 != null) { - _storage.removeLink(link1); - } - - if(link2 != null) { - _storage.removeLink(link2); - } - - return true; - } - - public PowerResult processGearblock(World world, Gearblock gearblock, boolean isPowered, List players) { - if(gearblock.isPowered() == isPowered) - return PowerResult.Unchanged; - - if(!isPowered) { - unlock(gearblock); - gearblock.setPowered(false); - addPendingTimerBatch(gearblock); - return PowerResult.Unpowered; - } - - if(System.currentTimeMillis() - gearblock.getLastSwitchTime() < CastleGates.getConfigManager().getSwitchTimeout()) { - return PowerResult.Unchanged; - } - - ICitadel citadel = getCitadel(world, gearblock, players); - DoorAccess doorAccess = canAccessDoors(world, gearblock, citadel); - - switch(doorAccess) { - case None: return PowerResult.NotInCitadelGroup; - case Partial: return PowerResult.DifferentCitadelGroup; - } - - if(extendDoorTimerBatch(gearblock)) - return PowerResult.Unchanged; - - if(!unlock(gearblock)) - return PowerResult.Locked; - - gearblock.setPowered(true); - - if(gearblock.getLink() != null) - { - PowerResult result = !gearblock.getLink().isDrawn() - ? canDraw(world, gearblock.getLink(), citadel) - : canUndraw(world, gearblock.getLink(), players, citadel); - - if(result != PowerResult.Allowed) - return result; - } - - PowerResult result = powerGear(world, gearblock, players, citadel); - - gearblock.setLastSwitchTime(); - - return result; - } - - private void addPendingTimerBatch(Gearblock gearblock) { - TimerBatch timerBatch = _pendingTimerBatches.get(gearblock); - - if(timerBatch != null && timerBatch.resetRunTime() && !timerBatch.isInvalid()) { - _timerWorker.addBatch(timerBatch); - } - } - - private PowerResult powerGear(World world, Gearblock gearblock, List players, ICitadel citadel) { - HashSet gearblocks = new HashSet<>(); - gearblocks.add(gearblock); - - PowerResult transferResult = transferPower(world, gearblock, true, players, citadel, gearblocks); - - if(transferResult != PowerResult.Allowed) - return transferResult; - - if(isLocked(gearblocks)) - return PowerResult.Locked; - - TimerBatch timerBatch = gearblock.getTimer() != null ? new TimerBatch(world, gearblock, gearblocks) : null; - Boolean draw = powerGearList(world, gearblocks, timerBatch); - - lock(gearblock, gearblocks); - - if(draw == null) - return PowerResult.Unchanged; - - PowerResult result = draw ? PowerResult.Drawn : PowerResult.Undrawn; - - if(timerBatch != null) { - timerBatch.setProcessStatus(result.status); - - if(gearblock.getTimerMode() == TimerMode.DEFAULT) { - _timerWorker.addBatch(timerBatch); - } else { - _pendingTimerBatches.put(gearblock, timerBatch); - } - } - - return result; - } - - private Boolean powerGearList(World world, HashSet gearblocks, TimerBatch timerBatch) { - Boolean draw = null; - - for(Gearblock gearFromList : gearblocks) { - GearblockLink linkFromList = gearFromList.getLink(); - - if(linkFromList == null) continue; - - if(draw == null) { - draw = !linkFromList.isDrawn(); - } - - if(!linkFromList.isDrawn()) { - draw(world, linkFromList); - } else { - undraw(world, linkFromList); - } - - if(timerBatch != null) { - timerBatch.addLink(linkFromList); - } - } - - return draw; - } - - private boolean unlock(Gearblock gearblock) { - if(gearblock.getLockGearblock() != null) { - return false; - } - - if(gearblock.getLockedGearblocks() == null) { - return true; - } - - for(Gearblock lockedGearblock : gearblock.getLockedGearblocks()) { - lockedGearblock.setLockGearblock(null); - } - - gearblock.setLockedGearblocks(null); - - return true; - } - - private void lock(Gearblock gearblock, HashSet gearblocks) { - List lockedGearblocks = new ArrayList<>(); - - for(Gearblock lockedGearblock : gearblocks) { - GearblockLink link = lockedGearblock.getLink(); - - if(lockedGearblock != gearblock) { - if(link != null) { - lockedGearblocks.add(link.getGearblock1()); - lockedGearblocks.add(link.getGearblock2()); - - link.getGearblock1().setLockGearblock(gearblock); - link.getGearblock2().setLockGearblock(gearblock); - } else { - lockedGearblocks.add(lockedGearblock); - lockedGearblock.setLockGearblock(gearblock); - } - } else if(link != null) { - if(link.getGearblock1() != lockedGearblock) { - lockedGearblocks.add(link.getGearblock1()); - link.getGearblock1().setLockGearblock(gearblock); - } else { - lockedGearblocks.add(link.getGearblock2()); - link.getGearblock2().setLockGearblock(gearblock); - } - } - } - - gearblock.setLockedGearblocks(lockedGearblocks); - } - - private boolean isLocked(HashSet gearblocks) { - for(Gearblock lockedGearblock : gearblocks) { - if(lockedGearblock.getLockGearblock() != null) { - return true; - } - } - - return false; - } - - private boolean extendDoorTimerBatch(Gearblock gearblock) { - if(gearblock.getTimer() == null - || gearblock.getTimerMode() != TimerMode.DOOR - || gearblock.getTimerBatch() == null - || gearblock.getTimerBatch().getTimerMode() != TimerMode.DOOR - || gearblock.getTimerBatch().isInvalid() - ) - { - return false; - } - - TimerBatch originalTimerBatch = gearblock.getTimerBatch(); - boolean canLock = true; - - for(Gearblock current : originalTimerBatch.getAllGearblocks()) { - if(current.getLockedGearblocks() != null && current != originalTimerBatch.getGearblock() - || current.getLockGearblock() != null && current.getLockGearblock() != originalTimerBatch.getGearblock() - ) - { - canLock = false; - break; - } - } - - if(canLock) { - gearblock.setPowered(true); - - originalTimerBatch.invalidate(); - - unlock(originalTimerBatch.getGearblock()); - lock(gearblock, originalTimerBatch.getAllGearblocks()); - - _pendingTimerBatches.put(gearblock, originalTimerBatch.clone(gearblock)); - } - - return true; - } - - public boolean processTimerBatch(TimerBatch timerBatch) { - timerBatch.clearTimerBatchForAllGearblocks(); - - boolean result = false; - World world = timerBatch.getWorld(); - - for(TimerLink timerLink : timerBatch.getLinks()) { - GearblockLink link = timerLink.getLink(); - - if(link.isRemoved() || link.isBroken() || link.isDrawn() == timerLink.isMustDraw()) { - continue; - } - - if(!link.isDrawn()) { - draw(world, link); - } else { - undraw(world, link); - } - - result = true; - } - - return result; - } - - private PowerResult transferPower( - World world, - Gearblock gearblock, - boolean isPowered, - List players, - ICitadel citadel, - HashSet gearblocks - ) - { - ConfigManager configManager = CastleGates.getConfigManager(); - BlockCoord gearLoc = gearblock.getCoord(); - - for(int i = 0; i < faces.length && gearblocks.size() <= configManager.getMaxPowerTransfers(); i++) { - BlockFace face = faces[i]; - BlockCoord loc = new BlockCoord(world.getUID(), gearLoc.getX() + face.getModX(), gearLoc.getY() + face.getModY(), gearLoc.getZ() + face.getModZ()); - Gearblock to = _storage.getGearblock(loc); - - if(to == null || to.isPowered() == isPowered || gearblocks.contains(to)) continue; - - DoorAccess access = canAccessDoors(world, to, citadel); - - if(access == DoorAccess.Partial) { - return PowerResult.DifferentCitadelGroup; - } else if(access == DoorAccess.None) { - continue; - } - - if(isPowered) { - GearblockLink link = to.getLink(); - - if(link != null) { - PowerResult result; - - if(!link.isDrawn()) { - result = canDraw(world, link, citadel); - } else { - result = canUndraw(world, link, players, citadel); - } - - if(result != PowerResult.Allowed) return result; - } - - gearblocks.add(to); - } - - PowerResult result = transferPower(world, to, isPowered, players, citadel, gearblocks); - - if(result != PowerResult.Allowed) return result; - } - - return PowerResult.Allowed; - } - - private BlockFace getLinkFace(GearblockLink link) { - BlockCoord loc1 = link.getGearblock1().getCoord(); - BlockCoord loc2 = link.getGearblock2().getCoord(); - - if(loc1.getX() != loc2.getX()) { - return loc1.getX() < loc2.getX() ? BlockFace.EAST: BlockFace.WEST; - } - else if(loc1.getY() != loc2.getY()) { - return loc1.getY() < loc2.getY() ? BlockFace.UP: BlockFace.DOWN; - } - else if(loc1.getZ() != loc2.getZ()) { - return loc1.getZ() < loc2.getZ() ? BlockFace.SOUTH: BlockFace.NORTH; - } - - return null; - } - - private PowerResult canDraw(World world, GearblockLink link, ICitadel citadel) { - ConfigManager configManager = CastleGates.getConfigManager(); - - BlockFace blockFace = getLinkFace(link); - if (blockFace == null) - return PowerResult.Locked; - - BlockCoord loc1 = link.getGearblock1().getCoord(); - BlockCoord loc2 = link.getGearblock2().getCoord(); - - int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); - int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - - while(x1 != x2 || y1 != y2 || z1 != z2) { - Block block = world.getBlockAt(x1, y1, z1); - - if(!configManager.isBridgeMaterial(block)) return new PowerResult(PowerResult.Status.Broken, block); - - if(_storage.hasGearblock(new BlockCoord(block))) return new PowerResult(PowerResult.Status.CannotDrawGear, block); - - if(!citadel.canAccessDoors(block.getLocation())) return PowerResult.DifferentCitadelGroup; - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - } - - return PowerResult.Allowed; - } - - private void draw(World world, GearblockLink link) { - BlockFace blockFace = getLinkFace(link); - if (blockFace == null) - return; - - BlockCoord loc1 = link.getGearblock1().getCoord(); - BlockCoord loc2 = link.getGearblock2().getCoord(); - - int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); - int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - - ICitadelManager citadelManager = CastleGates.getCitadelManager(); - ArrayList blockStates = new ArrayList<>(); - ArrayList locations = new ArrayList<>(); - ArrayList states = new ArrayList<>(); - - while(x1 != x2 || y1 != y2 || z1 != z2) { - Block block = world.getBlockAt(x1, y1, z1); - Location location = block.getLocation(); - - locations.add(location); - - ReinforcementInfo reinforcement = citadelManager.removeReinforcement(location); - BlockState blockState = new BlockState(block, reinforcement); - - blockStates.add(blockState); - - org.bukkit.block.BlockState state = block.getState(); - - state.setType(Material.AIR); - states.add(state); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - } - - // Call our event before committing world changes. - Bukkit.getPluginManager().callEvent(new CastleGatesDrawGateEvent(locations)); - - // commit world changes - for (org.bukkit.block.BlockState state : states) { - state.update(true, true); - } - - _storage.setLinkBlocks(link, blockStates); - } - - private PowerResult canUndraw(World world, GearblockLink link, List players, ICitadel citadel) { - BlockFace blockFace = getLinkFace(link); - if (blockFace == null) - return PowerResult.Locked; - - BlockCoord loc1 = link.getGearblock1().getCoord(); - BlockCoord loc2 = link.getGearblock2().getCoord(); - - int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); - int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - - List bridgeBlocks = new ArrayList<>(); - - while(x1 != x2 || y1 != y2 || z1 != z2) { - Block block = world.getBlockAt(x1, y1, z1); - - if(!Helper.isEmptyBlock(block)) - return new PowerResult(PowerResult.Status.Blocked, block); - - bridgeBlocks.add(block); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - } - - return CastleGates.getBastionManager().canUndraw(players, bridgeBlocks, citadel) - ? PowerResult.Allowed - : PowerResult.BastionBlocked; - } - - private void undraw(World world, GearblockLink link) { - BlockFace blockFace = getLinkFace(link); - - if (blockFace == null) - return; - - BlockCoord loc1 = link.getGearblock1().getCoord(); - BlockCoord loc2 = link.getGearblock2().getCoord(); - - int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); - int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - - ICitadelManager citadelManager = CastleGates.getCitadelManager(); - List linkBlocks = link.getBlocks(); - List worldBlocks = new ArrayList<>(); - ArrayList locations = new ArrayList<>(); - - while(x1 != x2 || y1 != y2 || z1 != z2) { - Block block = world.getBlockAt(x1, y1, z1); - worldBlocks.add(block); - - Location location = block.getLocation(); - locations.add(location); - - x1 += blockFace.getModX(); - y1 += blockFace.getModY(); - z1 += blockFace.getModZ(); - } - - Bukkit.getPluginManager().callEvent(new CastleGatesUndrawGateEvent(locations)); - - for (int i = 0; i < linkBlocks.size(); i++) { - BlockState blockState = linkBlocks.get(i); - BlockData blockData = Bukkit.createBlockData(blockState.getBlockData()); - Block block = worldBlocks.get(i); - - block.setBlockData(blockData, false); - - citadelManager.createReinforcement(blockState.getReinforcement(), block.getLocation()); - } - - // Apply physics - for (Block block : worldBlocks) - block.setBlockData(block.getBlockData(), true); - - _storage.setLinkBlocks(link, null); - } - - private static DoorAccess canAccessDoors(World world, Gearblock gearblock, ICitadel citadel) { - boolean hasAccess = citadel.canAccessDoors(getLocation(world, gearblock.getCoord())); - - if(!hasAccess) return DoorAccess.None; - - GearblockLink link = gearblock.getLink(); - - if(link == null) return DoorAccess.Full; - - Gearblock secondGearblock = link.getGearblock1() == gearblock - ? link.getGearblock2() - : link.getGearblock1(); - - return citadel.canAccessDoors(getLocation(world, secondGearblock.getCoord())) ? DoorAccess.Full : DoorAccess.Partial; - } - - private static Location getLocation(World world, BlockCoord coord) { - return new Location(world, coord.getX(), coord.getY(), coord.getZ()); - } - - private static ICitadel getCitadel(World world, Gearblock gearblock, List players) { - BlockCoord coord = gearblock.getCoord(); - Location location = new Location(world, coord.getX(), coord.getY(), coord.getZ()); - - return CastleGates.getCitadelManager().getCitadel(players, location); - } - - public boolean isNotSimpleGearblock(Gearblock gearblock, Player player) { - World world = player.getWorld(); - BlockCoord coord = gearblock.getCoord(); - List players = new ArrayList<>(); - - players.add(player); - - ICitadel citadel = getCitadel(world, gearblock, players); - - return hasAccessibleGearblock(world, coord.getForward(), players, citadel) - || hasAccessibleGearblock(world, coord.getBackward(), players, citadel) - || hasAccessibleGearblock(world, coord.getRight(), players, citadel) - || hasAccessibleGearblock(world, coord.getLeft(), players, citadel) - || hasAccessibleGearblock(world, coord.getTop(), players, citadel) - || hasAccessibleGearblock(world, coord.getBottom(), players, citadel); - } - - private boolean hasAccessibleGearblock(World world, BlockCoord coord, List players, ICitadel originalCitadel) { - Gearblock gearblock = _storage.getGearblock(coord); - if(gearblock == null) - return false; - - ICitadel citadel = getCitadel(world, gearblock, players); - - return originalCitadel.getGroupName() == null - ? citadel.getGroupName() == null - : originalCitadel.getGroupName().equalsIgnoreCase(citadel.getGroupName()); - } +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.engine.bridge; + +import java.util.*; +import java.util.logging.Level; + +import com.aleksey.castlegates.config.ConfigManager; +import com.aleksey.castlegates.database.ReinforcementInfo; +import com.aleksey.castlegates.engine.StorageManager; +import com.aleksey.castlegates.plugins.citadel.ICitadel; +import com.aleksey.castlegates.types.*; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.plugins.citadel.ICitadelManager; +import com.aleksey.castlegates.events.CastleGatesDrawGateEvent; +import com.aleksey.castlegates.events.CastleGatesUndrawGateEvent; +import com.aleksey.castlegates.utils.Helper; +import com.aleksey.castlegates.utils.TimerWorker; + +public class BridgeManager { + public static final BlockFace[] faces = new BlockFace[] { + BlockFace.EAST, + BlockFace.WEST, + BlockFace.UP, + BlockFace.DOWN, + BlockFace.SOUTH, + BlockFace.NORTH + }; + + public enum CreateResult { NotCreated, AlreadyExist, Created } + public enum RemoveResult { NotExist, Removed, RemovedWithLink } + public enum SearchBridgeBlockResult { NotFound, Bridge, Gates } + public enum DoorAccess { None, Partial, Full } + + private StorageManager _storage; + private Map _pendingTimerBatches; + private TimerWorker _timerWorker; + + public void init(StorageManager storage) { + _storage = storage; + _pendingTimerBatches = new HashMap<>(); + + _timerWorker = new TimerWorker(this); + _timerWorker.startThread(); + } + + public void close() { + if(_timerWorker != null) { + _timerWorker.terminateThread(); + _timerWorker = null; + } + } + + public SearchBridgeBlockResult searchBridgeBlock(BlockCoord coord) { + int maxLen = CastleGates.getConfigManager().getMaxBridgeLength(); + + for(BlockFace face : faces) { + BlockCoord current = coord.clone(); + + for(int i = 0; i < maxLen; i++) { + current.increment(face); + + Gearblock gearblock = _storage.getGearblock(current); + + if(gearblock != null) { + if(isBridgeBlock(gearblock, face)) { + return face == BlockFace.UP || face == BlockFace.DOWN + ? SearchBridgeBlockResult.Gates + : SearchBridgeBlockResult.Bridge; + } + + break; + } + } + } + + return SearchBridgeBlockResult.NotFound; + } + + private static boolean isBridgeBlock(Gearblock gearblock, BlockFace face) { + GearblockLink link = gearblock.getLink(); + + if(link == null || link.isDrawn()) return false; + + BlockCoord coord1 = link.getGearblock1().getCoord(); + BlockCoord coord2 = link.getGearblock2().getCoord(); + + return switch(face) { + case EAST -> coord1.getX() < gearblock.getCoord().getX() || coord2.getX() < gearblock.getCoord().getX(); + case WEST -> coord1.getX() > gearblock.getCoord().getX() || coord2.getX() > gearblock.getCoord().getX(); + case UP -> coord1.getY() < gearblock.getCoord().getY() || coord2.getY() < gearblock.getCoord().getY(); + case DOWN -> coord1.getY() > gearblock.getCoord().getY() || coord2.getY() > gearblock.getCoord().getY(); + case SOUTH -> coord1.getZ() < gearblock.getCoord().getZ() || coord2.getZ() < gearblock.getCoord().getZ(); + case NORTH -> coord1.getZ() > gearblock.getCoord().getZ() || coord2.getZ() > gearblock.getCoord().getZ(); + default -> false; + }; + } + + public CreateResult createGear(Block block) { + BlockCoord location = new BlockCoord(block); + + if(!CastleGates.getConfigManager().isGearBlockType(block)) return CreateResult.NotCreated; + if(_storage.hasGearblock(location)) return CreateResult.AlreadyExist; + + _storage.addGearblock(location); + + return CreateResult.Created; + } + + public RemoveResult removeGear(BlockCoord location) { + Gearblock gear = _storage.getGearblock(location); + + if(gear == null) return RemoveResult.NotExist; + + RemoveResult result = RemoveResult.Removed; + + if(gear.getLockGearblock() != null) { + unlock(gear.getLockGearblock()); + } else { + unlock(gear); + } + + if(gear.getBrokenLink() != null) { + removeLink(gear.getBrokenLink()); + result = RemoveResult.RemovedWithLink; + } + else if (gear.getLink() != null) { + if(gear.getLink().isDrawn()) { + _storage.setLinkBroken(gear); + } else { + removeLink(gear.getLink()); + result = RemoveResult.RemovedWithLink; + } + } + + _storage.removeGearblock(gear); + + return result; + } + + public void removeLink(GearblockLink link) { + if(link == null) + return; + + Gearblock gearblock1 = link.getGearblock1(); + + if(gearblock1 != null) { + if(gearblock1.getLockGearblock() != null) { + unlock(gearblock1.getLockGearblock()); + } else { + unlock(gearblock1); + } + } + + Gearblock gearblock2 = link.getGearblock2(); + + if(gearblock2 != null) { + if(gearblock2.getLockGearblock() != null) { + unlock(gearblock2.getLockGearblock()); + } else { + unlock(gearblock2); + } + } + + _storage.removeLink(link); + } + + public boolean createLink(Gearblock gearblock1, Gearblock gearblock2, int distance) { + if(!removeGearblocksLinks(gearblock1, gearblock2, distance)) return false; + + if(gearblock1.getLink() != null) return true; + + _storage.addLink(gearblock1, gearblock2); + + return true; + } + + private boolean removeGearblocksLinks(Gearblock gearblock1, Gearblock gearblock2, int distance) { + if(gearblock1.getBrokenLink() != null && gearblock2.getBrokenLink() != null + || gearblock1.getBrokenLink() != null && distance != gearblock1.getBrokenLink().getBlocks().size() + || gearblock2.getBrokenLink() != null && distance != gearblock2.getBrokenLink().getBlocks().size() + ) + { + return false; + } + + GearblockLink link1 = gearblock1.getLink(); + GearblockLink link2 = gearblock2.getLink(); + + if(link1 != null && link1.equals(link2)) return true; + + if(link1 != null && link1.isDrawn() || link2 != null && link2.isDrawn()) return false; + + if(link1 != null) { + _storage.removeLink(link1); + } + + if(link2 != null) { + _storage.removeLink(link2); + } + + return true; + } + + public PowerResult processGearblock(World world, Gearblock gearblock, boolean isPowered, List players) { + if(gearblock.isPowered() == isPowered) + return PowerResult.Unchanged; + + if(!isPowered) { + unlock(gearblock); + gearblock.setPowered(false); + addPendingTimerBatch(gearblock); + return PowerResult.Unpowered; + } + + if(System.currentTimeMillis() - gearblock.getLastSwitchTime() < CastleGates.getConfigManager().getSwitchTimeout()) { + return PowerResult.Unchanged; + } + + ICitadel citadel = getCitadel(world, gearblock, players); + DoorAccess doorAccess = canAccessDoors(world, gearblock, citadel); + + switch(doorAccess) { + case None: return PowerResult.NotInCitadelGroup; + case Partial: return PowerResult.DifferentCitadelGroup; + } + + if(extendDoorTimerBatch(gearblock)) + return PowerResult.Unchanged; + + if(!unlock(gearblock)) + return PowerResult.Locked; + + gearblock.setPowered(true); + + if(gearblock.getLink() != null) + { + PowerResult result = !gearblock.getLink().isDrawn() + ? canDraw(world, gearblock.getLink(), citadel) + : canUndraw(world, gearblock.getLink(), players, citadel); + + if(result != PowerResult.Allowed) + return result; + } + + PowerResult result = powerGear(world, gearblock, players, citadel); + + gearblock.setLastSwitchTime(); + + return result; + } + + private void addPendingTimerBatch(Gearblock gearblock) { + TimerBatch timerBatch = _pendingTimerBatches.get(gearblock); + + if(timerBatch != null && timerBatch.resetRunTime() && !timerBatch.isInvalid()) { + _timerWorker.addBatch(timerBatch); + } + } + + private PowerResult powerGear(World world, Gearblock gearblock, List players, ICitadel citadel) { + HashSet gearblocks = new HashSet<>(); + gearblocks.add(gearblock); + + PowerResult transferResult = transferPower(world, gearblock, true, players, citadel, gearblocks); + + if(transferResult != PowerResult.Allowed) + return transferResult; + + if(isLocked(gearblocks)) + return PowerResult.Locked; + + TimerBatch timerBatch = gearblock.getTimer() != null ? new TimerBatch(world, gearblock, gearblocks) : null; + Boolean draw = powerGearList(world, gearblocks, timerBatch); + + lock(gearblock, gearblocks); + + if(draw == null) + return PowerResult.Unchanged; + + PowerResult result = draw ? PowerResult.Drawn : PowerResult.Undrawn; + + if(timerBatch != null) { + timerBatch.setProcessStatus(result.status); + + if(gearblock.getTimerMode() == TimerMode.DEFAULT) { + _timerWorker.addBatch(timerBatch); + } else { + _pendingTimerBatches.put(gearblock, timerBatch); + } + } + + return result; + } + + private Boolean powerGearList(World world, HashSet gearblocks, TimerBatch timerBatch) { + Boolean draw = null; + + for(Gearblock gearFromList : gearblocks) { + GearblockLink linkFromList = gearFromList.getLink(); + + if(linkFromList == null) continue; + + if(draw == null) { + draw = !linkFromList.isDrawn(); + } + + if(!linkFromList.isDrawn()) { + draw(world, linkFromList); + } else { + undraw(world, linkFromList); + } + + if(timerBatch != null) { + timerBatch.addLink(linkFromList); + } + } + + return draw; + } + + private boolean unlock(Gearblock gearblock) { + if(gearblock.getLockGearblock() != null) { + return false; + } + + if(gearblock.getLockedGearblocks() == null) { + return true; + } + + for(Gearblock lockedGearblock : gearblock.getLockedGearblocks()) { + lockedGearblock.setLockGearblock(null); + } + + gearblock.setLockedGearblocks(null); + + return true; + } + + private void lock(Gearblock gearblock, HashSet gearblocks) { + List lockedGearblocks = new ArrayList<>(); + + for(Gearblock lockedGearblock : gearblocks) { + GearblockLink link = lockedGearblock.getLink(); + + if(lockedGearblock != gearblock) { + if(link != null) { + lockedGearblocks.add(link.getGearblock1()); + lockedGearblocks.add(link.getGearblock2()); + + link.getGearblock1().setLockGearblock(gearblock); + link.getGearblock2().setLockGearblock(gearblock); + } else { + lockedGearblocks.add(lockedGearblock); + lockedGearblock.setLockGearblock(gearblock); + } + } else if(link != null) { + if(link.getGearblock1() != lockedGearblock) { + lockedGearblocks.add(link.getGearblock1()); + link.getGearblock1().setLockGearblock(gearblock); + } else { + lockedGearblocks.add(link.getGearblock2()); + link.getGearblock2().setLockGearblock(gearblock); + } + } + } + + gearblock.setLockedGearblocks(lockedGearblocks); + } + + private boolean isLocked(HashSet gearblocks) { + for(Gearblock lockedGearblock : gearblocks) { + if(lockedGearblock.getLockGearblock() != null) { + return true; + } + } + + return false; + } + + private boolean extendDoorTimerBatch(Gearblock gearblock) { + if(gearblock.getTimer() == null + || gearblock.getTimerMode() != TimerMode.DOOR + || gearblock.getTimerBatch() == null + || gearblock.getTimerBatch().getTimerMode() != TimerMode.DOOR + || gearblock.getTimerBatch().isInvalid() + ) + { + return false; + } + + TimerBatch originalTimerBatch = gearblock.getTimerBatch(); + boolean canLock = true; + + for(Gearblock current : originalTimerBatch.getAllGearblocks()) { + if(current.getLockedGearblocks() != null && current != originalTimerBatch.getGearblock() + || current.getLockGearblock() != null && current.getLockGearblock() != originalTimerBatch.getGearblock() + ) + { + canLock = false; + break; + } + } + + if(canLock) { + gearblock.setPowered(true); + + originalTimerBatch.invalidate(); + + unlock(originalTimerBatch.getGearblock()); + lock(gearblock, originalTimerBatch.getAllGearblocks()); + + _pendingTimerBatches.put(gearblock, originalTimerBatch.clone(gearblock)); + } + + return true; + } + + public boolean processTimerBatch(TimerBatch timerBatch) { + timerBatch.clearTimerBatchForAllGearblocks(); + + boolean result = false; + World world = timerBatch.getWorld(); + + for(TimerLink timerLink : timerBatch.getLinks()) { + GearblockLink link = timerLink.getLink(); + + if(link.isRemoved() || link.isBroken() || link.isDrawn() == timerLink.isMustDraw()) { + continue; + } + + if(!link.isDrawn()) { + draw(world, link); + } else { + undraw(world, link); + } + + result = true; + } + + return result; + } + + private PowerResult transferPower( + World world, + Gearblock gearblock, + boolean isPowered, + List players, + ICitadel citadel, + HashSet gearblocks + ) + { + ConfigManager configManager = CastleGates.getConfigManager(); + BlockCoord gearLoc = gearblock.getCoord(); + + for(int i = 0; i < faces.length && gearblocks.size() <= configManager.getMaxPowerTransfers(); i++) { + BlockFace face = faces[i]; + BlockCoord loc = new BlockCoord(world.getUID(), gearLoc.getX() + face.getModX(), gearLoc.getY() + face.getModY(), gearLoc.getZ() + face.getModZ()); + Gearblock to = _storage.getGearblock(loc); + + if(to == null || to.isPowered() == isPowered || gearblocks.contains(to)) continue; + + DoorAccess access = canAccessDoors(world, to, citadel); + + if(access == DoorAccess.Partial) { + return PowerResult.DifferentCitadelGroup; + } else if(access == DoorAccess.None) { + continue; + } + + if(isPowered) { + GearblockLink link = to.getLink(); + + if(link != null) { + PowerResult result; + + if(!link.isDrawn()) { + result = canDraw(world, link, citadel); + } else { + result = canUndraw(world, link, players, citadel); + } + + if(result != PowerResult.Allowed) return result; + } + + gearblocks.add(to); + } + + PowerResult result = transferPower(world, to, isPowered, players, citadel, gearblocks); + + if(result != PowerResult.Allowed) return result; + } + + return PowerResult.Allowed; + } + + private BlockFace getLinkFace(GearblockLink link) { + BlockCoord loc1 = link.getGearblock1().getCoord(); + BlockCoord loc2 = link.getGearblock2().getCoord(); + + if(loc1.getX() != loc2.getX()) { + return loc1.getX() < loc2.getX() ? BlockFace.EAST: BlockFace.WEST; + } + else if(loc1.getY() != loc2.getY()) { + return loc1.getY() < loc2.getY() ? BlockFace.UP: BlockFace.DOWN; + } + else if(loc1.getZ() != loc2.getZ()) { + return loc1.getZ() < loc2.getZ() ? BlockFace.SOUTH: BlockFace.NORTH; + } + + return null; + } + + private PowerResult canDraw(World world, GearblockLink link, ICitadel citadel) { + ConfigManager configManager = CastleGates.getConfigManager(); + + BlockFace blockFace = getLinkFace(link); + if (blockFace == null) + return PowerResult.Locked; + + BlockCoord loc1 = link.getGearblock1().getCoord(); + BlockCoord loc2 = link.getGearblock2().getCoord(); + + int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); + int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + + while(x1 != x2 || y1 != y2 || z1 != z2) { + Block block = world.getBlockAt(x1, y1, z1); + + if(!configManager.isBridgeMaterial(block)) return new PowerResult(PowerResult.Status.Broken, block); + + if(_storage.hasGearblock(new BlockCoord(block))) return new PowerResult(PowerResult.Status.CannotDrawGear, block); + + if(!citadel.canAccessDoors(block.getLocation())) return PowerResult.DifferentCitadelGroup; + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + } + + return PowerResult.Allowed; + } + + private void draw(World world, GearblockLink link) { + BlockFace blockFace = getLinkFace(link); + if (blockFace == null) + return; + + BlockCoord loc1 = link.getGearblock1().getCoord(); + BlockCoord loc2 = link.getGearblock2().getCoord(); + + int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); + int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + + ICitadelManager citadelManager = CastleGates.getCitadelManager(); + ArrayList blockStates = new ArrayList<>(); + ArrayList locations = new ArrayList<>(); + ArrayList states = new ArrayList<>(); + + while(x1 != x2 || y1 != y2 || z1 != z2) { + Block block = world.getBlockAt(x1, y1, z1); + Location location = block.getLocation(); + + locations.add(location); + + ReinforcementInfo reinforcement = citadelManager.removeReinforcement(location); + BlockState blockState = new BlockState(block, reinforcement); + + blockStates.add(blockState); + + org.bukkit.block.BlockState state = block.getState(); + + state.setType(Material.AIR); + states.add(state); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + } + + // Call our event before committing world changes. + Bukkit.getPluginManager().callEvent(new CastleGatesDrawGateEvent(locations)); + + // commit world changes + for (org.bukkit.block.BlockState state : states) { + state.update(true, true); + } + + _storage.setLinkBlocks(link, blockStates); + } + + private PowerResult canUndraw(World world, GearblockLink link, List players, ICitadel citadel) { + BlockFace blockFace = getLinkFace(link); + if (blockFace == null) + return PowerResult.Locked; + + BlockCoord loc1 = link.getGearblock1().getCoord(); + BlockCoord loc2 = link.getGearblock2().getCoord(); + + int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); + int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + + List bridgeBlocks = new ArrayList<>(); + + while(x1 != x2 || y1 != y2 || z1 != z2) { + Block block = world.getBlockAt(x1, y1, z1); + + if(!Helper.isEmptyBlock(block)) + return new PowerResult(PowerResult.Status.Blocked, block); + + bridgeBlocks.add(block); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + } + + return CastleGates.getBastionManager().canUndraw(players, bridgeBlocks, citadel) + ? PowerResult.Allowed + : PowerResult.BastionBlocked; + } + + private void undraw(World world, GearblockLink link) { + BlockFace blockFace = getLinkFace(link); + + if (blockFace == null) + return; + + BlockCoord loc1 = link.getGearblock1().getCoord(); + BlockCoord loc2 = link.getGearblock2().getCoord(); + + int x1 = loc1.getX(), y1 = loc1.getY(), z1 = loc1.getZ(); + int x2 = loc2.getX(), y2 = loc2.getY(), z2 = loc2.getZ(); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + + ICitadelManager citadelManager = CastleGates.getCitadelManager(); + List linkBlocks = link.getBlocks(); + List worldBlocks = new ArrayList<>(); + ArrayList locations = new ArrayList<>(); + + while(x1 != x2 || y1 != y2 || z1 != z2) { + Block block = world.getBlockAt(x1, y1, z1); + worldBlocks.add(block); + + Location location = block.getLocation(); + locations.add(location); + + x1 += blockFace.getModX(); + y1 += blockFace.getModY(); + z1 += blockFace.getModZ(); + } + + Bukkit.getPluginManager().callEvent(new CastleGatesUndrawGateEvent(locations)); + + for (int i = 0; i < linkBlocks.size(); i++) { + BlockState blockState = linkBlocks.get(i); + BlockData blockData = Bukkit.createBlockData(blockState.getBlockData()); + Block block = worldBlocks.get(i); + + block.setBlockData(blockData, false); + + citadelManager.createReinforcement(blockState.getReinforcement(), block.getLocation()); + } + + // Apply physics + for (Block block : worldBlocks) + block.setBlockData(block.getBlockData(), true); + + _storage.setLinkBlocks(link, null); + } + + private static DoorAccess canAccessDoors(World world, Gearblock gearblock, ICitadel citadel) { + boolean hasAccess = citadel.canAccessDoors(getLocation(world, gearblock.getCoord())); + + if(!hasAccess) return DoorAccess.None; + + GearblockLink link = gearblock.getLink(); + + if(link == null) return DoorAccess.Full; + + Gearblock secondGearblock = link.getGearblock1() == gearblock + ? link.getGearblock2() + : link.getGearblock1(); + + return citadel.canAccessDoors(getLocation(world, secondGearblock.getCoord())) ? DoorAccess.Full : DoorAccess.Partial; + } + + private static Location getLocation(World world, BlockCoord coord) { + return new Location(world, coord.getX(), coord.getY(), coord.getZ()); + } + + private static ICitadel getCitadel(World world, Gearblock gearblock, List players) { + BlockCoord coord = gearblock.getCoord(); + Location location = new Location(world, coord.getX(), coord.getY(), coord.getZ()); + + return CastleGates.getCitadelManager().getCitadel(players, location); + } + + public boolean isNotSimpleGearblock(Gearblock gearblock, Player player) { + World world = player.getWorld(); + BlockCoord coord = gearblock.getCoord(); + List players = new ArrayList<>(); + + players.add(player); + + ICitadel citadel = getCitadel(world, gearblock, players); + + return hasAccessibleGearblock(world, coord.getForward(), players, citadel) + || hasAccessibleGearblock(world, coord.getBackward(), players, citadel) + || hasAccessibleGearblock(world, coord.getRight(), players, citadel) + || hasAccessibleGearblock(world, coord.getLeft(), players, citadel) + || hasAccessibleGearblock(world, coord.getTop(), players, citadel) + || hasAccessibleGearblock(world, coord.getBottom(), players, citadel); + } + + private boolean hasAccessibleGearblock(World world, BlockCoord coord, List players, ICitadel originalCitadel) { + Gearblock gearblock = _storage.getGearblock(coord); + if(gearblock == null) + return false; + + ICitadel citadel = getCitadel(world, gearblock, players); + + return originalCitadel.getGroupName() == null + ? citadel.getGroupName() == null + : originalCitadel.getGroupName().equalsIgnoreCase(citadel.getGroupName()); + } } \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/CastleGatesDrawGateEvent.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/CastleGatesDrawGateEvent.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/CastleGatesDrawGateEvent.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/CastleGatesDrawGateEvent.java index 975ae428b..3a991621d 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/CastleGatesDrawGateEvent.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/CastleGatesDrawGateEvent.java @@ -1,36 +1,36 @@ -package com.aleksey.castlegates.events; - -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -/** - * Called after the Gear is fully drawn (withdrawn). Lets other plugins update themselves based on the blocks changed. - * - * @author ProgrammerDan - * - */ -public class CastleGatesDrawGateEvent extends Event { - private static final HandlerList _handlers = new HandlerList(); - - private final List _impacted; - - public CastleGatesDrawGateEvent(final List impacted) { - this._impacted = impacted; - } - - public List getImpacted() { - return this._impacted; - } - - @Override - public HandlerList getHandlers() { - return CastleGatesDrawGateEvent._handlers; - } - - public static HandlerList getHandlerList() { - return _handlers; - } -} +package com.aleksey.castlegates.events; + +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called after the Gear is fully drawn (withdrawn). Lets other plugins update themselves based on the blocks changed. + * + * @author ProgrammerDan + * + */ +public class CastleGatesDrawGateEvent extends Event { + private static final HandlerList _handlers = new HandlerList(); + + private final List _impacted; + + public CastleGatesDrawGateEvent(final List impacted) { + this._impacted = impacted; + } + + public List getImpacted() { + return this._impacted; + } + + @Override + public HandlerList getHandlers() { + return CastleGatesDrawGateEvent._handlers; + } + + public static HandlerList getHandlerList() { + return _handlers; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/CastleGatesUndrawGateEvent.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/CastleGatesUndrawGateEvent.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/CastleGatesUndrawGateEvent.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/CastleGatesUndrawGateEvent.java index 1a4bb1583..fa8a19198 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/CastleGatesUndrawGateEvent.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/CastleGatesUndrawGateEvent.java @@ -1,36 +1,36 @@ -package com.aleksey.castlegates.events; - -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -/** - * Called after the Gear is fully drawn (withdrawn). Lets other plugins update themselves based on the blocks changed. - * - * @author ProgrammerDan - * - */ -public class CastleGatesUndrawGateEvent extends Event { - private static final HandlerList _handlers = new HandlerList(); - - private final List _impacted; - - public CastleGatesUndrawGateEvent(final List impacted) { - this._impacted = impacted; - } - - public List getImpacted() { - return this._impacted; - } - - @Override - public HandlerList getHandlers() { - return CastleGatesUndrawGateEvent._handlers; - } - - public static HandlerList getHandlerList() { - return _handlers; - } -} +package com.aleksey.castlegates.events; + +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called after the Gear is fully drawn (withdrawn). Lets other plugins update themselves based on the blocks changed. + * + * @author ProgrammerDan + * + */ +public class CastleGatesUndrawGateEvent extends Event { + private static final HandlerList _handlers = new HandlerList(); + + private final List _impacted; + + public CastleGatesUndrawGateEvent(final List impacted) { + this._impacted = impacted; + } + + public List getImpacted() { + return this._impacted; + } + + @Override + public HandlerList getHandlers() { + return CastleGatesUndrawGateEvent._handlers; + } + + public static HandlerList getHandlerList() { + return _handlers; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/package-info.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/package-info.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/package-info.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/package-info.java index a90abfcfd..ac8b1bf76 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/events/package-info.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/events/package-info.java @@ -1,8 +1,8 @@ -/** - * Augments for CastleGates to broadcast gate open / close events and pre-events. - */ -/** - * @author ProgrammerDan - * - */ +/** + * Augments for CastleGates to broadcast gate open / close events and pre-events. + */ +/** + * @author ProgrammerDan + * + */ package com.aleksey.castlegates.events; \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/listener/BlockListener.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/listener/BlockListener.java similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/listener/BlockListener.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/listener/BlockListener.java index 100be90c2..d495f0f78 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/listener/BlockListener.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/listener/BlockListener.java @@ -1,44 +1,44 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.listener; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockRedstoneEvent; - -import com.aleksey.castlegates.CastleGates; - -public class BlockListener implements Listener { - @EventHandler(priority=EventPriority.NORMAL, ignoreCancelled=true) - public void onBlockBreak(BlockBreakEvent event) { - CastleGates.getManager().handleBlockBreak(event); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) - public void onBlockRedstone(BlockRedstoneEvent event) { - CastleGates.getManager().handleBlockRedstone(event); - } - - @EventHandler(priority=EventPriority.NORMAL, ignoreCancelled=true) - public void onBlockPhysics(BlockPhysicsEvent event) { - CastleGates.getManager().handleBlockPhysics(event); - } - - @EventHandler(priority=EventPriority.HIGH, ignoreCancelled=true) - public void onBlockPistonExtend(BlockPistonExtendEvent event) { - CastleGates.getManager().handlePistonEvent(event.getBlocks()); - } - - @EventHandler(priority=EventPriority.HIGH, ignoreCancelled=true) - public void onBlockPistonRetract(BlockPistonRetractEvent event) { - CastleGates.getManager().handlePistonEvent(event.getBlocks()); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.listener; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockRedstoneEvent; + +import com.aleksey.castlegates.CastleGates; + +public class BlockListener implements Listener { + @EventHandler(priority=EventPriority.NORMAL, ignoreCancelled=true) + public void onBlockBreak(BlockBreakEvent event) { + CastleGates.getManager().handleBlockBreak(event); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) + public void onBlockRedstone(BlockRedstoneEvent event) { + CastleGates.getManager().handleBlockRedstone(event); + } + + @EventHandler(priority=EventPriority.NORMAL, ignoreCancelled=true) + public void onBlockPhysics(BlockPhysicsEvent event) { + CastleGates.getManager().handleBlockPhysics(event); + } + + @EventHandler(priority=EventPriority.HIGH, ignoreCancelled=true) + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + CastleGates.getManager().handlePistonEvent(event.getBlocks()); + } + + @EventHandler(priority=EventPriority.HIGH, ignoreCancelled=true) + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + CastleGates.getManager().handlePistonEvent(event.getBlocks()); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/listener/EntityListener.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/listener/EntityListener.java similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/listener/EntityListener.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/listener/EntityListener.java index d4bcc0efd..796f15c9b 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/listener/EntityListener.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/listener/EntityListener.java @@ -1,46 +1,46 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.listener; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import com.aleksey.castlegates.CastleGates; - -public class EntityListener implements Listener { - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerJoin(PlayerJoinEvent event) { - CastleGates.getManager().handlePlayerJoin(event); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerQuit(PlayerQuitEvent event) { - CastleGates.getManager().handlePlayerQuit(event); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerInteract(PlayerInteractEvent event) { - if(event.getClickedBlock() != null) { - CastleGates.getManager().handleBlockClicked(event); - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityExplode(EntityExplodeEvent event) { - CastleGates.getManager().handleEntityExplode(event); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityChangeBlock(EntityChangeBlockEvent event) { - CastleGates.getManager().handleEntityChangeBlock(event); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.listener; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import com.aleksey.castlegates.CastleGates; + +public class EntityListener implements Listener { + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerJoin(PlayerJoinEvent event) { + CastleGates.getManager().handlePlayerJoin(event); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerQuit(PlayerQuitEvent event) { + CastleGates.getManager().handlePlayerQuit(event); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEvent event) { + if(event.getClickedBlock() != null) { + CastleGates.getManager().handleBlockClicked(event); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityExplode(EntityExplodeEvent event) { + CastleGates.getManager().handleEntityExplode(event); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + CastleGates.getManager().handleEntityChangeBlock(event); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/BastionManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/BastionManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/BastionManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/BastionManager.java index 1da77a401..a7fcae2ff 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/BastionManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/BastionManager.java @@ -1,103 +1,103 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.plugins.bastion; - -import com.aleksey.castlegates.plugins.citadel.ICitadel; -import isaac.bastion.Bastion; -import isaac.bastion.BastionBlock; -import isaac.bastion.manager.BastionBlockManager; - -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import vg.civcraft.mc.citadel.Citadel; -import vg.civcraft.mc.citadel.ReinforcementManager; -import vg.civcraft.mc.citadel.model.Reinforcement; -import vg.civcraft.mc.namelayer.GroupManager; -import vg.civcraft.mc.namelayer.group.Group; -import vg.civcraft.mc.namelayer.GroupManager.PlayerType; -import vg.civcraft.mc.namelayer.permission.PermissionType; - -public class BastionManager implements IBastionManager { - private static final String PERMISSION_UNDRAW = "BASTION_BRIDGE_UNDRAW"; - - private BastionBlockManager _blockManager; - - public void init() { - _blockManager = Bastion.getBastionManager(); - - LinkedList memberAndAbove = new LinkedList<>(); - memberAndAbove.add(PlayerType.MEMBERS); - memberAndAbove.add(PlayerType.MODS); - memberAndAbove.add(PlayerType.ADMINS); - memberAndAbove.add(PlayerType.OWNER); - PermissionType.registerPermission(PERMISSION_UNDRAW, memberAndAbove, "Allows undrawing bridges/gates above bastions"); - } - - public boolean canUndraw(List players, List bridgeBlocks, ICitadel citadel) { - if (players != null) { - for(Player player : players) { - if(player.hasPermission("Bastion.bypass")) { - return true; - } - } - } - - for(Block block : bridgeBlocks) { - if(!hasBastionAccess(players, block, citadel)) { - return false; - } - } - - return true; - } - - private boolean hasBastionAccess(List players, Block block, ICitadel citadel) { - PermissionType perm = PermissionType.getPermission(PERMISSION_UNDRAW); - Location loc = block.getLocation(); - Set bastions = _blockManager.getBlockingBastions(loc); - - if (bastions == null) - return true; - - ReinforcementManager reinManager = Citadel.getInstance().getReinforcementManager(); - - for(BastionBlock bastion : bastions) { - if(bastion.getType().isOnlyDirectDestruction() || !bastion.inField(loc)) - continue; - - Reinforcement rein = reinManager.getReinforcement(bastion.getLocation()); - - if(rein == null) - continue; - - if(players == null) - return false; - - if(citadel.useJukeAlert() && !rein.getGroup().getName().equalsIgnoreCase(citadel.getGroupName())) - return false; - - boolean hasAccess = false; - - for (Player player : players) { - if (bastion.permAccess(player, perm)) { - hasAccess = true; - break; - } - } - - if (!hasAccess) - return false; - } - - return true; - } +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.plugins.bastion; + +import com.aleksey.castlegates.plugins.citadel.ICitadel; +import isaac.bastion.Bastion; +import isaac.bastion.BastionBlock; +import isaac.bastion.manager.BastionBlockManager; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import vg.civcraft.mc.citadel.Citadel; +import vg.civcraft.mc.citadel.ReinforcementManager; +import vg.civcraft.mc.citadel.model.Reinforcement; +import vg.civcraft.mc.namelayer.GroupManager; +import vg.civcraft.mc.namelayer.group.Group; +import vg.civcraft.mc.namelayer.GroupManager.PlayerType; +import vg.civcraft.mc.namelayer.permission.PermissionType; + +public class BastionManager implements IBastionManager { + private static final String PERMISSION_UNDRAW = "BASTION_BRIDGE_UNDRAW"; + + private BastionBlockManager _blockManager; + + public void init() { + _blockManager = Bastion.getBastionManager(); + + LinkedList memberAndAbove = new LinkedList<>(); + memberAndAbove.add(PlayerType.MEMBERS); + memberAndAbove.add(PlayerType.MODS); + memberAndAbove.add(PlayerType.ADMINS); + memberAndAbove.add(PlayerType.OWNER); + PermissionType.registerPermission(PERMISSION_UNDRAW, memberAndAbove, "Allows undrawing bridges/gates above bastions"); + } + + public boolean canUndraw(List players, List bridgeBlocks, ICitadel citadel) { + if (players != null) { + for(Player player : players) { + if(player.hasPermission("Bastion.bypass")) { + return true; + } + } + } + + for(Block block : bridgeBlocks) { + if(!hasBastionAccess(players, block, citadel)) { + return false; + } + } + + return true; + } + + private boolean hasBastionAccess(List players, Block block, ICitadel citadel) { + PermissionType perm = PermissionType.getPermission(PERMISSION_UNDRAW); + Location loc = block.getLocation(); + Set bastions = _blockManager.getBlockingBastions(loc); + + if (bastions == null) + return true; + + ReinforcementManager reinManager = Citadel.getInstance().getReinforcementManager(); + + for(BastionBlock bastion : bastions) { + if(bastion.getType().isOnlyDirectDestruction() || !bastion.inField(loc)) + continue; + + Reinforcement rein = reinManager.getReinforcement(bastion.getLocation()); + + if(rein == null) + continue; + + if(players == null) + return false; + + if(citadel.useJukeAlert() && !rein.getGroup().getName().equalsIgnoreCase(citadel.getGroupName())) + return false; + + boolean hasAccess = false; + + for (Player player : players) { + if (bastion.permAccess(player, perm)) { + hasAccess = true; + break; + } + } + + if (!hasAccess) + return false; + } + + return true; + } } \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/IBastionManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/IBastionManager.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/IBastionManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/IBastionManager.java index bbe406097..28ddab4f9 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/IBastionManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/IBastionManager.java @@ -1,17 +1,17 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.plugins.bastion; - -import java.util.List; - -import com.aleksey.castlegates.plugins.citadel.ICitadel; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -public interface IBastionManager { - void init(); - boolean canUndraw(List players, List bridgeBlocks, ICitadel jukeAlertCitadel); -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.plugins.bastion; + +import java.util.List; + +import com.aleksey.castlegates.plugins.citadel.ICitadel; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +public interface IBastionManager { + void init(); + boolean canUndraw(List players, List bridgeBlocks, ICitadel jukeAlertCitadel); +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/NoBastionManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/NoBastionManager.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/NoBastionManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/NoBastionManager.java index 9151b75dd..af38eb0ab 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/bastion/NoBastionManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/bastion/NoBastionManager.java @@ -1,21 +1,21 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.plugins.bastion; - -import java.util.List; - -import com.aleksey.castlegates.plugins.citadel.ICitadel; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -public class NoBastionManager implements IBastionManager { - public void init() { - } - - public boolean canUndraw(List players, List bridgeBlocks, ICitadel jukeAlertCitadel) { - return true; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.plugins.bastion; + +import java.util.List; + +import com.aleksey.castlegates.plugins.citadel.ICitadel; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +public class NoBastionManager implements IBastionManager { + public void init() { + } + + public boolean canUndraw(List players, List bridgeBlocks, ICitadel jukeAlertCitadel) { + return true; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/Citadel.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/Citadel.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/Citadel.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/Citadel.java index b1561676e..3f7377430 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/Citadel.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/Citadel.java @@ -1,42 +1,42 @@ -/** - * Created by Aleksey on 02.06.2017. - */ - -package com.aleksey.castlegates.plugins.citadel; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import vg.civcraft.mc.citadel.model.Reinforcement; - -import java.util.List; - -public class Citadel implements ICitadel { - private String _groupName; - private boolean _hasAccess; - private boolean _useJukeAlert; - - public Citadel(Reinforcement rein, boolean hasAccess, boolean useJukeAlert) { - _groupName = rein != null ? rein.getGroup().getName() : null; - _hasAccess = hasAccess; - _useJukeAlert = useJukeAlert; - } - - public boolean useJukeAlert() { return _useJukeAlert; } - - public String getGroupName() { - return _groupName; - } - - public boolean canAccessDoors(Location location) { - if(!_hasAccess) return false; - - Reinforcement rein = vg.civcraft.mc.citadel.Citadel - .getInstance() - .getReinforcementManager() - .getReinforcement(location); - - return rein == null - ? _groupName == null - : _groupName != null && _groupName.equalsIgnoreCase(rein.getGroup().getName()); - } +/** + * Created by Aleksey on 02.06.2017. + */ + +package com.aleksey.castlegates.plugins.citadel; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import vg.civcraft.mc.citadel.model.Reinforcement; + +import java.util.List; + +public class Citadel implements ICitadel { + private String _groupName; + private boolean _hasAccess; + private boolean _useJukeAlert; + + public Citadel(Reinforcement rein, boolean hasAccess, boolean useJukeAlert) { + _groupName = rein != null ? rein.getGroup().getName() : null; + _hasAccess = hasAccess; + _useJukeAlert = useJukeAlert; + } + + public boolean useJukeAlert() { return _useJukeAlert; } + + public String getGroupName() { + return _groupName; + } + + public boolean canAccessDoors(Location location) { + if(!_hasAccess) return false; + + Reinforcement rein = vg.civcraft.mc.citadel.Citadel + .getInstance() + .getReinforcementManager() + .getReinforcement(location); + + return rein == null + ? _groupName == null + : _groupName != null && _groupName.equalsIgnoreCase(rein.getGroup().getName()); + } } \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/CitadelManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/CitadelManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/CitadelManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/CitadelManager.java index 455ab22f9..f0af7c06d 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/CitadelManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/CitadelManager.java @@ -1,237 +1,237 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.plugins.citadel; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import vg.civcraft.mc.citadel.Citadel; -import vg.civcraft.mc.citadel.CitadelPermissionHandler; -import vg.civcraft.mc.citadel.model.Reinforcement; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.database.ReinforcementInfo; -import vg.civcraft.mc.citadel.playerstate.AbstractPlayerState; -import vg.civcraft.mc.citadel.playerstate.PlayerStateManager; -import vg.civcraft.mc.citadel.playerstate.ReinforcingState; - -public class CitadelManager extends Thread implements ICitadelManager, Runnable { - private static class UpdatedReinforcement { - public Reinforcement rein; - public boolean deleted; - - public UpdatedReinforcement(Reinforcement rein, boolean deleted) { - this.rein = rein; - this.deleted = deleted; - } - } - - private long _lastExecute = System.currentTimeMillis(); - private AtomicBoolean _kill = new AtomicBoolean(false); - private AtomicBoolean _run = new AtomicBoolean(false); - - private List _updatedReinforcements = new ArrayList(); - private Queue _localUpdatedReinforcements = new ArrayDeque(); - - @Override - public void init() { - startThread(); - } - - @Override - public void close() { - terminateThread(); - } - - @Override - public double getMaxRedstoneDistance() { - return CastleGates.getConfigManager().getMaxRedstoneDistance(); - } - - @Override - public ICitadel getCitadel(List players, Location loc) { - Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); - - boolean hasAccess = rein == null; - boolean useJukeAlert = false; - - if(!hasAccess) { - var doorsPermission= CitadelPermissionHandler.getDoors(); - - if (players != null && players.size() > 0) { - for (Player player : players) { - if (rein.hasPermission(player, doorsPermission) || player.hasPermission("citadel.admin")) { - hasAccess = true; - break; - } - } - } - - if(!hasAccess) { - if(CastleGates.getJukeAlertManager().hasJukeAlertAccess(loc, rein.getGroup().getName())) { - hasAccess = true; - useJukeAlert = true; - } - } - } - - return new com.aleksey.castlegates.plugins.citadel.Citadel(rein, hasAccess, useJukeAlert); - } - - @Override - public boolean isReinforced(Location loc) { - Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); - return rein != null; - } - - @Override - public boolean canBypass(Player player, Location loc) { - Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); - - if(rein == null) - return true; - - if(player == null) - return false; - - return rein.hasPermission(player, CitadelPermissionHandler.getBypass()) - || player.hasPermission("citadel.admin"); - } - - @Override - public boolean canViewInformation(Player player, Location loc) { - Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); - - if(rein == null) - return true; - - if(player == null) - return false; - - return rein.hasPermission(player, CitadelPermissionHandler.getInfo()) - || player.hasPermission("citadel.admin"); - } - - @Override - public ReinforcementInfo removeReinforcement(Location loc) { - Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); - - if(rein == null) - return null; - - ReinforcementInfo info = new ReinforcementInfo(); - info.CreationTime = rein.getCreationTime(); - info.TypeId = rein.getType().getID(); - info.Health = rein.getHealth(); - info.GroupId = rein.getGroupId(); - info.Insecure = rein.isInsecure(); - - synchronized(this._updatedReinforcements) { - this._updatedReinforcements.add(new UpdatedReinforcement(rein, true)); - } - - return info; - } - - @Override - public boolean createReinforcement(ReinforcementInfo info, Location loc) { - if(info == null) - return false; - - var type = Citadel.getInstance().getReinforcementTypeManager().getById(info.TypeId); - var rein = new Reinforcement(loc, type, info.GroupId, info.CreationTime, info.Health, info.Insecure, true); - - synchronized(this._updatedReinforcements) { - this._updatedReinforcements.add(new UpdatedReinforcement(rein, false)); - } - - return true; - } - - @Override - public boolean isReinforcingStateActive(Player player) { - PlayerStateManager stateManager = Citadel.getInstance().getStateManager(); - AbstractPlayerState currentState = stateManager.getState(player); - - return currentState instanceof ReinforcingState; - } - - public void startThread() { - setName("CastleGates CitadelManager Thread"); - setPriority(Thread.MIN_PRIORITY); - start(); - - CastleGates.getPluginLogger().log(Level.INFO, "CitadelManager thread started"); - } - - public void terminateThread() { - this._kill.set(true); - - while (this._run.get()) { - try { - Thread.sleep(100); - } catch (Exception e) { - e.printStackTrace(); - } - } - - saveData(); - - CastleGates.getPluginLogger().log(Level.INFO, "CitadelManager thread stopped"); - } - - @Override - public void run() { - this._run.set(true); - - try { - while (!this.isInterrupted() && !this._kill.get()) { - try { - long timeWait = _lastExecute + CastleGates.getConfigManager().getDataWorkerRate() - System.currentTimeMillis(); - _lastExecute = System.currentTimeMillis(); - if (timeWait > 0) { - Thread.sleep(timeWait); - } - - saveData(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } finally { - this._run.set(false); - } - } - - private void saveData() { - try { - synchronized (this._updatedReinforcements) { - if (this._updatedReinforcements.size() == 0) return; - - this._localUpdatedReinforcements.addAll(this._updatedReinforcements); - this._updatedReinforcements.clear(); - } - - UpdatedReinforcement updated; - - while ((updated = this._localUpdatedReinforcements.poll()) != null) { - if (updated.deleted) - updated.rein.setHealth(-1); - else - Citadel.getInstance().getReinforcementManager().putReinforcement(updated.rein); - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.plugins.citadel; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import vg.civcraft.mc.citadel.Citadel; +import vg.civcraft.mc.citadel.CitadelPermissionHandler; +import vg.civcraft.mc.citadel.model.Reinforcement; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.database.ReinforcementInfo; +import vg.civcraft.mc.citadel.playerstate.AbstractPlayerState; +import vg.civcraft.mc.citadel.playerstate.PlayerStateManager; +import vg.civcraft.mc.citadel.playerstate.ReinforcingState; + +public class CitadelManager extends Thread implements ICitadelManager, Runnable { + private static class UpdatedReinforcement { + public Reinforcement rein; + public boolean deleted; + + public UpdatedReinforcement(Reinforcement rein, boolean deleted) { + this.rein = rein; + this.deleted = deleted; + } + } + + private long _lastExecute = System.currentTimeMillis(); + private AtomicBoolean _kill = new AtomicBoolean(false); + private AtomicBoolean _run = new AtomicBoolean(false); + + private List _updatedReinforcements = new ArrayList(); + private Queue _localUpdatedReinforcements = new ArrayDeque(); + + @Override + public void init() { + startThread(); + } + + @Override + public void close() { + terminateThread(); + } + + @Override + public double getMaxRedstoneDistance() { + return CastleGates.getConfigManager().getMaxRedstoneDistance(); + } + + @Override + public ICitadel getCitadel(List players, Location loc) { + Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); + + boolean hasAccess = rein == null; + boolean useJukeAlert = false; + + if(!hasAccess) { + var doorsPermission= CitadelPermissionHandler.getDoors(); + + if (players != null && players.size() > 0) { + for (Player player : players) { + if (rein.hasPermission(player, doorsPermission) || player.hasPermission("citadel.admin")) { + hasAccess = true; + break; + } + } + } + + if(!hasAccess) { + if(CastleGates.getJukeAlertManager().hasJukeAlertAccess(loc, rein.getGroup().getName())) { + hasAccess = true; + useJukeAlert = true; + } + } + } + + return new com.aleksey.castlegates.plugins.citadel.Citadel(rein, hasAccess, useJukeAlert); + } + + @Override + public boolean isReinforced(Location loc) { + Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); + return rein != null; + } + + @Override + public boolean canBypass(Player player, Location loc) { + Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); + + if(rein == null) + return true; + + if(player == null) + return false; + + return rein.hasPermission(player, CitadelPermissionHandler.getBypass()) + || player.hasPermission("citadel.admin"); + } + + @Override + public boolean canViewInformation(Player player, Location loc) { + Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); + + if(rein == null) + return true; + + if(player == null) + return false; + + return rein.hasPermission(player, CitadelPermissionHandler.getInfo()) + || player.hasPermission("citadel.admin"); + } + + @Override + public ReinforcementInfo removeReinforcement(Location loc) { + Reinforcement rein = Citadel.getInstance().getReinforcementManager().getReinforcement(loc); + + if(rein == null) + return null; + + ReinforcementInfo info = new ReinforcementInfo(); + info.CreationTime = rein.getCreationTime(); + info.TypeId = rein.getType().getID(); + info.Health = rein.getHealth(); + info.GroupId = rein.getGroupId(); + info.Insecure = rein.isInsecure(); + + synchronized(this._updatedReinforcements) { + this._updatedReinforcements.add(new UpdatedReinforcement(rein, true)); + } + + return info; + } + + @Override + public boolean createReinforcement(ReinforcementInfo info, Location loc) { + if(info == null) + return false; + + var type = Citadel.getInstance().getReinforcementTypeManager().getById(info.TypeId); + var rein = new Reinforcement(loc, type, info.GroupId, info.CreationTime, info.Health, info.Insecure, true); + + synchronized(this._updatedReinforcements) { + this._updatedReinforcements.add(new UpdatedReinforcement(rein, false)); + } + + return true; + } + + @Override + public boolean isReinforcingStateActive(Player player) { + PlayerStateManager stateManager = Citadel.getInstance().getStateManager(); + AbstractPlayerState currentState = stateManager.getState(player); + + return currentState instanceof ReinforcingState; + } + + public void startThread() { + setName("CastleGates CitadelManager Thread"); + setPriority(Thread.MIN_PRIORITY); + start(); + + CastleGates.getPluginLogger().log(Level.INFO, "CitadelManager thread started"); + } + + public void terminateThread() { + this._kill.set(true); + + while (this._run.get()) { + try { + Thread.sleep(100); + } catch (Exception e) { + e.printStackTrace(); + } + } + + saveData(); + + CastleGates.getPluginLogger().log(Level.INFO, "CitadelManager thread stopped"); + } + + @Override + public void run() { + this._run.set(true); + + try { + while (!this.isInterrupted() && !this._kill.get()) { + try { + long timeWait = _lastExecute + CastleGates.getConfigManager().getDataWorkerRate() - System.currentTimeMillis(); + _lastExecute = System.currentTimeMillis(); + if (timeWait > 0) { + Thread.sleep(timeWait); + } + + saveData(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } finally { + this._run.set(false); + } + } + + private void saveData() { + try { + synchronized (this._updatedReinforcements) { + if (this._updatedReinforcements.size() == 0) return; + + this._localUpdatedReinforcements.addAll(this._updatedReinforcements); + this._updatedReinforcements.clear(); + } + + UpdatedReinforcement updated; + + while ((updated = this._localUpdatedReinforcements.poll()) != null) { + if (updated.deleted) + updated.rein.setHealth(-1); + else + Citadel.getInstance().getReinforcementManager().putReinforcement(updated.rein); + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadel.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadel.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadel.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadel.java index 30179cae5..c42e30bdf 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadel.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadel.java @@ -1,13 +1,13 @@ -/** - * Created by Aleksey on 02.06.2017. - */ - -package com.aleksey.castlegates.plugins.citadel; - -import org.bukkit.Location; - -public interface ICitadel { - boolean useJukeAlert(); - String getGroupName(); - boolean canAccessDoors(Location location); -} +/** + * Created by Aleksey on 02.06.2017. + */ + +package com.aleksey.castlegates.plugins.citadel; + +import org.bukkit.Location; + +public interface ICitadel { + boolean useJukeAlert(); + String getGroupName(); + boolean canAccessDoors(Location location); +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadelManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadelManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadelManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadelManager.java index 01b2219a6..af3dd07bf 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadelManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/ICitadelManager.java @@ -1,26 +1,26 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.plugins.citadel; - -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.database.ReinforcementInfo; - -public interface ICitadelManager { - void init(); - void close(); - double getMaxRedstoneDistance(); - ICitadel getCitadel(List players, Location loc); - boolean isReinforced(Location loc); - boolean canBypass(Player player, Location loc); - boolean canViewInformation(Player player, Location loc); - ReinforcementInfo removeReinforcement(Location loc); - boolean createReinforcement(ReinforcementInfo info, Location loc); - boolean isReinforcingStateActive(Player player); -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.plugins.citadel; + +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.database.ReinforcementInfo; + +public interface ICitadelManager { + void init(); + void close(); + double getMaxRedstoneDistance(); + ICitadel getCitadel(List players, Location loc); + boolean isReinforced(Location loc); + boolean canBypass(Player player, Location loc); + boolean canViewInformation(Player player, Location loc); + ReinforcementInfo removeReinforcement(Location loc); + boolean createReinforcement(ReinforcementInfo info, Location loc); + boolean isReinforcingStateActive(Player player); +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadel.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadel.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadel.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadel.java index a72fe8568..4a517e255 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadel.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadel.java @@ -1,13 +1,13 @@ -/** - * Created by Aleksey on 02.06.2017. - */ - -package com.aleksey.castlegates.plugins.citadel; - -import org.bukkit.Location; - -public class NoCitadel implements ICitadel { - public boolean useJukeAlert() { return false; } - public String getGroupName() { return null; } - public boolean canAccessDoors(Location location) { return true; } -} +/** + * Created by Aleksey on 02.06.2017. + */ + +package com.aleksey.castlegates.plugins.citadel; + +import org.bukkit.Location; + +public class NoCitadel implements ICitadel { + public boolean useJukeAlert() { return false; } + public String getGroupName() { return null; } + public boolean canAccessDoors(Location location) { return true; } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadelManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadelManager.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadelManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadelManager.java index d28931ccd..0f4af0c05 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadelManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/citadel/NoCitadelManager.java @@ -1,62 +1,62 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.plugins.citadel; - -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.database.ReinforcementInfo; - -public class NoCitadelManager implements ICitadelManager { - @Override - public void init() { - - } - - @Override - public void close() { - - } - - @Override - public double getMaxRedstoneDistance() { - return CastleGates.getConfigManager().getMaxRedstoneDistance(); - } - - @Override - public ICitadel getCitadel(List players, Location loc) { return new NoCitadel(); } - - @Override - public boolean isReinforced(Location loc) { return false; } - - @Override - public boolean canBypass(Player player, Location loc) { - return true; - } - - @Override - public boolean canViewInformation(Player player, Location loc) { - return true; - } - - @Override - public ReinforcementInfo removeReinforcement(Location loc) { - return null; - } - - @Override - public boolean createReinforcement(ReinforcementInfo info, Location loc) { - return false; - } - - @Override - public boolean isReinforcingStateActive(Player player) { - return false; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.plugins.citadel; + +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.database.ReinforcementInfo; + +public class NoCitadelManager implements ICitadelManager { + @Override + public void init() { + + } + + @Override + public void close() { + + } + + @Override + public double getMaxRedstoneDistance() { + return CastleGates.getConfigManager().getMaxRedstoneDistance(); + } + + @Override + public ICitadel getCitadel(List players, Location loc) { return new NoCitadel(); } + + @Override + public boolean isReinforced(Location loc) { return false; } + + @Override + public boolean canBypass(Player player, Location loc) { + return true; + } + + @Override + public boolean canViewInformation(Player player, Location loc) { + return true; + } + + @Override + public ReinforcementInfo removeReinforcement(Location loc) { + return null; + } + + @Override + public boolean createReinforcement(ReinforcementInfo info, Location loc) { + return false; + } + + @Override + public boolean isReinforcingStateActive(Player player) { + return false; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/IJukeAlertManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/IJukeAlertManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/IJukeAlertManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/IJukeAlertManager.java index 95bd8ef25..f50a07dbb 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/IJukeAlertManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/IJukeAlertManager.java @@ -1,7 +1,7 @@ -package com.aleksey.castlegates.plugins.jukealert; - -import org.bukkit.Location; - -public interface IJukeAlertManager { - boolean hasJukeAlertAccess(Location location, String groupName); +package com.aleksey.castlegates.plugins.jukealert; + +import org.bukkit.Location; + +public interface IJukeAlertManager { + boolean hasJukeAlertAccess(Location location, String groupName); } \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/JukeAlertManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/JukeAlertManager.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/JukeAlertManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/JukeAlertManager.java index ff5e1cd8a..e2727466a 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/JukeAlertManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/JukeAlertManager.java @@ -1,41 +1,41 @@ -package com.aleksey.castlegates.plugins.jukealert; - -import com.aleksey.castlegates.CastleGates; -import com.untamedears.jukealert.model.Snitch; -import com.untamedears.jukealert.model.appender.LeverToggleAppender; -import org.bukkit.Location; - -import com.untamedears.jukealert.JukeAlert; -import com.untamedears.jukealert.SnitchManager; - -import java.util.Set; - -public class JukeAlertManager implements IJukeAlertManager { - private final SnitchManager _snitchManager = JukeAlert.getInstance().getSnitchManager(); - - public boolean hasJukeAlertAccess(Location location, String groupName) { - if(!CastleGates.getConfigManager().getInteractWithSnitches()) return false; - - Set snitches = _snitchManager.getSnitchesCovering(location); - - if (snitches.size() > 0) { - double distance = CastleGates.getCitadelManager().getMaxRedstoneDistance(); - - for (Snitch snitch : snitches) { - if (snitch.getGroup().getName().equalsIgnoreCase(groupName) - && snitch.getLocation().distance(location) <= distance - ) - { - LeverToggleAppender toggleAppender = snitch.getAppender(LeverToggleAppender.class); - if (toggleAppender == null) { - continue; - } - if (toggleAppender.shouldToggle()) - return true; - } - } - } - - return false; - } -} +package com.aleksey.castlegates.plugins.jukealert; + +import com.aleksey.castlegates.CastleGates; +import com.untamedears.jukealert.model.Snitch; +import com.untamedears.jukealert.model.appender.LeverToggleAppender; +import org.bukkit.Location; + +import com.untamedears.jukealert.JukeAlert; +import com.untamedears.jukealert.SnitchManager; + +import java.util.Set; + +public class JukeAlertManager implements IJukeAlertManager { + private final SnitchManager _snitchManager = JukeAlert.getInstance().getSnitchManager(); + + public boolean hasJukeAlertAccess(Location location, String groupName) { + if(!CastleGates.getConfigManager().getInteractWithSnitches()) return false; + + Set snitches = _snitchManager.getSnitchesCovering(location); + + if (snitches.size() > 0) { + double distance = CastleGates.getCitadelManager().getMaxRedstoneDistance(); + + for (Snitch snitch : snitches) { + if (snitch.getGroup().getName().equalsIgnoreCase(groupName) + && snitch.getLocation().distance(location) <= distance + ) + { + LeverToggleAppender toggleAppender = snitch.getAppender(LeverToggleAppender.class); + if (toggleAppender == null) { + continue; + } + if (toggleAppender.shouldToggle()) + return true; + } + } + } + + return false; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/NoJukeAlertManager.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/NoJukeAlertManager.java similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/NoJukeAlertManager.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/NoJukeAlertManager.java index 9a494f585..d446ff1a1 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/NoJukeAlertManager.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/plugins/jukealert/NoJukeAlertManager.java @@ -1,8 +1,8 @@ -package com.aleksey.castlegates.plugins.jukealert; - -import com.aleksey.castlegates.plugins.citadel.ICitadel; -import org.bukkit.Location; - -public class NoJukeAlertManager implements IJukeAlertManager { - public boolean hasJukeAlertAccess(Location location, String groupName) { return false; } -} +package com.aleksey.castlegates.plugins.jukealert; + +import com.aleksey.castlegates.plugins.citadel.ICitadel; +import org.bukkit.Location; + +public class NoJukeAlertManager implements IJukeAlertManager { + public boolean hasJukeAlertAccess(Location location, String groupName) { return false; } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/BlockCoord.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/BlockCoord.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/BlockCoord.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/BlockCoord.java index 398ef2a44..68b498d95 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/BlockCoord.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/BlockCoord.java @@ -1,80 +1,80 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.types; - -import java.util.UUID; - -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; - -public class BlockCoord { - private final UUID _world; - private int _x; - private int _y; - private int _z; - - public BlockCoord(Block block) { - _world = block.getWorld().getUID(); - _x = block.getX(); - _y = block.getY(); - _z = block.getZ(); - } - - public BlockCoord(UUID world, int x, int y, int z) { - _world = world; - _x = x; - _y = y; - _z = z; - } - - @Override - public BlockCoord clone() { - return new BlockCoord(_world, _x, _y, _z); - } - - public UUID getWorldUID() { return _world; } - - public int getX() { return _x; } - - public int getY() { return _y; } - - public int getZ() { return _z; } - - public void increment(BlockFace face) { - _x += face.getModX(); - _y += face.getModY(); - _z += face.getModZ(); - } - - public BlockCoord getForward() { return new BlockCoord(_world, _x, _y, _z - 1); } - public BlockCoord getBackward() { return new BlockCoord(_world, _x, _y, _z + 1); } - public BlockCoord getRight() { return new BlockCoord(_world, _x - 1, _y, _z); } - public BlockCoord getLeft() { return new BlockCoord(_world, _x + 1, _y, _z); } - public BlockCoord getTop() { return new BlockCoord(_world, _x, _y + 1, _z); } - public BlockCoord getBottom() { return new BlockCoord(_world, _x, _y - 1, _z); } - - @Override - public boolean equals(Object other) { - if (!(other instanceof BlockCoord object)) - return false; - - return _world.equals(object._world) - && _x == object._x - && _y == object._y - && _z == object._z - ; - } - - @Override - public int hashCode() { - return _world.hashCode() ^ _x ^ _y ^ _z; - } - - @Override - public String toString() { - return "World UUID = " + _world + ", [" + _x + " " + _y + " " + _z + "]"; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.types; + +import java.util.UUID; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; + +public class BlockCoord { + private final UUID _world; + private int _x; + private int _y; + private int _z; + + public BlockCoord(Block block) { + _world = block.getWorld().getUID(); + _x = block.getX(); + _y = block.getY(); + _z = block.getZ(); + } + + public BlockCoord(UUID world, int x, int y, int z) { + _world = world; + _x = x; + _y = y; + _z = z; + } + + @Override + public BlockCoord clone() { + return new BlockCoord(_world, _x, _y, _z); + } + + public UUID getWorldUID() { return _world; } + + public int getX() { return _x; } + + public int getY() { return _y; } + + public int getZ() { return _z; } + + public void increment(BlockFace face) { + _x += face.getModX(); + _y += face.getModY(); + _z += face.getModZ(); + } + + public BlockCoord getForward() { return new BlockCoord(_world, _x, _y, _z - 1); } + public BlockCoord getBackward() { return new BlockCoord(_world, _x, _y, _z + 1); } + public BlockCoord getRight() { return new BlockCoord(_world, _x - 1, _y, _z); } + public BlockCoord getLeft() { return new BlockCoord(_world, _x + 1, _y, _z); } + public BlockCoord getTop() { return new BlockCoord(_world, _x, _y + 1, _z); } + public BlockCoord getBottom() { return new BlockCoord(_world, _x, _y - 1, _z); } + + @Override + public boolean equals(Object other) { + if (!(other instanceof BlockCoord object)) + return false; + + return _world.equals(object._world) + && _x == object._x + && _y == object._y + && _z == object._z + ; + } + + @Override + public int hashCode() { + return _world.hashCode() ^ _x ^ _y ^ _z; + } + + @Override + public String toString() { + return "World UUID = " + _world + ", [" + _x + " " + _y + " " + _z + "]"; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/BlockState.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/BlockState.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/BlockState.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/BlockState.java index ad5564f01..8a590ee6e 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/BlockState.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/BlockState.java @@ -1,39 +1,39 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.types; - -import org.bukkit.block.Block; - -import com.aleksey.castlegates.database.ReinforcementInfo; - -public class BlockState { - public static final char Separator = '\n'; - - private String _blockData; - public String getBlockData() { return _blockData; } - public int getBlockDataLen() { return _blockData.length() + 1; } - - private ReinforcementInfo _reinforcement; - public void setReinforcement(ReinforcementInfo reinforcement) { _reinforcement = reinforcement; } - public ReinforcementInfo getReinforcement() { return _reinforcement; } - - public BlockState(Block block, ReinforcementInfo reinforcement) { - _blockData = block.getBlockData().getAsString(); - _reinforcement = reinforcement; - } - - private BlockState(String blockData) { - _blockData = blockData; - } - public void serialize(StringBuilder data) { - data.append(_blockData); - data.append(Separator); - } - - public static BlockState deserialize(String blockData) { - return new BlockState(blockData); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.types; + +import org.bukkit.block.Block; + +import com.aleksey.castlegates.database.ReinforcementInfo; + +public class BlockState { + public static final char Separator = '\n'; + + private String _blockData; + public String getBlockData() { return _blockData; } + public int getBlockDataLen() { return _blockData.length() + 1; } + + private ReinforcementInfo _reinforcement; + public void setReinforcement(ReinforcementInfo reinforcement) { _reinforcement = reinforcement; } + public ReinforcementInfo getReinforcement() { return _reinforcement; } + + public BlockState(Block block, ReinforcementInfo reinforcement) { + _blockData = block.getBlockData().getAsString(); + _reinforcement = reinforcement; + } + + private BlockState(String blockData) { + _blockData = blockData; + } + public void serialize(StringBuilder data) { + data.append(_blockData); + data.append(Separator); + } + + public static BlockState deserialize(String blockData) { + return new BlockState(blockData); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/CommandMode.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/CommandMode.java similarity index 90% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/CommandMode.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/CommandMode.java index 14795e6e1..d4bb60655 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/CommandMode.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/CommandMode.java @@ -1,15 +1,15 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.types; - -public enum CommandMode { - OFF, - NORMAL, - CREATE, - LINK, - INFO, - TIMER -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.types; + +public enum CommandMode { + OFF, + NORMAL, + CREATE, + LINK, + INFO, + TIMER +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/Gearblock.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/Gearblock.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/Gearblock.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/Gearblock.java index 48f785e97..420861b90 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/Gearblock.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/Gearblock.java @@ -1,82 +1,82 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.types; - -import java.util.List; - - -public class Gearblock { - private int _id; - private final BlockCoord _coord; - private boolean _powered; - private boolean _removed; - private GearblockLink _link; - private Integer _timer; - private TimerOperation _timerOperation; - private TimerMode _timerMode; - private TimerBatch _timerBatch; - private long _lastSwitchTime; - private Gearblock _lockGearblock; - private List _lockedGearblocks; - - public Gearblock(BlockCoord coord) { - _coord = coord; - } - - public int getId() { return _id; } - public void setId(int value) { _id = value; } - - public BlockCoord getCoord() { return _coord; } - - public boolean isRemoved() { return _removed; } - public void setRemoved() { _removed = true; } - - public boolean isPowered() { return _powered; } - public void setPowered(boolean value) { _powered = value; } - - public GearblockLink getLink() { return _link != null && !_link.isBroken() ? _link : null; } - public GearblockLink getBrokenLink() { return _link != null && _link.isBroken() ? _link : null; } - public void setLink(GearblockLink link) { _link = link; } - - public Integer getTimer() { return _timer; } - public TimerOperation getTimerOperation() { return _timerOperation; } - public TimerMode getTimerMode() { return _timerMode; } - public void setTimer(Integer timer, TimerOperation timerOperation, TimerMode timerMode) { - _timer = timer; - _timerOperation = timerOperation; - _timerMode = timerMode; - } - - public TimerBatch getTimerBatch() { return _timerBatch; } - public void setTimerBatch(TimerBatch timerBatch) { _timerBatch = timerBatch; } - - public long getLastSwitchTime() { return _lastSwitchTime; } - public void setLastSwitchTime() { _lastSwitchTime = System.currentTimeMillis(); } - - public void setLockGearblock(Gearblock lockGearblock) { _lockGearblock = lockGearblock; } - public Gearblock getLockGearblock() { return _lockGearblock; } - - public void setLockedGearblocks(List lockedGearblocks) { _lockedGearblocks = lockedGearblocks; } - public List getLockedGearblocks() { return _lockedGearblocks; } - - @Override - public boolean equals(Object other) { - if (!(other instanceof Gearblock object)) - return false; - - return _coord.equals(object._coord); - } - - @Override - public int hashCode() { - return _coord.hashCode(); - } - - @Override - public String toString() { - return _coord.toString(); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.types; + +import java.util.List; + + +public class Gearblock { + private int _id; + private final BlockCoord _coord; + private boolean _powered; + private boolean _removed; + private GearblockLink _link; + private Integer _timer; + private TimerOperation _timerOperation; + private TimerMode _timerMode; + private TimerBatch _timerBatch; + private long _lastSwitchTime; + private Gearblock _lockGearblock; + private List _lockedGearblocks; + + public Gearblock(BlockCoord coord) { + _coord = coord; + } + + public int getId() { return _id; } + public void setId(int value) { _id = value; } + + public BlockCoord getCoord() { return _coord; } + + public boolean isRemoved() { return _removed; } + public void setRemoved() { _removed = true; } + + public boolean isPowered() { return _powered; } + public void setPowered(boolean value) { _powered = value; } + + public GearblockLink getLink() { return _link != null && !_link.isBroken() ? _link : null; } + public GearblockLink getBrokenLink() { return _link != null && _link.isBroken() ? _link : null; } + public void setLink(GearblockLink link) { _link = link; } + + public Integer getTimer() { return _timer; } + public TimerOperation getTimerOperation() { return _timerOperation; } + public TimerMode getTimerMode() { return _timerMode; } + public void setTimer(Integer timer, TimerOperation timerOperation, TimerMode timerMode) { + _timer = timer; + _timerOperation = timerOperation; + _timerMode = timerMode; + } + + public TimerBatch getTimerBatch() { return _timerBatch; } + public void setTimerBatch(TimerBatch timerBatch) { _timerBatch = timerBatch; } + + public long getLastSwitchTime() { return _lastSwitchTime; } + public void setLastSwitchTime() { _lastSwitchTime = System.currentTimeMillis(); } + + public void setLockGearblock(Gearblock lockGearblock) { _lockGearblock = lockGearblock; } + public Gearblock getLockGearblock() { return _lockGearblock; } + + public void setLockedGearblocks(List lockedGearblocks) { _lockedGearblocks = lockedGearblocks; } + public List getLockedGearblocks() { return _lockedGearblocks; } + + @Override + public boolean equals(Object other) { + if (!(other instanceof Gearblock object)) + return false; + + return _coord.equals(object._coord); + } + + @Override + public int hashCode() { + return _coord.hashCode(); + } + + @Override + public String toString() { + return _coord.toString(); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/GearblockForUpdate.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/GearblockForUpdate.java similarity index 95% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/GearblockForUpdate.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/GearblockForUpdate.java index 79004bba6..649266f02 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/GearblockForUpdate.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/GearblockForUpdate.java @@ -1,8 +1,8 @@ -package com.aleksey.castlegates.types; - -import com.aleksey.castlegates.database.GearblockInfo; - -public class GearblockForUpdate { - public Gearblock original; - public GearblockInfo info; -} +package com.aleksey.castlegates.types; + +import com.aleksey.castlegates.database.GearblockInfo; + +public class GearblockForUpdate { + public Gearblock original; + public GearblockInfo info; +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/GearblockLink.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/GearblockLink.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/GearblockLink.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/GearblockLink.java index 309c2c483..85252209b 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/GearblockLink.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/GearblockLink.java @@ -1,53 +1,53 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.types; - -import java.util.List; - -public class GearblockLink { - private int _id; - private Gearblock _gearblock1; - private Gearblock _gearblock2; - private boolean _removed; - private List _blocks; - - public GearblockLink(Gearblock gearblock1, Gearblock gearblock2) { - _gearblock1 = gearblock1; - _gearblock2 = gearblock2; - } - - public int getId() { return _id; } - public void setId(int value) { _id = value; } - - public Gearblock getGearblock1() { return _gearblock1; } - - public Gearblock getGearblock2() { return _gearblock2; } - - public boolean isBroken() { return _gearblock1 == null || _gearblock2 == null; } - - public void setBroken(Gearblock removedGear) { - if(_gearblock1 == removedGear) { - _gearblock1 = null; - } else { - _gearblock2 = null; - } - } - - public void setRestored(Gearblock addedGearblock) { - if(_gearblock1 == null) { - _gearblock1 = addedGearblock; - } else { - _gearblock2 = addedGearblock; - } - } - - public boolean isRemoved() { return _removed; } - public void setRemoved() { _removed = true; } - - public boolean isDrawn() { return _blocks != null; } - public List getBlocks() { return _blocks; } - public void setBlocks(List blocks) { _blocks = blocks; } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.types; + +import java.util.List; + +public class GearblockLink { + private int _id; + private Gearblock _gearblock1; + private Gearblock _gearblock2; + private boolean _removed; + private List _blocks; + + public GearblockLink(Gearblock gearblock1, Gearblock gearblock2) { + _gearblock1 = gearblock1; + _gearblock2 = gearblock2; + } + + public int getId() { return _id; } + public void setId(int value) { _id = value; } + + public Gearblock getGearblock1() { return _gearblock1; } + + public Gearblock getGearblock2() { return _gearblock2; } + + public boolean isBroken() { return _gearblock1 == null || _gearblock2 == null; } + + public void setBroken(Gearblock removedGear) { + if(_gearblock1 == removedGear) { + _gearblock1 = null; + } else { + _gearblock2 = null; + } + } + + public void setRestored(Gearblock addedGearblock) { + if(_gearblock1 == null) { + _gearblock1 = addedGearblock; + } else { + _gearblock2 = addedGearblock; + } + } + + public boolean isRemoved() { return _removed; } + public void setRemoved() { _removed = true; } + + public boolean isDrawn() { return _blocks != null; } + public List getBlocks() { return _blocks; } + public void setBlocks(List blocks) { _blocks = blocks; } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/LinkForUpdate.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/LinkForUpdate.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/LinkForUpdate.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/LinkForUpdate.java index 1e277fd15..0fadfb9f4 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/LinkForUpdate.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/LinkForUpdate.java @@ -1,13 +1,13 @@ -package com.aleksey.castlegates.types; - -import java.util.List; - -import com.aleksey.castlegates.database.ReinforcementInfo; - -public class LinkForUpdate { - public GearblockLink original; - public Gearblock gearblock1; - public Gearblock gearblock2; - public String blocks; - public List reinforcements; -} +package com.aleksey.castlegates.types; + +import java.util.List; + +import com.aleksey.castlegates.database.ReinforcementInfo; + +public class LinkForUpdate { + public GearblockLink original; + public Gearblock gearblock1; + public Gearblock gearblock2; + public String blocks; + public List reinforcements; +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/PowerResult.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/PowerResult.java similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/PowerResult.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/PowerResult.java index a525a9d52..ac6d43bd7 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/PowerResult.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/PowerResult.java @@ -1,38 +1,38 @@ -package com.aleksey.castlegates.types; - -import org.bukkit.block.Block; - -public class PowerResult { - public enum Status { - Unchanged, - Unpowered, - Blocked, - Broken, - Drawn, - Undrawn, - CannotDrawGear, - NotInCitadelGroup, - DifferentCitadelGroup, - BastionBlocked, - Locked, - Allowed - } - - public Status status; - public Block block; - - public PowerResult(Status status, Block block) { - this.status = status; - this.block = block; - } - - public static final PowerResult Unchanged = new PowerResult(Status.Unchanged, null); - public static final PowerResult Unpowered = new PowerResult(Status.Unpowered, null); - public static final PowerResult Drawn = new PowerResult(Status.Drawn, null); - public static final PowerResult Undrawn = new PowerResult(Status.Undrawn, null); - public static final PowerResult NotInCitadelGroup = new PowerResult(Status.NotInCitadelGroup, null); - public static final PowerResult DifferentCitadelGroup = new PowerResult(Status.DifferentCitadelGroup, null); - public static final PowerResult BastionBlocked = new PowerResult(Status.BastionBlocked, null); - public static final PowerResult Allowed = new PowerResult(Status.Allowed, null); - public static final PowerResult Locked = new PowerResult(Status.Locked, null); -} +package com.aleksey.castlegates.types; + +import org.bukkit.block.Block; + +public class PowerResult { + public enum Status { + Unchanged, + Unpowered, + Blocked, + Broken, + Drawn, + Undrawn, + CannotDrawGear, + NotInCitadelGroup, + DifferentCitadelGroup, + BastionBlocked, + Locked, + Allowed + } + + public Status status; + public Block block; + + public PowerResult(Status status, Block block) { + this.status = status; + this.block = block; + } + + public static final PowerResult Unchanged = new PowerResult(Status.Unchanged, null); + public static final PowerResult Unpowered = new PowerResult(Status.Unpowered, null); + public static final PowerResult Drawn = new PowerResult(Status.Drawn, null); + public static final PowerResult Undrawn = new PowerResult(Status.Undrawn, null); + public static final PowerResult NotInCitadelGroup = new PowerResult(Status.NotInCitadelGroup, null); + public static final PowerResult DifferentCitadelGroup = new PowerResult(Status.DifferentCitadelGroup, null); + public static final PowerResult BastionBlocked = new PowerResult(Status.BastionBlocked, null); + public static final PowerResult Allowed = new PowerResult(Status.Allowed, null); + public static final PowerResult Locked = new PowerResult(Status.Locked, null); +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerBatch.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerBatch.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerBatch.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerBatch.java index 7f06b6b71..bb8e8ccf7 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerBatch.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerBatch.java @@ -1,104 +1,104 @@ -package com.aleksey.castlegates.types; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import org.bukkit.World; - -public class TimerBatch { - private World _world; - private Gearblock _gearblock; - private HashSet _allGearblocks; - private long _runTimeMillis; - private PowerResult.Status _processStatus; - private TimerOperation _timerOperation; - private TimerMode _timerMode; - private boolean _isInvalid; - private List _links = new ArrayList<>(); - - public World getWorld() { - return _world; - } - - public Gearblock getGearblock() { - return _gearblock; - } - - public TimerMode getTimerMode() { return _timerMode; } - - public HashSet getAllGearblocks() { return _allGearblocks; } - public void clearTimerBatchForAllGearblocks() { - for(Gearblock gearblock : _allGearblocks) { - gearblock.setTimerBatch(null); - } - } - - public List getLinks() { - return _links; - } - - public long getRunTimeMillis() { - return _runTimeMillis; - } - - public boolean resetRunTime() { - if(_gearblock.getTimer() == null) return false; - - _runTimeMillis = System.currentTimeMillis() + _gearblock.getTimer() * 1000; - - return true; - } - - public void setProcessStatus(PowerResult.Status processStatus) { - _processStatus = processStatus; - } - - public PowerResult.Status getProcessStatus() { - return _processStatus; - } - - public boolean isInvalid() { return _isInvalid; } - public void invalidate() { _isInvalid = true; } - - public TimerBatch(World world, Gearblock gearblock, HashSet allGearblocks) { - _world = world; - _gearblock = gearblock; - _timerOperation = gearblock.getTimerOperation(); - _timerMode = gearblock.getTimerMode(); - _allGearblocks = allGearblocks; - - for(Gearblock current : _allGearblocks) { - if(current.getTimerBatch() != null) { - current.getTimerBatch().invalidate(); - } - - current.setTimerBatch(this); - } - - resetRunTime(); - } - - public void addLink(GearblockLink link) { - boolean mustDraw = _timerOperation == TimerOperation.DRAW - || _timerOperation == TimerOperation.REVERT && !link.isDrawn(); - - _links.add(new TimerLink(link, mustDraw)); - } - - public TimerBatch clone(Gearblock newGearblock) { - TimerBatch clone = new TimerBatch(_world, newGearblock, _allGearblocks); - - clone._world = _world; - clone._gearblock = newGearblock; - clone._allGearblocks = _allGearblocks; - clone._runTimeMillis = _runTimeMillis; - clone._processStatus = _processStatus; - clone._timerOperation = _timerOperation; - clone._timerMode = _timerMode; - clone._isInvalid = false; - clone._links = _links; - - return clone; - } -} +package com.aleksey.castlegates.types; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import org.bukkit.World; + +public class TimerBatch { + private World _world; + private Gearblock _gearblock; + private HashSet _allGearblocks; + private long _runTimeMillis; + private PowerResult.Status _processStatus; + private TimerOperation _timerOperation; + private TimerMode _timerMode; + private boolean _isInvalid; + private List _links = new ArrayList<>(); + + public World getWorld() { + return _world; + } + + public Gearblock getGearblock() { + return _gearblock; + } + + public TimerMode getTimerMode() { return _timerMode; } + + public HashSet getAllGearblocks() { return _allGearblocks; } + public void clearTimerBatchForAllGearblocks() { + for(Gearblock gearblock : _allGearblocks) { + gearblock.setTimerBatch(null); + } + } + + public List getLinks() { + return _links; + } + + public long getRunTimeMillis() { + return _runTimeMillis; + } + + public boolean resetRunTime() { + if(_gearblock.getTimer() == null) return false; + + _runTimeMillis = System.currentTimeMillis() + _gearblock.getTimer() * 1000; + + return true; + } + + public void setProcessStatus(PowerResult.Status processStatus) { + _processStatus = processStatus; + } + + public PowerResult.Status getProcessStatus() { + return _processStatus; + } + + public boolean isInvalid() { return _isInvalid; } + public void invalidate() { _isInvalid = true; } + + public TimerBatch(World world, Gearblock gearblock, HashSet allGearblocks) { + _world = world; + _gearblock = gearblock; + _timerOperation = gearblock.getTimerOperation(); + _timerMode = gearblock.getTimerMode(); + _allGearblocks = allGearblocks; + + for(Gearblock current : _allGearblocks) { + if(current.getTimerBatch() != null) { + current.getTimerBatch().invalidate(); + } + + current.setTimerBatch(this); + } + + resetRunTime(); + } + + public void addLink(GearblockLink link) { + boolean mustDraw = _timerOperation == TimerOperation.DRAW + || _timerOperation == TimerOperation.REVERT && !link.isDrawn(); + + _links.add(new TimerLink(link, mustDraw)); + } + + public TimerBatch clone(Gearblock newGearblock) { + TimerBatch clone = new TimerBatch(_world, newGearblock, _allGearblocks); + + clone._world = _world; + clone._gearblock = newGearblock; + clone._allGearblocks = _allGearblocks; + clone._runTimeMillis = _runTimeMillis; + clone._processStatus = _processStatus; + clone._timerOperation = _timerOperation; + clone._timerMode = _timerMode; + clone._isInvalid = false; + clone._links = _links; + + return clone; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerLink.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerLink.java similarity index 94% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerLink.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerLink.java index 6d236038c..798f4f2fc 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerLink.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerLink.java @@ -1,19 +1,19 @@ -package com.aleksey.castlegates.types; - -public class TimerLink { - private final GearblockLink _link; - private final boolean _mustDraw; - - public GearblockLink getLink() { - return _link; - } - - public boolean isMustDraw() { - return _mustDraw; - } - - public TimerLink(GearblockLink link, boolean mustDraw) { - _link = link; - _mustDraw = mustDraw; - } -} +package com.aleksey.castlegates.types; + +public class TimerLink { + private final GearblockLink _link; + private final boolean _mustDraw; + + public GearblockLink getLink() { + return _link; + } + + public boolean isMustDraw() { + return _mustDraw; + } + + public TimerLink(GearblockLink link, boolean mustDraw) { + _link = link; + _mustDraw = mustDraw; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerMode.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerMode.java similarity index 93% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerMode.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerMode.java index cf06dbd24..4c53640f0 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerMode.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerMode.java @@ -1,10 +1,10 @@ -/** - * Created by Aleksey on 24.05.2017. - */ - -package com.aleksey.castlegates.types; - -public enum TimerMode { - DEFAULT, - DOOR -} +/** + * Created by Aleksey on 24.05.2017. + */ + +package com.aleksey.castlegates.types; + +public enum TimerMode { + DEFAULT, + DOOR +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerOperation.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerOperation.java similarity index 93% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerOperation.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerOperation.java index 8d8b41c10..be27241d6 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/types/TimerOperation.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/types/TimerOperation.java @@ -1,7 +1,7 @@ -package com.aleksey.castlegates.types; - -public enum TimerOperation { - DRAW, - UNDRAW, - REVERT -} +package com.aleksey.castlegates.types; + +public enum TimerOperation { + DRAW, + UNDRAW, + REVERT +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/DataWorker.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/DataWorker.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/DataWorker.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/DataWorker.java index 21bf210c0..94592d817 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/DataWorker.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/DataWorker.java @@ -1,422 +1,422 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.utils; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.database.GearblockInfo; -import com.aleksey.castlegates.database.GearblockSource; -import com.aleksey.castlegates.database.LinkInfo; -import com.aleksey.castlegates.database.LinkSource; -import com.aleksey.castlegates.database.ReinforcementInfo; -import com.aleksey.castlegates.database.ReinforcementSource; -import com.aleksey.castlegates.database.SqlDatabase; -import com.aleksey.castlegates.types.*; - -public class DataWorker extends Thread implements Runnable { - private static final int DRAW_CODE = 0; - private static final int UNDRAW_CODE = 1; - private static final int REVERT_CODE = 2; - private static final int OPERATION_MASK = 3; - private static final int MODE_MASK = 4; - - private final SqlDatabase _db; - private final GearblockSource _gearblockSource; - private final LinkSource _linkSource; - private final ReinforcementSource _reinforcementSource; - - private final Map _changedGearblocks = new HashMap<>(); - private final Map _changedLinks = new HashMap<>(); - - private final ArrayList _localChangedGearblocks = new ArrayList<>(); - private final ArrayList _localChangedLinks = new ArrayList<>(); - - private long _lastExecute = System.currentTimeMillis(); - private final AtomicBoolean _kill = new AtomicBoolean(false); - private final AtomicBoolean _run = new AtomicBoolean(false); - - public DataWorker(SqlDatabase db) { - _db = db; - _gearblockSource = new GearblockSource(db); - _linkSource = new LinkSource(db); - _reinforcementSource = new ReinforcementSource(db); - } - - public void close() { - terminateThread(); - } - - public Map load() throws SQLException { - Map gearblocks = new HashMap<>(); - Map gearblocksById = new HashMap<>(); - Map linksById = new HashMap<>(); - - loadGears(gearblocks, gearblocksById); - loadLinks(linksById, gearblocksById); - loadReinforcements(linksById); - - return gearblocks; - } - - private void loadGears(Map gearblocks, Map gearblocksById) throws SQLException { - int gearblockCount = _gearblockSource.countAll(); - - CastleGates.getPluginLogger().log(Level.INFO, "Gearblock count: " + gearblockCount); - - List gearData = _gearblockSource.selectAll(); - int timerCount = 0; - - for(GearblockInfo info : gearData) { - UUID world = UUID.fromString(info.WorldId); - BlockCoord location = new BlockCoord(world, info.X, info.Y, info.Z); - Gearblock gearblock = new Gearblock(location); - - TimerOperation timerOperation = null; - TimerMode timerMode = null; - - if(info.TimerOperation != null) { - timerMode = (info.TimerOperation & MODE_MASK) != 0 ? TimerMode.DOOR : TimerMode.DEFAULT; - - switch(info.TimerOperation & OPERATION_MASK) { - case DRAW_CODE -> timerOperation = TimerOperation.DRAW; - case UNDRAW_CODE -> timerOperation = TimerOperation.UNDRAW; - case REVERT_CODE -> timerOperation = TimerOperation.REVERT; - } - - timerCount++; - } - - gearblock.setId(info.GearblockId); - gearblock.setTimer(info.Timer, timerOperation, timerMode); - - gearblocks.put(location, gearblock); - gearblocksById.put(info.GearblockId, gearblock); - } - - CastleGates.getPluginLogger().log(Level.INFO, "Loaded gearblocks: " + gearblocks.size()); - CastleGates.getPluginLogger().log(Level.INFO, "Loaded gearblocksById: " + gearblocksById.size()); - CastleGates.getPluginLogger().log(Level.INFO, "Timers: " + timerCount); - } - - private void loadLinks(Map linksById, Map gearblocksById) throws SQLException { - int linkCount = _linkSource.countAll(); - - CastleGates.getPluginLogger().log(Level.INFO, "Link count: " + linkCount); - - List linkData = _linkSource.selectAll(); - List invalidLinks = new ArrayList<>(); - int drawnLinkCount = 0, brokenLinkCount = 0; - - for(LinkInfo info : linkData) { - Gearblock gearblock1 = info.StartGearblockId != null ? gearblocksById.get(info.StartGearblockId) : null; - Gearblock gearblock2 = info.EndGearblockId != null ? gearblocksById.get(info.EndGearblockId) : null; - List blocks = deserializeBlocks(info.Blocks); - GearblockLink link = new GearblockLink(gearblock1, gearblock2); - - link.setId(info.LinkId); - link.setBlocks(blocks); - - if(gearblock1 != null) { - gearblock1.setLink(link); - } - - if(gearblock2 != null) { - gearblock2.setLink(link); - } - - linksById.put(link.getId(), link); - - if(gearblock1 == null && gearblock2 == null) { - invalidLinks.add(info); - } - - if(link.isDrawn()) { - drawnLinkCount++; - } - - if(link.isBroken()) { - brokenLinkCount++; - } - } - - CastleGates.getPluginLogger().log(Level.INFO, "Loaded links: " + linkData.size()); - - if(drawnLinkCount > 0) { - CastleGates.getPluginLogger().log(Level.INFO, "Links in DRAWN state: " + drawnLinkCount); - } - - if(brokenLinkCount > 0) { - CastleGates.getPluginLogger().log(Level.INFO, "Links in BROKEN state: " + brokenLinkCount); - } - - if(invalidLinks.size() > 0) { - CastleGates.getPluginLogger().log(Level.WARNING, "Invalid links (i.e. BUG): " + invalidLinks.size()); - - String filePath = new InvalidLinkLogger().write(invalidLinks); - - CastleGates.getPluginLogger().log(Level.INFO, "List of invalid links saved to: " + filePath); - } - } - - private void loadReinforcements(Map linksById) throws SQLException { - List reinforcementData = _reinforcementSource.selectAll(); - GearblockLink link = null; - - for(ReinforcementInfo info : reinforcementData) { - if(link == null || link.getId() != info.LinkId) { - link = linksById.get(info.LinkId); - } - - BlockState blockState = link.getBlocks().get(info.BlockSequence); - blockState.setReinforcement(info); - } - } - - public void startThread() { - _kill.set(false); - - setName("CastleGates DataWorker Thread"); - setPriority(Thread.MIN_PRIORITY); - start(); - - CastleGates.getPluginLogger().log(Level.INFO, "DataWorker thread started"); - } - - public void terminateThread() { - _kill.set(true); - - while (_run.get()) { - try { - Thread.sleep(100); - } catch (Exception e) { - e.printStackTrace(); - } - } - - saveData(); - - CastleGates.getPluginLogger().log(Level.INFO, "DataWorker thread stopped"); - } - - public void run() { - _run.set(true); - - try { - while (!isInterrupted() && !_kill.get()) { - try { - long timeWait = _lastExecute + CastleGates.getConfigManager().getDataWorkerRate() - System.currentTimeMillis(); - _lastExecute = System.currentTimeMillis(); - if (timeWait > 0) { - Thread.sleep(timeWait); - } - - saveData(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } finally { - _run.set(false); - } - } - - private void saveData() { - try { - synchronized (_changedGearblocks) { - _localChangedGearblocks.addAll(_changedGearblocks.values()); - _changedGearblocks.clear(); - } - - synchronized (_changedLinks) { - _localChangedLinks.addAll(_changedLinks.values()); - _changedLinks.clear(); - } - - if (_localChangedGearblocks.size() > 0 || _localChangedLinks.size() > 0) { - if (_db.checkConnection()) { - try { - updateGears(); - updateLinks(); - } finally { - _localChangedGearblocks.clear(); - _localChangedLinks.clear(); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void updateGears() throws SQLException { - for(GearblockForUpdate gearForUpdate : _localChangedGearblocks) { - if(gearForUpdate.original.isRemoved()) { - if(gearForUpdate.original.getId() != 0) { - _gearblockSource.delete(gearForUpdate.original.getId()); - } - } - else if(gearForUpdate.original.getId() != 0) { - _gearblockSource.update(gearForUpdate.info); - } - else { - _gearblockSource.insert(gearForUpdate.info); - gearForUpdate.original.setId(gearForUpdate.info.GearblockId); - } - } - } - - private void updateLinks() throws SQLException { - for(LinkForUpdate linkForUpdate : _localChangedLinks) { - if(linkForUpdate.original.isRemoved()) { - if(linkForUpdate.original.getId() != 0) { - _reinforcementSource.deleteByLinkId(linkForUpdate.original.getId()); - _linkSource.delete(linkForUpdate.original.getId()); - } - } else { - LinkInfo info = new LinkInfo(); - info.LinkId = linkForUpdate.original.getId(); - info.StartGearblockId = linkForUpdate.gearblock1 != null ? linkForUpdate.gearblock1.getId(): null; - info.EndGearblockId = linkForUpdate.gearblock2 != null ? linkForUpdate.gearblock2.getId(): null; - info.Blocks = linkForUpdate.blocks; - - if(info.LinkId != 0) { - _linkSource.update(info); - - if(info.Blocks == null) { - _reinforcementSource.deleteByLinkId(info.LinkId); - } - } else { - _linkSource.insert(info); - linkForUpdate.original.setId(info.LinkId); - } - - if(linkForUpdate.reinforcements != null) { - for(ReinforcementInfo reinforcement : linkForUpdate.reinforcements) { - if(reinforcement.LinkId != 0) continue; - - reinforcement.LinkId = info.LinkId; - - _reinforcementSource.insert(reinforcement); - } - } - } - } - } - - public void addChangedGearblock(Gearblock gearblock) { - GearblockInfo info; - - if(gearblock.isRemoved()) { - info = null; - } else { - info = new GearblockInfo(); - - BlockCoord location = gearblock.getCoord(); - info.GearblockId = gearblock.getId(); - info.WorldId = location.getWorldUID().toString(); - info.X = location.getX(); - info.Y = location.getY(); - info.Z = location.getZ(); - info.Timer = gearblock.getTimer(); - - if(gearblock.getTimerOperation() != null) { - switch(gearblock.getTimerOperation()) { - case DRAW -> info.TimerOperation = DRAW_CODE; - case UNDRAW -> info.TimerOperation = UNDRAW_CODE; - case REVERT -> info.TimerOperation = REVERT_CODE; - } - - if(gearblock.getTimerMode() == TimerMode.DOOR) { - info.TimerOperation |= MODE_MASK; - } - } - } - - GearblockForUpdate gearForUpdate = new GearblockForUpdate(); - gearForUpdate.original = gearblock; - gearForUpdate.info = info; - - synchronized(_changedGearblocks) { - _changedGearblocks.put(gearblock, gearForUpdate); - } - } - - public void addChangedLink(GearblockLink link) { - LinkForUpdate linkForUpdate = new LinkForUpdate(); - linkForUpdate.original = link; - - if(!link.isRemoved()) { - linkForUpdate.gearblock1 = link.getGearblock1(); - linkForUpdate.gearblock2 = link.getGearblock2(); - linkForUpdate.blocks = serializeBlocks(link); - - if(link.getBlocks() != null) { - linkForUpdate.reinforcements = new ArrayList<>(); - - for(int i = 0; i < link.getBlocks().size(); i++) { - ReinforcementInfo reinforcement = link.getBlocks().get(i).getReinforcement(); - - if(reinforcement != null && reinforcement.LinkId == 0) { - reinforcement.BlockSequence = i; - linkForUpdate.reinforcements.add(reinforcement); - } - } - } - } - - synchronized(_changedLinks) { - _changedLinks.put(link, linkForUpdate); - } - } - - private static String serializeBlocks(GearblockLink link) { - if(link.getBlocks() == null) - return null; - - int length = 0; - for(BlockState block : link.getBlocks()) - length += block.getBlockDataLen(); - - StringBuilder blockSerialized = new StringBuilder(length); - for(BlockState block : link.getBlocks()) - block.serialize(blockSerialized); - - return blockSerialized.toString(); - } - - public static List deserializeBlocks(String blockDataList) { - if(blockDataList == null || blockDataList.length() == 0) - return null; - - List blocks = new ArrayList<>(); - int len = blockDataList.length(); - int startIndex = 0; - int index = 0; - - while (index < len) { - if (blockDataList.charAt(index) == BlockState.Separator) { - String blockData = blockDataList.substring(startIndex, index); - BlockState block = BlockState.deserialize(blockData); - - blocks.add(block); - - startIndex = index + 1; - } - - index++; - } - - return blocks; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.utils; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.database.GearblockInfo; +import com.aleksey.castlegates.database.GearblockSource; +import com.aleksey.castlegates.database.LinkInfo; +import com.aleksey.castlegates.database.LinkSource; +import com.aleksey.castlegates.database.ReinforcementInfo; +import com.aleksey.castlegates.database.ReinforcementSource; +import com.aleksey.castlegates.database.SqlDatabase; +import com.aleksey.castlegates.types.*; + +public class DataWorker extends Thread implements Runnable { + private static final int DRAW_CODE = 0; + private static final int UNDRAW_CODE = 1; + private static final int REVERT_CODE = 2; + private static final int OPERATION_MASK = 3; + private static final int MODE_MASK = 4; + + private final SqlDatabase _db; + private final GearblockSource _gearblockSource; + private final LinkSource _linkSource; + private final ReinforcementSource _reinforcementSource; + + private final Map _changedGearblocks = new HashMap<>(); + private final Map _changedLinks = new HashMap<>(); + + private final ArrayList _localChangedGearblocks = new ArrayList<>(); + private final ArrayList _localChangedLinks = new ArrayList<>(); + + private long _lastExecute = System.currentTimeMillis(); + private final AtomicBoolean _kill = new AtomicBoolean(false); + private final AtomicBoolean _run = new AtomicBoolean(false); + + public DataWorker(SqlDatabase db) { + _db = db; + _gearblockSource = new GearblockSource(db); + _linkSource = new LinkSource(db); + _reinforcementSource = new ReinforcementSource(db); + } + + public void close() { + terminateThread(); + } + + public Map load() throws SQLException { + Map gearblocks = new HashMap<>(); + Map gearblocksById = new HashMap<>(); + Map linksById = new HashMap<>(); + + loadGears(gearblocks, gearblocksById); + loadLinks(linksById, gearblocksById); + loadReinforcements(linksById); + + return gearblocks; + } + + private void loadGears(Map gearblocks, Map gearblocksById) throws SQLException { + int gearblockCount = _gearblockSource.countAll(); + + CastleGates.getPluginLogger().log(Level.INFO, "Gearblock count: " + gearblockCount); + + List gearData = _gearblockSource.selectAll(); + int timerCount = 0; + + for(GearblockInfo info : gearData) { + UUID world = UUID.fromString(info.WorldId); + BlockCoord location = new BlockCoord(world, info.X, info.Y, info.Z); + Gearblock gearblock = new Gearblock(location); + + TimerOperation timerOperation = null; + TimerMode timerMode = null; + + if(info.TimerOperation != null) { + timerMode = (info.TimerOperation & MODE_MASK) != 0 ? TimerMode.DOOR : TimerMode.DEFAULT; + + switch(info.TimerOperation & OPERATION_MASK) { + case DRAW_CODE -> timerOperation = TimerOperation.DRAW; + case UNDRAW_CODE -> timerOperation = TimerOperation.UNDRAW; + case REVERT_CODE -> timerOperation = TimerOperation.REVERT; + } + + timerCount++; + } + + gearblock.setId(info.GearblockId); + gearblock.setTimer(info.Timer, timerOperation, timerMode); + + gearblocks.put(location, gearblock); + gearblocksById.put(info.GearblockId, gearblock); + } + + CastleGates.getPluginLogger().log(Level.INFO, "Loaded gearblocks: " + gearblocks.size()); + CastleGates.getPluginLogger().log(Level.INFO, "Loaded gearblocksById: " + gearblocksById.size()); + CastleGates.getPluginLogger().log(Level.INFO, "Timers: " + timerCount); + } + + private void loadLinks(Map linksById, Map gearblocksById) throws SQLException { + int linkCount = _linkSource.countAll(); + + CastleGates.getPluginLogger().log(Level.INFO, "Link count: " + linkCount); + + List linkData = _linkSource.selectAll(); + List invalidLinks = new ArrayList<>(); + int drawnLinkCount = 0, brokenLinkCount = 0; + + for(LinkInfo info : linkData) { + Gearblock gearblock1 = info.StartGearblockId != null ? gearblocksById.get(info.StartGearblockId) : null; + Gearblock gearblock2 = info.EndGearblockId != null ? gearblocksById.get(info.EndGearblockId) : null; + List blocks = deserializeBlocks(info.Blocks); + GearblockLink link = new GearblockLink(gearblock1, gearblock2); + + link.setId(info.LinkId); + link.setBlocks(blocks); + + if(gearblock1 != null) { + gearblock1.setLink(link); + } + + if(gearblock2 != null) { + gearblock2.setLink(link); + } + + linksById.put(link.getId(), link); + + if(gearblock1 == null && gearblock2 == null) { + invalidLinks.add(info); + } + + if(link.isDrawn()) { + drawnLinkCount++; + } + + if(link.isBroken()) { + brokenLinkCount++; + } + } + + CastleGates.getPluginLogger().log(Level.INFO, "Loaded links: " + linkData.size()); + + if(drawnLinkCount > 0) { + CastleGates.getPluginLogger().log(Level.INFO, "Links in DRAWN state: " + drawnLinkCount); + } + + if(brokenLinkCount > 0) { + CastleGates.getPluginLogger().log(Level.INFO, "Links in BROKEN state: " + brokenLinkCount); + } + + if(invalidLinks.size() > 0) { + CastleGates.getPluginLogger().log(Level.WARNING, "Invalid links (i.e. BUG): " + invalidLinks.size()); + + String filePath = new InvalidLinkLogger().write(invalidLinks); + + CastleGates.getPluginLogger().log(Level.INFO, "List of invalid links saved to: " + filePath); + } + } + + private void loadReinforcements(Map linksById) throws SQLException { + List reinforcementData = _reinforcementSource.selectAll(); + GearblockLink link = null; + + for(ReinforcementInfo info : reinforcementData) { + if(link == null || link.getId() != info.LinkId) { + link = linksById.get(info.LinkId); + } + + BlockState blockState = link.getBlocks().get(info.BlockSequence); + blockState.setReinforcement(info); + } + } + + public void startThread() { + _kill.set(false); + + setName("CastleGates DataWorker Thread"); + setPriority(Thread.MIN_PRIORITY); + start(); + + CastleGates.getPluginLogger().log(Level.INFO, "DataWorker thread started"); + } + + public void terminateThread() { + _kill.set(true); + + while (_run.get()) { + try { + Thread.sleep(100); + } catch (Exception e) { + e.printStackTrace(); + } + } + + saveData(); + + CastleGates.getPluginLogger().log(Level.INFO, "DataWorker thread stopped"); + } + + public void run() { + _run.set(true); + + try { + while (!isInterrupted() && !_kill.get()) { + try { + long timeWait = _lastExecute + CastleGates.getConfigManager().getDataWorkerRate() - System.currentTimeMillis(); + _lastExecute = System.currentTimeMillis(); + if (timeWait > 0) { + Thread.sleep(timeWait); + } + + saveData(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } finally { + _run.set(false); + } + } + + private void saveData() { + try { + synchronized (_changedGearblocks) { + _localChangedGearblocks.addAll(_changedGearblocks.values()); + _changedGearblocks.clear(); + } + + synchronized (_changedLinks) { + _localChangedLinks.addAll(_changedLinks.values()); + _changedLinks.clear(); + } + + if (_localChangedGearblocks.size() > 0 || _localChangedLinks.size() > 0) { + if (_db.checkConnection()) { + try { + updateGears(); + updateLinks(); + } finally { + _localChangedGearblocks.clear(); + _localChangedLinks.clear(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void updateGears() throws SQLException { + for(GearblockForUpdate gearForUpdate : _localChangedGearblocks) { + if(gearForUpdate.original.isRemoved()) { + if(gearForUpdate.original.getId() != 0) { + _gearblockSource.delete(gearForUpdate.original.getId()); + } + } + else if(gearForUpdate.original.getId() != 0) { + _gearblockSource.update(gearForUpdate.info); + } + else { + _gearblockSource.insert(gearForUpdate.info); + gearForUpdate.original.setId(gearForUpdate.info.GearblockId); + } + } + } + + private void updateLinks() throws SQLException { + for(LinkForUpdate linkForUpdate : _localChangedLinks) { + if(linkForUpdate.original.isRemoved()) { + if(linkForUpdate.original.getId() != 0) { + _reinforcementSource.deleteByLinkId(linkForUpdate.original.getId()); + _linkSource.delete(linkForUpdate.original.getId()); + } + } else { + LinkInfo info = new LinkInfo(); + info.LinkId = linkForUpdate.original.getId(); + info.StartGearblockId = linkForUpdate.gearblock1 != null ? linkForUpdate.gearblock1.getId(): null; + info.EndGearblockId = linkForUpdate.gearblock2 != null ? linkForUpdate.gearblock2.getId(): null; + info.Blocks = linkForUpdate.blocks; + + if(info.LinkId != 0) { + _linkSource.update(info); + + if(info.Blocks == null) { + _reinforcementSource.deleteByLinkId(info.LinkId); + } + } else { + _linkSource.insert(info); + linkForUpdate.original.setId(info.LinkId); + } + + if(linkForUpdate.reinforcements != null) { + for(ReinforcementInfo reinforcement : linkForUpdate.reinforcements) { + if(reinforcement.LinkId != 0) continue; + + reinforcement.LinkId = info.LinkId; + + _reinforcementSource.insert(reinforcement); + } + } + } + } + } + + public void addChangedGearblock(Gearblock gearblock) { + GearblockInfo info; + + if(gearblock.isRemoved()) { + info = null; + } else { + info = new GearblockInfo(); + + BlockCoord location = gearblock.getCoord(); + info.GearblockId = gearblock.getId(); + info.WorldId = location.getWorldUID().toString(); + info.X = location.getX(); + info.Y = location.getY(); + info.Z = location.getZ(); + info.Timer = gearblock.getTimer(); + + if(gearblock.getTimerOperation() != null) { + switch(gearblock.getTimerOperation()) { + case DRAW -> info.TimerOperation = DRAW_CODE; + case UNDRAW -> info.TimerOperation = UNDRAW_CODE; + case REVERT -> info.TimerOperation = REVERT_CODE; + } + + if(gearblock.getTimerMode() == TimerMode.DOOR) { + info.TimerOperation |= MODE_MASK; + } + } + } + + GearblockForUpdate gearForUpdate = new GearblockForUpdate(); + gearForUpdate.original = gearblock; + gearForUpdate.info = info; + + synchronized(_changedGearblocks) { + _changedGearblocks.put(gearblock, gearForUpdate); + } + } + + public void addChangedLink(GearblockLink link) { + LinkForUpdate linkForUpdate = new LinkForUpdate(); + linkForUpdate.original = link; + + if(!link.isRemoved()) { + linkForUpdate.gearblock1 = link.getGearblock1(); + linkForUpdate.gearblock2 = link.getGearblock2(); + linkForUpdate.blocks = serializeBlocks(link); + + if(link.getBlocks() != null) { + linkForUpdate.reinforcements = new ArrayList<>(); + + for(int i = 0; i < link.getBlocks().size(); i++) { + ReinforcementInfo reinforcement = link.getBlocks().get(i).getReinforcement(); + + if(reinforcement != null && reinforcement.LinkId == 0) { + reinforcement.BlockSequence = i; + linkForUpdate.reinforcements.add(reinforcement); + } + } + } + } + + synchronized(_changedLinks) { + _changedLinks.put(link, linkForUpdate); + } + } + + private static String serializeBlocks(GearblockLink link) { + if(link.getBlocks() == null) + return null; + + int length = 0; + for(BlockState block : link.getBlocks()) + length += block.getBlockDataLen(); + + StringBuilder blockSerialized = new StringBuilder(length); + for(BlockState block : link.getBlocks()) + block.serialize(blockSerialized); + + return blockSerialized.toString(); + } + + public static List deserializeBlocks(String blockDataList) { + if(blockDataList == null || blockDataList.length() == 0) + return null; + + List blocks = new ArrayList<>(); + int len = blockDataList.length(); + int startIndex = 0; + int index = 0; + + while (index < len) { + if (blockDataList.charAt(index) == BlockState.Separator) { + String blockData = blockDataList.substring(startIndex, index); + BlockState block = BlockState.deserialize(blockData); + + blocks.add(block); + + startIndex = index + 1; + } + + index++; + } + + return blocks; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/Helper.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/Helper.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/Helper.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/Helper.java index 431dabd1c..e24359cf0 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/Helper.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/Helper.java @@ -1,197 +1,197 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; - -import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.util.Vector; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.types.TimerOperation; - -public class Helper { - public static int getItemDamage(ItemStack item) { - ItemMeta meta = item.getItemMeta(); - return meta == null ? 0 : ((Damageable) meta).getDamage(); - } - - public static boolean isEmptyBlock(Block block) { - Material material = block.getType(); - - return material == Material.AIR - || material == Material.WATER - || material == Material.LAVA - ; - } - - public static TimerOperation parseTimerOperation(String name) { - if(name == null) { - return null; - } - - return switch(name.toLowerCase()) { - case "draw" -> TimerOperation.DRAW; - case "undraw" -> TimerOperation.UNDRAW; - case "revert" -> TimerOperation.REVERT; - default -> null; - }; - } - - public static String getLore(ItemStack item) { - ItemMeta meta = item.getItemMeta(); - - if(meta == null || !meta.hasLore()) - return null; - - StringBuilder lore = new StringBuilder(); - - for (Component line: meta.lore()) { - if(lore.length() > 0) { - lore.append("\n"); - } - - lore.append(line); - } - - return lore.toString(); - } - - public static void setLore(ItemStack item, String lore) { - if (lore == null || lore.length() == 0) - return; - - String[] textList = lore.split("\n"); - List loreList = new ArrayList<>(); - - for (String loreText : textList) - loreList.add(Component.text(loreText)); - - ItemMeta meta = item.getItemMeta(); - meta.lore(loreList); - item.setItemMeta(meta); - } - - public static List getNearbyPlayers(Location location) { - double distance = CastleGates.getCitadelManager().getMaxRedstoneDistance(); - double minX = location.getX() - distance; - double minZ = location.getZ() - distance; - double maxX = location.getX() + distance; - double maxZ = location.getZ() + distance; - - List players = new ArrayList<>(); - - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.isDead()) continue; - - Location playerLocation = player.getLocation(); - - if(!playerLocation.getWorld().equals(location.getWorld())) continue; - - double playerX = playerLocation.getX(); - double playerZ = playerLocation.getZ(); - - if (playerX < minX || playerX > maxX - || playerZ < minZ || playerZ > maxZ) - { - continue; - } - - double playerDistance = playerLocation.distance(location); - - if (playerDistance <= distance) { - players.add(player); - } - } - - return players; - } - - public static List getConsumeSlots(Player player, ItemStack consumeItem) { - if(consumeItem == null) return null; - - List list = new ArrayList<>(); - PlayerInventory inventory = player.getInventory(); - int inventorySize = inventory.getSize(); - int requiredAmount = consumeItem.getAmount(); - - try { - for(int i = 0; i < inventorySize && requiredAmount > 0; i++) { - ItemStack item = inventory.getItem(i); - - if(item == null || !consumeItem.isSimilar(item)) { - continue; - } - - list.add(i); - - requiredAmount -= item.getAmount(); - } - } catch (Exception ex) { - } - - return requiredAmount > 0 ? null :list; - } - - public static void consumeItem(Player player, ItemStack consumeItem, List list) { - if(list == null) - return; - - PlayerInventory inventory = player.getInventory(); - int requiredAmount = consumeItem.getAmount(); - - for(int i = 0; i < list.size() && requiredAmount > 0; i++) { - int slot = list.get(i); - ItemStack item = inventory.getItem(slot); - int itemAmount = item.getAmount(); - int amountToRemove = Math.min(itemAmount, requiredAmount); - - if(itemAmount > amountToRemove) { - item.setAmount(itemAmount - amountToRemove); - } else { - inventory.clear(slot); - } - - requiredAmount -= amountToRemove; - } - } - - public static void putItemToInventoryOrDrop(Player player, Location dropLocation, ItemStack dropItem) { - if (player != null){ - Inventory inv = player.getInventory(); - - for(ItemStack leftover : inv.addItem(dropItem).values()) { - dropItemAtLocation(dropLocation, leftover); - } - } - else { - dropItemAtLocation(dropLocation, dropItem); - } - } - - private static void dropItemAtLocation(final Location dropLocation, final ItemStack dropItem) { - Bukkit.getScheduler().scheduleSyncDelayedTask(CastleGates.getInstance(), () -> { - try { - Location newDropLocation = dropLocation.add(0.5, 0.5, 0.5); - dropLocation.getWorld().dropItem(newDropLocation, dropItem).setVelocity(new Vector(0, 0.05, 0)); - } catch (Exception e) { - CastleGates.getPluginLogger().log(Level.WARNING, "dropItemAtLocation called but errored: ", e); - } - }, 1); - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; + +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.util.Vector; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.types.TimerOperation; + +public class Helper { + public static int getItemDamage(ItemStack item) { + ItemMeta meta = item.getItemMeta(); + return meta == null ? 0 : ((Damageable) meta).getDamage(); + } + + public static boolean isEmptyBlock(Block block) { + Material material = block.getType(); + + return material == Material.AIR + || material == Material.WATER + || material == Material.LAVA + ; + } + + public static TimerOperation parseTimerOperation(String name) { + if(name == null) { + return null; + } + + return switch(name.toLowerCase()) { + case "draw" -> TimerOperation.DRAW; + case "undraw" -> TimerOperation.UNDRAW; + case "revert" -> TimerOperation.REVERT; + default -> null; + }; + } + + public static String getLore(ItemStack item) { + ItemMeta meta = item.getItemMeta(); + + if(meta == null || !meta.hasLore()) + return null; + + StringBuilder lore = new StringBuilder(); + + for (Component line: meta.lore()) { + if(lore.length() > 0) { + lore.append("\n"); + } + + lore.append(line); + } + + return lore.toString(); + } + + public static void setLore(ItemStack item, String lore) { + if (lore == null || lore.length() == 0) + return; + + String[] textList = lore.split("\n"); + List loreList = new ArrayList<>(); + + for (String loreText : textList) + loreList.add(Component.text(loreText)); + + ItemMeta meta = item.getItemMeta(); + meta.lore(loreList); + item.setItemMeta(meta); + } + + public static List getNearbyPlayers(Location location) { + double distance = CastleGates.getCitadelManager().getMaxRedstoneDistance(); + double minX = location.getX() - distance; + double minZ = location.getZ() - distance; + double maxX = location.getX() + distance; + double maxZ = location.getZ() + distance; + + List players = new ArrayList<>(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.isDead()) continue; + + Location playerLocation = player.getLocation(); + + if(!playerLocation.getWorld().equals(location.getWorld())) continue; + + double playerX = playerLocation.getX(); + double playerZ = playerLocation.getZ(); + + if (playerX < minX || playerX > maxX + || playerZ < minZ || playerZ > maxZ) + { + continue; + } + + double playerDistance = playerLocation.distance(location); + + if (playerDistance <= distance) { + players.add(player); + } + } + + return players; + } + + public static List getConsumeSlots(Player player, ItemStack consumeItem) { + if(consumeItem == null) return null; + + List list = new ArrayList<>(); + PlayerInventory inventory = player.getInventory(); + int inventorySize = inventory.getSize(); + int requiredAmount = consumeItem.getAmount(); + + try { + for(int i = 0; i < inventorySize && requiredAmount > 0; i++) { + ItemStack item = inventory.getItem(i); + + if(item == null || !consumeItem.isSimilar(item)) { + continue; + } + + list.add(i); + + requiredAmount -= item.getAmount(); + } + } catch (Exception ex) { + } + + return requiredAmount > 0 ? null :list; + } + + public static void consumeItem(Player player, ItemStack consumeItem, List list) { + if(list == null) + return; + + PlayerInventory inventory = player.getInventory(); + int requiredAmount = consumeItem.getAmount(); + + for(int i = 0; i < list.size() && requiredAmount > 0; i++) { + int slot = list.get(i); + ItemStack item = inventory.getItem(slot); + int itemAmount = item.getAmount(); + int amountToRemove = Math.min(itemAmount, requiredAmount); + + if(itemAmount > amountToRemove) { + item.setAmount(itemAmount - amountToRemove); + } else { + inventory.clear(slot); + } + + requiredAmount -= amountToRemove; + } + } + + public static void putItemToInventoryOrDrop(Player player, Location dropLocation, ItemStack dropItem) { + if (player != null){ + Inventory inv = player.getInventory(); + + for(ItemStack leftover : inv.addItem(dropItem).values()) { + dropItemAtLocation(dropLocation, leftover); + } + } + else { + dropItemAtLocation(dropLocation, dropItem); + } + } + + private static void dropItemAtLocation(final Location dropLocation, final ItemStack dropItem) { + Bukkit.getScheduler().scheduleSyncDelayedTask(CastleGates.getInstance(), () -> { + try { + Location newDropLocation = dropLocation.add(0.5, 0.5, 0.5); + dropLocation.getWorld().dropItem(newDropLocation, dropItem).setVelocity(new Vector(0, 0.05, 0)); + } catch (Exception e) { + CastleGates.getPluginLogger().log(Level.WARNING, "dropItemAtLocation called but errored: ", e); + } + }, 1); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/InvalidLinkLogger.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/InvalidLinkLogger.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/InvalidLinkLogger.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/InvalidLinkLogger.java index a1e77f5e0..901c501fb 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/InvalidLinkLogger.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/InvalidLinkLogger.java @@ -1,73 +1,73 @@ -/** - * Created by Aleksey on 28.06.2017. - */ - -package com.aleksey.castlegates.utils; - -import com.aleksey.castlegates.database.LinkInfo; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.PrintWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - -public class InvalidLinkLogger { - private static final DateFormat fileDateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss"); - private static final String folderName = "castlegates_logs"; - - private String _filePath; - - public String write(List links) { - try { - PrintWriter writer = getWriter(); - - try { - for(LinkInfo link : links) { - writeLink(link, writer); - } - } catch (Exception e) { - e.printStackTrace(); - } - finally { - writer.flush(); - writer.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return _filePath; - } - - private static void writeLink(LinkInfo link, PrintWriter writer) { - writer.print("link_id="); - writer.print(link.LinkId); - - writer.print(",gearblock1_id="); - writer.print(link.StartGearblockId != null ? link.StartGearblockId.toString() : "none"); - - writer.print(",gearblock2_id="); - writer.print(link.EndGearblockId != null ? link.EndGearblockId.toString() : "none"); - - writer.println(); - } - - private PrintWriter getWriter() throws FileNotFoundException { - File folder = new File(folderName); - - if(!folder.exists()) - folder.mkdirs(); - - _filePath = folder + "/InvalidLinks_" + fileDateFormat.format(new Date()) + ".txt"; - - File file = new File(_filePath); - - return file.exists() - ? new PrintWriter(new FileOutputStream(file, true)) - : new PrintWriter(_filePath); - } -} +/** + * Created by Aleksey on 28.06.2017. + */ + +package com.aleksey.castlegates.utils; + +import com.aleksey.castlegates.database.LinkInfo; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +public class InvalidLinkLogger { + private static final DateFormat fileDateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss"); + private static final String folderName = "castlegates_logs"; + + private String _filePath; + + public String write(List links) { + try { + PrintWriter writer = getWriter(); + + try { + for(LinkInfo link : links) { + writeLink(link, writer); + } + } catch (Exception e) { + e.printStackTrace(); + } + finally { + writer.flush(); + writer.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return _filePath; + } + + private static void writeLink(LinkInfo link, PrintWriter writer) { + writer.print("link_id="); + writer.print(link.LinkId); + + writer.print(",gearblock1_id="); + writer.print(link.StartGearblockId != null ? link.StartGearblockId.toString() : "none"); + + writer.print(",gearblock2_id="); + writer.print(link.EndGearblockId != null ? link.EndGearblockId.toString() : "none"); + + writer.println(); + } + + private PrintWriter getWriter() throws FileNotFoundException { + File folder = new File(folderName); + + if(!folder.exists()) + folder.mkdirs(); + + _filePath = folder + "/InvalidLinks_" + fileDateFormat.format(new Date()) + ".txt"; + + File file = new File(_filePath); + + return file.exists() + ? new PrintWriter(new FileOutputStream(file, true)) + : new PrintWriter(_filePath); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/ParticleHelper.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/ParticleHelper.java similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/ParticleHelper.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/ParticleHelper.java index ce1270fb5..1aa7662ac 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/ParticleHelper.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/ParticleHelper.java @@ -1,37 +1,37 @@ -package com.aleksey.castlegates.utils; - -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.types.BlockCoord; -import com.aleksey.castlegates.types.Gearblock; - -public class ParticleHelper { - public enum Type { Info, Warning } - - public static void spawn(Player player, Gearblock gearblock, Type type) { - BlockCoord coord = gearblock.getCoord(); - Location location = new Location(player.getWorld(), 0.5 + coord.getX(), 0.5 + coord.getY(), 0.5 + coord.getZ()); - - spawn(location, type); - } - - public static void spawn(Block block, Type type) { - Location location = new Location(block.getWorld(), 0.5 + block.getX(), 0.5 + block.getY(), 0.5 + block.getZ()); - - spawn(location, type); - } - - public static void spawn(Location location, Type type) { - final Particle particle = type == Type.Info ? Particle.ENCHANTMENT_TABLE: Particle.EXPLOSION_NORMAL; - final float offsetX = 0; - final float offsetY = 0; - final float offsetZ = 0; - final float speed = 0.5f; - final int particleCount = 80; - - location.getWorld().spawnParticle(particle, location, particleCount, offsetX, offsetY, offsetZ, speed, null); - } -} +package com.aleksey.castlegates.utils; + +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.types.BlockCoord; +import com.aleksey.castlegates.types.Gearblock; + +public class ParticleHelper { + public enum Type { Info, Warning } + + public static void spawn(Player player, Gearblock gearblock, Type type) { + BlockCoord coord = gearblock.getCoord(); + Location location = new Location(player.getWorld(), 0.5 + coord.getX(), 0.5 + coord.getY(), 0.5 + coord.getZ()); + + spawn(location, type); + } + + public static void spawn(Block block, Type type) { + Location location = new Location(block.getWorld(), 0.5 + block.getX(), 0.5 + block.getY(), 0.5 + block.getZ()); + + spawn(location, type); + } + + public static void spawn(Location location, Type type) { + final Particle particle = type == Type.Info ? Particle.ENCHANTMENT_TABLE: Particle.EXPLOSION_NORMAL; + final float offsetX = 0; + final float offsetY = 0; + final float offsetZ = 0; + final float speed = 0.5f; + final int particleCount = 80; + + location.getWorld().spawnParticle(particle, location, particleCount, offsetX, offsetY, offsetZ, speed, null); + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/PowerResultHelper.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/PowerResultHelper.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/PowerResultHelper.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/PowerResultHelper.java index c4d27a3cd..9a37c7136 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/PowerResultHelper.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/PowerResultHelper.java @@ -1,89 +1,89 @@ -package com.aleksey.castlegates.utils; - -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -import com.aleksey.castlegates.types.PowerResult; - -public class PowerResultHelper { - public static void showStatus(Location location, List players, PowerResult result) { - String message = switch(result.status) { - case Blocked -> getBlockedMessage(result); - case Broken -> getBrokenMessage(result); - case CannotDrawGear -> getCannotDrawGearMessage(result); - case NotInCitadelGroup -> ChatColor.RED + "Citadel has prevented that operation."; - case DifferentCitadelGroup -> ChatColor.RED + "All blocks must be reinforced by the same group."; - case BastionBlocked -> ChatColor.RED + "A bastion has prevented the bridge/gate from undrawing."; - case Locked -> ChatColor.RED + "The gearblock is locked."; - default -> null; - }; - - if(message != null) { - for(Player player : players) { - player.sendMessage(message); - } - } - else if(result.status == PowerResult.Status.Drawn || result.status == PowerResult.Status.Undrawn){ - playSound(location, result.status); - } - - if(result.block != null) { - ParticleHelper.spawn(result.block, ParticleHelper.Type.Warning); - } - } - - public static void playSound(Location location, PowerResult.Status status) { - Sound sound = status == PowerResult.Status.Drawn - ? Sound.BLOCK_PISTON_CONTRACT - : Sound.BLOCK_PISTON_EXTEND; - - location.getWorld().playSound(location, sound, 0.7f, 1); - } - - private static String getBlockedMessage(PowerResult result) { - Location location = result.block.getLocation(); - - return ChatColor.RED + - "The bridge/gate undraw path is blocked at [" + location.getBlockX() + - " " + location.getBlockY() + - " " + location.getBlockZ() + - "]." - ; - } - - private static String getBrokenMessage(PowerResult result) { - Location location = result.block.getLocation(); - - if(result.block.getType() == Material.AIR) { - return ChatColor.RED + - "The bridge/gate is broken at [" + location.getBlockX() + - " " + location.getBlockY() + - " " + location.getBlockZ() + - "]." - ; - } - - return ChatColor.RED + - "The " + result.block.getType() + " block at [" + location.getBlockX() + - " " + location.getBlockY() + - " " + location.getBlockZ() + - "] is not allowed to be used as a part of bridges/gates." - ; - } - - private static String getCannotDrawGearMessage(PowerResult result) { - Location location = result.block.getLocation(); - - return ChatColor.RED + - "The gearblock at [" + location.getBlockX() + - " " + location.getBlockY() + - " " + location.getBlockZ() + - "] is not allowed to be used as a part of bridges/gates." - ; - } -} +package com.aleksey.castlegates.utils; + +import java.util.List; + +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import com.aleksey.castlegates.types.PowerResult; + +public class PowerResultHelper { + public static void showStatus(Location location, List players, PowerResult result) { + String message = switch(result.status) { + case Blocked -> getBlockedMessage(result); + case Broken -> getBrokenMessage(result); + case CannotDrawGear -> getCannotDrawGearMessage(result); + case NotInCitadelGroup -> ChatColor.RED + "Citadel has prevented that operation."; + case DifferentCitadelGroup -> ChatColor.RED + "All blocks must be reinforced by the same group."; + case BastionBlocked -> ChatColor.RED + "A bastion has prevented the bridge/gate from undrawing."; + case Locked -> ChatColor.RED + "The gearblock is locked."; + default -> null; + }; + + if(message != null) { + for(Player player : players) { + player.sendMessage(message); + } + } + else if(result.status == PowerResult.Status.Drawn || result.status == PowerResult.Status.Undrawn){ + playSound(location, result.status); + } + + if(result.block != null) { + ParticleHelper.spawn(result.block, ParticleHelper.Type.Warning); + } + } + + public static void playSound(Location location, PowerResult.Status status) { + Sound sound = status == PowerResult.Status.Drawn + ? Sound.BLOCK_PISTON_CONTRACT + : Sound.BLOCK_PISTON_EXTEND; + + location.getWorld().playSound(location, sound, 0.7f, 1); + } + + private static String getBlockedMessage(PowerResult result) { + Location location = result.block.getLocation(); + + return ChatColor.RED + + "The bridge/gate undraw path is blocked at [" + location.getBlockX() + + " " + location.getBlockY() + + " " + location.getBlockZ() + + "]." + ; + } + + private static String getBrokenMessage(PowerResult result) { + Location location = result.block.getLocation(); + + if(result.block.getType() == Material.AIR) { + return ChatColor.RED + + "The bridge/gate is broken at [" + location.getBlockX() + + " " + location.getBlockY() + + " " + location.getBlockZ() + + "]." + ; + } + + return ChatColor.RED + + "The " + result.block.getType() + " block at [" + location.getBlockX() + + " " + location.getBlockY() + + " " + location.getBlockZ() + + "] is not allowed to be used as a part of bridges/gates." + ; + } + + private static String getCannotDrawGearMessage(PowerResult result) { + Location location = result.block.getLocation(); + + return ChatColor.RED + + "The gearblock at [" + location.getBlockX() + + " " + location.getBlockY() + + " " + location.getBlockZ() + + "] is not allowed to be used as a part of bridges/gates." + ; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/ResourceHelper.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/ResourceHelper.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/ResourceHelper.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/ResourceHelper.java index e40787d78..597b37a4d 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/ResourceHelper.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/ResourceHelper.java @@ -1,51 +1,51 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; - -import com.aleksey.castlegates.CastleGates; - -public class ResourceHelper { - public static ArrayList readScriptList(String resourcePath) { - InputStream stream = CastleGates.class.getResourceAsStream(resourcePath); - - if(stream == null) - return null; - - StringBuilder script = new StringBuilder(); - ArrayList list = new ArrayList<>(); - - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - String line; - - while ((line = reader.readLine()) != null) { - if(line.endsWith(";")) { - script.append(line); - list.add(script.toString()); - script.delete(0, script.length()); - } - else { - script.append(line); - script.append("\n"); - } - } - - if(script.length() > 0) { - list.add(script.toString()); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return list; - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; + +import com.aleksey.castlegates.CastleGates; + +public class ResourceHelper { + public static ArrayList readScriptList(String resourcePath) { + InputStream stream = CastleGates.class.getResourceAsStream(resourcePath); + + if(stream == null) + return null; + + StringBuilder script = new StringBuilder(); + ArrayList list = new ArrayList<>(); + + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + String line; + + while ((line = reader.readLine()) != null) { + if(line.endsWith(";")) { + script.append(line); + list.add(script.toString()); + script.delete(0, script.length()); + } + else { + script.append(line); + script.append("\n"); + } + } + + if(script.length() > 0) { + list.add(script.toString()); + } + } catch (IOException e) { + e.printStackTrace(); + } + + return list; + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/TimerWorker.java b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/TimerWorker.java similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/TimerWorker.java rename to plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/TimerWorker.java index 022316c19..a6427e3c6 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/java/com/aleksey/castlegates/utils/TimerWorker.java +++ b/plugins/castlegates-paper/src/main/java/com/aleksey/castlegates/utils/TimerWorker.java @@ -1,133 +1,133 @@ -/** - * @author Aleksey Terzi - * - */ - -package com.aleksey.castlegates.utils; - -import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; - -import org.bukkit.Location; - -import com.aleksey.castlegates.CastleGates; -import com.aleksey.castlegates.engine.bridge.BridgeManager; -import com.aleksey.castlegates.types.BlockCoord; -import com.aleksey.castlegates.types.Gearblock; -import com.aleksey.castlegates.types.TimerBatch; - -public class TimerWorker extends Thread implements Runnable { - private BridgeManager _bridgeManager; - private List _batches; - - private long _lastExecute = System.currentTimeMillis(); - private AtomicBoolean _kill = new AtomicBoolean(false); - private AtomicBoolean _run = new AtomicBoolean(false); - - public TimerWorker(BridgeManager bridgeManager) { - _bridgeManager = bridgeManager; - _batches = new ArrayList(); - } - - public void startThread() { - _kill.set(false); - - setName("CastleGates TimerWorker Thread"); - setPriority(Thread.MIN_PRIORITY); - start(); - - CastleGates.getPluginLogger().log(Level.INFO, "TimerWorker thread started"); - } - - public void terminateThread() { - _kill.set(true); - - while (_run.get()) { - try { - Thread.sleep(100); - } catch (Exception e) { - e.printStackTrace(); - } - } - - try { - for (TimerBatch batch : _batches) { - _bridgeManager.processTimerBatch(batch); - } - } catch (Exception e) { - e.printStackTrace(); - } - - _batches.clear(); - - CastleGates.getPluginLogger().log(Level.INFO, "TimerWorker thread stopped"); - } - - public void run() { - _run.set(true); - - try { - Map localBatchMap = new HashMap(); - List localBatches = new ArrayList(); - - while (!isInterrupted() && !_kill.get()) { - try { - long timeWait = _lastExecute + CastleGates.getConfigManager().getTimerWorkerRate() - System.currentTimeMillis(); - _lastExecute = System.currentTimeMillis(); - if (timeWait > 0) { - Thread.sleep(timeWait); - } - - synchronized (_batches) { - if (_batches.size() > 0) { - for (TimerBatch batch : _batches) { - localBatchMap.put(batch.getGearblock(), batch); - } - - _batches.clear(); - } - } - - long currentTimeMillis = System.currentTimeMillis(); - - localBatches.addAll(localBatchMap.values()); - - for (TimerBatch batch : localBatches) { - if (batch.getRunTimeMillis() <= currentTimeMillis) { - runBatch(batch); - localBatchMap.remove(batch.getGearblock()); - } - } - - localBatches.clear(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } finally { - _run.set(false); - } - } - - private void runBatch(final TimerBatch batch) { - final BridgeManager bridgeManager = _bridgeManager; - - CastleGates.runTask(new Runnable() { - public void run() { - if(!batch.isInvalid() && bridgeManager.processTimerBatch(batch)) { - BlockCoord blockCoord = batch.getGearblock().getCoord(); - Location location = new Location(batch.getWorld(), blockCoord.getX(), blockCoord.getY(), blockCoord.getZ()); - - PowerResultHelper.playSound(location, batch.getProcessStatus()); - } - } - }); - } - - public void addBatch(TimerBatch batch) { - synchronized(_batches) { - _batches.add(batch); - } - } -} +/** + * @author Aleksey Terzi + * + */ + +package com.aleksey.castlegates.utils; + +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; + +import org.bukkit.Location; + +import com.aleksey.castlegates.CastleGates; +import com.aleksey.castlegates.engine.bridge.BridgeManager; +import com.aleksey.castlegates.types.BlockCoord; +import com.aleksey.castlegates.types.Gearblock; +import com.aleksey.castlegates.types.TimerBatch; + +public class TimerWorker extends Thread implements Runnable { + private BridgeManager _bridgeManager; + private List _batches; + + private long _lastExecute = System.currentTimeMillis(); + private AtomicBoolean _kill = new AtomicBoolean(false); + private AtomicBoolean _run = new AtomicBoolean(false); + + public TimerWorker(BridgeManager bridgeManager) { + _bridgeManager = bridgeManager; + _batches = new ArrayList(); + } + + public void startThread() { + _kill.set(false); + + setName("CastleGates TimerWorker Thread"); + setPriority(Thread.MIN_PRIORITY); + start(); + + CastleGates.getPluginLogger().log(Level.INFO, "TimerWorker thread started"); + } + + public void terminateThread() { + _kill.set(true); + + while (_run.get()) { + try { + Thread.sleep(100); + } catch (Exception e) { + e.printStackTrace(); + } + } + + try { + for (TimerBatch batch : _batches) { + _bridgeManager.processTimerBatch(batch); + } + } catch (Exception e) { + e.printStackTrace(); + } + + _batches.clear(); + + CastleGates.getPluginLogger().log(Level.INFO, "TimerWorker thread stopped"); + } + + public void run() { + _run.set(true); + + try { + Map localBatchMap = new HashMap(); + List localBatches = new ArrayList(); + + while (!isInterrupted() && !_kill.get()) { + try { + long timeWait = _lastExecute + CastleGates.getConfigManager().getTimerWorkerRate() - System.currentTimeMillis(); + _lastExecute = System.currentTimeMillis(); + if (timeWait > 0) { + Thread.sleep(timeWait); + } + + synchronized (_batches) { + if (_batches.size() > 0) { + for (TimerBatch batch : _batches) { + localBatchMap.put(batch.getGearblock(), batch); + } + + _batches.clear(); + } + } + + long currentTimeMillis = System.currentTimeMillis(); + + localBatches.addAll(localBatchMap.values()); + + for (TimerBatch batch : localBatches) { + if (batch.getRunTimeMillis() <= currentTimeMillis) { + runBatch(batch); + localBatchMap.remove(batch.getGearblock()); + } + } + + localBatches.clear(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } finally { + _run.set(false); + } + } + + private void runBatch(final TimerBatch batch) { + final BridgeManager bridgeManager = _bridgeManager; + + CastleGates.runTask(new Runnable() { + public void run() { + if(!batch.isInvalid() && bridgeManager.processTimerBatch(batch)) { + BlockCoord blockCoord = batch.getGearblock().getCoord(); + Location location = new Location(batch.getWorld(), blockCoord.getX(), blockCoord.getY(), blockCoord.getZ()); + + PowerResultHelper.playSound(location, batch.getProcessStatus()); + } + } + }); + } + + public void addBatch(TimerBatch batch) { + synchronized(_batches) { + _batches.add(batch); + } + } +} diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/resources/create_db.txt b/plugins/castlegates-paper/src/main/resources/create_db.txt similarity index 96% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/resources/create_db.txt rename to plugins/castlegates-paper/src/main/resources/create_db.txt index 56e24317f..788753ad8 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/resources/create_db.txt +++ b/plugins/castlegates-paper/src/main/resources/create_db.txt @@ -1,32 +1,32 @@ -CREATE TABLE IF NOT EXISTS cg_gearblock ( - GearblockId INT NOT NULL AUTO_INCREMENT - ,WorldId VARCHAR(36) NOT NULL - ,X INT NOT NULL - ,Y INT NOT NULL - ,Z INT NOT NULL - ,Timer INT - ,TimerOperation INT - - ,CONSTRAINT pk_cg_gearblock PRIMARY KEY (GearblockId) -); - -CREATE TABLE IF NOT EXISTS cg_link ( - LinkId INT NOT NULL AUTO_INCREMENT - ,StartGearblockId INT - ,EndGearblockId INT - ,Blocks VARCHAR(1024) - - ,CONSTRAINT pk_cg_link PRIMARY KEY (LinkId) -); - -CREATE TABLE IF NOT EXISTS cg_reinforcement ( - LinkId INT NOT NULL - ,BlockSequence INT NOT NULL - ,CreationTime BIGINT NOT NULL - ,TypeId SMALLINT NOT NULL - ,Health FLOAT NOT NULL - ,GroupId INT NOT NULL - ,Insecure BOOL NOT NULL - - ,CONSTRAINT pk_cg_reinforcement PRIMARY KEY (LinkId, BlockSequence) +CREATE TABLE IF NOT EXISTS cg_gearblock ( + GearblockId INT NOT NULL AUTO_INCREMENT + ,WorldId VARCHAR(36) NOT NULL + ,X INT NOT NULL + ,Y INT NOT NULL + ,Z INT NOT NULL + ,Timer INT + ,TimerOperation INT + + ,CONSTRAINT pk_cg_gearblock PRIMARY KEY (GearblockId) +); + +CREATE TABLE IF NOT EXISTS cg_link ( + LinkId INT NOT NULL AUTO_INCREMENT + ,StartGearblockId INT + ,EndGearblockId INT + ,Blocks VARCHAR(1024) + + ,CONSTRAINT pk_cg_link PRIMARY KEY (LinkId) +); + +CREATE TABLE IF NOT EXISTS cg_reinforcement ( + LinkId INT NOT NULL + ,BlockSequence INT NOT NULL + ,CreationTime BIGINT NOT NULL + ,TypeId SMALLINT NOT NULL + ,Health FLOAT NOT NULL + ,GroupId INT NOT NULL + ,Insecure BOOL NOT NULL + + ,CONSTRAINT pk_cg_reinforcement PRIMARY KEY (LinkId, BlockSequence) ) \ No newline at end of file diff --git a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/resources/plugin.yml b/plugins/castlegates-paper/src/main/resources/plugin.yml similarity index 97% rename from plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/resources/plugin.yml rename to plugins/castlegates-paper/src/main/resources/plugin.yml index ed5c1c05d..a645bd745 100644 --- a/plugins/castlegates-paper/plugins/castlegates-paper/paper/src/main/resources/plugin.yml +++ b/plugins/castlegates-paper/src/main/resources/plugin.yml @@ -1,4 +1,4 @@ -name: ${name} +name: CastleGates main: com.aleksey.castlegates.CastleGates version: ${version} author: Aleksey-Terzi diff --git a/plugins/donum-paper/src/main/resources/plugin.yml b/plugins/donum-paper/src/main/resources/plugin.yml index 10783dd67..d69c4ac6b 100644 --- a/plugins/donum-paper/src/main/resources/plugin.yml +++ b/plugins/donum-paper/src/main/resources/plugin.yml @@ -1,4 +1,4 @@ -name: ${name} +name: Donum main: com.github.civcraft.donum.Donum author: Maxopoly version: ${version} diff --git a/settings.gradle.kts b/settings.gradle.kts index 7f5ded6d6..34dae7fe9 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -8,6 +8,7 @@ include(":ansible") include(":plugins:banstick-paper") include(":plugins:bastion-paper") +include(":plugins:castlegates-paper") include(":plugins:citadel-paper") include(":plugins:civchat2-paper") include(":plugins:civmodcore-paper")