diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 3112e129d..000000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,13 +0,0 @@ -# These are supported funding model platforms - -#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] -#patreon: # Replace with a single Patreon username -#open_collective: # Replace with a single Open Collective username -ko_fi: ghostchu -#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -#liberapay: # Replace with a single Liberapay username -#issuehunt: # Replace with a single IssueHunt username -#otechie: # Replace with a single Otechie username -#lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry -custom: [ "https://imgur.com/a/fgES06K" ] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 00b6cbfda..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,72 +0,0 @@ -name: 'Bug Report' -description: 'Report a bug with QuickShop to us.' - -title: '[BUG] ' -labels: - - 'Bug' - -body: - - type: 'markdown' - attributes: - value: |- - ## Please Read! - This Form is reserved for **Bug reports only!** - - - For performance issues with QuickShop, open a [Performance Report](https://github.com/Ghost-chu/QuickShop-Hikari/issues/new?template=performance.yml&labels=performance). - - For contributions towards the wiki, open a [Wiki Contribution](https://github.com/Ghost-chu/QuickShop-Hikari/issues/new?template=wiki_contribution.yml.yml&labels=wiki). - - Feature requests or other suggestions should be made in the [Discussions](https://github.com/Ghost-chu/QuickShop-Hikari/discussions). - - Please fill out all required fields in their entirety and as detailed as possible. Failing to do so could get your issue closed without any warning. - - type: 'textarea' - attributes: - label: 'Description' - description: |- - Describe the bug as detailed as possible. - You cann upload screenshots of the bug in the "screenshots" section further down. - placeholder: 'When I used Quickshop did ... happen.' - validations: - required: true - - type: 'textarea' - attributes: - label: 'Steps to reproduce' - description: 'List your steps on how to reproduce this bug reliably here.' - placeholder: |- - 1. Do something - 2. ... - 3. Bug! - validations: - required: true - - type: 'textarea' - attributes: - label: 'Expected Behaviour' - description: 'What did you expect QuickShop to do?' - placeholder: 'QuickShop should ...' - validations: - required: true - - type: 'textarea' - attributes: - label: 'Screenshots' - description: |- - Provide screenshots to show the bug, if possible. - Gifs or Videos are also welcome if they can help explaining the issue. - placeholder: 'When I used Quickshop did ... happen.' - validations: - required: true - - type: 'input' - attributes: - label: '`/quickshop paste` URL' - description: |- - Please execute `/quickshop paste` in-game or `quickshop paste` in your server console. - The plugin will generate a URL that you can then post in the field below. - - If you can't create a paste, should you upload other files such as the `latest.log` file to https://paste.helpch.at and share the URL. - - If QuickShop is unable to generate a Paste will it create a file under `plugins/QuickShop/` - placeholder: 'https://paste.helpch.at/...' - validations: - required: true - - type: 'textarea' - attributes: - label: 'Additional Context' - description: 'Feel free to include any info that may not fit any of the previous sections.' - placeholder: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam ...' diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 7166f29c4..000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,16 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: 'Development Builds' - about: |- - Bleeding-edge builds with the latest features and bug fixes. - DEV-BUILDS MAY CAUSE DAMAGE TO YOUR SERVER! MAKE BACKUPS FIRST! - url: 'https://ci.codemc.io/job/Ghost-chu/job/QuickShop-Hikari/' - - name: 'Feature Requests' - about: 'Use our discussions page to request changes towards QuickShop.' - url: 'https://github.com/Ghost-chu/QuickShop-Hikari/discussions/categories/ideas' - - name: 'Wiki' - about: 'Find info about QuickShop in our dedicated wiki.' - url: 'https://github.com/Ghost-chu/QuickShop-Hikari/wiki' - - name: 'Discord' - about: 'Join our Discord to ask questions and get fast support.' - url: 'https://discord.gg/Bu3dVtmsD3' diff --git a/.github/ISSUE_TEMPLATE/performance.yml b/.github/ISSUE_TEMPLATE/performance.yml deleted file mode 100644 index 90b397907..000000000 --- a/.github/ISSUE_TEMPLATE/performance.yml +++ /dev/null @@ -1,90 +0,0 @@ -name: 'Performance Report' -description: 'Report performance issues with QuickShop.' - -title: '[PERFORMANCE] ' -labels: - - 'Performance Issue' - -body: - - type: 'markdown' - attributes: - value: |- - ## Please Read! - This Form is reserved for **Performance reports only!** - - - For Bugs or issues with QuickShop, open a [Bug Report](https://github.com/Ghost-chu/QuickShop-Hikari/issues/new?template=bug_report.yml&labels=bug). - - For contributions towards the wiki, open a [Wiki Contribution](https://github.com/Ghost-chu/QuickShop-Hikari/issues/new?template=wiki_contribution.yml.yml&labels=wiki). - - Feature requests or other suggestions should be made in the [Discussions](https://github.com/Ghost-chu/QuickShop-Hikari/discussions). - - Please fill out all required fields in their entirety and as details as possible. Failing to do so could get your issue closed without any warning. - - #### Additional Notes - Please only provide Sampler results from [Spark](https://www.spigotmc.org/resources/57242/)! Spigot Timings - no matter if v1 or v2 - will be ignored. - Your issue will be closed without any reply if only a Spigot Timings Report was provided. - - type: 'textarea' - attributes: - label: 'Description' - description: |- - Describe the issue as detailed as possible. - You cann upload screenshots of the issue in the "screenshots" section further down. - placeholder: 'When I used Quickshop did ... happen.' - validations: - required: true - - type: 'textarea' - attributes: - label: 'Steps to reproduce' - description: 'List your steps on how to reproduce this issue reliably here.' - placeholder: |- - 1. Do something - 2. ... - 3. Bad performance! - validations: - required: true - - type: 'textarea' - attributes: - label: 'Expected Behaviour' - description: 'What did you expect QuickShop to do?' - placeholder: 'QuickShop should ...' - validations: - required: true - - type: 'textarea' - attributes: - label: 'Screenshots' - description: |- - Provide screenshots to show the performance problems, if possible. - Gifs or Videos are also welcome if they can help explaining the issue. - placeholder: 'When I used Quickshop did ... happen.' - validations: - required: true - - type: 'input' - attributes: - label: '`/quickshop paste` URL' - description: |- - Please execute `/quickshop paste` in-game or `qs paste` in your server console. - The plugin will generate a URL that you can then post in the field below. - - If you can't create a paste, should you upload other files such as the `latest.log` file to https://paste.helpch.at and share the URL. - - If QuickShop is unable to generate a Paste will it create a file under `plugins/QuickShop/` - placeholder: 'https://paste.helpch.at/...' - validations: - required: true - - type: 'input' - attributes: - label: 'Spark Sample URL' - description: |- - **How to use [Spark](https://www.spigotmc.org/resources/57242/)** - - 1. Download the plugin from the Spigot page (linked above) if you haven't already. - 2. Add it to the server like any other plugin (Stop Server, add jar, start server). - 3. Join the server and execute `/spark sampler --start` - 4. Wait at least 10 minutes and/or perform the actions that cause performance issues with QuickShop. - 5. Execute `/spark sampler --stop` to get the URL - 6. Paste the URL in the field below. - validations: - required: true - - type: 'textarea' - attributes: - label: 'Additional Context' - description: 'Feel free to include any info that may not fit any of the previous sections.' - placeholder: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam ...' diff --git a/.github/ISSUE_TEMPLATE/wiki_contribution.yml b/.github/ISSUE_TEMPLATE/wiki_contribution.yml deleted file mode 100644 index 3e4a799e6..000000000 --- a/.github/ISSUE_TEMPLATE/wiki_contribution.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: 'Wiki Contribution' -description: 'Inform about a Contribution that you want to make towards the wiki.' - -title: '[WIKI] ' -labels: - - 'Wiki' - -body: - - type: 'markdown' - attributes: - value: |- - ## Please Read! - This Form is reserved for **Wiki Contributions only!** - - - For Bugs or issues with QuickShop, open a [Bug Report](https://github.com/Ghost-chu/QuickShop-Hikari/issues/new?template=bug_report.yml&labels=bug). - - For performance issues with QuickShop, open a [Performance Report](https://github.com/Ghost-chu/QuickShop-Hikari/issues/new?template=performance.yml&labels=performance). - - Feature requests or other suggestions should be made in the [Discussions](https://github.com/Ghost-chu/QuickShop-Hikari/discussions). - - Please fill out all required fields in their entirety and as detailed as possible. Failing to do so could get your issue closed without any warning. - - type: 'input' - attributes: - label: 'Repository URL' - description: 'Provide a URL to your GitHub Repository containing your Wiki changes.' - placeholder: 'https://github.com/example/repo' - validations: - required: true - - type: 'textarea' - attributes: - label: 'Changes' - description: 'Provide a list of all changes you made.' - placeholder: |- - - Changed this. - - Changed that. - - Also changed this! - validations: - required: true diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 97610d625..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,49 +0,0 @@ -version: 2 -updates: - - package-ecosystem: maven - directory: "/" - schedule: - interval: daily - open-pull-requests-limit: 10 - ignore: - - dependency-name: com.github.ben-manes.caffeine:caffeine - versions: - - "> 2.8.8" - - dependency-name: com.github.TownyAdvanced:Towny - versions: - - "> 0.96.2.0" - - dependency-name: io.sentry:sentry - versions: - - "> 3.1.1" - - dependency-name: net.kyori:adventure-text-serializer-gson - versions: - - "> 4.2.0, < 5" - - dependency-name: net.minidev:json-smart - versions: - - "> 1.3.2" - - dependency-name: net.tnemc:Reserve - versions: - - "> 0.1.3.0" - - dependency-name: org.junit.jupiter:junit-jupiter - versions: - - "> RELEASE" - - dependency-name: org.slf4j:slf4j-nop - versions: - - "> 1.7.6" - - dependency-name: com.massivecraft:Factions - versions: - - 1.6.9.5-2.6.8-STABLE - - dependency-name: com.github.angeschossen:LandsAPI - versions: - - 5.2.1 - - 5.2.2 - - 5.3.2 - - 5.3.3 - - 5.5.5 - - dependency-name: com.github.seeseemelk:MockBukkit-v1.16 - versions: - - 0.25.0 - - 0.27.0 - - 0.28.0 - - 0.32.1 - - 0.32.2 diff --git a/.github/icons/Bukkit.png b/.github/icons/Bukkit.png deleted file mode 100644 index e1d9d0f0c..000000000 Binary files a/.github/icons/Bukkit.png and /dev/null differ diff --git a/.github/icons/Discord.svg b/.github/icons/Discord.svg deleted file mode 100644 index 08e618028..000000000 --- a/.github/icons/Discord.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/.github/icons/Github.png b/.github/icons/Github.png deleted file mode 100644 index 6dcb298ee..000000000 Binary files a/.github/icons/Github.png and /dev/null differ diff --git a/.github/icons/Jenkins.svg b/.github/icons/Jenkins.svg deleted file mode 100644 index 2be438068..000000000 --- a/.github/icons/Jenkins.svg +++ /dev/null @@ -1,121 +0,0 @@ - - - \ No newline at end of file diff --git a/.github/icons/MCBBS.png b/.github/icons/MCBBS.png deleted file mode 100644 index 2ccaedaf6..000000000 Binary files a/.github/icons/MCBBS.png and /dev/null differ diff --git a/.github/icons/Spigot.png b/.github/icons/Spigot.png deleted file mode 100644 index 7f8cc476d..000000000 Binary files a/.github/icons/Spigot.png and /dev/null differ diff --git a/.github/issue_label_bot.yaml b/.github/issue_label_bot.yaml deleted file mode 100644 index 2c3bdeb71..000000000 --- a/.github/issue_label_bot.yaml +++ /dev/null @@ -1,4 +0,0 @@ -label-alias: - bug: 'Bug' - feature_request: 'Enhancement' - question: 'Question' diff --git a/.github/labeler.yml b/.github/labeler.yml deleted file mode 100644 index ca89cba8e..000000000 --- a/.github/labeler.yml +++ /dev/null @@ -1,5 +0,0 @@ -# Number of labels to fetch (optional). Defaults to 20 -numLabels: 40 -# These labels will not be used even if the issue contains them -excludeLabels: - - pinned diff --git a/.github/workflows/code_quality.yml b/.github/workflows/code_quality.yml deleted file mode 100644 index 40a2ed6ad..000000000 --- a/.github/workflows/code_quality.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Qodana -on: - workflow_dispatch: - pull_request: - push: - branches: - - '*' - - 'hikari' - - 'release' - -jobs: - qodana: - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - checks: write - steps: - - uses: actions/checkout@v3 - with: - ref: ${{ github.event.pull_request.head.sha }} # to check out the actual pull request commit, not the merge commit - fetch-depth: 0 # a full history is required for pull request analysis - - name: 'Qodana Scan' - uses: JetBrains/qodana-action@v2023.2 - env: - QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }} diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml deleted file mode 100644 index 5bf292b64..000000000 --- a/.github/workflows/maven.yml +++ /dev/null @@ -1,33 +0,0 @@ -# This workflow will build a Java project with Maven -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven - -name: Maven CI - -on: - push: - branches: [ hikari, cleanup ] - pull_request: - branches: [ hikari, cleanup ] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 17 - uses: actions/setup-java@v2 - with: - java-version: '17' - distribution: 'temurin' - cache: 'maven' - - name: Build with Maven - run: mvn package --batch-mode --update-snapshots -T 1.5C -f pom.xml -P github - - uses: actions/upload-artifact@v3 - with: - name: quickshop-snapshots - path: | - **/target/*.jar - - name: Upload coverage reports to Codecov - uses: codecov/codecov-action@v3 - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/mc-publish.yml b/.github/workflows/mc-publish.yml deleted file mode 100644 index e38c46d32..000000000 --- a/.github/workflows/mc-publish.yml +++ /dev/null @@ -1,99 +0,0 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: mc-publish - -on: - workflow_dispatch: - release: - types: - - published -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Set up JDK 17 - uses: actions/setup-java@v3 - with: - java-version: '17' - distribution: 'temurin' - cache: maven - - name: Build with Maven - run: mvn -B package -T 1.5C --file pom.xml - - uses: Kir-Antipov/mc-publish@v3.3 - with: - modrinth-id: ijC5dDkD - modrinth-featured: true - modrinth-token: ${{ secrets.MODRINTH_TOKEN }} - - github-discussion: Announcements - github-token: ${{ secrets.GITHUB_TOKEN }} - github-draft: false - files: | - quickshop-bukkit/target/QuickShop-Hikari-*.jar - **/target/+(Compat*|Addon*).jar - loaders: | - spigot - paper - purpur - game-versions: | - >=1.18.2 <=1.20.4 - game-version-filter: releases - java: | - 17 - dependencies: | - essentialsx(optional) - nbtapi(optional) - discordsrv(optional) - bluemap(optional) - dynmap(optional) - worldedit(optional) - worldguard(optional) - plan(optional) - bentobox(optional) - clearlag(optional) - elitemobs(optional) - griefprevention(optional) - lands(optional) - openinv(optional) - placeholderapi(optional) - residence(optional) - towny(optional) - superiorskyblock(optional) - luckperms(optional) - vault(optional) - plan(optional) - advancedregionmarket(optional) - ecoenchants(optional) - reforges(optional) - packetlistenerapi(conflicting) - # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive - - name: Update dependency graph - uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 - - name: Build Translations - uses: Ghost-chu/CrowdinCopyDeploy-action@master - with: - args: uploads3 - env: - CROWDIN_ACCESS_TOKEN: ${{ secrets.CROWDIN_ACCESS_TOKEN }} - CROWDIN_PROJECT_BRANCH_ID: '126' - CROWDIN_PROJECT_ID: '524354' - #DEPLOY_PATH: './deploy-prod' - AWS_S3_ENDPOINT: ${{ secrets.AWS_S3_ENDPOINT }} - AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }} - AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - AWS_REGION: auto - - name: Purge CloudFlare cache - uses: jakejarvis/cloudflare-purge-action@master - env: - # Zone is required by both authentication methods - CLOUDFLARE_ZONE: ${{ secrets.CLOUDFLARE_ZONE }} - CLOUDFLARE_TOKEN: ${{ secrets.CLOUDFLARE_TOKEN }} - CLOUDFLARE_EMAIL: ${{ secrets.CLOUDFLARE_EMAIL }} diff --git a/.github/workflows/sync-crowdinota.yml b/.github/workflows/sync-crowdinota.yml deleted file mode 100644 index 146410f92..000000000 --- a/.github/workflows/sync-crowdinota.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: ota-distribution - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - steps: - # - uses: actions/checkout@v3 - # - name: Set up JDK 17 - # uses: actions/setup-java@v3 - # with: - # java-version: '17' - # distribution: 'temurin' - - name: Build Translations - uses: Ghost-chu/CrowdinCopyDeploy-action@master - with: - args: uploads3 - env: - CROWDIN_ACCESS_TOKEN: ${{ secrets.CROWDIN_ACCESS_TOKEN }} - CROWDIN_PROJECT_BRANCH_ID: '126' - CROWDIN_PROJECT_ID: '524354' - #DEPLOY_PATH: './deploy-prod' - AWS_S3_ENDPOINT: ${{ secrets.AWS_S3_ENDPOINT }} - AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }} - AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - AWS_REGION: auto - - name: Purge CloudFlare cache - uses: jakejarvis/cloudflare-purge-action@master - env: - # Zone is required by both authentication methods - CLOUDFLARE_ZONE: ${{ secrets.CLOUDFLARE_ZONE }} - CLOUDFLARE_TOKEN: ${{ secrets.CLOUDFLARE_TOKEN }} - CLOUDFLARE_EMAIL: ${{ secrets.CLOUDFLARE_EMAIL }} diff --git a/.gitignore b/.gitignore index c5f846d68..68b8cb9f3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,11 @@ # IntelliJ out/ +# Eclipse +.classpath +.project +.settings/ + # Compiled class file *.class @@ -95,7 +100,8 @@ $RECYCLE.BIN/ # Windows shortcuts *.lnk -target/ +bin/ +build/ pom.xml.tag pom.xml.releaseBackup @@ -113,3 +119,5 @@ buildNumber.properties run/ /build-artifacts/ /.vscode/settings.json +/.gradle/ +/build/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..68234fe5a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "libs/Utilities-OG"] + path = libs/Utilities-OG + url = https://github.com/true-og/Utilities-OG diff --git a/.mergify.yml b/.mergify.yml deleted file mode 100644 index 88cbdcaca..000000000 --- a/.mergify.yml +++ /dev/null @@ -1,10 +0,0 @@ -pull_request_rules: - - name: Automatic merge on Crowdin - conditions: - - and: - - author=Ghost-chu - - title=New Crowdin updates - actions: - merge: - method: squash - commit_message_template: "Automatically merge Crowdin translations" diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index d58dfb70b..000000000 --- a/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -wrapperVersion=3.3.2 -distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/README.md b/README.md index 8f3398d93..dee204ac8 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,5 @@ -[codacy]: https://www.codacy.com/gh/Ghost-chu/QuickShop-Hikari/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Ghost-chu/QuickShop-Hikari&utm_campaign=Badge_Grade - -[codeFactor]: https://www.codefactor.io/repository/github/ghost-chu/quickshop-hikari - -[codeScore]: https://app.codiga.io/public/project/32011/QuickShop-Hikari/dashboard - [license]: https://github.com/Ghost-chu/QuickShop-Hikari/blob/hikari/LICENSE [contributors]: https://github.com/Ghost-chu/QuickShop-Hikari/graphs/contributors @@ -22,8 +16,6 @@ [quickshop-original]: https://github.com/KaiKikuchi/QuickShop -[codemc]: https://ci.codemc.io/job/Ghost-chu/job/QuickShop-Hikari/ - [clearlagg]: https://www.spigotmc.org/resources/68271/ [worldguard]: https://dev.bukkit.org/projects/worldguard @@ -36,28 +28,16 @@ [optional_modules]: https://ci.codemc.io/job/Ghost-chu/job/QuickShop-Hikari/ -[googlejava]: https://google.github.io/styleguide/javaguide.html - -[adoptium]: https://adoptium.net/ - [bStats-site]: https://bstats.org [bStats-plugin]: https://bstats.org/plugin/bukkit/QuickShop-Hikari/14281 -[codacyBadge]: https://app.codacy.com/project/badge/Grade/a04ef7174d9f4e65b60ae28b09222809 - -[codeFactorBadge]: https://www.codefactor.io/repository/github/ghost-chu/quickshop-hikari/badge - -[codeScoreBadge]: https://api.codiga.io/project/32011/score/svg - [licenseBadge]: https://img.shields.io/github/license/Ghost-chu/QuickShop-Hikari.svg [contributorsBadge]: https://img.shields.io/github/contributors/Ghost-chu/QuickShop-Hikari -[passedTests]: https://img.shields.io/jenkins/tests?compact_message&jobUrl=https://ci.codemc.io/job/Ghost-chu/job/QuickShop-Hikari - [fossaStatusBadge]: https://app.fossa.com/api/projects/git%2Bgithub.com%2FGhost-chu%2FQuickShop-Hikari.svg?type=shield [fossaStatusImageLarge]: https://app.fossa.com/api/projects/git%2Bgithub.com%2FGhost-chu%2FQuickShop-Hikari.svg?type=large @@ -70,16 +50,9 @@ [Ver]: https://img.shields.io/spiget/version/100125?label=version - - - - +# QuickShop-OG -# QuickShop-Hikari - -[![codacyBadge]][codacy] -[![codeScoreBadge]][codeScore] [![licenseBadge]][license] [![contributorsBadge]][contributors] ![passedTests] @@ -91,23 +64,17 @@ ## Introduction -QuickShop Hikari is a Shop plugin that allows players to create Chest Shops to easily sell and buy items, without the +QuickShop-OG is a GPLv3 based fork of QuickShop Hikari maintained by [TrueOG Network](https://trueog.net) for Purpur 1.19.4. QuickShop Hikari is a Shop plugin that allows players to create Chest Shops to easily sell and buy items, without the need for any commands. In fact, all commands in QuickShop are not even needed for normal gameplay. -This version of QuickShop ([Ghost-chu/QuickShop-Hikari][quickshop-hikari]) is a fork +QuickShop-OG is based on an older version of ([Ghost-chu/QuickShop-Hikari][quickshop-hikari]), which is a fork from [PotatoCraft-Studio's version][quickshop-potato] which itself is a fork from the [Reremake][quickshop-ghostchu] of the [original QuickShop][quickshop-original]. QuickShop Hikari is maintained by Ghost-Chu and has the goal to modernize the core content of QuickShop and adapt it to the latest versions of Minecraft. -## Community & Support - -[Discussions](https://github.com/Ghost-chu/QuickShop-Hikari/discussions) -[Bug Tracker](https://github.com/Ghost-chu/QuickShop-Hikari/issues) -[Discord](https://discord.gg/Bu3dVtmsD3) - ## Features - Easy to use @@ -136,10 +103,6 @@ the latest versions of Minecraft. - Shop benefits between shop owner and other players! - And much much more! -## Downloads - -Obtain the latest version from [ci.codemc.io][codemc] - ## Compatibility Modules You can download optional modules [here][optional_modules] for compatibility with other plugins. @@ -164,16 +127,9 @@ You can download optional modules [here][optional_modules] for compatibility wit - Flag-based shop control. -## Contribute - -If you're a developer, you can contribute to the QuickShop source code! Just make a fork, install the Lombok plugin (if -not done automatically), make your changes and create a pull request when you're done! -Please try to follow [Google's Java Code Style][googlejava] and do not increase the Plugin version. Thank you! - ### Distributing forks You're allowed to create your fork to share. No permission is needed. -Though it would be nice if you could pull-request your changes into this repository when they are good ones. ### Compile and Debugging diff --git a/addon/.gitignore b/addon/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/addon/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/addon/bluemap/pom.xml b/addon/bluemap/pom.xml deleted file mode 100644 index 38f336d60..000000000 --- a/addon/bluemap/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - bluemap - jar - - Addon-BlueMap - - Displaying the quickshops on your BlueMap instance - - 17 - UTF-8 - - - - - jitpack.io - https://jitpack.io - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - com.github.BlueMap-Minecraft - BlueMapAPI - 2.6.2 - provided - - - diff --git a/addon/bluemap/src/main/java/com/ghostchu/quickshop/addon/bluemap/Main.java b/addon/bluemap/src/main/java/com/ghostchu/quickshop/addon/bluemap/Main.java index 724348cd2..4c12326ea 100644 --- a/addon/bluemap/src/main/java/com/ghostchu/quickshop/addon/bluemap/Main.java +++ b/addon/bluemap/src/main/java/com/ghostchu/quickshop/addon/bluemap/Main.java @@ -8,6 +8,7 @@ import de.bluecolored.bluemap.api.BlueMapMap; import de.bluecolored.bluemap.api.BlueMapWorld; import de.bluecolored.bluemap.api.markers.MarkerSet; import de.bluecolored.bluemap.api.markers.POIMarker; +import java.util.Optional; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.Bukkit; @@ -18,8 +19,6 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; -import java.util.Optional; - public final class Main extends JavaPlugin implements Listener { static Main instance; private QuickShop plugin; @@ -43,7 +42,9 @@ public final class Main extends JavaPlugin implements Listener { BlueMapAPI.onEnable(blueMapAPI -> { getLogger().info("Found BlueMap loaded! Hooking!"); createMarkerSet(); - Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::updateAllMarkers, 1, getConfig().getInt("refresh-per-seconds") * 20L); + Bukkit.getScheduler() + .runTaskTimerAsynchronously( + this, this::updateAllMarkers, 1, getConfig().getInt("refresh-per-seconds") * 20L); }); BlueMapAPI.onDisable(api -> Bukkit.getScheduler().cancelTasks(this)); @@ -69,7 +70,8 @@ public final class Main extends JavaPlugin implements Listener { } private void updateAllMarkers() { - blueMapAPI.getWorlds().forEach(bWorld -> bWorld.getMaps().forEach(bMap -> bMap.getMarkerSets().remove("quickshop-hikari-shops"))); + blueMapAPI.getWorlds().forEach(bWorld -> bWorld.getMaps() + .forEach(bMap -> bMap.getMarkerSets().remove("quickshop-hikari-shops"))); plugin.getShopManager().getAllShops().forEach(this::updateShopMarker); } @@ -79,12 +81,14 @@ public final class Main extends JavaPlugin implements Listener { return; } for (BlueMapMap map : bWorld.get().getMaps()) { - MarkerSet markerSet = map.getMarkerSets().computeIfAbsent("quickshop-hikari-shops", (key) -> createMarkerSet()); + MarkerSet markerSet = + map.getMarkerSets().computeIfAbsent("quickshop-hikari-shops", (key) -> createMarkerSet()); String markerName = fillPlaceholders(getConfig().getString("marker-label"), shop); String desc = fillPlaceholders(getConfig().getString("marker-detail"), shop); POIMarker marker = POIMarker.builder() .label(markerName) - .position(shop.getLocation().getX(), + .position( + shop.getLocation().getX(), shop.getLocation().getY(), shop.getLocation().getZ()) .maxDistance(getConfig().getDouble("max-distance")) diff --git a/addon/discount/pom.xml b/addon/discount/pom.xml deleted file mode 100644 index 1b7edd8e5..000000000 --- a/addon/discount/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - discount - jar - - Addon-Discount - - Add discount code to your QuickShop-Hikari server - - 17 - UTF-8 - - - - - dv8tion - m2-dv8tion - https://m2.dv8tion.net/releases - - - Scarsz-Nexus - https://nexus.scarsz.me/content/groups/public/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - - - - - - - diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCode.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCode.java index 323d463bf..374578b5d 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCode.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCode.java @@ -7,14 +7,13 @@ import com.ghostchu.quickshop.api.localization.text.TextManager; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.common.util.CalculateUtil; import com.ghostchu.quickshop.common.util.JsonUtil; +import java.util.*; import net.kyori.adventure.text.Component; import org.apache.commons.lang3.StringUtils; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - public class DiscountCode { private final String code; private final UUID owner; @@ -27,7 +26,16 @@ public class DiscountCode { private long expiredTime; - public DiscountCode(@NotNull UUID owner, @NotNull String code, @NotNull CodeType codeType, @NotNull DiscountRate rate, int maxUsage, @NotNull Map usages, @NotNull Set shopScope, double threshold, long expiredTime) { + public DiscountCode( + @NotNull UUID owner, + @NotNull String code, + @NotNull CodeType codeType, + @NotNull DiscountRate rate, + int maxUsage, + @NotNull Map usages, + @NotNull Set shopScope, + double threshold, + long expiredTime) { this.owner = owner; this.code = code; this.codeType = codeType; @@ -39,7 +47,14 @@ public class DiscountCode { this.expiredTime = expiredTime; } - public DiscountCode(@NotNull UUID owner, @NotNull String code, @NotNull CodeType codeType, @NotNull DiscountRate rate, int maxUsage, double threshold, long expiredTime) { + public DiscountCode( + @NotNull UUID owner, + @NotNull String code, + @NotNull CodeType codeType, + @NotNull DiscountRate rate, + int maxUsage, + double threshold, + long expiredTime) { this.owner = owner; this.code = code; this.codeType = codeType; @@ -87,7 +102,8 @@ public class DiscountCode { } else { rate = JsonUtil.getGson().fromJson(data.getRate(), FixedDiscountRate.class); } - return new DiscountCode(data.getOwner(), + return new DiscountCode( + data.getOwner(), data.getCode(), data.getCodeType(), rate, @@ -135,7 +151,8 @@ public class DiscountCode { public boolean addShopToScope(@NotNull Shop shop) { if (codeType != CodeType.SPECIFIC_SHOPS) { - throw new IllegalStateException("Cannot add shop to code scope, because this code is not a specific shop code."); + throw new IllegalStateException( + "Cannot add shop to code scope, because this code is not a specific shop code."); } return this.shopScope.add(shop.getShopId()); } @@ -218,23 +235,24 @@ public class DiscountCode { if (usage + 1 > maxUsage) { return ApplicableType.REACHED_THE_LIMIT; } - ApplicableType type = switch (codeType) { - case SPECIFIC_SHOPS -> { - if (shopScope.contains(shop.getShopId())) { - yield ApplicableType.APPLICABLE; - } else { - yield ApplicableType.NOT_APPLICABLE; - } - } - case PLAYER_ALL_SHOPS -> { - if (owner.equals(shop.getOwner().getUniqueId())) { - yield ApplicableType.APPLICABLE; - } else { - yield ApplicableType.NOT_APPLICABLE; - } - } - case SERVER_ALL_SHOPS -> ApplicableType.APPLICABLE; - }; + ApplicableType type = + switch (codeType) { + case SPECIFIC_SHOPS -> { + if (shopScope.contains(shop.getShopId())) { + yield ApplicableType.APPLICABLE; + } else { + yield ApplicableType.NOT_APPLICABLE; + } + } + case PLAYER_ALL_SHOPS -> { + if (owner.equals(shop.getOwner().getUniqueId())) { + yield ApplicableType.APPLICABLE; + } else { + yield ApplicableType.NOT_APPLICABLE; + } + } + case SERVER_ALL_SHOPS -> ApplicableType.APPLICABLE; + }; if (type != ApplicableType.APPLICABLE) { return type; } @@ -256,8 +274,7 @@ public class DiscountCode { threshold, maxUsage, usages, - shopScope - ); + shopScope); return JsonUtil.getGson().toJson(data); } @@ -274,22 +291,28 @@ public class DiscountCode { if (!(o instanceof DiscountCode that)) { return false; } - return maxUsage == that.maxUsage && Double.compare(that.threshold, threshold) == 0 && expiredTime == that.expiredTime && code.equals(that.code) && owner.equals(that.owner) && shopScope.equals(that.shopScope) && codeType == that.codeType && rate.equals(that.rate); + return maxUsage == that.maxUsage + && Double.compare(that.threshold, threshold) == 0 + && expiredTime == that.expiredTime + && code.equals(that.code) + && owner.equals(that.owner) + && shopScope.equals(that.shopScope) + && codeType == that.codeType + && rate.equals(that.rate); } @Override public String toString() { - return "DiscountCode{" + - "code='" + code + '\'' + - ", owner=" + owner + - ", usages=" + usages + - ", shopScope=" + shopScope + - ", codeType=" + codeType + - ", rate=" + rate + - ", maxUsage=" + maxUsage + - ", threshold=" + threshold + - ", expiredTime=" + expiredTime + - '}'; + return "DiscountCode{" + "code='" + + code + '\'' + ", owner=" + + owner + ", usages=" + + usages + ", shopScope=" + + shopScope + ", codeType=" + + codeType + ", rate=" + + rate + ", maxUsage=" + + maxUsage + ", threshold=" + + threshold + ", expiredTime=" + + expiredTime + '}'; } public interface DiscountRate { @@ -319,7 +342,9 @@ public class DiscountCode { @Override public @NotNull Component format(@NotNull CommandSender sender, @NotNull TextManager textManager) { - return textManager.of(sender, "addon.discount.fixed-off", String.format("%.2f", rate)).forLocale(); + return textManager + .of(sender, "addon.discount.fixed-off", String.format("%.2f", rate)) + .forLocale(); } } @@ -343,7 +368,9 @@ public class DiscountCode { @Override public @NotNull Component format(@NotNull CommandSender sender, @NotNull TextManager textManager) { - return textManager.of(sender, "addon.discount.percentage-off", CalculateUtil.multiply(percent, 100)).forLocale(); + return textManager + .of(sender, "addon.discount.percentage-off", CalculateUtil.multiply(percent, 100)) + .forLocale(); } } } diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeData.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeData.java index 46964b96b..74553da18 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeData.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeData.java @@ -2,13 +2,12 @@ package com.ghostchu.quickshop.addon.discount; import com.ghostchu.quickshop.addon.discount.type.CodeType; import com.ghostchu.quickshop.addon.discount.type.RateType; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - import java.util.Map; import java.util.Set; import java.util.UUID; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; @Data @AllArgsConstructor @@ -24,5 +23,4 @@ public class DiscountCodeData { private int maxUsage; private Map usages; private Set shopScope; - } diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeManager.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeManager.java index 19740ae34..f1044dcb7 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeManager.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountCodeManager.java @@ -3,16 +3,15 @@ package com.ghostchu.quickshop.addon.discount; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.addon.discount.type.CodeCreationResponse; import com.ghostchu.quickshop.addon.discount.type.CodeType; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.regex.Pattern; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class DiscountCodeManager { public static final String NAME_REG_EXP = "[a-zA-Z0-9_]*"; @@ -49,7 +48,8 @@ public class DiscountCodeManager { public void saveDatabase() { try { - this.config.set("codes", this.codes.stream().map(DiscountCode::saveToString).toList()); + this.config.set( + "codes", this.codes.stream().map(DiscountCode::saveToString).toList()); this.config.save(this.file); } catch (IOException e) { main.getLogger().log(Level.WARNING, "Couldn't save the player discount codes status into database.", e); @@ -76,7 +76,15 @@ public class DiscountCodeManager { } @NotNull - public CodeCreationResponse createDiscountCode(@NotNull CommandSender sender, @NotNull UUID owner, @NotNull String code, @NotNull CodeType codeType, @NotNull String rate, int maxUsage, double threshold, long expiredTime) { + public CodeCreationResponse createDiscountCode( + @NotNull CommandSender sender, + @NotNull UUID owner, + @NotNull String code, + @NotNull CodeType codeType, + @NotNull String rate, + int maxUsage, + double threshold, + long expiredTime) { if (!namePattern.matcher(code).matches()) { return CodeCreationResponse.REGEX_FAILURE; } @@ -96,15 +104,18 @@ public class DiscountCodeManager { if (discountRate == null) { return CodeCreationResponse.INVALID_RATE; } - if (!QuickShop.getPermissionManager().hasPermission(sender, "quickshopaddon.discount.create." + codeType.name().toLowerCase())) { + if (!QuickShop.getPermissionManager() + .hasPermission( + sender, + "quickshopaddon.discount.create." + codeType.name().toLowerCase())) { return CodeCreationResponse.PERMISSION_DENIED; } - DiscountCode discountCode = new DiscountCode(owner, code, codeType, discountRate, maxUsage, threshold, expiredTime); + DiscountCode discountCode = + new DiscountCode(owner, code, codeType, discountRate, maxUsage, threshold, expiredTime); if (!this.codes.add(discountCode)) { return CodeCreationResponse.CODE_EXISTS; } main.getCodeManager().saveDatabase(); return CodeCreationResponse.SUCCESS; } - } diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountStatusManager.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountStatusManager.java index 7cf3a5811..a8479e098 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountStatusManager.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/DiscountStatusManager.java @@ -1,11 +1,10 @@ package com.ghostchu.quickshop.addon.discount; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class DiscountStatusManager { private final Map PLAYER_STATUS = new HashMap<>(); diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/Main.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/Main.java index 9a314356e..e236692bf 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/Main.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/Main.java @@ -5,15 +5,14 @@ import com.ghostchu.quickshop.addon.discount.command.DiscountCommand; import com.ghostchu.quickshop.addon.discount.listener.MainListener; import com.ghostchu.quickshop.api.command.CommandContainer; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermissionGroup; +import java.io.IOException; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; -import java.io.IOException; -import java.util.logging.Level; - public final class Main extends JavaPlugin implements Listener { static Main instance; private final DiscountStatusManager discountStatusManager = new DiscountStatusManager(); @@ -43,20 +42,27 @@ public final class Main extends JavaPlugin implements Listener { return; } getLogger().info("Registering the per shop permissions..."); - plugin.getShopPermissionManager().registerPermission(BuiltInShopPermissionGroup.ADMINISTRATOR.getNamespacedNode(), this, "discount_code_create"); - plugin.getShopPermissionManager().registerPermission(BuiltInShopPermissionGroup.ADMINISTRATOR.getNamespacedNode(), this, "discount_code_use"); - plugin.getShopPermissionManager().registerPermission(BuiltInShopPermissionGroup.EVERYONE.getNamespacedNode(), this, "discount_code_use"); - plugin.getShopPermissionManager().registerPermission(BuiltInShopPermissionGroup.STAFF.getNamespacedNode(), this, "discount_code_use"); + plugin.getShopPermissionManager() + .registerPermission( + BuiltInShopPermissionGroup.ADMINISTRATOR.getNamespacedNode(), this, "discount_code_create"); + plugin.getShopPermissionManager() + .registerPermission( + BuiltInShopPermissionGroup.ADMINISTRATOR.getNamespacedNode(), this, "discount_code_use"); + plugin.getShopPermissionManager() + .registerPermission(BuiltInShopPermissionGroup.EVERYONE.getNamespacedNode(), this, "discount_code_use"); + plugin.getShopPermissionManager() + .registerPermission(BuiltInShopPermissionGroup.STAFF.getNamespacedNode(), this, "discount_code_use"); Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> codeManager.cleanExpiredCodes(), 1L, 20 * 60 * 30); Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> codeManager.saveDatabase(), 1L, 20 * 60 * 15); getLogger().info("Registering the listeners..."); Bukkit.getPluginManager().registerEvents(this, this); Bukkit.getPluginManager().registerEvents(new MainListener(this), this); - plugin.getCommandManager().registerCmd( - CommandContainer - .builder() + plugin.getCommandManager() + .registerCmd(CommandContainer.builder() .prefix("discount") - .description((locale) -> plugin.text().of("addon.discount.commands.discount.description").forLocale(locale)) + .description((locale) -> plugin.text() + .of("addon.discount.commands.discount.description") + .forLocale(locale)) .permission("quickshopaddon.discount.use") .executor(new DiscountCommand(this, plugin)) .build()); diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/command/DiscountCommand.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/command/DiscountCommand.java index 56a18f487..adbd60ed1 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/command/DiscountCommand.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/command/DiscountCommand.java @@ -12,6 +12,8 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.ChatSheetPrinter; import com.ghostchu.quickshop.util.logger.Log; +import java.text.SimpleDateFormat; +import java.util.*; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; @@ -20,9 +22,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.text.SimpleDateFormat; -import java.util.*; - public class DiscountCommand implements CommandHandler { private final Main main; private final QuickShop quickshop; @@ -35,7 +34,13 @@ public class DiscountCommand implements CommandHandler { @Override public void onCommand(CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().isEmpty()) { - quickshop.text().of(sender, "command-incorrect", "/quickshop discount ").send(); + quickshop + .text() + .of( + sender, + "command-incorrect", + "/quickshop discount ") + .send(); return; } String[] passThroughArgs = new String[parser.getArgs().size() - 1]; @@ -48,8 +53,13 @@ public class DiscountCommand implements CommandHandler { case "info" -> info(sender, passThroughArgs); case "config" -> config(sender, passThroughArgs); case "list" -> list(sender, passThroughArgs); - default -> - quickshop.text().of(sender, "command-incorrect", "/quickshop discount ").send(); + default -> quickshop + .text() + .of( + sender, + "command-incorrect", + "/quickshop discount ") + .send(); } } @@ -59,7 +69,10 @@ public class DiscountCommand implements CommandHandler { return; } if (passThroughArgs.length < 1) { - quickshop.text().of(sender, "command-incorrect", "/quickshop discount install ").send(); + quickshop + .text() + .of(sender, "command-incorrect", "/quickshop discount install ") + .send(); return; } String codeStr = passThroughArgs[0]; @@ -69,7 +82,10 @@ public class DiscountCommand implements CommandHandler { return; } main.getStatusManager().set(p.getUniqueId(), code); - quickshop.text().of(sender, "addon.discount.discount-code-installed", code.getCode()).send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-installed", code.getCode()) + .send(); } private void uninstall(CommandSender sender, String[] passThroughArgs) { @@ -87,12 +103,24 @@ public class DiscountCommand implements CommandHandler { return; } if (passThroughArgs.length < 1) { - quickshop.text().of(sender, "command-incorrect", "/quickshop discount create [max-usage] [threshold] [expired-time]").send(); + quickshop + .text() + .of( + sender, + "command-incorrect", + "/quickshop discount create [max-usage] [threshold] [expired-time]") + .send(); return; } // code, code-type, rate, max-usage, threshold, expired-time if (passThroughArgs.length < 3) { - quickshop.text().of(sender, "command-incorrect", "/quickshop discount create [max-usage] [threshold] [expired-time]").send(); + quickshop + .text() + .of( + sender, + "command-incorrect", + "/quickshop discount create [max-usage] [threshold] [expired-time]") + .send(); return; } String code = passThroughArgs[0]; @@ -105,7 +133,10 @@ public class DiscountCommand implements CommandHandler { } } if (codeType == null) { - quickshop.text().of(sender, "addon.discount.invalid-code-type", codeTypeStr).send(); + quickshop + .text() + .of(sender, "addon.discount.invalid-code-type", codeTypeStr) + .send(); return; } int maxUsages = -1; @@ -130,34 +161,66 @@ public class DiscountCommand implements CommandHandler { if (passThroughArgs.length >= 6 && !"-1".equalsIgnoreCase(passThroughArgs[5])) { Date date = CommonUtil.parseTime(passThroughArgs[5]); if (date == null) { - quickshop.text().of(sender, "not-a-valid-time", passThroughArgs[5]).send(); + quickshop + .text() + .of(sender, "not-a-valid-time", passThroughArgs[5]) + .send(); return; } expiredOn = date.getTime(); } - CodeCreationResponse response = main.getCodeManager().createDiscountCode(p, p.getUniqueId(), code, codeType, passThroughArgs[2], maxUsages, threshold, expiredOn); + CodeCreationResponse response = main.getCodeManager() + .createDiscountCode( + p, p.getUniqueId(), code, codeType, passThroughArgs[2], maxUsages, threshold, expiredOn); switch (response) { - case PERMISSION_DENIED -> quickshop.text().of(sender, "no-permission").send(); - case INVALID_RATE -> quickshop.text().of(sender, "addon.discount.invalid-discount-rate").send(); - case REGEX_FAILURE -> - quickshop.text().of(sender, "addon.discount.invalid-discount-code-regex", DiscountCodeManager.NAME_REG_EXP).send(); - case INVALID_USAGE -> quickshop.text().of(sender, "addon.discount.invalid-usage-restriction").send(); - case INVALID_THRESHOLD -> - quickshop.text().of(sender, "addon.discount.invalid-threshold-restriction").send(); - case INVALID_EXPIRE_TIME -> quickshop.text().of(sender, "addon.discount.invalid-expire-time").send(); - case CODE_EXISTS -> quickshop.text().of(sender, "addon.discount.discount-code-already-exists").send(); - case SUCCESS -> quickshop.text().of(sender, "addon.discount.discount-code-created-successfully", - code, - CommonUtil.prettifyText(codeType.name()), - "/quickshop discount install " + code, - "/quickshop discount config " + code + " addshop").send(); + case PERMISSION_DENIED -> quickshop + .text() + .of(sender, "no-permission") + .send(); + case INVALID_RATE -> quickshop + .text() + .of(sender, "addon.discount.invalid-discount-rate") + .send(); + case REGEX_FAILURE -> quickshop + .text() + .of(sender, "addon.discount.invalid-discount-code-regex", DiscountCodeManager.NAME_REG_EXP) + .send(); + case INVALID_USAGE -> quickshop + .text() + .of(sender, "addon.discount.invalid-usage-restriction") + .send(); + case INVALID_THRESHOLD -> quickshop + .text() + .of(sender, "addon.discount.invalid-threshold-restriction") + .send(); + case INVALID_EXPIRE_TIME -> quickshop + .text() + .of(sender, "addon.discount.invalid-expire-time") + .send(); + case CODE_EXISTS -> quickshop + .text() + .of(sender, "addon.discount.discount-code-already-exists") + .send(); + case SUCCESS -> quickshop + .text() + .of( + sender, + "addon.discount.discount-code-created-successfully", + code, + CommonUtil.prettifyText(codeType.name()), + "/quickshop discount install " + code, + "/quickshop discount config " + code + " addshop") + .send(); } Log.debug("Discount code created: " + main.getCodeManager().getCode(code)); } private void remove(CommandSender sender, String[] passThroughArgs) { if (passThroughArgs.length < 1) { - quickshop.text().of(sender, "command-incorrect", "/quickshop discount remove ").send(); + quickshop + .text() + .of(sender, "command-incorrect", "/quickshop discount remove ") + .send(); return; } String codeStr = passThroughArgs[0]; @@ -167,7 +230,8 @@ public class DiscountCommand implements CommandHandler { return; } if (sender instanceof Player p) { - if (!code.getOwner().equals(p.getUniqueId()) && !quickshop.perm().hasPermission(sender, "quickshopaddon.discount.remove.bypass")) { + if (!code.getOwner().equals(p.getUniqueId()) + && !quickshop.perm().hasPermission(sender, "quickshopaddon.discount.remove.bypass")) { quickshop.text().of(sender, "no-permission").send(); return; } @@ -178,7 +242,10 @@ public class DiscountCommand implements CommandHandler { } } main.getCodeManager().removeCode(code); - quickshop.text().of(sender, "addon.discount.discount-code-removed", code.getCode()).send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-removed", code.getCode()) + .send(); } private void info(CommandSender sender, String[] passThroughArgs) { @@ -188,7 +255,10 @@ public class DiscountCommand implements CommandHandler { } DiscountCode code = main.getStatusManager().get(p.getUniqueId(), main.getCodeManager()); if (code == null) { - quickshop.text().of(sender, "addon.discount.discount-code-query-nothing").send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-query-nothing") + .send(); return; } String name = "Unknown"; @@ -196,7 +266,10 @@ public class DiscountCommand implements CommandHandler { if (lookupName != null) { name = lookupName; } - Component appliedTo = quickshop.text().of(sender, "addon.discount.code-type." + code.getCodeType().name()).forLocale(); + Component appliedTo = quickshop + .text() + .of(sender, "addon.discount.code-type." + code.getCodeType().name()) + .forLocale(); String remainsUsage; int remains = code.getRemainsUsage(((Player) sender).getUniqueId()); if (remains == -1) { @@ -207,7 +280,19 @@ public class DiscountCommand implements CommandHandler { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); String expiredOn = sdf.format(new Date(code.getExpiredTime())); - quickshop.text().of(sender, "addon.discount.discount-code-details", code.getCode(), name, appliedTo, remainsUsage, expiredOn, code.getThreshold(), code.getRate().format(sender, quickshop.text())).send(); + quickshop + .text() + .of( + sender, + "addon.discount.discount-code-details", + code.getCode(), + name, + appliedTo, + remainsUsage, + expiredOn, + code.getThreshold(), + code.getRate().format(sender, quickshop.text())) + .send(); } private void config(CommandSender sender, String[] passThroughArgs) { @@ -216,12 +301,21 @@ public class DiscountCommand implements CommandHandler { return; } if (passThroughArgs.length < 2) { - quickshop.text().of(sender, "command-incorrect", "/quickshop discount config [args]").send(); + quickshop + .text() + .of( + sender, + "command-incorrect", + "/quickshop discount config [args]") + .send(); return; } DiscountCode code = main.getCodeManager().getCode(passThroughArgs[0]); if (code == null) { - quickshop.text().of(sender, "addon.discount.invalid-discount-code", passThroughArgs[0]).send(); + quickshop + .text() + .of(sender, "addon.discount.invalid-discount-code", passThroughArgs[0]) + .send(); return; } switch (passThroughArgs[1]) { @@ -236,10 +330,16 @@ public class DiscountCommand implements CommandHandler { return; } if (code.getShopScope().add(shop.getShopId())) { - quickshop.text().of(sender, "addon.discount.discount-code-config-shop-added", shop.getShopId()).send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-config-shop-added", shop.getShopId()) + .send(); main.getCodeManager().saveDatabase(); } else { - quickshop.text().of(sender, "addon.discount.discount-code-config-shop-add-failure", shop.getShopId()).send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-config-shop-add-failure", shop.getShopId()) + .send(); } } case "removeshop" -> { @@ -253,27 +353,42 @@ public class DiscountCommand implements CommandHandler { return; } if (code.getShopScope().remove(shop.getShopId())) { - quickshop.text().of(sender, "addon.discount.discount-code-config-shop-removed", shop.getShopId()).send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-config-shop-removed", shop.getShopId()) + .send(); main.getCodeManager().saveDatabase(); } else { - quickshop.text().of(sender, "addon.discount.discount-code-config-shop-remove-failure", shop.getShopId()).send(); + quickshop + .text() + .of(sender, "addon.discount.discount-code-config-shop-remove-failure", shop.getShopId()) + .send(); } } case "scope" -> { if (passThroughArgs.length < 3) { -// StringJoiner joiner = new StringJoiner("<", "/", ">"); -// Arrays.stream(CodeType.values()).forEach(t -> joiner.add(t.name())); - quickshop.text().of(sender, "command-incorrect", "/quickshop discount config scope ").send(); + // StringJoiner joiner = new StringJoiner("<", "/", ">"); + // Arrays.stream(CodeType.values()).forEach(t -> joiner.add(t.name())); + quickshop + .text() + .of(sender, "command-incorrect", "/quickshop discount config scope ") + .send(); return; } - if (!code.getOwner().equals(((Player) sender).getUniqueId()) && !quickshop.perm().hasPermission(sender, "quickshopaddon.discount.bypass")) { + if (!code.getOwner().equals(((Player) sender).getUniqueId()) + && !quickshop.perm().hasPermission(sender, "quickshopaddon.discount.bypass")) { quickshop.text().of(sender, "no-permission").send(); return; } String newScope = passThroughArgs[2].toUpperCase(Locale.ROOT).replace("-", "_"); try { CodeType type = CodeType.valueOf(newScope); - if (!quickshop.perm().hasPermission(sender, "quickshopaddon.discount.create." + type.name().toLowerCase())) { + if (!quickshop + .perm() + .hasPermission( + sender, + "quickshopaddon.discount.create." + + type.name().toLowerCase())) { quickshop.text().of(sender, "no-permission").send(); return; } @@ -281,7 +396,10 @@ public class DiscountCommand implements CommandHandler { quickshop.text().of(sender, "discount-code-config-applied").send(); main.getCodeManager().saveDatabase(); } catch (IllegalArgumentException e) { - quickshop.text().of(sender, "addon.discount.invalid-code-type", newScope).send(); + quickshop + .text() + .of(sender, "addon.discount.invalid-code-type", newScope) + .send(); } } } @@ -298,31 +416,37 @@ public class DiscountCommand implements CommandHandler { } ChatSheetPrinter printer = new ChatSheetPrinter(sender); printer.printHeader(); - printer.printLine(quickshop.text().of(sender, "addon.discount.discount-code-list").forLocale()); - main.getCodeManager().getCodes().stream().filter(code -> code.getOwner().equals(((Player) sender).getUniqueId())).forEach(code -> printer.printLine(Component.text(code.getCode()).color(NamedTextColor.AQUA))); + printer.printLine( + quickshop.text().of(sender, "addon.discount.discount-code-list").forLocale()); + main.getCodeManager().getCodes().stream() + .filter(code -> code.getOwner().equals(((Player) sender).getUniqueId())) + .forEach( + code -> printer.printLine(Component.text(code.getCode()).color(NamedTextColor.AQUA))); printer.printFooter(); } @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { + public @Nullable List onTabComplete( + @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { if (cmdArg.length == 1) { return Arrays.asList("install", "uninstall", "create", "remove", "info", "config", "list"); } if (cmdArg.length == 2) { return switch (cmdArg[0]) { - case "install", "uninstall", "remove", "create", "config" -> List.of(PlainTextComponentSerializer - .plainText() - .serialize(quickshop - .text() - .of(sender, - "addon.discount.tab-complete.discount.general.code" - ).forLocale())); + case "install", "uninstall", "remove", "create", "config" -> List.of( + PlainTextComponentSerializer.plainText() + .serialize(quickshop + .text() + .of(sender, "addon.discount.tab-complete.discount.general.code") + .forLocale())); default -> Collections.emptyList(); }; } if (cmdArg.length == 3) { return switch (cmdArg[0]) { - case "create" -> Arrays.stream(CodeType.values()).map(Enum::name).toList(); + case "create" -> Arrays.stream(CodeType.values()) + .map(Enum::name) + .toList(); case "config" -> List.of("scope", "addshop", "removeshop"); default -> Collections.emptyList(); }; @@ -355,7 +479,8 @@ public class DiscountCommand implements CommandHandler { } private List tabCompleteHint(@NotNull CommandSender sender, @NotNull String key) { - String str = PlainTextComponentSerializer.plainText().serialize(quickshop.text().of(sender, key).forLocale()); + String str = PlainTextComponentSerializer.plainText() + .serialize(quickshop.text().of(sender, key).forLocale()); List list = new ArrayList<>(); String[] explode = str.split("\n"); for (int i = 0; i < explode.length; i++) { diff --git a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/listener/MainListener.java b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/listener/MainListener.java index aa72c33a5..b8e93082c 100644 --- a/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/listener/MainListener.java +++ b/addon/discount/src/main/java/com/ghostchu/quickshop/addon/discount/listener/MainListener.java @@ -9,14 +9,13 @@ import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.UUID; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - public class MainListener implements Listener { private final Main main; private final QuickShop quickshop; @@ -41,17 +40,39 @@ public class MainListener implements Listener { String code = codeInstalled.getCode(); Util.mainThreadRun(() -> { switch (codeInstalled.applicableShop(purchaser, shop)) { - case APPLICABLE -> - quickshop.text().of(purchaser, "addon.discount.discount-code-applicable", code).send(); - case APPLICABLE_WITH_THRESHOLD -> - quickshop.text().of(purchaser, "addon.discount.discount-code-applicable", code, quickshop.getEconomy().format(codeInstalled.getThreshold(), shop.getLocation().getWorld(), shop.getCurrency())).send(); - case NOT_APPLICABLE -> - quickshop.text().of(purchaser, "addon.discount.discount-code-not-applicable", code).send(); - case REACHED_THE_LIMIT -> - quickshop.text().of(purchaser, "addon.discount.discount-code-reach-the-limit", code).send(); - case NO_PERMISSION -> - quickshop.text().of(purchaser, "addon.discount.discount-code-no-permission", code).send(); - case EXPIRED -> quickshop.text().of(purchaser, "addon.discount.discount-code-expired", code).send(); + case APPLICABLE -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-applicable", code) + .send(); + case APPLICABLE_WITH_THRESHOLD -> quickshop + .text() + .of( + purchaser, + "addon.discount.discount-code-applicable", + code, + quickshop + .getEconomy() + .format( + codeInstalled.getThreshold(), + shop.getLocation().getWorld(), + shop.getCurrency())) + .send(); + case NOT_APPLICABLE -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-not-applicable", code) + .send(); + case REACHED_THE_LIMIT -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-reach-the-limit", code) + .send(); + case NO_PERMISSION -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-no-permission", code) + .send(); + case EXPIRED -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-expired", code) + .send(); } }); } @@ -78,25 +99,66 @@ public class MainListener implements Listener { double beforeDiscount = event.getTotal(); event.setTotal(codeInstalled.apply(purchaser, event.getTotal())); double discounted = beforeDiscount - event.getTotal(); - quickshop.text().of(purchaser, "addon.discount.discount-code-applied-in-purchase", code, quickshop.getEconomy().format(discounted, shop.getLocation().getWorld(), shop.getCurrency())).send(); + quickshop + .text() + .of( + purchaser, + "addon.discount.discount-code-applied-in-purchase", + code, + quickshop + .getEconomy() + .format(discounted, shop.getLocation().getWorld(), shop.getCurrency())) + .send(); } case APPLICABLE_WITH_THRESHOLD -> { if (event.getTotal() < codeInstalled.getThreshold()) { - quickshop.text().of(purchaser, "addon.discount.discount-code-under-threshold", quickshop.getEconomy().format(codeInstalled.getThreshold(), shop.getLocation().getWorld(), shop.getCurrency())).send(); + quickshop + .text() + .of( + purchaser, + "addon.discount.discount-code-under-threshold", + quickshop + .getEconomy() + .format( + codeInstalled.getThreshold(), + shop.getLocation().getWorld(), + shop.getCurrency())) + .send(); } else { double beforeDiscount = event.getTotal(); event.setTotal(codeInstalled.apply(purchaser, event.getTotal())); double discounted = beforeDiscount - event.getTotal(); - quickshop.text().of(purchaser, "addon.discount.discount-code-applied-in-purchase", code, quickshop.getEconomy().format(discounted, shop.getLocation().getWorld(), shop.getCurrency())).send(); + quickshop + .text() + .of( + purchaser, + "addon.discount.discount-code-applied-in-purchase", + code, + quickshop + .getEconomy() + .format( + discounted, + shop.getLocation().getWorld(), + shop.getCurrency())) + .send(); } } - case NOT_APPLICABLE -> - quickshop.text().of(purchaser, "addon.discount.discount-code-not-applicable", code).send(); - case REACHED_THE_LIMIT -> - quickshop.text().of(purchaser, "addon.discount.discount-code-reach-the-limit", code).send(); - case NO_PERMISSION -> - quickshop.text().of(purchaser, "addon.discount.discount-code-no-permission", code).send(); - case EXPIRED -> quickshop.text().of(purchaser, "addon.discount.discount-code-expired", code).send(); + case NOT_APPLICABLE -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-not-applicable", code) + .send(); + case REACHED_THE_LIMIT -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-reach-the-limit", code) + .send(); + case NO_PERMISSION -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-no-permission", code) + .send(); + case EXPIRED -> quickshop + .text() + .of(purchaser, "addon.discount.discount-code-expired", code) + .send(); } } @@ -104,5 +166,4 @@ public class MainListener implements Listener { public void onQuit(PlayerQuitEvent event) { main.getStatusManager().unset(event.getPlayer().getUniqueId()); } - } diff --git a/addon/displaycontrol/pom.xml b/addon/displaycontrol/pom.xml deleted file mode 100644 index 6d26eddd7..000000000 --- a/addon/displaycontrol/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - displaycontrol - jar - - Addon-DisplayControl - - Allow clients toggle the virtual display items status - - 17 - UTF-8 - - - - - dv8tion - m2-dv8tion - https://m2.dv8tion.net/releases - - - Scarsz-Nexus - https://nexus.scarsz.me/content/groups/public/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - - - - - - - diff --git a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/Main.java b/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/Main.java deleted file mode 100644 index 8b8c08a15..000000000 --- a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/Main.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.ghostchu.quickshop.addon.displaycontrol; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.displaycontrol.bean.ClientType; -import com.ghostchu.quickshop.addon.displaycontrol.bean.DisplayOption; -import com.ghostchu.quickshop.addon.displaycontrol.command.SubCommand_DisplayControl; -import com.ghostchu.quickshop.addon.displaycontrol.database.DisplayControlDatabaseHelper; -import com.ghostchu.quickshop.api.command.CommandContainer; -import com.ghostchu.quickshop.api.event.DisplayApplicableCheckEvent; -import com.ghostchu.quickshop.util.PackageUtil; -import com.ghostchu.quickshop.util.Util; -import com.ghostchu.quickshop.util.logger.Log; -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteStreams; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.plugin.messaging.PluginMessageListener; -import org.jetbrains.annotations.NotNull; - -import java.sql.SQLException; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; - -public final class Main extends JavaPlugin implements Listener, PluginMessageListener { - private static final String BUNGEE_CHANNEL = "quickshopcompat:bcgeyser"; - private static final String RESPONSE_PREFIX = "CLIENTTYPE"; - static Main instance; - private final Map playerClientMapping = new ConcurrentHashMap<>(); - private final Map playerDisplayStatus = new ConcurrentHashMap<>(); - private QuickShop plugin; - private DisplayControlDatabaseHelper databaseHelper; - - @Override - public void onLoad() { - instance = this; - } - - @Override - public void onDisable() { - HandlerList.unregisterAll((Plugin) this); - } - - @Override - public void onEnable() { - saveDefaultConfig(); - plugin = QuickShop.getInstance(); - try { - databaseHelper = new DisplayControlDatabaseHelper(instance, plugin.getSqlManager(), plugin.getDbPrefix()); - } catch (SQLException e) { - getLogger().log(Level.WARNING, "Failed to init database helper", e); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - Bukkit.getPluginManager().registerEvents(this, this); - Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> this.playerClientMapping.entrySet().removeIf(e -> Bukkit.getPlayer(e.getKey()) == null), 60 * 20 * 60, 60 * 20 * 60); - plugin.getCommandManager().registerCmd(CommandContainer.builder() - .prefix("displaycontrol") - .permission("quickshopaddon.displaycontrol.use") - .description((locale) -> plugin.text().of("addon.displaycontrol.command.displaycontrol").forLocale(locale)) - .executor(new SubCommand_DisplayControl(plugin, this)) - .build()); - getLogger().info("BungeeCord: " + Util.checkIfBungee()); - if (Util.checkIfBungee()) { - getLogger().info("Detected BungeeCord, register the BungeeCord client information forward module, you will need install Compat-BungeeCord-Geyser module to make this feature work."); - Bukkit.getMessenger().registerIncomingPluginChannel - (this, BUNGEE_CHANNEL, this); // we register the incoming channel - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void playerLogin(AsyncPlayerPreLoginEvent event) { - UUID uuid = event.getUniqueId(); - try { - DisplayOption displayOption = databaseHelper.getDisplayOption(uuid); - this.playerDisplayStatus.put(uuid, displayOption); - } catch (SQLException e) { - getLogger().log(Level.WARNING, "Failed to getting the player display status from database", e); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void playerQuit(PlayerQuitEvent event) { - cleanup(event.getPlayer().getUniqueId()); - } - - private void cleanup(UUID uuid) { - this.playerDisplayStatus.remove(uuid); - this.playerClientMapping.remove(uuid); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void displaySending(DisplayApplicableCheckEvent event) { - UUID uuid = event.getPlayer(); - DisplayOption option = this.playerDisplayStatus.getOrDefault(uuid, DisplayOption.AUTO); - boolean bedrockClient = this.playerClientMapping.getOrDefault(uuid, ClientType.UNDISCOVERED).isBedrockType(); - if (!option.isDisplayAvailable(bedrockClient)) { - event.setApplicable(false); - } - } - - public DisplayControlDatabaseHelper getDatabaseHelper() { - return databaseHelper; - } - - @Override - public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte @NotNull [] message) { - if (!channel.equalsIgnoreCase(BUNGEE_CHANNEL)) { - return; - } - ByteArrayDataInput in = ByteStreams.newDataInput(message); - String prefix = in.readUTF(); - //noinspection SwitchStatementWithTooFewBranches - switch (prefix) { - case RESPONSE_PREFIX -> handleBungeeBedrockPlayerCallback(in); - default -> getLogger().log(Level.WARNING, "Unrecognized type: " + prefix); - } - } - - private void handleBungeeBedrockPlayerCallback(ByteArrayDataInput in) { - if (!PackageUtil.parsePackageProperly("acceptBungeeCordBedrockPlayerDiscoveryCallback").asBoolean(true)) { - return; - } - UUID uuid = UUID.fromString(in.readUTF()); - int responseType = in.readShort(); - ClientType clientType = ClientType.UNDISCOVERED; - if (responseType == 0) { - clientType = ClientType.JAVA_EDITION_PLAYER; - } - if (responseType == 1) { - clientType = ClientType.BEDROCK_EDITION_PLAYER_GEYSER; - } - if (responseType == 2) { - clientType = ClientType.BEDROCK_EDITION_PLAYER_FLOODGATE; - } - Log.debug("Player " + uuid + " client type check callback: " + clientType.name() + ", isBedrockClient: " + clientType.isBedrockType()); - if (this.playerClientMapping.getOrDefault(uuid, ClientType.UNDISCOVERED).isWaitingDiscover()) { - Log.debug("[BUNGEE-CALLBACK] Discovered player " + uuid + " client type is: " + clientType.name()); - this.playerClientMapping.put(uuid, clientType); - } - } -} diff --git a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/bean/ClientType.java b/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/bean/ClientType.java deleted file mode 100644 index 39559b8a8..000000000 --- a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/bean/ClientType.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ghostchu.quickshop.addon.displaycontrol.bean; - -public enum ClientType { - UNDISCOVERED, - BEDROCK_EDITION_PLAYER_GEYSER, - BEDROCK_EDITION_PLAYER_FLOODGATE, - JAVA_EDITION_PLAYER; - - public boolean isBedrockType() { - return this == BEDROCK_EDITION_PLAYER_FLOODGATE || this == BEDROCK_EDITION_PLAYER_GEYSER; - } - - public boolean isWaitingDiscover() { - return this == UNDISCOVERED; - } -} diff --git a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/bean/DisplayOption.java b/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/bean/DisplayOption.java deleted file mode 100644 index b69c37718..000000000 --- a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/bean/DisplayOption.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ghostchu.quickshop.addon.displaycontrol.bean; - -public enum DisplayOption { - AUTO(0), - ENABLED(1), - DISABLED(2); - private final int id; - - DisplayOption(int id) { - this.id = id; - } - - public boolean isDisplayAvailable(boolean bedrock) { - if (this == AUTO) { - return !bedrock; - } - return this == ENABLED; - } - - public static DisplayOption fromId(int id) { - for (DisplayOption value : values()) { - if (value.id == id) { - return value; - } - } - return AUTO; - } - - public int getId() { - return id; - } -} diff --git a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/command/SubCommand_DisplayControl.java b/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/command/SubCommand_DisplayControl.java deleted file mode 100644 index 334e66548..000000000 --- a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/command/SubCommand_DisplayControl.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.ghostchu.quickshop.addon.displaycontrol.command; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.displaycontrol.Main; -import com.ghostchu.quickshop.addon.displaycontrol.bean.DisplayOption; -import com.ghostchu.quickshop.api.command.CommandHandler; -import com.ghostchu.quickshop.api.command.CommandParser; -import com.ghostchu.quickshop.util.Util; -import com.ghostchu.quickshop.util.logger.Log; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.sql.SQLException; -import java.util.Collections; -import java.util.List; -import java.util.logging.Level; - -public class SubCommand_DisplayControl implements CommandHandler { - private final QuickShop qs; - private final Main plugin; - - public SubCommand_DisplayControl(QuickShop qs, Main plugin) { - this.qs = qs; - this.plugin = plugin; - } - - @Override - public void onCommand(Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - if (parser.getArgs().isEmpty()) { - qs.text().of(sender, "command-incorrect", "/quickshop displaycontrol ").send(); - return; - } - DisplayOption option = DisplayOption.AUTO; - String userInput = parser.getArgs().get(0).trim(); - if ("enable".equalsIgnoreCase(userInput)) { - option = DisplayOption.ENABLED; - } - if ("disable".equalsIgnoreCase(userInput)) { - option = DisplayOption.DISABLED; - } - DisplayOption optionFinCopy = option; - Util.asyncThreadRun(() -> { - try { - Integer i = plugin.getDatabaseHelper().setDisplayDisableForPlayer(sender.getUniqueId(), optionFinCopy); - Log.debug("Execute DisplayToggle with id " + i + " affected"); - qs.text().of(sender, "addon.displaycontrol.toggle", optionFinCopy.name()).send(); - } catch (SQLException e) { - qs.text().of(sender, "addon.displaycontrol.toggle-exception").send(); - plugin.getLogger().log(Level.WARNING, "Cannot save the player display status", e); - } - }); - } - - - @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - if (parser.getArgs().size() == 1) { - return List.of("enable", "disable"); - } - return Collections.emptyList(); - } -} diff --git a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/database/DisplayControlDatabaseHelper.java b/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/database/DisplayControlDatabaseHelper.java deleted file mode 100644 index ffdcc2e54..000000000 --- a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/database/DisplayControlDatabaseHelper.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ghostchu.quickshop.addon.displaycontrol.database; - -import cc.carm.lib.easysql.api.SQLManager; -import cc.carm.lib.easysql.api.SQLQuery; -import com.ghostchu.quickshop.addon.displaycontrol.Main; -import com.ghostchu.quickshop.addon.displaycontrol.bean.DisplayOption; -import com.ghostchu.quickshop.util.Util; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.UUID; -import java.util.logging.Level; - -public class DisplayControlDatabaseHelper { - private final Main plugin; - - public DisplayControlDatabaseHelper(@NotNull Main plugin, @NotNull SQLManager sqlManager, @NotNull String dbPrefix) throws SQLException { - this.plugin = plugin; - try { - DisplayControlTables.initializeTables(sqlManager, dbPrefix); - } catch (SQLException e) { - plugin.getLogger().log(Level.WARNING, "Cannot initialize tables", e); - throw e; - } - - } - - public @NotNull Integer setDisplayDisableForPlayer(@NotNull UUID uuid, DisplayOption status) throws SQLException { - Util.ensureThread(true); - try (SQLQuery query = DisplayControlTables.DISPLAY_CONTROL_PLAYERS.createQuery() - .setLimit(1) - .addCondition("player", uuid.toString()) - .build().execute(); - ResultSet set = query.getResultSet()) { - if (set.next()) { - return DisplayControlTables.DISPLAY_CONTROL_PLAYERS.createUpdate() - .setLimit(1) - .addCondition("player", uuid.toString()) - .setColumnValues("displayOption", status.getId()) - .build().execute(); - } else { - return DisplayControlTables.DISPLAY_CONTROL_PLAYERS.createInsert() - .setColumnNames("player", "displayOption") - .setParams(uuid.toString(), status.getId()) - .returnGeneratedKey() - .execute(); - } - } - - } - - @Nullable - public DisplayOption getDisplayOption(@NotNull UUID player) throws SQLException { - Util.ensureThread(true); - try (SQLQuery query = DisplayControlTables.DISPLAY_CONTROL_PLAYERS - .createQuery() - .selectColumns("displayOption") - .addCondition("player", player.toString()).setLimit(1).build().execute(); - ResultSet set = query.getResultSet()) { - if (set.next()) { - int optionId = set.getInt("displayOption"); - return DisplayOption.fromId(optionId); - } - return DisplayOption.AUTO; - } - } -} diff --git a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/database/DisplayControlTables.java b/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/database/DisplayControlTables.java deleted file mode 100644 index e99cfbb1c..000000000 --- a/addon/displaycontrol/src/main/java/com/ghostchu/quickshop/addon/displaycontrol/database/DisplayControlTables.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.ghostchu.quickshop.addon.displaycontrol.database; - -import cc.carm.lib.easysql.api.SQLManager; -import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction; -import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction; -import cc.carm.lib.easysql.api.builder.*; -import cc.carm.lib.easysql.api.enums.IndexType; -import cc.carm.lib.easysql.api.function.SQLHandler; -import com.ghostchu.quickshop.util.Util; -import com.ghostchu.quickshop.util.logger.Log; -import org.jetbrains.annotations.NotNull; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -public enum DisplayControlTables { - - DISPLAY_CONTROL_PLAYERS("display_control_psettings", (table) -> { - table.addAutoIncrementColumn("id", true); // SHOP DATA ID - table.addColumn("player", "VARCHAR(36) NOT NULL"); // SHOP DATA OWNER (ALL-ZERO if this is server) - table.addColumn("displayOption", "INT NOT NULL DEFAULT 0"); // DISPLAY SETTINGS, JSON ENCODE - table.setIndex(IndexType.INDEX, "idx_qs_addon_display_control_psettings", "player"); - }); - private final @NotNull String name; - private final @NotNull SQLHandler tableHandler; - - private String prefix; - private SQLManager manager; - - DisplayControlTables(@NotNull String name, - @NotNull SQLHandler tableHandler) { - this.name = name; - this.tableHandler = tableHandler; - } - - public static void initializeTables(@NotNull SQLManager sqlManager, - @NotNull String tablePrefix) throws SQLException { - for (DisplayControlTables value : values()) { - value.create(sqlManager, tablePrefix); - } - } - - private void create(@NotNull SQLManager sqlManager, @NotNull String tablePrefix) throws SQLException { - if (this.manager == null) { - this.manager = sqlManager; - } - this.prefix = tablePrefix; - - TableCreateBuilder tableBuilder = sqlManager.createTable(this.getName()); - tableHandler.accept(tableBuilder); - tableBuilder.build().execute(); - Log.debug("Table creating:" + this.getName()); - } - - public @NotNull String getName() { - return this.prefix + this.name; - } - - public @NotNull DeleteBuilder createDelete() { - return this.createDelete(this.manager); - } - - public @NotNull DeleteBuilder createDelete(@NotNull SQLManager sqlManager) { - return sqlManager.createDelete(this.getName()); - } - - public @NotNull InsertBuilder> createInsert() { - return this.createInsert(this.manager); - } - - public @NotNull InsertBuilder> createInsert(@NotNull SQLManager sqlManager) { - return sqlManager.createInsert(this.getName()); - } - - public @NotNull InsertBuilder> createInsertBatch() { - return this.createInsertBatch(this.manager); - } - - public @NotNull InsertBuilder> createInsertBatch(@NotNull SQLManager sqlManager) { - return sqlManager.createInsertBatch(this.getName()); - } - - public @NotNull TableQueryBuilder createQuery() { - return this.createQuery(this.manager); - } - - public @NotNull TableQueryBuilder createQuery(@NotNull SQLManager sqlManager) { - return sqlManager.createQuery().inTable(this.getName()); - } - - public @NotNull ReplaceBuilder> createReplace() { - return this.createReplace(this.manager); - } - - public @NotNull ReplaceBuilder> createReplace(@NotNull SQLManager sqlManager) { - return sqlManager.createReplace(this.getName()); - } - - public @NotNull ReplaceBuilder> createReplaceBatch() { - return this.createReplaceBatch(this.manager); - } - - public @NotNull ReplaceBuilder> createReplaceBatch(@NotNull SQLManager sqlManager) { - return sqlManager.createReplaceBatch(this.getName()); - } - - public @NotNull UpdateBuilder createUpdate() { - return this.createUpdate(this.manager); - } - - public @NotNull UpdateBuilder createUpdate(@NotNull SQLManager sqlManager) { - return sqlManager.createUpdate(this.getName()); - } - - public boolean isExists() { - return isExists(this.manager); - } - - public boolean isExists(@NotNull SQLManager manager) { - boolean match = false; - try { - try (Connection connection = manager.getConnection(); ResultSet rs = connection.getMetaData().getTables(null, null, "%", null)) { - while (rs.next()) { - if (getName().equalsIgnoreCase(rs.getString("TABLE_NAME"))) { - match = true; - break; - } - } - } - } catch (SQLException e) { - if (Util.isDevMode()) { - e.printStackTrace(); - } - Log.debug("Error while checking table existence: " + getName()); - } - return match; - } - - public boolean purgeTable() { - return purgeTable(this.manager); - } - - public boolean purgeTable(@NotNull SQLManager sqlManager) { - try { - sqlManager.createDelete(this.getName()) - .addCondition("1=1") - .build().execute(); - return true; - } catch (SQLException e) { - Log.debug("Failed to purge table " + this.getName() + e); - return false; - } - } -} diff --git a/addon/displaycontrol/src/main/resources/config.yml b/addon/displaycontrol/src/main/resources/config.yml deleted file mode 100644 index fd2f6664d..000000000 --- a/addon/displaycontrol/src/main/resources/config.yml +++ /dev/null @@ -1 +0,0 @@ -config-version: 1 \ No newline at end of file diff --git a/addon/displaycontrol/src/main/resources/plugin.yml b/addon/displaycontrol/src/main/resources/plugin.yml deleted file mode 100644 index 6cdfdecc8..000000000 --- a/addon/displaycontrol/src/main/resources/plugin.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: qsaddon-${project.artifactId} -version: '${project.version}' -main: com.ghostchu.quickshop.addon.${project.artifactId}.Main -api-version: 1.18 -depend: - - QuickShop-Hikari -authors: [ Ghost_chu ] -permissions: - quickshopaddon.displaycontrol.use: - description: Allows players to use displaycontrol commands - default: true \ No newline at end of file diff --git a/addon/dynmap/pom.xml b/addon/dynmap/pom.xml deleted file mode 100644 index ee4d48d5f..000000000 --- a/addon/dynmap/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - dynmap - jar - - Addon-Dynmap - - Displaying the quickshops on your Dynmap instance - - 17 - UTF-8 - - - - - MikeRepo - https://repo.mikeprimm.com/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - us.dynmap - dynmap-api - 3.4-beta-3 - provided - - - diff --git a/addon/dynmap/src/main/java/com/ghostchu/quickshop/addon/dynmap/Main.java b/addon/dynmap/src/main/java/com/ghostchu/quickshop/addon/dynmap/Main.java deleted file mode 100644 index 22164b90d..000000000 --- a/addon/dynmap/src/main/java/com/ghostchu/quickshop/addon/dynmap/Main.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.ghostchu.quickshop.addon.dynmap; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.api.event.*; -import com.ghostchu.quickshop.api.localization.text.TextManager; -import com.ghostchu.quickshop.api.shop.Shop; -import com.ghostchu.quickshop.api.shop.ShopType; -import com.ghostchu.quickshop.util.PackageUtil; -import com.ghostchu.quickshop.util.Util; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.world.WorldLoadEvent; -import org.bukkit.event.world.WorldUnloadEvent; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.dynmap.DynmapAPI; -import org.dynmap.markers.*; -import org.jetbrains.annotations.NotNull; - -public final class Main extends JavaPlugin implements Listener { - static Main instance; - private QuickShop plugin; - private DynmapAPI dynmapAPI; - private MarkerAPI markerAPI; - - @Override - public void onLoad() { - instance = this; - } - - @Override - public void onDisable() { - HandlerList.unregisterAll((Plugin) this); - } - - @Override - public void onEnable() { - saveDefaultConfig(); - plugin = QuickShop.getInstance(); - this.dynmapAPI = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); - this.markerAPI = this.dynmapAPI.getMarkerAPI(); - Bukkit.getPluginManager().registerEvents(this, this); - Bukkit.getScheduler().runTaskLater(this, this::updateAllMarkers, 80); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(WorldLoadEvent event) { - Util.mainThreadRun(this::updateAllMarkers); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(WorldUnloadEvent event) { - Util.mainThreadRun(this::updateAllMarkers); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(QSConfigurationReloadEvent event) { - Util.mainThreadRun(this::updateAllMarkers); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopCreateSuccessEvent event) { - updateShopMarker(event.getShop()); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopDeleteEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopPriceChangeEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopItemChangeEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopOwnershipTransferEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopSuccessPurchaseEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopTypeChangeEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @EventHandler(ignoreCancelled = true) - public void onEvent(ShopNamingEvent event) { - Util.mainThreadRun(() -> updateShopMarker(event.getShop())); - } - - @NotNull - public String plain(@NotNull Component component) { - return PlainTextComponentSerializer.plainText().serialize(component); - } - - @NotNull - public TextManager text() { - return plugin.getTextManager(); - } - - public MarkerSet getMarkerSet() { - String id = PackageUtil.parsePackageProperly("marker-id").asString("quickshop-hikari-shops"); - MarkerSet markerSet = markerAPI.getMarkerSet(id); - if (markerSet == null) { - markerSet = markerAPI.createMarkerSet(id, plain(text().of("addon.dynmap.markerset-title").forLocale()), null, false); - } - markerSet.setHideByDefault(getConfig().getBoolean("display-by-default", true)); - return markerSet; - } - - public MarkerIcon getShopMarkerIcon() { - return markerAPI.getMarkerIcon(PackageUtil.parsePackageProperly("marker-icon").asString("chest")); - } - - public void updateAllMarkers() { - MarkerSet markerSet = getMarkerSet(); - markerSet.getMarkers().forEach(GenericMarker::deleteMarker); - for (Shop shop : plugin.getShopManager().getAllShops()) { - updateShopMarker(shop); - } - } - - public void updateShopMarker(Shop shop) { - MarkerSet markerSet = getMarkerSet(); - String shopName = shop.getShopName(); - String posStr = String.format("%s %s, %s, %s", shop.getLocation().getWorld().getName(), shop.getLocation().getBlockX(), shop.getLocation().getBlockY(), shop.getLocation().getBlockZ()); - if (shopName == null) { - shopName = posStr; - } - Marker marker = markerSet.findMarker("quickshop-hikari-shop-" + shop.getShopId()); - String markerName = plain(text().of("addon.dynmap.marker-name", - shopName, - plain(shop.ownerName()), - plain(Util.getItemStackName(shop.getItem())), - plugin.getShopManager().format(shop.getPrice(), shop), - shop.getShopStackingAmount(), - shop.getShopType() == ShopType.SELLING ? plain(text().of("shop-type.selling").forLocale()) : plain(text().of("shop-type.buying").forLocale()), - shop.isUnlimited(), - posStr - ).forLocale()); - if (marker == null) { - marker = markerSet.createMarker("quickshop-hikari-shop-" + shop.getShopId() - , markerName - , shop.getLocation().getWorld().getName(), - shop.getLocation().getX(), - shop.getLocation().getY(), - shop.getLocation().getZ(), - getShopMarkerIcon(), false); - } else { - marker.setLocation(shop.getLocation().getWorld().getName(), - shop.getLocation().getX(), - shop.getLocation().getY(), - shop.getLocation().getZ()); - } - String desc = plain(text().of("addon.dynmap.marker-description", - shopName, - plain(shop.ownerName()), - plain(Util.getItemStackName(shop.getItem())), - plugin.getShopManager().format(shop.getPrice(), shop), - shop.getShopStackingAmount(), - shop.getShopType() == ShopType.SELLING ? plain(text().of("shop-type.selling").forLocale()) : plain(text().of("shop-type.buying").forLocale()), - shop.isUnlimited(), - posStr - ).forLocale()); - marker.setDescription(desc.replace("\n", "
")); - } - -} diff --git a/addon/dynmap/src/main/resources/config.yml b/addon/dynmap/src/main/resources/config.yml deleted file mode 100644 index 58745ecb4..000000000 --- a/addon/dynmap/src/main/resources/config.yml +++ /dev/null @@ -1,2 +0,0 @@ -config-version: 1 -display-by-default: true \ No newline at end of file diff --git a/addon/dynmap/src/main/resources/plugin.yml b/addon/dynmap/src/main/resources/plugin.yml deleted file mode 100644 index 129733f71..000000000 --- a/addon/dynmap/src/main/resources/plugin.yml +++ /dev/null @@ -1,7 +0,0 @@ -name: qsaddon-${project.artifactId} -version: '${project.version}' -main: com.ghostchu.quickshop.addon.${project.artifactId}.Main -api-version: 1.18 -depend: - - dynmap -authors: [ Ghost_chu ] diff --git a/addon/limited/pom.xml b/addon/limited/pom.xml deleted file mode 100644 index bf2c5dc6c..000000000 --- a/addon/limited/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - limited - jar - - Addon-Limited - - Limit the player max amount of item can purchase in your specific shop - - 17 - UTF-8 - - - - - dv8tion - m2-dv8tion - https://m2.dv8tion.net/releases - - - Scarsz-Nexus - https://nexus.scarsz.me/content/groups/public/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - - - - - - - diff --git a/addon/limited/src/main/java/com/ghostchu/quickshop/addon/limited/Main.java b/addon/limited/src/main/java/com/ghostchu/quickshop/addon/limited/Main.java deleted file mode 100644 index f7ac639b9..000000000 --- a/addon/limited/src/main/java/com/ghostchu/quickshop/addon/limited/Main.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ghostchu.quickshop.addon.limited; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.limited.command.SubCommand_Limit; -import com.ghostchu.quickshop.api.command.CommandContainer; -import com.ghostchu.quickshop.api.event.CalendarEvent; -import com.ghostchu.quickshop.api.event.ShopClickEvent; -import com.ghostchu.quickshop.api.event.ShopPurchaseEvent; -import com.ghostchu.quickshop.api.event.ShopSuccessPurchaseEvent; -import com.ghostchu.quickshop.api.localization.text.Text; -import com.ghostchu.quickshop.api.shop.Shop; -import com.ghostchu.quickshop.util.Util; -import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.UUID; - -public final class Main extends JavaPlugin implements Listener { - public static Main instance; - private QuickShop plugin; - - private CommandContainer container; - - @Override - public void onDisable() { - // Plugin shutdown logic - plugin.getCommandManager().unregisterCmd(container); - } - - @Override - public void onEnable() { - // Plugin startup logic - instance = this; - saveDefaultConfig(); - Bukkit.getPluginManager().registerEvents(this, this); - this.plugin = QuickShop.getInstance(); - this.container = CommandContainer.builder() - .prefix("limit") - .permission("quickshopaddon.limit.use") - .description((locale) -> plugin.text().of("addon.limited.commands.limit").forLocale(locale)) - .executor(new SubCommand_Limit(plugin)) - .build(); - plugin.getCommandManager().registerCmd(container); - - } - - @EventHandler(ignoreCancelled = true) - public void shopPurchase(ShopPurchaseEvent event) { - Shop shop = event.getShop(); - ConfigurationSection storage = shop.getExtra(this); - if (storage.getInt("limit") < 1) { - return; - } - int limit = storage.getInt("limit"); - UUID uuid = event.getPurchaser().getUniqueIdIfRealPlayer().orElse(null); - if (uuid != null) { - int playerUsedLimit = storage.getInt("data." + uuid, 0); - if (playerUsedLimit + event.getAmount() > limit) { - Text text = plugin.text().of(event.getPurchaser(), "addon.limited.trade-limit-reached-cancel-reason"); - text.send(); - event.setCancelled(true, PlainTextComponentSerializer.plainText().serialize(text.forLocale())); - } - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void shopClick(ShopClickEvent event) { - Shop shop = event.getShop(); - ConfigurationSection storage = shop.getExtra(this); - if (storage.getInt("limit") < 1) { - Log.debug("Shop limit is not enabled on this shop."); - return; - } - int limit = storage.getInt("limit"); - int playerUsedLimit = storage.getInt("data." + event.getClicker().getUniqueId(), 0); - plugin.text().of(event.getClicker(), "addon.limited.remains-limits", limit - playerUsedLimit).send(); - Log.debug("Shop limit is enabled on this shop. Limit: " + limit + " Used: " + playerUsedLimit); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void shopPurchaseSuccess(ShopSuccessPurchaseEvent event) { - Shop shop = event.getShop(); - ConfigurationSection storage = shop.getExtra(this); - if (storage.getInt("limit") < 1) { - return; - } - UUID uuid = event.getPurchaser().getUniqueIdIfRealPlayer().orElse(null); - if (uuid != null) { - int limit = storage.getInt("limit"); - int playerUsedLimit = storage.getInt("data." + uuid, 0); - playerUsedLimit += event.getAmount(); - storage.set("data." + uuid, playerUsedLimit); - shop.setExtra(this, storage); - Player player = Bukkit.getPlayer(uuid); - if (player != null) { - player.sendTitle( - LegacyComponentSerializer.legacySection() - .serialize(plugin.text().of(player, "addon.limited.titles.title") - .forLocale()), - LegacyComponentSerializer.legacySection() - .serialize(plugin.text().of(player, "addon.limited.titles.subtitle" - , (limit - playerUsedLimit)).forLocale())); - } - } - } - - @EventHandler(ignoreCancelled = true) - public void scheduleEvent(CalendarEvent event) { - if (event.getCalendarTriggerType() == CalendarEvent.CalendarTriggerType.SECOND - || event.getCalendarTriggerType() == CalendarEvent.CalendarTriggerType.NOTHING_CHANGED) { - return; - } - Util.asyncThreadRun(() -> plugin.getShopManager().getAllShops().forEach(shop -> { - ConfigurationSection manager = shop.getExtra(this); - int limit = manager.getInt("limit"); - if (limit < 1) { - return; - } - if (StringUtils.isEmpty(manager.getString("period"))) { - return; - } - try { - if (event.getCalendarTriggerType().ordinal() >= CalendarEvent.CalendarTriggerType.valueOf(manager.getString("period")).ordinal()) { - manager.set("data", null); - shop.setExtra(this, manager); - Log.debug("Limit data has been reset. Shop -> " + shop); - } - } catch (IllegalArgumentException ignored) { - Log.debug("Limit data failed to reset. Shop -> " + shop + " type " + manager.getString("period") + " not exists."); - manager.set("period", null); - shop.setExtra(this, manager); - } - })); - - } -} diff --git a/addon/limited/src/main/java/com/ghostchu/quickshop/addon/limited/command/SubCommand_Limit.java b/addon/limited/src/main/java/com/ghostchu/quickshop/addon/limited/command/SubCommand_Limit.java deleted file mode 100644 index 1e4d8b8ba..000000000 --- a/addon/limited/src/main/java/com/ghostchu/quickshop/addon/limited/command/SubCommand_Limit.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ghostchu.quickshop.addon.limited.command; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.limited.Main; -import com.ghostchu.quickshop.api.command.CommandHandler; -import com.ghostchu.quickshop.api.command.CommandParser; -import com.ghostchu.quickshop.api.event.CalendarEvent; -import com.ghostchu.quickshop.api.shop.Shop; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -public class SubCommand_Limit implements CommandHandler { - private final QuickShop quickshop; - - public SubCommand_Limit(QuickShop quickshop) { - this.quickshop = quickshop; - } - - @Override - public void onCommand(Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - if (parser.getArgs().isEmpty()) { - quickshop.text().of(sender, "command.wrong-args").send(); - return; - } - Shop shop = getLookingShop(sender); - if (shop == null) { - quickshop.text().of(sender, "not-looking-at-shop").send(); - return; - } - ConfigurationSection manager = shop.getExtra(Main.instance); - switch (parser.getArgs().get(0)) { - case "set" -> { - try { - int limitAmount = Integer.parseInt(parser.getArgs().get(1)); - if (limitAmount > 0) { - manager.set("limit", limitAmount); - quickshop.text().of(sender, "addon.limited.success-setup").send(); - } else { - manager.set("limit", null); - manager.set("data", null); - quickshop.text().of(sender, "addon.limited.success-remove").send(); - } - shop.setExtra(Main.instance, manager); - } catch (NumberFormatException e) { - quickshop.text().of(sender, "not-a-integer", parser.getArgs().get(1)).send(); - } - } - case "unset" -> { - manager.set("limit", null); - manager.set("data", null); - quickshop.text().of(sender, "addon.limited.success-remove").send(); - shop.setExtra(Main.instance, manager); - } - case "reset" -> { - manager.set("data", null); - shop.setExtra(Main.instance, manager); - quickshop.text().of(sender, "addon.limited.success-reset").send(); - } - case "period" -> { - try { - CalendarEvent.CalendarTriggerType type = CalendarEvent.CalendarTriggerType.valueOf(parser.getArgs().get(1).toUpperCase(Locale.ROOT)); - manager.set("period", type.name()); - quickshop.text().of(sender, "addon.limited.success-setup").send(); - shop.setExtra(Main.instance, manager); - } catch (IllegalArgumentException ignored) { - quickshop.text().of(sender, "command.wrong-args", parser.getArgs().get(1)).send(); - } - } - } - } - - @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { - if (cmdArg.length < 2) { - return List.of("set", "unset", "reset", "period"); - } - if (cmdArg.length < 3) { - switch (cmdArg[0]) { - case "set" -> { - return List.of(""); - } - case "period" -> { - return Arrays.stream(CalendarEvent.CalendarTriggerType.values()) - .filter(e -> !e.equals(CalendarEvent.CalendarTriggerType.SECOND)) - .filter(e -> !e.equals(CalendarEvent.CalendarTriggerType.NOTHING_CHANGED)) - .map(Enum::name).toList(); - } - } - } - return Collections.emptyList(); - } -} diff --git a/addon/limited/src/main/resources/config.yml b/addon/limited/src/main/resources/config.yml deleted file mode 100644 index fd2f6664d..000000000 --- a/addon/limited/src/main/resources/config.yml +++ /dev/null @@ -1 +0,0 @@ -config-version: 1 \ No newline at end of file diff --git a/addon/limited/src/main/resources/plugin.yml b/addon/limited/src/main/resources/plugin.yml deleted file mode 100644 index 49579d3ad..000000000 --- a/addon/limited/src/main/resources/plugin.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: qssuite-limited -version: '${project.version}' -main: com.ghostchu.quickshop.addon.${project.artifactId}.Main -api-version: 1.18 -depend: - - QuickShop-Hikari -authors: [ Ghost_chu ] -permissions: - quickshopaddon.limit.use: - description: Allow player to use /quickshop limit - default: op \ No newline at end of file diff --git a/addon/list/pom.xml b/addon/list/pom.xml deleted file mode 100644 index b5b26cd46..000000000 --- a/addon/list/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - list - jar - - Addon-List - - Listing the all your quickshop - - 17 - UTF-8 - - - - - dv8tion - m2-dv8tion - https://m2.dv8tion.net/releases - - - Scarsz-Nexus - https://nexus.scarsz.me/content/groups/public/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - - - - - - - diff --git a/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/Main.java b/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/Main.java index 074db4b3c..2cbd92da2 100644 --- a/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/Main.java +++ b/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/Main.java @@ -29,11 +29,11 @@ public final class Main extends JavaPlugin implements Listener { plugin = QuickShop.getInstance(); getLogger().info("Registering the per shop permissions..."); Bukkit.getPluginManager().registerEvents(this, this); - plugin.getCommandManager().registerCmd( - CommandContainer - .builder() + plugin.getCommandManager() + .registerCmd(CommandContainer.builder() .prefix("list") - .description((locale) -> plugin.text().of("addon.list.commands.list").forLocale(locale)) + .description((locale) -> + plugin.text().of("addon.list.commands.list").forLocale(locale)) .selectivePermission("quickshopaddon.list.self") .selectivePermission("quickshopaddon.list.other") .executor(new SubCommand_List(plugin)) diff --git a/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/command/SubCommand_List.java b/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/command/SubCommand_List.java index 433605895..11d97425a 100644 --- a/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/command/SubCommand_List.java +++ b/addon/list/src/main/java/com/ghostchu/quickshop/addon/list/command/SubCommand_List.java @@ -1,11 +1,16 @@ package com.ghostchu.quickshop.addon.list.command; +import static com.ghostchu.quickshop.util.Util.getPlayerList; + import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.util.ChatSheetPrinter; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.List; +import java.util.UUID; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; @@ -16,12 +21,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import static com.ghostchu.quickshop.util.Util.getPlayerList; - public class SubCommand_List implements CommandHandler { private final QuickShop quickshop; @@ -39,7 +38,8 @@ public class SubCommand_List implements CommandHandler { } @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().size() == 1) { if (sender.hasPermission("quickshopaddon.list.other")) { return getPlayerList(); @@ -73,24 +73,53 @@ public class SubCommand_List implements CommandHandler { List shops = quickshop.getShopManager().getAllShops(lookupUser); ChatSheetPrinter printer = new ChatSheetPrinter(sender); printer.printHeader(); - printer.printLine(quickshop.text().of(sender, "addon.list.table-prefix", name, shops.size()).forLocale()); + printer.printLine(quickshop + .text() + .of(sender, "addon.list.table-prefix", name, shops.size()) + .forLocale()); int counter = 1; for (Shop shop : shops) { String shopName = shop.getShopName(); Location location = shop.getLocation(); - String combineLocation = location.getWorld().getName() + " " + location.getBlockX() + ", " + location.getBlockY() + ", " + location.getBlockZ(); + String combineLocation = location.getWorld().getName() + " " + location.getBlockX() + ", " + + location.getBlockY() + ", " + location.getBlockZ(); if (StringUtils.isEmpty(shopName)) { shopName = combineLocation; } - Component shopNameComponent = LegacyComponentSerializer.legacySection().deserialize(shopName).append(Component.textOfChildren(Component.text(" (").append(Util.getItemStackName(shop.getItem())).append(Component.text(")"))).color(NamedTextColor.GRAY)); + Component shopNameComponent = LegacyComponentSerializer.legacySection() + .deserialize(shopName) + .append(Component.textOfChildren(Component.text(" (") + .append(Util.getItemStackName(shop.getItem())) + .append(Component.text(")"))) + .color(NamedTextColor.GRAY)); Component shopTypeComponent; if (shop.isBuying()) { - shopTypeComponent = quickshop.text().of(sender, "menu.this-shop-is-buying").forLocale(); + shopTypeComponent = + quickshop.text().of(sender, "menu.this-shop-is-buying").forLocale(); } else { - shopTypeComponent = quickshop.text().of(sender, "menu.this-shop-is-selling").forLocale(); + shopTypeComponent = + quickshop.text().of(sender, "menu.this-shop-is-selling").forLocale(); } - Component component = quickshop.text().of(sender, "addon.list.entry", counter, shopNameComponent, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), quickshop.getEconomy().format(shop.getPrice(), shop.getLocation().getWorld(), shop.getCurrency()), shop.getShopStackingAmount(), Util.getItemStackName(shop.getItem()), shopTypeComponent).forLocale(); - component = component.clickEvent(ClickEvent.runCommand("/quickshop silentpreview " + shop.getRuntimeRandomUniqueId())); + Component component = quickshop + .text() + .of( + sender, + "addon.list.entry", + counter, + shopNameComponent, + location.getWorld().getName(), + location.getBlockX(), + location.getBlockY(), + location.getBlockZ(), + quickshop + .getEconomy() + .format(shop.getPrice(), shop.getLocation().getWorld(), shop.getCurrency()), + shop.getShopStackingAmount(), + Util.getItemStackName(shop.getItem()), + shopTypeComponent) + .forLocale(); + component = component.clickEvent( + ClickEvent.runCommand("/quickshop silentpreview " + shop.getRuntimeRandomUniqueId())); printer.printLine(component); counter++; } diff --git a/addon/plan/.gitignore b/addon/plan/.gitignore deleted file mode 100644 index 4788b4b45..000000000 --- a/addon/plan/.gitignore +++ /dev/null @@ -1,113 +0,0 @@ -# User-specific stuff -.idea/ - -*.iml -*.ipr -*.iws - -# IntelliJ -out/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -*~ - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# .nfs files are created when an open file is removed but is still being accessed -.nfs* - -# General -.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# Windows thumbnail cache files -Thumbs.db -Thumbs.db:encryptable -ehthumbs.db -ehthumbs_vista.db - -# Dump file -*.stackdump - -# Folder config file -[Dd]esktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msix -*.msm -*.msp - -# Windows shortcuts -*.lnk - -target/ - -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next - -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties -.mvn/wrapper/maven-wrapper.jar -.flattened-pom.xml - -# Common working directory -run/ diff --git a/addon/plan/pom.xml b/addon/plan/pom.xml deleted file mode 100644 index 0bb1eb9cd..000000000 --- a/addon/plan/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - plan - jar - - Addon-Plan - - Showcase the metrics about QuickShop-Hikari on your Plan page - - 17 - UTF-8 - - - - - jitpack - https://jitpack.io - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - com.github.plan-player-analytics - Plan - 5.6.2614 - provided - - - com.github.juliomarcopineda - jdbc-stream - 0.1.1 - compile - - - cc.carm.lib - easysql-api - 0.4.7 - provided - - - - - - - - - diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/HikariDataExtension.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/HikariDataExtension.java deleted file mode 100644 index 79703a09b..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/HikariDataExtension.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.ghostchu.quickshop.addon.plan; - -import com.djrapitops.plan.extension.CallEvents; -import com.djrapitops.plan.extension.DataExtension; -import com.djrapitops.plan.extension.annotation.*; -import com.djrapitops.plan.extension.icon.Color; -import com.djrapitops.plan.extension.icon.Family; -import com.djrapitops.plan.extension.icon.Icon; -import com.djrapitops.plan.extension.table.Table; -import com.ghostchu.quickshop.addon.plan.util.DataUtil; -import com.ghostchu.quickshop.addon.plan.util.DateUtil; -import com.ghostchu.quickshop.addon.plan.util.MetricQuery; -import com.ghostchu.quickshop.api.database.ShopMetricRecord; -import com.ghostchu.quickshop.api.database.bean.DataRecord; -import com.ghostchu.quickshop.api.shop.Shop; -import com.ghostchu.quickshop.common.util.CommonUtil; -import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; -import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; - -import java.text.DecimalFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -@PluginInfo(name = "QuickShop-Hikari", iconName = "credit-card", iconFamily = Family.REGULAR, color = Color.LIGHT_BLUE) -@TabInfo(tab = "Summary", iconName = "info-circle", iconFamily = Family.SOLID, elementOrder = {}) -@TabInfo(tab = "Purchases", iconName = "inbox", elementOrder = {}) -@TabInfo(tab = "Shops", iconName = "list", iconFamily = Family.SOLID, elementOrder = {}) -@TabOrder({"Summary", "Purchases", "Shops"}) -public class HikariDataExtension implements DataExtension { - private final Main main; - private final MetricQuery metricQuery; - private final DataUtil dataUtil; - private final DecimalFormat df = new DecimalFormat("#.00"); - - public HikariDataExtension(Main main) { - this.main = main; - this.dataUtil = new DataUtil(main); - this.metricQuery = new MetricQuery(main.getQuickShop(), (SimpleDatabaseHelperV2) main.getQuickShop().getDatabaseHelper()); - } - - @Override - public CallEvents[] callExtensionMethodsOn() { - return new CallEvents[]{ - CallEvents.PLAYER_LEAVE, - CallEvents.SERVER_PERIODICAL}; - } - - // ======================= GLOBAL PROVIDERS ======================= - - @StringProvider(text = "Total shops", description = "How many shops exists on this server", iconName = "hashtable", iconColor = Color.GREEN, priority = 100) - @Tab("Summary") - public String shopCreated() { - return String.valueOf(main.getQuickShop().getShopManager().getAllShops().size()); - } - - @Tab("Summary") - @StringProvider(text = "Total purchases", description = "Number of purchases on this server", iconName = "hashtable", iconColor = Color.GREEN, priority = 100) - public String totalTransactions() { - return String.valueOf(metricQuery.queryServerPurchaseCount()); - } - - @TableProvider(tableColor = Color.BLUE) - @Tab("Purchases") - public Table purchasesTab() { - Table.Factory tableBuilder = Table.builder() - .columnOne("Player", Icon.called("user").build()) - .columnTwo("Action", Icon.called("code-branch").build()) - .columnThree("Shop", Icon.called("shopping-cart").build()) - .columnFour("Item(amount)", Icon.called("box").build()) - .columnFive("Balance", Icon.called("money-bill-wave").build()); - List records = this.metricQuery.queryServerPurchaseRecords(DateUtil.daysAgo(365), 1000, true).stream().filter(record -> switch (record.getType()) { - //noinspection deprecation - case PURCHASE, PURCHASE_BUYING_SHOP, PURCHASE_SELLING_SHOP -> true; - default -> false; - }).toList(); - try { - LinkedHashMap recordsMapped = this.metricQuery.mapToDataRecord(records); - recordsMapped.forEach((metric, data) -> { - String player = metric.getPlayer(); - String action = CommonUtil.prettifyText(metric.getType().name()); - String shop = dataUtil.getShopName(metric, data); - String item = dataUtil.getItemName(data) + " (" + metric.getAmount() + ")"; - String balance = dataUtil.formatEconomy(metric); - tableBuilder.addRow(player, action, shop, item, balance); - }); - } catch (ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - return tableBuilder.build(); - } - - - @TableProvider(tableColor = Color.CYAN) - @Tab("Shops") - public Table shopsTab() { - Table.Factory tableBuilder = Table.builder() - .columnOne("Owner", Icon.called("user").build()) - .columnTwo("Item", Icon.called("shopping-cart").build()) - .columnThree("Price", Icon.called("money-bill-wave").build()) - .columnFour("Type", Icon.called("code-branch").build()) - .columnFive("Location", Icon.called("location-arrow").build()); - for (Shop shop : main.getQuickShop().getShopManager().getAllShops()) { - String owner = PlainTextComponentSerializer.plainText().serialize(shop.ownerName()); - String item = dataUtil.getItemName(shop.getItem()) + " x" + shop.getShopStackingAmount(); - String price = df.format(shop.getPrice()); - if (main.getQuickShop().getEconomy() != null) { - price = main.getQuickShop().getEconomy().format(shop.getPrice(), shop.getLocation().getWorld(), shop.getCurrency()); - } - String type = switch (shop.getShopType()) { - case BUYING -> "Buying"; - case SELLING -> "Selling"; - }; - String location = dataUtil.loc2String(shop.getLocation()); - tableBuilder.addRow(owner, item, price, type, location); - } - return tableBuilder.build(); - } - - - // ======================= PLAYER PROVIDERS ======================= - - @StringProvider(text = "Owned shops", description = "How many shops created and exists by this player", iconName = "hashtable", iconColor = Color.GREEN, priority = 100, showInPlayerTable = true) - public String shopCreatedPlayer(UUID playerUUID) { - return String.valueOf(main.getQuickShop().getShopManager().getAllShops(playerUUID).size()); - } - - @TableProvider(tableColor = Color.BLUE) - @Tab("Purchases") - public Table purchasesTabPlayer(UUID playerUUID) { - Table.Factory tableBuilder = Table.builder() - .columnOne("Action", Icon.called("code-branch").build()) - .columnTwo("Location", Icon.called("location-arrow").build()) - .columnThree("Item(amount)", Icon.called("box").build()) - .columnFour("Balance", Icon.called("money-bill-wave").build()); - - List records = this.metricQuery.queryServerPurchaseRecords(DateUtil.daysAgo(365), 50, true).stream().filter(record -> switch (record.getType()) { - //noinspection deprecation - case PURCHASE, PURCHASE_BUYING_SHOP, PURCHASE_SELLING_SHOP -> true; - default -> false; - }).toList(); - try { - LinkedHashMap recordsMapped = this.metricQuery.mapToDataRecord(records); - recordsMapped.forEach((metric, data) -> { - String action = CommonUtil.prettifyText(metric.getType().name()); - String shop = dataUtil.getShopName(metric, data); - String item = dataUtil.getItemName(data) + " (" + metric.getAmount() + ")"; - String balance = dataUtil.formatEconomy(metric); - tableBuilder.addRow(action, shop, item, balance); - }); - } catch (ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - return tableBuilder.build(); - } - - @TableProvider(tableColor = Color.CYAN) - @Tab("Shops") - public Table shopsTabPlayer(UUID playerUUID) { - Table.Factory tableBuilder = Table.builder() - .columnOne("Item", Icon.called("shopping-cart").build()) - .columnTwo("Price", Icon.called("money-bill-wave").build()) - .columnThree("Type", Icon.called("code-branch").build()) - .columnFour("Location", Icon.called("location-arrow").build()); - for (Shop shop : main.getQuickShop().getShopManager().getAllShops(playerUUID)) { - String item = dataUtil.getItemName(shop.getItem()) + " x" + shop.getShopStackingAmount(); - String price = df.format(shop.getPrice()); - if (main.getQuickShop().getEconomy() != null) { - price = main.getQuickShop().getEconomy().format(shop.getPrice(), shop.getLocation().getWorld(), shop.getCurrency()); - } - String type = switch (shop.getShopType()) { - case BUYING -> "Buying"; - case SELLING -> "Selling"; - }; - String location = dataUtil.loc2String(shop.getLocation()); - tableBuilder.addRow(item, price, type, location); - } - return tableBuilder.build(); - } -} diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/Main.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/Main.java deleted file mode 100644 index 538b85d19..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/Main.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ghostchu.quickshop.addon.plan; - -import com.ghostchu.quickshop.QuickShop; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; - -public final class Main extends JavaPlugin implements Listener { - private QuickShop quickshop; - - @Override - public void onEnable() { - saveDefaultConfig(); - quickshop = QuickShop.getInstance(); - new PlanHook(this).hookIntoPlan(); - } - - public QuickShop getQuickShop() { - return quickshop; - } -} diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/PlanHook.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/PlanHook.java deleted file mode 100644 index b2e0e55ec..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/PlanHook.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ghostchu.quickshop.addon.plan; - -import com.djrapitops.plan.capability.CapabilityService; -import com.djrapitops.plan.extension.ExtensionService; -import org.bukkit.Bukkit; - -public class PlanHook { - private final Main main; - private final CapabilityService capabilities = CapabilityService.getInstance(); - - public PlanHook(Main main) { - this.main = main; - } - - public void hookIntoPlan() { - registerDataExtension(); - listenForPlanReloads(); - } - - private void registerDataExtension() { - try { - if (capabilities.hasCapability("DATA_EXTENSION_TABLES") - && capabilities.hasCapability("DATA_EXTENSION_VALUES")) { - ExtensionService.getInstance().register(new HikariDataExtension(main)); - } else { - main.getLogger().severe("Your Plan build doesn't support DATA_EXTENSION_TABLES or DATA_EXTENSION_VALUES capability!"); - Bukkit.getPluginManager().disablePlugin(main); - } - } catch (IllegalStateException planIsNotEnabled) { - // Plan is not enabled, handle exception - } catch (IllegalArgumentException dataExtensionImplementationIsInvalid) { - // The DataExtension implementation has an implementation error, handle exception - } - } - - private void listenForPlanReloads() { - CapabilityService.getInstance().registerEnableListener( - isPlanEnabled -> { - // Register DataExtension again - if (isPlanEnabled) { - registerDataExtension(); - } - } - ); - } -} diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/DataUtil.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/DataUtil.java deleted file mode 100644 index 427b188f0..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/DataUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.ghostchu.quickshop.addon.plan.util; - -import com.ghostchu.quickshop.addon.plan.Main; -import com.ghostchu.quickshop.api.database.ShopMetricRecord; -import com.ghostchu.quickshop.api.database.bean.DataRecord; -import com.ghostchu.quickshop.api.shop.Shop; -import com.ghostchu.quickshop.common.util.CommonUtil; -import com.ghostchu.quickshop.util.Util; -import com.google.common.html.HtmlEscapers; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.text.DecimalFormat; -import java.util.UUID; - -public class DataUtil { - public final Main main; - - public DataUtil(@NotNull Main main) { - this.main = main; - } - - @NotNull - public String formatEconomy(@NotNull ShopMetricRecord record) { - Shop shop = main.getQuickShop().getShopManager().getShop(record.getShopId()); - if (shop == null || main.getQuickShop().getEconomy() == null) { - DecimalFormat df = new DecimalFormat("#.00"); - return df.format(record.getTotal()); - } - return main.getQuickShop().getEconomy().format(record.getTotal(), shop.getLocation().getWorld(), shop.getCurrency()); - } - - @NotNull - public String getItemName(@NotNull DataRecord dataRecord) { - ItemStack stack; - try { - stack = Util.deserialize(dataRecord.getItem()); - } catch (InvalidConfigurationException e) { - return "[Failed to deserialize]"; - } - if (stack == null) { - return "[Failed to deserialize]"; - } - String name = CommonUtil.prettifyText(stack.getType().name()); - if (stack.getItemMeta() != null && stack.getItemMeta().hasDisplayName()) { - name = stack.getItemMeta().getDisplayName(); - } - return HtmlEscapers.htmlEscaper().escape(name); - } - - @NotNull - public String getItemName(@NotNull ItemStack stack) { - String name = CommonUtil.prettifyText(stack.getType().name()); - if (stack.getItemMeta() != null && stack.getItemMeta().hasDisplayName()) { - name = stack.getItemMeta().getDisplayName(); - } - return HtmlEscapers.htmlEscaper().escape(name); - } - - @NotNull - public String getShopName(@NotNull ShopMetricRecord record, @NotNull DataRecord dataRecord) { - StringBuilder nameBuilder = new StringBuilder(); - Shop shop = main.getQuickShop().getShopManager().getShop(record.getShopId()); - if (shop == null) { - nameBuilder.append("[Deleted] "); - } - String shopName = dataRecord.getName(); - if (shopName != null) { - nameBuilder.append(ChatColor.stripColor(shopName)); - } else { - if (shop != null) { - Location location = shop.getLocation(); - String template = "%s %s,%s,%s"; - nameBuilder.append(String.format(template, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); - } else { - nameBuilder.append("N/A"); - } - } - return HtmlEscapers.htmlEscaper().escape(nameBuilder.toString()); - } - - @NotNull - public String loc2String(@NotNull Location location) { - String template = "%s %s,%s,%s"; - return String.format(template, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - @NotNull - public String getPlayerName(@NotNull UUID uuid) { - if (CommonUtil.getNilUniqueId().equals(uuid)) { - return "[Server]"; - } - String name = main.getQuickShop().getPlayerFinder().uuid2Name(uuid); - if (name == null || name.isEmpty()) { - return uuid.toString(); - } - return HtmlEscapers.htmlEscaper().escape(name); - } -} diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/DateUtil.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/DateUtil.java deleted file mode 100644 index 2e9c5b3b6..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/DateUtil.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ghostchu.quickshop.addon.plan.util; - -import org.jetbrains.annotations.NotNull; - -import java.util.Calendar; -import java.util.Date; - -public class DateUtil { - @NotNull - public static Date daysAgo(int ago) { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, -ago); - return cal.getTime(); - } -} diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/MetricQuery.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/MetricQuery.java deleted file mode 100644 index 06131dd02..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/MetricQuery.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.ghostchu.quickshop.addon.plan.util; - -import cc.carm.lib.easysql.api.SQLQuery; -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.api.database.ShopMetricRecord; -import com.ghostchu.quickshop.api.database.ShopOperationEnum; -import com.ghostchu.quickshop.api.database.bean.DataRecord; -import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; -import com.ghostchu.quickshop.obj.QUserImpl; -import com.ghostchu.quickshop.util.logger.Log; -import org.jetbrains.annotations.NotNull; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; -import java.util.concurrent.ExecutionException; - -public class MetricQuery { - private final SimpleDatabaseHelperV2 databaseHelper; - private final QuickShop plugin; - - public MetricQuery(QuickShop plugin, SimpleDatabaseHelperV2 databaseHelper) { - this.databaseHelper = databaseHelper; - this.plugin = plugin; - } - - - public long queryServerPurchaseCount() { - String sql = "SELECT COUNT(*) AS result FROM " + databaseHelper.getPrefix() + "log_purchase"; - try (SQLQuery query = databaseHelper.getManager().createQuery().withPreparedSQL(sql).setParams(Collections.emptyList()).execute()) { - ResultSet set = query.getResultSet(); - if (set.next()) { - return set.getInt("result"); - } else { - return -1; - } - } catch (SQLException e) { - return -1; - } - } - - @NotNull - public List queryTransactions(@NotNull Date startTime, long limit, boolean descending) { - List list = new ArrayList<>(); - try (SQLQuery query = databaseHelper.getManager().createQuery() - .inTable(databaseHelper.getPrefix() + "log_transaction") - .addTimeCondition("time", startTime, null) - .selectColumns() - .setLimit(1000) - .orderBy("id", !descending).build().execute()) { - ResultSet set = query.getResultSet(); - while (set.next()) { - //"time", "shop", "data", "buyer", "type", "amount", "money", "tax" - ShopTransactionRecord record = new ShopTransactionRecord( - set.getDate("time"), - UUID.fromString(set.getString("from")), - UUID.fromString(set.getString("to")), - set.getString("currency"), - set.getDouble("amount"), - UUID.fromString(set.getString("tax_currency")), - set.getDouble("tax_amount"), - set.getString("error") - ); - list.add(record); - } - } catch (SQLException e) { - e.printStackTrace(); - return list; - } - return list; - } - - // Use LinkedHashMap forced because we need keep the order. - public @NotNull LinkedHashMap mapToDataRecord(@NotNull List metricRecords) throws ExecutionException, InterruptedException { - // map ShopMetricRecord#getShopId to DataRecord with blocking future - LinkedHashMap dataRecords = new LinkedHashMap<>(); - for (ShopMetricRecord metricRecord : metricRecords) { - long shopId = metricRecord.getShopId(); - Long dataId = databaseHelper.locateShopDataId(shopId).get(); - if (dataId == null) { - Log.debug("dataId is null for shopId " + shopId); - continue; - } - DataRecord dataRecord = databaseHelper.getDataRecord(dataId).get(); - dataRecords.put(metricRecord, dataRecord); - } - return dataRecords; - - } - - @NotNull - public List queryServerPurchaseRecords(@NotNull Date startTime, long limit, boolean descending) { - List list = new ArrayList<>(); - try (SQLQuery query = databaseHelper.getManager().createQuery() - .inTable(databaseHelper.getPrefix() + "log_purchase") - .addTimeCondition("time", startTime, null) - .selectColumns() - .setLimit(1000) - .orderBy("id", !descending).build().execute()) { - ResultSet set = query.getResultSet(); - while (set.next()) { - //"time", "shop", "data", "buyer", "type", "amount", "money", "tax" - ShopMetricRecord record = ShopMetricRecord.builder() - .time(set.getDate("time").getTime()) - .shopId(set.getLong("shop")) - .type(ShopOperationEnum.valueOf(set.getString("type"))) - .total(set.getDouble("money")) - .tax(set.getDouble("tax")) - .amount(set.getInt("amount")) - .player(QUserImpl.createSync(plugin.getPlayerFinder(), set.getString("buyer"))) - .build(); - list.add(record); - } - } catch (SQLException e) { - e.printStackTrace(); - return list; - } - return list; - } -} diff --git a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/ShopTransactionRecord.java b/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/ShopTransactionRecord.java deleted file mode 100644 index 77d530b1c..000000000 --- a/addon/plan/src/main/java/com/ghostchu/quickshop/addon/plan/util/ShopTransactionRecord.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ghostchu.quickshop.addon.plan.util; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -@Data -@AllArgsConstructor -@Builder -public class ShopTransactionRecord { - private Date time; - private UUID from; - private UUID to; - private String currency; - private double amount; - private UUID taxAccount; - private double taxAmount; - private String error; -} diff --git a/addon/plan/src/main/resources/config.yml b/addon/plan/src/main/resources/config.yml deleted file mode 100644 index e534f88ef..000000000 --- a/addon/plan/src/main/resources/config.yml +++ /dev/null @@ -1,2 +0,0 @@ -config-version: 1 - diff --git a/addon/plan/src/main/resources/plugin.yml b/addon/plan/src/main/resources/plugin.yml deleted file mode 100644 index 9eee1a3a7..000000000 --- a/addon/plan/src/main/resources/plugin.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: qsaddon-${project.artifactId} -version: '${project.version}' -main: com.ghostchu.quickshop.addon.${project.artifactId}.Main -api-version: 1.18 -depend: - - QuickShop-Hikari - - Plan -authors: [ Ghost_chu ] -#libraries: -# - net.dv8tion:JDA:4.4.0_352.fix-2 \ No newline at end of file diff --git a/addon/reremake-migrator/pom.xml b/addon/reremake-migrator/pom.xml deleted file mode 100644 index 1354eb868..000000000 --- a/addon/reremake-migrator/pom.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - reremake-migrator - jar - - Addon-Reremake-Migrator - - Migrator QuickShop-Reremake data to QuickShop-Hikari - - 17 - UTF-8 - - - - - quickshop-repo - https://repo.codemc.io/repository/maven-public/ - - - minebench-repo - https://repo.minebench.de/ - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-shade-plugin - 3.5.1 - - - package - - shade - - - ${name}-${version} - - true - false - false - false - true - true - - - - - - - - - de.themoep:minedown-adventure:* - com.ghostchu.thirdparty:JsonConfiguration:* - net.minidev:json-smart:* - - - - - de.themoep.minedown. - - com.ghostchu.quickshop.addon.reremakemigrator.shade.de.themoep.minedown. - - - - com.dumptruckman. - - com.ghostchu.quickshop.addon.reremakemigrator.shade.com.dumptruckman. - - - - net.minidev. - com.ghostchu.quickshop.addon.reremakemigrator.shade.net.minidev. - - - - - - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/*.kotlin_module - META-INF/*.txt - META-INF/proguard/* - META-INF/services/* - META-INF/versions/9/* - *License* - *LICENSE* - - - - - - - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - org.maxgamer - QuickShop - 5.1.2.5 - provided - - - de.themoep - minedown-adventure - 1.7.2-SNAPSHOT - compile - - - com.ghostchu.thirdparty - JsonConfiguration - 1.2-20230922.165143-1 - - - - net.minidev - json-smart - 1.1.1 - compile - - - - - - - - - diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/Main.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/Main.java deleted file mode 100644 index 0686277a2..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/Main.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.reremakemigrator.command.SubCommand_ReremakeMigrate; -import com.ghostchu.quickshop.api.command.CommandContainer; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -public class Main extends JavaPlugin implements Listener { - static Main instance; - private QuickShop hikari; - private org.maxgamer.quickshop.QuickShop reremake; - private String deniedMessage; - - @Override - public void onLoad() { - instance = this; - } - - @Override - public void onEnable() { - saveDefaultConfig(); - hikari = QuickShop.getInstance(); - reremake = org.maxgamer.quickshop.QuickShop.getInstance(); - getLogger().info("Found QuickShop-Hikari: " + hikari.getJavaPlugin().getDescription().getVersion()); - getLogger().info("Found QuickShop-Reremake: " + reremake.getDescription().getVersion()); - Bukkit.getPluginManager().registerEvents(this, this); - hikari.getCommandManager().registerCmd( - CommandContainer - .builder() - .prefix("migratefromreremake") - .description((locale) -> hikari.text().of("addon.reremake-migrator.commands.migratefromreremake").forLocale(locale)) - .permission("quickshopaddon.reremakemigrator.migrator-admin") - .executor(new SubCommand_ReremakeMigrate(this, hikari, reremake)) - .build()); - } - - @Override - public void onDisable() { - HandlerList.unregisterAll((Plugin) this); - } - - public QuickShop getHikari() { - return hikari; - } - - public org.maxgamer.quickshop.QuickShop getReremake() { - return reremake; - } - - public void setDeniedMessage(String deniedMessage) { - this.deniedMessage = deniedMessage; - } - - public void setDeniedMessage(Component deniedMessage) { - this.deniedMessage = LegacyComponentSerializer.legacySection().serialize(deniedMessage); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerJoin(AsyncPlayerPreLoginEvent event) { - if (this.deniedMessage != null) { - event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, this.deniedMessage); - } - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/command/SubCommand_ReremakeMigrate.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/command/SubCommand_ReremakeMigrate.java deleted file mode 100644 index 67365d6fa..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/command/SubCommand_ReremakeMigrate.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.command; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; -import com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent.*; -import com.ghostchu.quickshop.api.command.CommandHandler; -import com.ghostchu.quickshop.api.command.CommandParser; -import com.ghostchu.quickshop.util.ProgressMonitor; -import com.ghostchu.quickshop.util.Util; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -public class SubCommand_ReremakeMigrate implements CommandHandler { - private final Main plugin; - private final QuickShop hikari; - private final org.maxgamer.quickshop.QuickShop reremake; - private final AtomicBoolean running = new AtomicBoolean(false); - - public SubCommand_ReremakeMigrate(Main main, QuickShop hikari, org.maxgamer.quickshop.QuickShop reremake) { - this.plugin = main; - this.hikari = hikari; - this.reremake = reremake; - } - - @Override - public void onCommand(ConsoleCommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - if (running.get()) { - return; - } - if (parser.getArgs().isEmpty() || parser.getArgs().size() < 2) { - hikari.text().of(sender, "command-incorrect", "/quickshop reremakemigrate ").send(); - return; - } - if (!Bukkit.getOnlinePlayers().isEmpty()) { - hikari.text().of(sender, "addon.reremake-migrator.server-not-empty").send(); - return; - } - boolean shouldOverrideExistShops = Boolean.parseBoolean(parser.getArgs().get(0)); - boolean shouldMigrateTransactionLogs = Boolean.parseBoolean(parser.getArgs().get(1)); - List migrateComponentList = new ArrayList<>(); - migrateComponentList.add(new ConfigMigrate(plugin, hikari, reremake, sender)); - migrateComponentList.add(new TranslationMigrateComponent(plugin, hikari, reremake, sender)); - migrateComponentList.add(new ShopMigrate(plugin, hikari, reremake, sender, shouldOverrideExistShops)); - if (shouldMigrateTransactionLogs) { - migrateComponentList.add(new ShopLogsMigrate(plugin, hikari, reremake, sender)); - } - Util.asyncThreadRun(() -> { - running.set(true); - plugin.setDeniedMessage(hikari.text().of(sender, "addon.reremake-migrator.join_blocking_converting").forLocale()); - for (MigrateComponent migrateComponent : new ProgressMonitor<>(migrateComponentList, triple -> hikari.text().of(sender, "addon.reremake-migrator.executing", triple.getRight().getClass().getSimpleName(), triple.getLeft(), triple.getMiddle()).send())) { - String migrateComponentName = migrateComponent.getClass().getSimpleName(); - try { - if (!migrateComponent.migrate()) { - // Something failed during the migration? - hikari.text().of(sender, "addon.reremake-migrator.failed", migrateComponentName).send(); - running.set(false); - return; - } - } catch (Exception e) { - hikari.logger().warn("Failed to execute migrate component {}", migrateComponentName, e); - running.set(false); - return; - } - } - hikari.text().of(sender, "addon.reremake-migrator.completed").send(); - plugin.setDeniedMessage(hikari.text().of(sender, "addon.reremake-migrator.join_blocking_finished").forLocale()); - running.set(false); - }); - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/AbstractMigrateComponent.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/AbstractMigrateComponent.java deleted file mode 100644 index 1dd1bacd1..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/AbstractMigrateComponent.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.QuickShopBukkit; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; -import com.ghostchu.quickshop.api.localization.text.Text; -import org.bukkit.command.CommandSender; - -public abstract class AbstractMigrateComponent implements MigrateComponent { - private final Main plugin; - private final QuickShop hikari; - private final org.maxgamer.quickshop.QuickShop reremake; - private final CommandSender sender; - - public AbstractMigrateComponent(Main main, QuickShop hikari, org.maxgamer.quickshop.QuickShop reremake, CommandSender sender) { - this.plugin = main; - this.hikari = hikari; - this.reremake = reremake; - this.sender = sender; - } - - @Override - public QuickShop getHikari() { - return this.hikari; - } - - @Override - public QuickShopBukkit getHikariJavaPlugin() { - return this.hikari.getJavaPlugin(); - } - - @Override - public org.maxgamer.quickshop.QuickShop getReremake() { - return this.reremake; - } - - @Override - public Main getPlugin() { - return plugin; - } - - public CommandSender getSender() { - return sender; - } - - public Text text(String modulePath, Object... objects) { - return getHikari().text().of(sender, "addon.reremake-migrator." + modulePath, objects); - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ConfigMigrate.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ConfigMigrate.java deleted file mode 100644 index c11aeab24..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ConfigMigrate.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; -import com.ghostchu.quickshop.util.ProgressMonitor; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.List; -import java.util.UUID; - -public class ConfigMigrate extends AbstractMigrateComponent { - // tax-free-for-unlimited-shop - // - private final String[] DIRECT_COPY_KEYS = new String[]{ - "game-language", "enabled-languages", "mojangapi-mirror", "dev-mode", "tax", "tax-account", "unlimited-shop-owner-change", - "unlimited-shop-owner-change-account", "show-tax", "respect-item-flag", "currency", "logging", "trying-fix-banlance-insuffient", - "include-offlineplayer-list", "economy-type", "use-decimal-format", "decimal-format", "send-display-item-protection-alert", - "send-shop-protection-alert", "chat-type", "limits", "shop-block", "shop.cost", "shop.refund", - "shop.sending-stock-message-to-staffs", "shop.disable-creative-mode-trading", "shop.disable-super-tool", - "shop.allow-owner-break-shop-sign", "shop.price-change-requires-fee", "shop.fee-for-price-change", "shop.lock", - "shop.disable-quick-create", "shop.auto-sign", "shop.sign-glowing", "shop.sign-dye-color", "shop.pay-unlimited-shop-owners", - "shop.display-items", "shop.display-items-check-ticks", "shop.display-type", "shop.display-auto-despawn", - "shop.display-despawn-range", "shop.display-check-time", "shop.display-allow-stacks", "shop.finding", "shop.alternate-currency-symbol", - "shop.alternate-currency-symbol-list", "shop.disable-vault-format", "shop.currency-symbol-on-right", "shop.ignore-unlimited-shop-messages", - "shop.auto-fetch-shop-messages", "shop.ignore-cancel-chat-event", "shop.allow-shop-without-space-for-sign", - "shop.maximum-digits-in-price", "shop.show-owner-uuid-in-controlpanel-if-op", "shop.sign-material", - "shop.use-enchantment-for-enchanted-book", "shop.use-effect-for-potion-item", "shop.blacklist-world", - "shop.blacklist-lores", "shop.protection-checking", "shop.protection-checking-blacklist", "shop.protection-checking-listener-blacklist", - "shop.max-shops-checks-in-once", "shop.display-item-use-name", "shop.update-sign-when-inventory-moving", "shop.allow-economy-loan", - "shop.word-for-trade-all-items", "shop.ongoing-fee", "shop.force-load-downgrade-items", "shop.remove-protection-trigger", - "shop.allow-stacks", "shop.force-use-item-original-name", "blacklist", "plugin.Multiverse-Core", "plugin.WorldEdit", - "effect", "matcher", "protect.explode", "protect.hopper", "protect.entity", "custom-item-stacksize", "purge", "debug" - }; - - public ConfigMigrate(Main main, QuickShop hikari, org.maxgamer.quickshop.QuickShop reremake, CommandSender sender) { - super(main, hikari, reremake, sender); - } - - @Override - public boolean migrate() { - copyValues(); - migrateCommandAlias(); - migratePriceRestrictions(); - setFixedConfigValues(); - getHikariJavaPlugin().reloadConfig(); - return true; - } - - private void migrateCommandAlias() { - List commandAlias = getReremake().getConfig().getStringList("custom-commands"); - if (!commandAlias.contains("qs")) { - commandAlias.add("qs"); - } - getHikari().getConfig().set("custom-commands", commandAlias); - getHikariJavaPlugin().saveConfig(); - } - - private void setFixedConfigValues() { - getHikari().getConfig().set("legacy-updater.shop-sign", true); - } - - private void migratePriceRestrictions() { - // Generating price-restriction.yml, copy from SimplePriceLimiter.java - text("modules.config.migrate-price-restriction").send(); - File configFile = new File(getHikariJavaPlugin().getDataFolder(), "price-restriction.yml"); - if (!configFile.exists()) { - try { - Files.copy(getHikariJavaPlugin().getResource("price-restriction.yml"), configFile.toPath()); - } catch (IOException e) { - getHikari().logger().warn("Failed to copy price-restriction.yml.yml to plugin folder!", e); - } - } - FileConfiguration configuration = YamlConfiguration.loadConfiguration(configFile); - // migrate the minimum-price and maximum-price - configuration.set("undefined.min", getReremake().getConfig().get("shop.minimum-price", "0.01")); - configuration.set("undefined.max", getReremake().getConfig().get("shop.maximum-price", 999999999999999999999999999999.99d)); - configuration.set("enable", true); - // migrate the whole-number setting from Reremake configuration - configuration.set("whole-number-only", getReremake().getConfig().get("shop.whole-number-prices-only")); - List str = getReremake().getConfig().getStringList("shop.price-restriction"); - for (String record : new ProgressMonitor<>(str, (triple) -> text("modules.migrate-price-restriction-entry", triple.getLeft(), triple.getMiddle()).send())) { - try { - String[] records = record.split(";"); - if (records.length != 3) { - continue; - } - Material material = Material.matchMaterial(records[0]); - double min = Double.parseDouble(records[1]); - double max = Double.parseDouble(records[2]); - String name = UUID.randomUUID().toString().replace("-", ""); - if (material == null) { - continue; - } - configuration.set("rules." + name + ".items", List.of(material)); - configuration.set("rules." + name + ".currency", List.of("*")); - configuration.set("rules." + name + ".min", min); - configuration.set("rules." + name + ".max", max); - } catch (Exception e) { - getHikari().logger().warn("Failed to migrate rule {}", record, e); - } - } - try { - configuration.save(configFile); - } catch (IOException e) { - getHikari().logger().warn("Failed to save the price-restriction.yml", e); - } - } - - - private void copyValues() { - text("modules.config.copy-values", DIRECT_COPY_KEYS.length).send(); - for (String directCopyKey : new ProgressMonitor<>(DIRECT_COPY_KEYS, triple -> - text("modules.config.copying-value", triple.getRight(), triple.getLeft(), triple.getMiddle()).send())) { - copyValue(directCopyKey); - } - getHikariJavaPlugin().saveConfig(); - } - - private void copyValue(String keyName) { - if (getReremake().getConfig().contains(keyName)) { - getHikari().getConfig().set(keyName, getReremake().getConfig().get(keyName)); - } - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/MigrateComponent.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/MigrateComponent.java deleted file mode 100644 index dd6445e77..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/MigrateComponent.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.QuickShopBukkit; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; - -public interface MigrateComponent { - QuickShop getHikari(); - - QuickShopBukkit getHikariJavaPlugin(); - - org.maxgamer.quickshop.QuickShop getReremake(); - - boolean migrate(); - - Main getPlugin(); -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/MockPlugin.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/MockPlugin.java deleted file mode 100644 index 784fb64e4..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/MockPlugin.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.generator.BiomeProvider; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginLoader; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.InputStream; -import java.util.List; -import java.util.logging.Logger; - -public class MockPlugin implements Plugin { - - private final String pluginName; - - public MockPlugin(String pluginName) { - this.pluginName = pluginName; - } - - @NotNull - @Override - public File getDataFolder() { - return null; - } - - @NotNull - @Override - public PluginDescriptionFile getDescription() { - return new PluginDescriptionFile(pluginName, "0.0.0", "N/A"); - } - - @NotNull - @Override - public FileConfiguration getConfig() { - return null; - } - - @Nullable - @Override - public InputStream getResource(@NotNull String s) { - return null; - } - - @Override - public void saveConfig() { - - } - - @Override - public void saveDefaultConfig() { - - } - - @Override - public void saveResource(@NotNull String s, boolean b) { - - } - - @Override - public void reloadConfig() { - - } - - @NotNull - @Override - public PluginLoader getPluginLoader() { - return null; - } - - @NotNull - @Override - public Server getServer() { - return null; - } - - @Override - public boolean isEnabled() { - return false; - } - - @Override - public void onDisable() { - - } - - @Override - public void onLoad() { - - } - - @Override - public void onEnable() { - - } - - @Override - public boolean isNaggable() { - return false; - } - - @Override - public void setNaggable(boolean b) { - - } - - @Nullable - @Override - public ChunkGenerator getDefaultWorldGenerator(@NotNull String s, @Nullable String s1) { - return null; - } - - @Nullable - @Override - public BiomeProvider getDefaultBiomeProvider(@NotNull String s, @Nullable String s1) { - return null; - } - - @NotNull - @Override - public Logger getLogger() { - return null; - } - - @NotNull - @Override - public String getName() { - return pluginName; - } - - @Override - public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { - return false; - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { - return null; - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ShopLogsMigrate.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ShopLogsMigrate.java deleted file mode 100644 index 59ff56312..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ShopLogsMigrate.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; -import com.ghostchu.quickshop.api.database.ShopMetricRecord; -import com.ghostchu.quickshop.api.database.ShopOperationEnum; -import com.ghostchu.quickshop.api.shop.Shop; -import com.ghostchu.quickshop.api.shop.ShopType; -import com.ghostchu.quickshop.common.util.CommonUtil; -import com.ghostchu.quickshop.common.util.JsonUtil; -import com.ghostchu.quickshop.common.util.QuickExecutor; -import com.ghostchu.quickshop.obj.QUserImpl; -import com.google.gson.JsonObject; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.InvalidConfigurationException; -import org.jetbrains.annotations.Nullable; - -import java.io.*; -import java.nio.charset.Charset; -import java.nio.charset.MalformedInputException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; -import java.time.temporal.TemporalAccessor; -import java.util.Base64; -import java.util.Date; -import java.util.UUID; -import java.util.zip.GZIPInputStream; - -public class ShopLogsMigrate extends AbstractMigrateComponent { - private final String template = "[2023-11-11 19:35:43.502] "; - DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneId.systemDefault()); - - public ShopLogsMigrate(Main main, QuickShop hikari, org.maxgamer.quickshop.QuickShop reremake, CommandSender sender) { - super(main, hikari, reremake, sender); - } - - @Override - public boolean migrate() { - text("modules.shop-logs.start-migrate").send(); - File logsFile = new File(getReremake().getDataFolder(), "appended-qs.log"); - File filteredFile = new File(getReremake().getDataFolder(), "filtered-qs.log"); - File formattedFile = new File(getReremake().getDataFolder(), "formatted-qs.log"); - try (PrintWriter printWriter = new PrintWriter(logsFile, StandardCharsets.UTF_8)) { - logsFile.createNewFile(); - filteredFile.createNewFile(); - appendFiles(getReremake().getDataFolder(), printWriter); - printWriter.flush(); - migrateAppendedLogs(logsFile, filteredFile); - readAndFormatEntire(filteredFile, formattedFile); - importToDatabase(formattedFile); - } catch (Exception ex) { - getHikari().logger().warn("Failed to migrate logs", ex); - return true; - } finally { - logsFile.delete(); - filteredFile.delete(); - formattedFile.delete(); - } - return true; - } - - private void importToDatabase(File filteredFile) throws IOException { - long sumLines = countLines(filteredFile); - BufferedReader bufferedReader = new BufferedReader(new FileReader(filteredFile)); - try (bufferedReader) { - String cursor; - long count = 0; - while ((cursor = bufferedReader.readLine()) != null) { - try { - count++; - text("modules.shop-logs.import-entry", "", count, sumLines); - DatedLogEntry entry = JsonUtil.standard().fromJson(new String(Base64.getDecoder().decode(cursor), StandardCharsets.UTF_8), DatedLogEntry.class); - Date date = entry.getDate(); - JsonObject jObj = JsonUtil.readObject(entry.getContent()); - if (jObj.has("shop") && jObj.has("type") && jObj.has("trader") - && jObj.has("itemStack") && jObj.has("amount") - && jObj.has("balance") - && jObj.has("tax")) { - try { - importThePurchaseRecord(date, jObj); - } catch (Exception e) { - getHikari().logger().warn("Error on importing to database", e); - } - continue; - } -// if (jObj.has("creator") && jObj.has("shop") && jObj.has("location")) { -// importTheCreationRecord(date, jObj); -// continue; -// } - getHikari().logger().warn("Invalid record {}, skipping", entry); - } catch (Exception e2) { - getHikari().logger().warn("Parse the log failed, cursor [{}]", cursor, e2); - } - } - } - } - - private long countLines(File filteredFile) throws FileNotFoundException { - BufferedReader bufferedReader = new BufferedReader(new FileReader(filteredFile)); - return bufferedReader.lines().count(); - } - -// private void importTheCreationRecord(Date date, JsonObject jObj) { -// UUID creator = UUID.fromString(jObj.getAsJsonObject("creator").getAsString()); -// JsonObject shopObj = jObj.get("shop").getAsJsonObject(); -// JsonObject loc = jObj.get("location").getAsJsonObject(); -// String worldName = loc.get("world").getAsString(); -// int x = loc.get("x").getAsInt(); -// int y = loc.get("y").getAsInt(); -// int z = loc.get("z").getAsInt(); -// World world = Bukkit.getWorld("worldName"); -// if (world == null) { -// getHikari().logger().warn("Failed to migrate record, world is null."); -// return; -// } -// Shop shop = getHikari().getShopManager().getShop(new Location(world, x, y, z)); -// if (shop == null) { -// getHikari().logger().warn("Failed to migrate record, shop already no-longer exists."); -// return; -// } -// -// } - - private void importThePurchaseRecord(Date date, JsonObject jObj) throws InvalidConfigurationException { - int amount = jObj.get("amount").getAsInt(); - double balance = jObj.get("balance").getAsDouble(); - double tax = jObj.get("tax").getAsDouble(); - UUID trader = UUID.fromString(jObj.get("trader").getAsString()); - ShopType type = ShopType.valueOf(jObj.get("type").getAsString()); - JsonObject shop = jObj.get("shop").getAsJsonObject(); - JsonObject pos = shop.get("position").getAsJsonObject(); - World world = Bukkit.getWorld(pos.get("world").getAsString()); - if (world == null) { - throw new IllegalArgumentException("World " + jObj.get("world").getAsString() + " not exists."); - } - int x = pos.get("x").getAsInt(); - int y = pos.get("y").getAsInt(); - int z = pos.get("z").getAsInt(); - Location location = new Location(world, x, y, z); - Shop shopInstance = getHikari().getShopManager().getShop(location); - if (shopInstance == null) { - throw new IllegalArgumentException("Shop at " + location + " not exists anymore"); - } - ShopMetricRecord shopMetricRecord = new ShopMetricRecord( - date.getTime(), - shopInstance.getShopId(), - type == ShopType.SELLING ? ShopOperationEnum.PURCHASE_SELLING_SHOP : ShopOperationEnum.PURCHASE_BUYING_SHOP, - balance, - tax, - amount, - QUserImpl.createSync(getHikari().getPlayerFinder(), trader, QuickExecutor.getSecondaryProfileIoExecutor()) - ); - getHikari().getDatabaseHelper().insertMetricRecord(shopMetricRecord); - } - - private void readAndFormatEntire(File filteredFile, File formattedFile) throws IOException { - BufferedReader bufferedReader = new BufferedReader(new FileReader(filteredFile)); - formattedFile.createNewFile(); - PrintWriter writer = new PrintWriter(formattedFile, StandardCharsets.UTF_8); - StringBuilder buffer = new StringBuilder(); - try (bufferedReader; writer) { - String cursor; - while ((cursor = bufferedReader.readLine()) != null) { - if (_isNewLineStart(cursor)) { - // Clean buffer - if (!buffer.isEmpty()) { - DatedLogEntry formatted = _formatLine(buffer.toString()); - if (formatted != null) { - writer.println(Base64.getEncoder().encodeToString(JsonUtil.standard().toJson(formatted) - .getBytes(StandardCharsets.UTF_8))); - } else { - getHikari().logger().warn("Entry {} is invalid.", cursor); - } - buffer = new StringBuilder(); - } - buffer.append(cursor); - } else { - buffer.append(cursor); - } - } - writer.flush(); - } - } - - @Data - @AllArgsConstructor - static class DatedLogEntry { - private Date date; - private String content; - } - - @Nullable - private DatedLogEntry _formatLine(String line) throws DateTimeParseException { - String json = StringUtils.substringAfter(line, "] "); - if (!CommonUtil.isJson(json)) return null; - String dateStr = line.substring(1, template.length() - 1).trim(); - TemporalAccessor accessor = DATETIME_FORMATTER.parse(dateStr); - return new DatedLogEntry(new Date(accessor.getLong(ChronoField.MILLI_OF_SECOND)), json); - } - - private boolean _isNewLineStart(String line) { - if (!line.startsWith("[")) return false; - if (line.length() < template.length()) return false; - return line.endsWith("] "); - } - - private void migrateAppendedLogs(File logsFile, File filteredFile) throws IOException { - text("modules.shop-logs.filter-history-files").send(); - BufferedReader bufferedReader = new BufferedReader(new FileReader(logsFile)); - PrintWriter writer = new PrintWriter(filteredFile, StandardCharsets.UTF_8); - long counter = 0; - try (bufferedReader; writer) { - String line; - while ((line = bufferedReader.readLine()) != null) { - if (line.contains("beforeTrading") && line.contains("player") && line.contains("holding")) { - continue; - } - if (StringUtils.isBlank(line)) { - continue; - } - writer.println(line); - counter++; - } - } finally { - writer.flush(); - logsFile.delete(); - text("modules.shop-logs.filtered-history-files", counter); - } - } - - private void appendFiles(File dataFolder, PrintWriter logsFile) throws IOException { - text("modules.shop-logs.extract-history-files").send(); - File logsSubFolder = new File(dataFolder, "logs"); - if (logsSubFolder.exists()) { - File[] files = logsSubFolder.listFiles(f -> f.getName().endsWith(".log.gz")); - if (files != null) { - for (File file : files) { - try (GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(file))) { - String content = new String(gzipInputStream.readAllBytes(), StandardCharsets.UTF_8); - logsFile.println(content); - logsFile.flush(); - } - } - } - } - File mainLogFile = new File(dataFolder, "qs.log"); - getHikari().logger().info("Selected main log file: " + mainLogFile.getAbsolutePath()); - if (mainLogFile.exists()) { - try { - logsFile.println(Files.readString(mainLogFile.toPath())); - } catch (MalformedInputException e) { - logsFile.println(Files.readString(mainLogFile.toPath(), Charset.defaultCharset())); - } - } else { - throw new IllegalStateException("Main qs.log log file not exists"); - } - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ShopMigrate.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ShopMigrate.java deleted file mode 100644 index cde39f51c..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/ShopMigrate.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; -import com.ghostchu.quickshop.api.shop.ShopType; -import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermissionGroup; -import com.ghostchu.quickshop.common.util.CommonUtil; -import com.ghostchu.quickshop.common.util.QuickExecutor; -import com.ghostchu.quickshop.economy.SimpleBenefit; -import com.ghostchu.quickshop.obj.QUserImpl; -import com.ghostchu.quickshop.shop.ContainerShop; -import com.ghostchu.quickshop.shop.inventory.BukkitInventoryWrapper; -import com.ghostchu.quickshop.util.ProgressMonitor; -import com.ghostchu.quickshop.util.performance.BatchBukkitExecutor; -import com.google.common.io.Files; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.block.BlockState; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.inventory.InventoryHolder; -import org.maxgamer.quickshop.api.shop.Shop; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -public class ShopMigrate extends AbstractMigrateComponent { - private final boolean override; - - public ShopMigrate(Main main, QuickShop hikari, org.maxgamer.quickshop.QuickShop reremake, CommandSender sender, boolean overrideExists) { - super(main, hikari, reremake, sender); - this.override = overrideExists; - } - - @Override - public boolean migrate() { - final AtomicBoolean success = new AtomicBoolean(true); - final AtomicInteger c = new AtomicInteger(0); - List allShops = getReremake().getShopManager().getAllShops(); - List preparedShops = new ArrayList<>(); - text("modules.shop.start-migrate", allShops.size()).send(); - BatchBukkitExecutor batchBukkitExecutor = new BatchBukkitExecutor<>(); - batchBukkitExecutor.addTasks(allShops); - batchBukkitExecutor.startHandle(getHikari().getJavaPlugin(), reremakeShop -> { - text("modules.shop.migrate-entry", reremakeShop.toString(), c.incrementAndGet(), allShops.size()).send(); - try { - Location shopLoc = reremakeShop.getLocation(); - com.ghostchu.quickshop.api.shop.Shop hikariShop = getHikari().getShopManager().getShop(shopLoc, true); - if (hikariShop != null) { - if (!override) { - text("modules.shop.conflict", "SKIPPING").send(); - return; - } else { - text("modules.shop.conflict", "OVERWRITING").send(); - getHikari().getShopManager().deleteShop(hikariShop); - } - } - BlockState block = shopLoc.getBlock().getState(); - if (!(block instanceof InventoryHolder container)) { - getHikari().logger().warn("Shop Invalid: Shop block not a valid Container, failed to create InventoryHolder."); - return; - } - ContainerShop hikariRawShop = new ContainerShop( - getHikari(), - -1, - shopLoc, - Math.min(reremakeShop.getPrice(), 999999999999999999999999999999.99), // DECIMAL (32,2) MAX - reremakeShop.getItem().clone(), - QUserImpl.createSync(getHikari().getPlayerFinder(), reremakeShop.getOwner()), - reremakeShop.isUnlimited(), - ShopType.fromID(reremakeShop.getShopType().toID()), - getReremakeShopExtra(reremakeShop), - reremakeShop.getCurrency(), - reremakeShop.isDisableDisplay(), - reremakeShop.getTaxAccountActual() == null ? null : QUserImpl.createSync(getHikari().getPlayerFinder(), reremakeShop.getTaxAccountActual()), - getHikari().getJavaPlugin().getName(), - getHikari().getInventoryWrapperManager().mklink(new BukkitInventoryWrapper(container.getInventory())), - null, - Collections.emptyMap(), - new SimpleBenefit() - ); - migrateReremakeBanAddonData(reremakeShop, hikariRawShop); - hikariRawShop.setDirty(); - preparedShops.add(hikariRawShop); - } catch (Exception e) { - getHikari().logger().warn("Failed to migrate shop " + reremakeShop, e); - } - }).thenAcceptAsync(a -> { - unloadAndMoveAwayReremake(); - registerHikariShops(preparedShops); - saveHikariShops(); - }, QuickExecutor.getCommonExecutor()).exceptionally((error) -> { - getHikari().logger().warn("Error while migrating shops", error); - success.set(false); - return null; - }).join(); - return success.get(); - } - - private void migrateReremakeBanAddonData(Shop reremakeShop, ContainerShop hikariRawShop) { - try { - ConfigurationSection reremakeBanExtra = reremakeShop.getExtra(new MockPlugin("QuickShopBan")); - for (String bannedPlayer : reremakeBanExtra.getStringList("bannedplayers")) { - if (!CommonUtil.isUUID(bannedPlayer)) continue; - getHikari().logger().info("Migrating shop ban record {} at {} to new Hikari container shop.", bannedPlayer, reremakeShop); - UUID uuid = UUID.fromString(bannedPlayer); - hikariRawShop.setPlayerGroup(uuid, BuiltInShopPermissionGroup.BLOCKED); - } - } catch (Throwable th) { - getHikari().logger().warn("Failed to migrate the shop ban record", th); - } - } - - private YamlConfiguration getReremakeShopExtra(Shop reremakeShop) { - YamlConfiguration configuration = new YamlConfiguration(); - try { - configuration.loadFromString(reremakeShop.saveExtraToYaml()); - } catch (InvalidConfigurationException ignored) { - } - return configuration; - } - - private void saveHikariShops() { - CompletableFuture[] shopsToSaveFuture = getHikari().getShopManager().getAllShops().stream().filter(com.ghostchu.quickshop.api.shop.Shop::isDirty) - .map(com.ghostchu.quickshop.api.shop.Shop::update) - .toArray(CompletableFuture[]::new); - text("modules.shop.saving-shops", shopsToSaveFuture.length).send(); - for (CompletableFuture completableFuture : new ProgressMonitor<>(shopsToSaveFuture, triple -> text("modules.shop.save-entry", triple.getLeft(), triple.getMiddle()).send())) { - try { - completableFuture.join(); - } catch (Exception e) { - getHikari().logger().warn("Error while saving shops, skipping", e); - } - } -// CompletableFuture.allOf(shopsToSaveFuture) -// .thenAcceptAsync((v) -> { -// if (shopsToSaveFuture.length != 0) { -// Log.debug("Saved " + shopsToSaveFuture.length + " shops in background."); -// } -// }, QuickExecutor.getShopSaveExecutor()) -// .exceptionally(e -> { -// getHikari().logger().warn("Error while saving shops", e); -// return null; -// }).join(); - } - - private void registerHikariShops(List preparedShops) { - for (com.ghostchu.quickshop.api.shop.Shop shop : new ProgressMonitor<>(preparedShops, triple -> text("modules.shop.register-entry", triple.getRight(), triple.getLeft(), triple.getMiddle()).send())) { - getHikari().getShopManager().registerShop(shop, true).join(); - shop.setDirty(); - } - } - - private void unloadAndMoveAwayReremake() { - text("modules.shop.unloading-reremake").send(); - Bukkit.getPluginManager().disablePlugin(getReremake()); - File reremakeDataDirectory = new File(getHikari().getDataFolder(), "QuickShop"); - try { - Files.move(reremakeDataDirectory, new File(getHikari().getDataFolder(), "QuickShop.migrated")); - } catch (IOException e) { - getHikari().logger().warn("Failed to move QuickShop-Reremake data directory, it may cause issues. You should manually move it to another location."); - } - } -} diff --git a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/TranslationMigrateComponent.java b/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/TranslationMigrateComponent.java deleted file mode 100644 index f2bec4827..000000000 --- a/addon/reremake-migrator/src/main/java/com/ghostchu/quickshop/addon/reremakemigrator/migratecomponent/TranslationMigrateComponent.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.ghostchu.quickshop.addon.reremakemigrator.migratecomponent; - -import com.dumptruckman.bukkit.configuration.json.JsonConfiguration; -import com.ghostchu.quickshop.QuickShop; -import com.ghostchu.quickshop.addon.reremakemigrator.Main; -import com.ghostchu.quickshop.util.ProgressMonitor; -import de.themoep.minedown.adventure.MineDown; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -public class TranslationMigrateComponent extends AbstractMigrateComponent { - - public TranslationMigrateComponent(Main main, QuickShop hikari, org.maxgamer.quickshop.QuickShop reremake, CommandSender sender) { - super(main, hikari, reremake, sender); - } - - @Override - public boolean migrate() { - text("modules.translation.start-migrate").send(); - File reremakeOverrideFolder = new File(getReremake().getDataFolder(), "overrides"); - if (!reremakeOverrideFolder.exists()) { - return true; - } - File[] fileTree = reremakeOverrideFolder.listFiles(); - if (fileTree == null) { - getHikari().logger().warn("Skipping translation migrate (no file tree)"); - return true; - } - - for (File langFolder : new ProgressMonitor<>(fileTree, (triple) -> text("modules.translation.migrate-entry", triple.getRight().getName(), triple.getLeft(), triple.getMiddle()))) { - File langJsonFile = new File(langFolder, "messages.json"); - if (!langJsonFile.exists()) { - continue; - } - try { - migrateFile(langFolder, langJsonFile); - } catch (Exception exception) { - getHikari().logger().warn("Failed migrate lang file " + langJsonFile.getName() + ".", exception); - } - } - return true; - } - - private void migrateFile(File langFolder, File langJsonFile) throws IOException { - File hikariOverrideFolder = new File(getHikari().getDataFolder(), "overrides"); - File targetLangFolder = new File(hikariOverrideFolder, langFolder.getName()); - if (!targetLangFolder.exists()) { - if (!targetLangFolder.mkdirs()) { - throw new IOException("Failed to create lang " + langFolder.getName() + " directory."); - } - } - JsonConfiguration jsonConfiguration = JsonConfiguration.loadConfiguration(langJsonFile); - YamlConfiguration yamlConfiguration = new YamlConfiguration(); - File targetLangFile = new File(targetLangFolder, langJsonFile.getName().replace(".json", ".yml")); - if (targetLangFile.exists()) { - yamlConfiguration = YamlConfiguration.loadConfiguration(targetLangFile); - } - getHikari().logger().info("Migrating the Reremake language file: " + langJsonFile.getAbsolutePath() + "..."); - Set keys = jsonConfiguration.getKeys(true); - text("modules.translation.copy-values", targetLangFolder.getName(), keys.size()).send(); - for (String key : new ProgressMonitor<>(keys, (triple) -> text("modules.translation.copying-value", triple.getRight(), triple.getLeft(), triple.getMiddle()).send())) { - if ("_comment".equals(key)) { - continue; - } - if (jsonConfiguration.isConfigurationSection(key)) { - continue; - } - if (jsonConfiguration.isString(key)) { - String originalValue = jsonConfiguration.getString(key); - Component component = MineDown.parse(originalValue).compact(); - String convertedValue = MiniMessage.miniMessage().serialize(component); - yamlConfiguration.set(key, convertedValue); - } else { - if (jsonConfiguration.isList(key)) { - List list = jsonConfiguration.getStringList(key); - List convert = new ArrayList<>(); - list.forEach(s -> { - Component component = MineDown.parse(s).compact(); - String convertedValue = MiniMessage.miniMessage().serialize(component); - convert.add(convertedValue); - }); - yamlConfiguration.set(key, convert); - } else { - yamlConfiguration.set(key, jsonConfiguration.get(key)); - } - } - } - if (!targetLangFile.exists()) { - if (!targetLangFile.createNewFile()) { - getHikari().logger().warn("Couldn't save converted data to file: file creation failed"); - return; - } - } - yamlConfiguration.save(targetLangFile); - } -} diff --git a/addon/reremake-migrator/src/main/resources/config.yml b/addon/reremake-migrator/src/main/resources/config.yml deleted file mode 100644 index fd2f6664d..000000000 --- a/addon/reremake-migrator/src/main/resources/config.yml +++ /dev/null @@ -1 +0,0 @@ -config-version: 1 \ No newline at end of file diff --git a/addon/reremake-migrator/src/main/resources/plugin.yml b/addon/reremake-migrator/src/main/resources/plugin.yml deleted file mode 100644 index 148e0d12f..000000000 --- a/addon/reremake-migrator/src/main/resources/plugin.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: qsaddon-reremakemigrator -version: '${project.version}' -main: com.ghostchu.quickshop.addon.reremakemigrator.Main -api-version: 1.18 -depend: - - QuickShop-Hikari - - QuickShop -authors: [ Ghost_chu ] -permissions: - quickshopaddon.reremakemigrator.migrator-admin: - default: op - description: Migrate from QuickShop-Reremake \ No newline at end of file diff --git a/addon/shopitemonly/pom.xml b/addon/shopitemonly/pom.xml deleted file mode 100644 index a3b581ced..000000000 --- a/addon/shopitemonly/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.addon - shopitemonly - jar - - Addon-ShopItemOnly - - Restrict only store items can be placed in store containers - - 17 - UTF-8 - - - - - dv8tion - m2-dv8tion - https://m2.dv8tion.net/releases - - - Scarsz-Nexus - https://nexus.scarsz.me/content/groups/public/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - - org.apache.commons - commons-lang3 - 3.14.0 - provided - - - - - - - - - diff --git a/addon/shopitemonly/src/main/java/com/ghostchu/quickshop/addon/shopitemonly/Main.java b/addon/shopitemonly/src/main/java/com/ghostchu/quickshop/addon/shopitemonly/Main.java index 36241abe9..59bf0f56a 100644 --- a/addon/shopitemonly/src/main/java/com/ghostchu/quickshop/addon/shopitemonly/Main.java +++ b/addon/shopitemonly/src/main/java/com/ghostchu/quickshop/addon/shopitemonly/Main.java @@ -2,6 +2,8 @@ package com.ghostchu.quickshop.addon.shopitemonly; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.shop.Shop; +import java.util.ArrayList; +import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -16,9 +18,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; -import java.util.ArrayList; -import java.util.List; - public final class Main extends JavaPlugin implements Listener { static Main instance; private QuickShop plugin; @@ -40,7 +39,6 @@ public final class Main extends JavaPlugin implements Listener { Bukkit.getPluginManager().registerEvents(this, this); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void invClose(InventoryCloseEvent event) { Inventory inventory = event.getInventory(); @@ -75,19 +73,21 @@ public final class Main extends JavaPlugin implements Listener { inventory.remove(item); invLocation.getWorld().dropItemNaturally(invLocation.add(0, 1, 0), item); } - plugin.text().of(event.getPlayer(), "addon.shopitemonly.message", pendingForRemoval.size()).send(); + plugin.text() + .of(event.getPlayer(), "addon.shopitemonly.message", pendingForRemoval.size()) + .send(); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void invMove(InventoryMoveItemEvent event) { - if (event.getDestination() == null) { //Stupid CMIGUI plugin + if (event.getDestination() == null) { // Stupid CMIGUI plugin return; } if (event.getDestination().getLocation() == null) { return; } - Shop shop = plugin.getShopManager().getShopIncludeAttached(event.getDestination().getLocation()); + Shop shop = plugin.getShopManager() + .getShopIncludeAttached(event.getDestination().getLocation()); if (shop == null) { return; } diff --git a/bootstrap.sh b/bootstrap.sh new file mode 100755 index 000000000..46a1e94bd --- /dev/null +++ b/bootstrap.sh @@ -0,0 +1,4 @@ +#!/usr/bin/bash + +# Fetch all submodule content. +git submodule update --force --recursive --init diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..f3176ec54 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,301 @@ +val quickshopVersion = "5.9" +val purpurApiVersion = "1.19.4-R0.1-SNAPSHOT" +val javaLanguageVersion = 17 +val jetbrainsAnnotationsVersion = "24.1.0" +val adventureApiVersion = "4.22.0" +val adventureExtraVersion = "4.2.0" +val adventurePlatformVersion = "4.3.2" +val viaversionApi = "4.3.0" + +plugins { + id("java-library") + id("io.freefair.lombok") version "8.14" apply false + id("com.gradleup.shadow") version "8.3.6" apply false + id("com.diffplug.spotless") version "7.0.4" +} + +subprojects { + apply(plugin = "java-library") + apply(plugin = "io.freefair.lombok") + apply(plugin = "com.diffplug.spotless") + apply(plugin = "com.gradleup.shadow") + apply(plugin = "eclipse") + + group = "com.ghostchu" + version = quickshopVersion + + java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(javaLanguageVersion)) + vendor.set(org.gradle.jvm.toolchain.JvmVendorSpec.GRAAL_VM) + } + } + + repositories { + mavenCentral() + maven("https://repo.viaversion.com") + maven("https://repo.purpurmc.org/snapshots") + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://repo.codemc.io/repository/maven-public/") + maven("https://repo.codemc.io/repository/nms/") + maven("https://repo.md-5.net/content/repositories/releases/") + maven("https://repo.md-5.net/content/repositories/snapshots/") + maven("https://repo.dmulloy2.net/repository/public/") + maven("https://repo.essentialsx.net/releases/") + maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") + maven("https://maven.enginehub.org/repo/") + maven("https://m2.dv8tion.net/releases") + maven("https://nexus.scarsz.me/content/groups/public/") + maven("https://www.jitpack.io") + } + + dependencies { compileOnly("org.jetbrains:annotations:$jetbrainsAnnotationsVersion") } + + if (path != ":libs:Utilities-OG") { + spotless { + java { + removeUnusedImports() + palantirJavaFormat() + } + kotlinGradle { + ktfmt().kotlinlangStyle().configure { it.setMaxWidth(120) } + target("build.gradle.kts", "settings.gradle.kts") + } + } + } + + tasks.withType().configureEach { + isPreserveFileTimestamps = false + isReproducibleFileOrder = true + } + tasks.withType().configureEach { + dependsOn("spotlessApply") + options.compilerArgs.addAll(listOf("-parameters", "-Xlint:deprecation")) + options.encoding = "UTF-8" + options.isFork = true + } +} + +project(":quickshop-common") { + dependencies { + api("net.kyori:adventure-api:$adventureApiVersion") + api("net.kyori:adventure-nbt:$adventureApiVersion") + api("com.ghostchu:simplereloadlib:1.1.2") + implementation("org.apache.commons:commons-lang3:3.14.0") + implementation("org.slf4j:slf4j-jdk14:2.0.9") + implementation("com.google.code.gson:gson:2.10.1") + api("cc.carm.lib:easysql-hikaricp:0.4.7") + api("org.apache.commons:commons-text:1.11.0") + api("org.apache.commons:commons-compress:1.25.0") + compileOnly("org.purpurmc.purpur:purpur-api:$purpurApiVersion") + compileOnlyApi(project(":libs:Utilities-OG")) + } +} + +project(":quickshop-api") { + dependencies { + api(project(":quickshop-common")) + implementation("com.vdurmont:semver4j:3.1.0") + compileOnly("cc.carm.lib:easysql-api:0.4.7") + compileOnly("org.purpurmc.purpur:purpur-api:$purpurApiVersion") + } +} + +val platformApi = "org.purpurmc.purpur:purpur-api:$purpurApiVersion" + +project(":platform:quickshop-platform-interface") { + dependencies { + api(project(":quickshop-common")) + compileOnly(platformApi) + compileOnly("de.tr7zw:item-nbt-api-plugin:2.12.1") + } +} + +project(":platform:quickshop-platform-spigot-abstract") { + dependencies { + api(project(":platform:quickshop-platform-interface")) + compileOnly(platformApi) + implementation("commons-lang:commons-lang:2.6") + compileOnly("de.tr7zw:item-nbt-api-plugin:2.12.1") + } +} + +project(":platform:quickshop-platform-paper") { + dependencies { + implementation(project(":platform:quickshop-platform-interface")) + compileOnly("io.papermc.paper:paper-api:$purpurApiVersion") + } +} + +listOf( + "v1_19_R1" to "1.19.1-R0.1-SNAPSHOT", + "v1_19_R2" to "1.19.3-R0.1-SNAPSHOT", + "v1_19_R3" to "1.19.4-R0.1-SNAPSHOT" +).forEach { (suffix, spigotVer) -> + project(":platform:quickshop-platform-spigot-$suffix") { + dependencies { + api(project(":platform:quickshop-platform-spigot-abstract")) + compileOnly("org.spigotmc:spigot:$spigotVer:remapped-mojang") + compileOnly("de.tr7zw:item-nbt-api-plugin:2.12.1") + } + } +} + +project(":quickshop-bukkit") { + tasks.processResources { + val versionString = project.version.toString() + val props = mapOf( + "version" to versionString, + "project" to mapOf("version" to versionString) + ) + inputs.properties(props) + filesMatching("plugin.yml") { expand(props) } + } + + dependencies { + implementation(project(":quickshop-api")) + implementation(project(":platform:quickshop-platform-spigot-abstract")) + implementation("com.ghostchu.crowdin:crowdinota:1.0.3") + compileOnly(project(":libs:Utilities-OG")) + listOf( + ":platform:quickshop-platform-spigot-v1_19_R1", + ":platform:quickshop-platform-spigot-v1_19_R2", + ":platform:quickshop-platform-spigot-v1_19_R3", + ":platform:quickshop-platform-paper" + ).forEach { implementation(project(it)) } + compileOnly(platformApi) + compileOnly("net.kyori:adventure-platform-bukkit:$adventurePlatformVersion") + compileOnly("net.kyori:adventure-platform-viaversion:$adventurePlatformVersion") + compileOnly("net.kyori:adventure-text-serializer-ansi:$adventureExtraVersion") + compileOnly("net.kyori:adventure-text-serializer-bungeecord:$adventureExtraVersion") + compileOnly("com.viaversion:viaversion-api:$viaversionApi") + compileOnly("com.h2database:h2:2.2.224") + compileOnly("com.comphenix.protocol:ProtocolLib:5.0.0") + compileOnly("com.github.MilkBowl:VaultAPI:1.7.1") + compileOnly("me.clip:placeholderapi:2.11.5") + compileOnly("net.tnemc:EconomyCore:0.1.2.6-Pre1") + compileOnly("net.tnemc:Reserve:0.1.5.3-SNAPSHOT-4") + compileOnly("org.bstats:bstats-bukkit:3.0.2") + compileOnly("com.konghq:unirest-java:3.14.5") + compileOnly("com.github.juliomarcopineda:jdbc-stream:0.1.1") + compileOnly("net.sourceforge.csvjdbc:csvjdbc:1.0.41") + compileOnly("org.dom4j:dom4j:2.1.4") + compileOnly("net.essentialsx:EssentialsX:2.20.1") + compileOnly("com.rollbar:rollbar-java:1.10.0") + compileOnly(files("lib/GemsEconomy-4.9.2.jar")) + } + + tasks.named("shadowJar") { + archiveClassifier.set("") + minimize() + relocate("io.papermc.lib", "com.ghostchu.quickshop.shade.io.papermc.lib") + relocate("de.tr7zw.changeme.nbtapi", "com.ghostchu.quickshop.shade.de.tr7zw.changeme.nbtapi") + relocate("org.bstats", "com.ghostchu.quickshop.shade.org.bstats") + relocate("de.themoep.minedown", "com.ghostchu.quickshop.shade.de.themoep.minedown") + manifest { attributes["Main-Class"] = "com.ghostchu.quickshop.bootstrap.Bootstrap" } + exclude( + "META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA", + "META-INF/*.kotlin_module", "META-INF/*.txt", + "META-INF/proguard/*", "META-INF/services/*", + "META-INF/versions/9/*", "*License*", "*LICENSE*" + ) + } + + tasks.named("jar") { archiveClassifier.set("original") } + + tasks.register("copyReleaseJar") { + dependsOn("shadowJar") + from(tasks.named("shadowJar").flatMap { it.archiveFile }) + into(layout.projectDirectory.dir("../target")) + } + + tasks.build { + dependsOn(tasks.spotlessApply) + dependsOn("shadowJar", "copyReleaseJar") + } +} + +val commonAddOnDeps = listOf( + platformApi, + "org.apache.commons:commons-lang3:3.14.0" +) + +project(":addon:bluemap") { + dependencies { + compileOnly(project(":quickshop-bukkit")) + compileOnly(project(":quickshop-api")) + compileOnly("com.github.BlueMap-Minecraft:BlueMapAPI:2.6.2") + commonAddOnDeps.forEach { compileOnly(it) } + } +} + +listOf("discount", "list", "shopitemonly").forEach { name -> + project(":addon:$name") { + dependencies { + compileOnly(project(":quickshop-bukkit")) + compileOnly(project(":quickshop-api")) + commonAddOnDeps.forEach { compileOnly(it) } + } + } +} + +project(":compatibility:common") { + dependencies { + compileOnly(platformApi) + api(project(":quickshop-common")) + compileOnly(project(":quickshop-api")) + compileOnly(project(":quickshop-bukkit")) + } +} + +project(":compatibility:clearlag") { + dependencies { + implementation(project(":compatibility:common")) + compileOnly(project(":quickshop-bukkit")) + compileOnly(platformApi) + compileOnly(files("lib/Clearlag-3.2.2.jar")) + } +} + +project(":compatibility:nocheatplus") { + dependencies { + implementation(project(":compatibility:common")) + compileOnly(project(":quickshop-bukkit")) + compileOnly(platformApi) + compileOnly(project(":quickshop-api")) + compileOnly("fr.neatmonster:nocheatplus:3.16.1-SNAPSHOT") + } +} + +project(":compatibility:openinv") { + dependencies { + implementation(project(":compatibility:common")) + compileOnly(project(":quickshop-bukkit")) + compileOnly(platformApi) + compileOnly(project(":quickshop-api")) + compileOnly("com.github.true-og.OpenInv:openinvapi:a85e8ebc28") + } +} + +project(":compatibility:worldedit") { + dependencies { + implementation(project(":compatibility:common")) + compileOnly(project(":quickshop-bukkit")) + compileOnly(project(":quickshop-api")) + compileOnly(platformApi) + compileOnly("com.sk89q.worldedit:worldedit-bukkit:7.2.17") + } +} + +project(":compatibility:worldguard") { + dependencies { + implementation(project(":compatibility:common")) + compileOnly(project(":quickshop-bukkit")) + compileOnly(project(":quickshop-api")) + compileOnly(platformApi) + compileOnly("com.sk89q.worldguard:worldguard-bukkit:7.0.8") + compileOnly("com.github.juliomarcopineda:jdbc-stream:0.1.1") + compileOnly("one.util:streamex:0.8.2") + } +} diff --git a/compatibility/.gitignore b/compatibility/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/compatibility/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/compatibility/clearlag/pom.xml b/compatibility/clearlag/pom.xml deleted file mode 100644 index a80092936..000000000 --- a/compatibility/clearlag/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.compatibility - clearlag - jar - - Compat-Clearlag - - Compatibility module for ClearLagg - - 17 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - src/main/resources - true - - - - - - - org.spigotmc - spigot-api - - - com.ghostchu.quickshop.compatibility - common - ${parent.version} - compile - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - me.minebuilders - clearlag - 3.2.2 - system - ${basedir}/lib/Clearlag-3.2.2.jar - - - diff --git a/compatibility/clearlag/src/main/java/com/ghostchu/quickshop/compatibility/clearlag/Main.java b/compatibility/clearlag/src/main/java/com/ghostchu/quickshop/compatibility/clearlag/Main.java index 9dd87ade7..2f69e3073 100644 --- a/compatibility/clearlag/src/main/java/com/ghostchu/quickshop/compatibility/clearlag/Main.java +++ b/compatibility/clearlag/src/main/java/com/ghostchu/quickshop/compatibility/clearlag/Main.java @@ -2,14 +2,13 @@ package com.ghostchu.quickshop.compatibility.clearlag; import com.ghostchu.quickshop.compatibility.CompatibilityModule; import com.ghostchu.quickshop.shop.display.AbstractDisplayItem; +import java.util.Iterator; import me.minebuilders.clearlag.events.EntityRemoveEvent; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import java.util.Iterator; - public final class Main extends CompatibilityModule implements Listener { @Override diff --git a/compatibility/common/pom.xml b/compatibility/common/pom.xml deleted file mode 100644 index db539e9e0..000000000 --- a/compatibility/common/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.compatibility - common - jar - - quickshop-compatibility-common - - Compatibility module for Commons - - 17 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - src/main/resources - true - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - diff --git a/compatibility/common/src/main/java/com/ghostchu/quickshop/compatibility/CompatibilityModule.java b/compatibility/common/src/main/java/com/ghostchu/quickshop/compatibility/CompatibilityModule.java index 5ba2a5279..f29367397 100644 --- a/compatibility/common/src/main/java/com/ghostchu/quickshop/compatibility/CompatibilityModule.java +++ b/compatibility/common/src/main/java/com/ghostchu/quickshop/compatibility/CompatibilityModule.java @@ -7,6 +7,9 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.logging.container.ShopRemoveLog; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.event.EventHandler; @@ -18,10 +21,6 @@ import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - public abstract class CompatibilityModule extends JavaPlugin implements Listener { private QuickShopAPI api; diff --git a/compatibility/nocheatplus/pom.xml b/compatibility/nocheatplus/pom.xml deleted file mode 100644 index 30a692b62..000000000 --- a/compatibility/nocheatplus/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.compatibility - nocheatplus - jar - - Compat-NoCheatPlus - - - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - src/main/resources - true - - - - - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - codemc-releases - https://repo.codemc.io/repository/maven-releases/ - - - md_5-snapshots - https://repo.md-5.net/content/repositories/snapshots/ - - - - - - org.spigotmc - spigot-api - - - fr.neatmonster - nocheatplus - 3.16.1-SNAPSHOT - provided - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - com.ghostchu.quickshop.compatibility - common - ${parent.version} - compile - - - diff --git a/compatibility/nocheatplus/src/main/java/com/ghostchu/quickshop/compatibility/nocheatplus/Main.java b/compatibility/nocheatplus/src/main/java/com/ghostchu/quickshop/compatibility/nocheatplus/Main.java index 92dc17e1f..e8542a7f3 100644 --- a/compatibility/nocheatplus/src/main/java/com/ghostchu/quickshop/compatibility/nocheatplus/Main.java +++ b/compatibility/nocheatplus/src/main/java/com/ghostchu/quickshop/compatibility/nocheatplus/Main.java @@ -9,9 +9,7 @@ import org.bukkit.event.Listener; public final class Main extends CompatibilityModule implements Listener { @Override - public void init() { - - } + public void init() {} @EventHandler(ignoreCancelled = true) public void onFakeEventBegin(ShopProtectionCheckEvent event) { diff --git a/compatibility/openinv/pom.xml b/compatibility/openinv/pom.xml deleted file mode 100644 index feaac9a8f..000000000 --- a/compatibility/openinv/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.compatibility - openinv - jar - - Compat-OpenInv - - - 17 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - jitpack.io - https://www.jitpack.io - - - - - - org.spigotmc - spigot-api - - - com.github.true-og.OpenInv - openinvapi - a85e8ebc28 - provided - - - com.ghostchu.quickshop.compatibility - common - ${parent.version} - compile - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - diff --git a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/EnderChestWrapper.java b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/EnderChestWrapper.java index 365069897..2194b9f1f 100644 --- a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/EnderChestWrapper.java +++ b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/EnderChestWrapper.java @@ -5,6 +5,7 @@ import com.ghostchu.quickshop.api.inventory.InventoryWrapperIterator; import com.ghostchu.quickshop.api.inventory.InventoryWrapperManager; import com.ghostchu.quickshop.api.inventory.InventoryWrapperType; import com.lishid.openinv.IOpenInv; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.OfflinePlayer; @@ -14,8 +15,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - public class EnderChestWrapper implements InventoryWrapper { private final UUID uuid; private final Player player; @@ -26,7 +25,6 @@ public class EnderChestWrapper implements InventoryWrapper { this.uuid = uuid; OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); this.player = iOpenInv.loadPlayer(offlinePlayer); - } public UUID getUuid() { diff --git a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/Main.java b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/Main.java index fe9bde7c8..cfa735c0a 100644 --- a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/Main.java +++ b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/Main.java @@ -30,7 +30,14 @@ public final class Main extends CompatibilityModule implements Listener { @Override public void onEnable() { super.onEnable(); - getApi().getCommandManager().registerCmd(CommandContainer.builder().prefix("echest").permission("quickshop.echest").description((locale) -> LegacyComponentSerializer.legacySection().deserialize(getConfig().getString("messages.description"))).executor(new OpenInvCommand(this)).build()); + getApi().getCommandManager() + .registerCmd(CommandContainer.builder() + .prefix("echest") + .permission("quickshop.echest") + .description((locale) -> LegacyComponentSerializer.legacySection() + .deserialize(getConfig().getString("messages.description"))) + .executor(new OpenInvCommand(this)) + .build()); } @Override diff --git a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvCommand.java b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvCommand.java index c25542a8f..b817aafbc 100644 --- a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvCommand.java +++ b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvCommand.java @@ -5,14 +5,13 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.shop.inventory.BukkitInventoryWrapper; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; - public class OpenInvCommand implements CommandHandler { private final Main plugin; @@ -34,16 +33,27 @@ public class OpenInvCommand implements CommandHandler { plugin.getApi().getTextManager().of(sender, "not-looking-at-shop").send(); return; } - if (!sender.getUniqueId().equals(shop.getOwner().getUniqueId()) && !QuickShop.getPermissionManager().hasPermission(sender, "quickshop.admin")) { + if (!sender.getUniqueId().equals(shop.getOwner().getUniqueId()) + && !QuickShop.getPermissionManager().hasPermission(sender, "quickshop.admin")) { plugin.getApi().getTextManager().of(sender, "no-permission").send(); return; } if (shop.getInventory() instanceof EnderChestWrapper) { - shop.setInventory(new BukkitInventoryWrapper((((InventoryHolder) shop.getLocation().getBlock().getState()).getInventory())), plugin.getApi().getInventoryWrapperRegistry().get("QuickShop-Hikari")); - sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.to-chest"))); + shop.setInventory( + new BukkitInventoryWrapper( + (((InventoryHolder) shop.getLocation().getBlock().getState()).getInventory())), + plugin.getApi().getInventoryWrapperRegistry().get("QuickShop-Hikari")); + sender.sendMessage(ChatColor.translateAlternateColorCodes( + '&', plugin.getConfig().getString("messages.to-chest"))); } else { - shop.setInventory(new EnderChestWrapper(shop.getOwner().getUniqueIdIfRealPlayer().orElse(CommonUtil.getNilUniqueId()), plugin.getOpenInv(), plugin), plugin.getManager()); - sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.to-echest"))); + shop.setInventory( + new EnderChestWrapper( + shop.getOwner().getUniqueIdIfRealPlayer().orElse(CommonUtil.getNilUniqueId()), + plugin.getOpenInv(), + plugin), + plugin.getManager()); + sender.sendMessage(ChatColor.translateAlternateColorCodes( + '&', plugin.getConfig().getString("messages.to-echest"))); } } @@ -56,7 +66,8 @@ public class OpenInvCommand implements CommandHandler { * @return Candidate list */ @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { return CommandHandler.super.onTabComplete(sender, commandLabel, cmdArg); } } diff --git a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvInventoryManager.java b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvInventoryManager.java index 61469364f..33e91b59f 100644 --- a/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvInventoryManager.java +++ b/compatibility/openinv/src/main/java/com/ghostchu/quickshop/compatibility/openinv/OpenInvInventoryManager.java @@ -3,9 +3,8 @@ package com.ghostchu.quickshop.compatibility.openinv; import com.ghostchu.quickshop.api.inventory.InventoryWrapper; import com.ghostchu.quickshop.api.inventory.InventoryWrapperManager; import com.lishid.openinv.IOpenInv; -import org.jetbrains.annotations.NotNull; - import java.util.UUID; +import org.jetbrains.annotations.NotNull; public class OpenInvInventoryManager implements InventoryWrapperManager { private final IOpenInv openInv; @@ -42,6 +41,7 @@ public class OpenInvInventoryManager implements InventoryWrapperManager { if (wrapper instanceof EnderChestWrapper wrap) { return wrap.getUuid().toString(); } - throw new IllegalArgumentException("Cannot create symbol link for target Inventory: " + wrapper.getClass().getName()); + throw new IllegalArgumentException("Cannot create symbol link for target Inventory: " + + wrapper.getClass().getName()); } } diff --git a/compatibility/worldedit/pom.xml b/compatibility/worldedit/pom.xml deleted file mode 100644 index 615523004..000000000 --- a/compatibility/worldedit/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.compatibility - worldedit - jar - - Compat-WorldEdit - - - 17 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - src/main/resources - true - - - - - - - enginehub-repo - https://maven.enginehub.org/repo/ - - - - - - org.spigotmc - spigot-api - - - com.sk89q.worldedit - worldedit-bukkit - 7.2.17 - provided - - - org.bstats - * - - - - - com.ghostchu.quickshop.compatibility - common - ${parent.version} - compile - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - diff --git a/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/Main.java b/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/Main.java index 3e3d10271..55e8fca08 100644 --- a/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/Main.java +++ b/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/Main.java @@ -17,7 +17,8 @@ public final class Main extends CompatibilityModule implements Listener { @Override public void onEnable() { // Plugin startup logic - WorldEditPlugin worldEditPlugin = (WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"); + WorldEditPlugin worldEditPlugin = + (WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"); adapter = new WorldEditAdapter(worldEditPlugin); Bukkit.getPluginManager().registerEvents(adapter, this); super.onEnable(); @@ -27,5 +28,4 @@ public final class Main extends CompatibilityModule implements Listener { public void init() { // There no init stuffs need to do } - } diff --git a/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditAdapter.java b/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditAdapter.java index cd6b034fd..4cb4aed5f 100644 --- a/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditAdapter.java +++ b/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditAdapter.java @@ -33,6 +33,4 @@ public class WorldEditAdapter implements Listener { public void unregister() { weBukkit.getWorldEdit().getEventBus().unregister(this); } - - } diff --git a/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditBlockListener.java b/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditBlockListener.java index 2416a6d0b..aa509bedd 100644 --- a/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditBlockListener.java +++ b/compatibility/worldedit/src/main/java/com/ghostchu/quickshop/compatibility/worldedit/WorldEditBlockListener.java @@ -36,7 +36,8 @@ public class WorldEditBlockListener extends AbstractDelegateExtent { } @Override - public > boolean setBlock(final BlockVector3 position, final T block) throws WorldEditException { + public > boolean setBlock(final BlockVector3 position, final T block) + throws WorldEditException { if (!(this.world instanceof BukkitWorld)) { return super.setBlock(position, block); } @@ -48,11 +49,19 @@ public class WorldEditBlockListener extends AbstractDelegateExtent { if (extent.setBlock(position, block)) { // Block Changed - if (oldBlock.getBlockType().getMaterial().hasContainer() && !newBlock.getBlockType().getMaterial().hasContainer()) { - Shop shop = api.getShopManager().getShop(location, true); // Because WorldEdit can only remove half of shop, so we can keep another half as shop if it is doublechest shop. + if (oldBlock.getBlockType().getMaterial().hasContainer() + && !newBlock.getBlockType().getMaterial().hasContainer()) { + Shop shop = api.getShopManager() + .getShop( + location, + true); // Because WorldEdit can only remove half of shop, so we can keep another half as + // shop if it is doublechest shop. if (shop != null) { Util.mainThreadRun(() -> { - api.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "WorldEdit", false), "WorldEdit", shop.saveToInfoStorage())); + api.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "WorldEdit", false), + "WorldEdit", + shop.saveToInfoStorage())); api.getShopManager().deleteShop(shop); }); } diff --git a/compatibility/worldguard/pom.xml b/compatibility/worldguard/pom.xml deleted file mode 100644 index 8ca861dcf..000000000 --- a/compatibility/worldguard/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - com.ghostchu.quickshop.compatibility - worldguard - jar - - Compat-WorldGuard - - - 17 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - enginehub-repo - https://maven.enginehub.org/repo/ - - - - - - org.spigotmc - spigot-api - - - com.sk89q.worldguard - worldguard-bukkit - 7.0.9 - provided - - - com.ghostchu.quickshop.compatibility - common - ${parent.version} - compile - - - com.ghostchu - quickshop-bukkit - ${parent.version} - provided - - - com.github.juliomarcopineda - jdbc-stream - 0.1.1 - provided - - - one.util - streamex - 0.8.2 - provided - - - diff --git a/compatibility/worldguard/src/main/java/com/ghostchu/quickshop/compatibility/worldguard/Main.java b/compatibility/worldguard/src/main/java/com/ghostchu/quickshop/compatibility/worldguard/Main.java index 57ccb546e..a2324c0af 100644 --- a/compatibility/worldguard/src/main/java/com/ghostchu/quickshop/compatibility/worldguard/Main.java +++ b/compatibility/worldguard/src/main/java/com/ghostchu/quickshop/compatibility/worldguard/Main.java @@ -22,6 +22,8 @@ import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionContainer; import com.sk89q.worldguard.protection.regions.RegionQuery; +import java.util.*; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; @@ -29,9 +31,6 @@ import org.bukkit.World; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import java.util.*; -import java.util.logging.Level; - public final class Main extends CompatibilityModule implements Listener { private StateFlag createFlag; private StateFlag tradeFlag; @@ -43,8 +42,10 @@ public final class Main extends CompatibilityModule implements Listener { FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); try { // create a flag with the name "my-custom-flag", defaulting to true - StateFlag createFlag = new StateFlag("quickshophikari-create", getConfig().getBoolean("create.default-allow", false)); - StateFlag tradeFlag = new StateFlag("quickshophikari-trade", getConfig().getBoolean("trade.default-allow", true)); + StateFlag createFlag = + new StateFlag("quickshophikari-create", getConfig().getBoolean("create.default-allow", false)); + StateFlag tradeFlag = + new StateFlag("quickshophikari-trade", getConfig().getBoolean("trade.default-allow", true)); registry.register(createFlag); registry.register(tradeFlag); this.createFlag = createFlag; @@ -73,7 +74,6 @@ public final class Main extends CompatibilityModule implements Listener { super.onLoad(); } - @Override public void init() { // There no init stuffs need to do @@ -87,10 +87,12 @@ public final class Main extends CompatibilityModule implements Listener { if (manager == null) { return; } - ApplicableRegionSet set = manager.getApplicableRegions(BlockVector3.at(shopLoc.getX(), shopLoc.getY(), shopLoc.getZ())); + ApplicableRegionSet set = + manager.getApplicableRegions(BlockVector3.at(shopLoc.getX(), shopLoc.getY(), shopLoc.getZ())); for (ProtectedRegion region : set.getRegions()) { if (region.getOwners().contains(event.getAuthorizer())) { - if (event.getNamespace().equals(QuickShop.getInstance().getJavaPlugin()) && event.getPermission().equals(BuiltInShopPermission.DELETE.getRawNode())) { + if (event.getNamespace().equals(QuickShop.getInstance().getJavaPlugin()) + && event.getPermission().equals(BuiltInShopPermission.DELETE.getRawNode())) { event.setResult(true); } } @@ -104,10 +106,13 @@ public final class Main extends CompatibilityModule implements Listener { RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionQuery query = container.createQuery(); if (!query.testState(BukkitAdapter.adapt(event.getLocation()), localPlayer, this.createFlag)) { - event.setCancelled(true, getApi().getTextManager().of(event.getCreator(), "addon.worldguard.creation-flag-test-failed").forLocale()); + event.setCancelled( + true, + getApi().getTextManager() + .of(event.getCreator(), "addon.worldguard.creation-flag-test-failed") + .forLocale()); } }); - } @EventHandler(ignoreCancelled = true) @@ -117,15 +122,27 @@ public final class Main extends CompatibilityModule implements Listener { RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionQuery query = container.createQuery(); if (!query.testState(BukkitAdapter.adapt(event.getShop().getLocation()), localPlayer, this.createFlag)) { - event.setCancelled(true, getApi().getTextManager().of(event.getCreator(), "addon.worldguard.creation-flag-test-failed").forLocale()); + event.setCancelled( + true, + getApi().getTextManager() + .of(event.getCreator(), "addon.worldguard.creation-flag-test-failed") + .forLocale()); return; } - Set regions = container.createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getShop().getLocation())).getRegions(); + Set regions = container + .createQuery() + .getApplicableRegions(BukkitAdapter.adapt(event.getShop().getLocation())) + .getRegions(); List shops = new ArrayList<>(); - regions.forEach(r -> shops.addAll(getRegionShops(r, event.getShop().getLocation().getWorld()).values())); + regions.forEach(r -> shops.addAll( + getRegionShops(r, event.getShop().getLocation().getWorld()).values())); if (limitPerRegion > 0) { if (shops.size() + 1 > limitPerRegion) { - event.setCancelled(true, getApi().getTextManager().of(event.getCreator(), "addon.worldguard.reached-per-region-amount-limit").forLocale()); + event.setCancelled( + true, + getApi().getTextManager() + .of(event.getCreator(), "addon.worldguard.reached-per-region-amount-limit") + .forLocale()); } } }); @@ -160,7 +177,11 @@ public final class Main extends CompatibilityModule implements Listener { RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionQuery query = container.createQuery(); if (!query.testState(BukkitAdapter.adapt(event.getShop().getLocation()), localPlayer, this.tradeFlag)) { - event.setCancelled(true, getApi().getTextManager().of(event.getPurchaser(), "addon.worldguard.trade-flag-test-failed").forLocale()); + event.setCancelled( + true, + getApi().getTextManager() + .of(event.getPurchaser(), "addon.worldguard.trade-flag-test-failed") + .forLocale()); } }); } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..ff23a68d7 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..23d15a936 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/HEAD/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# 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="\\\"\\\"" + + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..5eed7ee84 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/libs/.gitignore b/libs/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/libs/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/libs/Utilities-OG b/libs/Utilities-OG new file mode 160000 index 000000000..e68d3fec7 --- /dev/null +++ b/libs/Utilities-OG @@ -0,0 +1 @@ +Subproject commit e68d3fec7a08ffb7f5850b06df963b34802b3dbf diff --git a/mvnw b/mvnw deleted file mode 100755 index 19529ddf8..000000000 --- a/mvnw +++ /dev/null @@ -1,259 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.2 -# -# Optional ENV vars -# ----------------- -# JAVA_HOME - location of a JDK home dir, required when download maven via java source -# MVNW_REPOURL - repo url base for downloading maven distribution -# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output -# ---------------------------------------------------------------------------- - -set -euf -[ "${MVNW_VERBOSE-}" != debug ] || set -x - -# OS specific support. -native_path() { printf %s\\n "$1"; } -case "$(uname)" in -CYGWIN* | MINGW*) - [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" - native_path() { cygpath --path --windows "$1"; } - ;; -esac - -# set JAVACMD and JAVACCMD -set_java_home() { - # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched - 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" - JAVACCMD="$JAVA_HOME/jre/sh/javac" - else - JAVACMD="$JAVA_HOME/bin/java" - JAVACCMD="$JAVA_HOME/bin/javac" - - if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then - echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 - echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 - return 1 - fi - fi - else - JAVACMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v java - )" || : - JAVACCMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v javac - )" || : - - if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then - echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 - return 1 - fi - fi -} - -# hash string like Java String::hashCode -hash_string() { - str="${1:-}" h=0 - while [ -n "$str" ]; do - char="${str%"${str#?}"}" - h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) - str="${str#?}" - done - printf %x\\n $h -} - -verbose() { :; } -[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - -die() { - printf %s\\n "$1" >&2 - exit 1 -} - -trim() { - # MWRAPPER-139: - # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. - # Needed for removing poorly interpreted newline sequences when running in more - # exotic environments such as mingw bash on Windows. - printf "%s" "${1}" | tr -d '[:space:]' -} - -# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties -while IFS="=" read -r key value; do - case "${key-}" in - distributionUrl) distributionUrl=$(trim "${value-}") ;; - distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; - esac -done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" - -case "${distributionUrl##*/}" in -maven-mvnd-*bin.*) - MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ - case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in - *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; - :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; - :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; - :Linux*x86_64*) distributionPlatform=linux-amd64 ;; - *) - echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 - distributionPlatform=linux-amd64 - ;; - esac - distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" - ;; -maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" -distributionUrlName="${distributionUrl##*/}" -distributionUrlNameMain="${distributionUrlName%.*}" -distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" -MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" - -exec_maven() { - unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : - exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" -} - -if [ -d "$MAVEN_HOME" ]; then - verbose "found existing MAVEN_HOME at $MAVEN_HOME" - exec_maven "$@" -fi - -case "${distributionUrl-}" in -*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; -*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; -esac - -# prepare tmp dir -if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then - clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } - trap clean HUP INT TERM EXIT -else - die "cannot create temp dir" -fi - -mkdir -p -- "${MAVEN_HOME%/*}" - -# Download and Install Apache Maven -verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -verbose "Downloading from: $distributionUrl" -verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -# select .zip or .tar.gz -if ! command -v unzip >/dev/null; then - distributionUrl="${distributionUrl%.zip}.tar.gz" - distributionUrlName="${distributionUrl##*/}" -fi - -# verbose opt -__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' -[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v - -# normalize http auth -case "${MVNW_PASSWORD:+has-password}" in -'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; -has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; -esac - -if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then - verbose "Found wget ... using wget" - wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" -elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then - verbose "Found curl ... using curl" - curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" -elif set_java_home; then - verbose "Falling back to use Java to download" - javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" - targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" - cat >"$javaSource" <<-END - public class Downloader extends java.net.Authenticator - { - protected java.net.PasswordAuthentication getPasswordAuthentication() - { - return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); - } - public static void main( String[] args ) throws Exception - { - setDefault( new Downloader() ); - java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); - } - } - END - # For Cygwin/MinGW, switch paths to Windows format before running javac and java - verbose " - Compiling Downloader.java ..." - "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" - verbose " - Running Downloader.java ..." - "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" -fi - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -if [ -n "${distributionSha256Sum-}" ]; then - distributionSha256Result=false - if [ "$MVN_CMD" = mvnd.sh ]; then - echo "Checksum validation is not supported for maven-mvnd." >&2 - echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - elif command -v sha256sum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - elif command -v shasum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - else - echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 - echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - fi - if [ $distributionSha256Result = false ]; then - echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 - echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 - exit 1 - fi -fi - -# unzip and move -if command -v unzip >/dev/null; then - unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" -else - tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" -fi -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd deleted file mode 100644 index b150b91ed..000000000 --- a/mvnw.cmd +++ /dev/null @@ -1,149 +0,0 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.2 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' -$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" -if ($env:MAVEN_USER_HOME) { - $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" -} -$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/platform/.gitignore b/platform/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-interface/.gitignore b/platform/quickshop-platform-interface/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/quickshop-platform-interface/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-interface/pom.xml b/platform/quickshop-platform-interface/pom.xml deleted file mode 100644 index 3edcfee13..000000000 --- a/platform/quickshop-platform-interface/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - - quickshop-platform-interface - jar - - quickshop-platform-interface - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - src/main/resources - true - - - - - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-common - ${parent.version} - compile - - - de.tr7zw - item-nbt-api-plugin - 2.12.1 - provided - - - * - * - - - - - diff --git a/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Platform.java b/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Platform.java index eabb760f7..9152a91a7 100644 --- a/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Platform.java +++ b/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Platform.java @@ -1,6 +1,9 @@ package com.ghostchu.quickshop.platform; import de.tr7zw.nbtapi.NBTItem; +import java.util.Collection; +import java.util.List; +import java.util.Map; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.minimessage.MiniMessage; @@ -21,16 +24,14 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; -import java.util.Collection; -import java.util.List; -import java.util.Map; - public interface Platform { void shutdown(); - @NotNull Component getDisplayName(@NotNull ItemStack stack); + @NotNull + Component getDisplayName(@NotNull ItemStack stack); - @Nullable Component getDisplayName(@NotNull ItemMeta meta); + @Nullable + Component getDisplayName(@NotNull ItemMeta meta); @Nullable default String getItemShopId(@NotNull ItemStack stack) { @@ -45,43 +46,60 @@ public interface Platform { return shopId; } - @NotNull HoverEvent getItemStackHoverEvent(@NotNull ItemStack stack); + @NotNull + HoverEvent getItemStackHoverEvent(@NotNull ItemStack stack); - @NotNull Component getLine(@NotNull Sign sign, int line); + @NotNull + Component getLine(@NotNull Sign sign, int line); - @Nullable List getLore(@NotNull ItemStack stack); + @Nullable + List getLore(@NotNull ItemStack stack); - @Nullable List getLore(@NotNull ItemMeta meta); + @Nullable + List getLore(@NotNull ItemMeta meta); - @NotNull String getMinecraftVersion(); + @NotNull + String getMinecraftVersion(); - @NotNull Component getTranslation(@NotNull Material material); + @NotNull + Component getTranslation(@NotNull Material material); - @NotNull Component getTranslation(@NotNull EntityType entity); + @NotNull + Component getTranslation(@NotNull EntityType entity); - @NotNull Component getTranslation(@NotNull PotionEffectType potionEffectType); + @NotNull + Component getTranslation(@NotNull PotionEffectType potionEffectType); - @NotNull Component getTranslation(@NotNull Enchantment enchantment); + @NotNull + Component getTranslation(@NotNull Enchantment enchantment); - @NotNull Component getTranslation(@NotNull ItemStack itemStack); + @NotNull + Component getTranslation(@NotNull ItemStack itemStack); - @NotNull String getTranslationKey(@NotNull Material material); + @NotNull + String getTranslationKey(@NotNull Material material); - @NotNull String getTranslationKey(@NotNull EntityType entity); + @NotNull + String getTranslationKey(@NotNull EntityType entity); - @NotNull String getTranslationKey(@NotNull PotionEffectType potionEffectType); + @NotNull + String getTranslationKey(@NotNull PotionEffectType potionEffectType); - @NotNull String getTranslationKey(@NotNull Enchantment enchantment); + @NotNull + String getTranslationKey(@NotNull Enchantment enchantment); - @NotNull String getTranslationKey(@NotNull ItemStack stack); + @NotNull + String getTranslationKey(@NotNull ItemStack stack); - @NotNull MiniMessage miniMessage(); + @NotNull + MiniMessage miniMessage(); void registerCommand(@NotNull String prefix, @NotNull Command command); void sendMessage(@NotNull CommandSender sender, @NotNull Component component); - void sendSignTextChange(@NotNull Player player, @NotNull Sign sign, boolean glowing, @NotNull List components); + void sendSignTextChange( + @NotNull Player player, @NotNull Sign sign, boolean glowing, @NotNull List components); void setDisplayName(@NotNull ItemStack stack, @Nullable Component component); @@ -93,5 +111,6 @@ public interface Platform { void updateTranslationMappingSection(@NotNull Map mapping); - @NotNull Logger getSlf4jLogger(@NotNull Plugin parent); + @NotNull + Logger getSlf4jLogger(@NotNull Plugin parent); } diff --git a/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Util.java b/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Util.java index 4c009bd3b..7c4b39a25 100644 --- a/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Util.java +++ b/platform/quickshop-platform-interface/src/main/java/com/ghostchu/quickshop/platform/Util.java @@ -2,8 +2,7 @@ package com.ghostchu.quickshop.platform; public class Util { - private Util() { - } + private Util() {} public static boolean methodExists(Class clazz, String methodName) { try { diff --git a/platform/quickshop-platform-paper/.gitignore b/platform/quickshop-platform-paper/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/quickshop-platform-paper/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-paper/pom.xml b/platform/quickshop-platform-paper/pom.xml deleted file mode 100644 index f084d6b3a..000000000 --- a/platform/quickshop-platform-paper/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - - quickshop-platform-paper - jar - quickshop-platform-paper - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - - src/main/resources - true - - - - - - - papermc - https://repo.papermc.io/repository/maven-public/ - - - - - - com.ghostchu - quickshop-platform-interface - ${parent.version} - compile - - - io.papermc.paper - paper-api - 1.19.4-R0.1-SNAPSHOT - provided - - - diff --git a/platform/quickshop-platform-paper/src/main/java/com/ghostchu/quickshop/platform/paper/PaperPlatform.java b/platform/quickshop-platform-paper/src/main/java/com/ghostchu/quickshop/platform/paper/PaperPlatform.java index efd6117a1..442da7988 100644 --- a/platform/quickshop-platform-paper/src/main/java/com/ghostchu/quickshop/platform/paper/PaperPlatform.java +++ b/platform/quickshop-platform-paper/src/main/java/com/ghostchu/quickshop/platform/paper/PaperPlatform.java @@ -2,6 +2,7 @@ package com.ghostchu.quickshop.platform.paper; import com.ghostchu.quickshop.common.util.QuickSLF4JLogger; import com.ghostchu.quickshop.platform.Platform; +import java.util.*; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.minimessage.MiniMessage; @@ -22,8 +23,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; -import java.util.*; - @SuppressWarnings("removal") public class PaperPlatform implements Platform { @@ -34,9 +33,7 @@ public class PaperPlatform implements Platform { } @Override - public void shutdown() { - - } + public void shutdown() {} @Override public @NotNull Component getDisplayName(@NotNull ItemStack stack) { @@ -169,7 +166,8 @@ public class PaperPlatform implements Platform { } @Override - public void sendSignTextChange(@NotNull Player player, @NotNull Sign sign, boolean glowing, @NotNull List components) { + public void sendSignTextChange( + @NotNull Player player, @NotNull Sign sign, boolean glowing, @NotNull List components) { player.sendSignChange(sign.getLocation(), components); } @@ -185,7 +183,6 @@ public class PaperPlatform implements Platform { stack.customName(component); } - @Override public void setLines(@NotNull Sign sign, @NotNull List component) { for (int i = 0; i < Math.min(component.size(), 4); i++) { @@ -199,7 +196,6 @@ public class PaperPlatform implements Platform { stack.lore(new ArrayList<>(components)); } - @Override public void updateTranslationMappingSection(@NotNull Map mapping) { this.translationMapping = mapping; diff --git a/platform/quickshop-platform-spigot-abstract/.gitignore b/platform/quickshop-platform-spigot-abstract/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/quickshop-platform-spigot-abstract/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-spigot-abstract/pom.xml b/platform/quickshop-platform-spigot-abstract/pom.xml deleted file mode 100644 index 3b410e8e5..000000000 --- a/platform/quickshop-platform-spigot-abstract/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - - quickshop-platform-spigot-abstract - jar - - quickshop-platform-spigot-abstract - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - src/main/resources - true - - - - - - - codemc-repo - https://repo.codemc.org/repository/maven-public/ - - - - - - com.ghostchu - quickshop-platform-interface - ${parent.version} - compile - - - org.spigotmc - spigot-api - - - - commons-lang - commons-lang - 2.6 - compile - - - de.tr7zw - item-nbt-api-plugin - 2.12.1 - provided - - - * - * - - - - - diff --git a/platform/quickshop-platform-spigot-abstract/src/main/java/com/ghostchu/quickshop/platform/spigot/AbstractSpigotPlatform.java b/platform/quickshop-platform-spigot-abstract/src/main/java/com/ghostchu/quickshop/platform/spigot/AbstractSpigotPlatform.java index a450929a8..2be285fd0 100644 --- a/platform/quickshop-platform-spigot-abstract/src/main/java/com/ghostchu/quickshop/platform/spigot/AbstractSpigotPlatform.java +++ b/platform/quickshop-platform-spigot-abstract/src/main/java/com/ghostchu/quickshop/platform/spigot/AbstractSpigotPlatform.java @@ -5,12 +5,15 @@ import com.ghostchu.quickshop.platform.Platform; import de.tr7zw.nbtapi.NBT; import de.tr7zw.nbtapi.iface.ReadWriteNBT; import de.tr7zw.nbtapi.iface.ReadWriteNBTList; -import net.kyori.adventure.platform.bukkit.BukkitAudiences; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.logging.Logger; +import java.util.stream.Collectors; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.trueog.utilitiesog.UtilitiesOG; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Sign; @@ -26,25 +29,14 @@ import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; -import java.util.stream.Collectors; - public abstract class AbstractSpigotPlatform implements Platform { protected final Logger logger = Logger.getLogger("QuickShop-Hikari"); - private final Plugin plugin; protected Map translationMapping; - private BukkitAudiences audience; public AbstractSpigotPlatform(@NotNull Plugin instance) { - this.plugin = instance; - //TODO use method to replace if (Bukkit.getPluginManager().getPlugin("NBTAPI") == null) { throw new IllegalStateException("Must install NBT-API if you're running on Spigot server"); } - //this.translationMapping = mapping; } @NotNull @@ -55,8 +47,8 @@ public abstract class AbstractSpigotPlatform implements Platform { @Override public @NotNull Component getDisplayName(@NotNull ItemStack stack) { - if (stack.getItemMeta() != null) { - return LegacyComponentSerializer.legacySection().deserialize(stack.getItemMeta().getDisplayName()); + if (stack.getItemMeta() != null && stack.getItemMeta().hasDisplayName()) { + return stack.getItemMeta().displayName(); } return Component.empty(); } @@ -64,33 +56,28 @@ public abstract class AbstractSpigotPlatform implements Platform { @Override public @NotNull Component getDisplayName(@NotNull ItemMeta meta) { if (meta.hasDisplayName()) { - return LegacyComponentSerializer.legacySection().deserialize(meta.getDisplayName()); + return meta.displayName(); } return Component.empty(); } @Override public @NotNull Component getLine(@NotNull Sign sign, int line) { - return LegacyComponentSerializer.legacySection().deserialize(sign.getLine(line)); + return UtilitiesOG.trueogColorize(sign.getLine(line)); } @Override public @Nullable List getLore(@NotNull ItemStack stack) { - if (!stack.hasItemMeta()) { - return null; - } - if (!stack.getItemMeta().hasLore()) { - return null; - } - return stack.getItemMeta().getLore().stream().map(LegacyComponentSerializer.legacySection()::deserialize).collect(Collectors.toList()); + if (!stack.hasItemMeta()) return null; + ItemMeta meta = stack.getItemMeta(); + if (!meta.hasLore()) return null; + return meta.getLore().stream().map(UtilitiesOG::trueogColorize).collect(Collectors.toList()); } @Override public @Nullable List getLore(@NotNull ItemMeta meta) { - if (!meta.hasLore()) { - return null; - } - return meta.getLore().stream().map(LegacyComponentSerializer.legacySection()::deserialize).collect(Collectors.toList()); + if (!meta.hasLore()) return null; + return meta.getLore().stream().map(UtilitiesOG::trueogColorize).collect(Collectors.toList()); } @Override @@ -119,80 +106,57 @@ public abstract class AbstractSpigotPlatform implements Platform { } @Override - public @NotNull MiniMessage miniMessage() { + public MiniMessage miniMessage() { return MiniMessage.miniMessage(); } - @Override public void sendMessage(@NotNull CommandSender sender, @NotNull Component component) { - if (this.audience == null) { - this.audience = BukkitAudiences.create(this.plugin); - } - //this.audience.sender(sender).sendMessage(component); - sender.spigot().sendMessage(BungeeComponentSerializer.get().serialize(component)); + sender.sendMessage(MiniMessage.miniMessage().serialize(component)); } @Override - public void shutdown() { - if (this.audience != null) { - this.audience.close(); - } - } + public void shutdown() {} @Override - public void sendSignTextChange(@NotNull Player player, @NotNull Sign sign, boolean glowing, @NotNull List components) { - //player.sendSignChange(sign.getLocation(), components.stream().map(com -> LegacyComponentSerializer.legacySection().serialize(com)).toArray(String[]::new)); - } + public void sendSignTextChange( + @NotNull Player player, @NotNull Sign sign, boolean glowing, @NotNull List components) {} @Override public void setDisplayName(@NotNull ItemStack stack, @Nullable Component component) { - if (stack.getItemMeta() == null) { - return; - } + if (!stack.hasItemMeta()) return; ItemMeta meta = stack.getItemMeta(); - if (component == null) { - meta.setDisplayName(null); - } else { - meta.setDisplayName(LegacyComponentSerializer.legacySection().serialize(component)); - } + meta.displayName(component); stack.setItemMeta(meta); } @Override public void setDisplayName(@NotNull Item stack, @Nullable Component component) { - if (component == null) { - stack.setCustomName(null); - } else { - stack.setCustomName(LegacyComponentSerializer.legacySection().serialize(component)); - } + stack.setCustomName(component == null ? null : MiniMessage.miniMessage().serialize(component)); } @Override public void setLines(@NotNull Sign sign, @NotNull List component) { - String EMPTY_LINE_NBT = "{\"text\":\"\"}"; + String emptyJson = "{\"text\":\"\"}"; ReadWriteNBT root = NBT.createNBTObject(); - ReadWriteNBT front_text = root.getOrCreateCompound("front_text"); // > 1.20 - ReadWriteNBTList messages = front_text.getStringList("messages"); // > 1.20 + ReadWriteNBT frontText = root.getOrCreateCompound("front_text"); + ReadWriteNBTList messages = frontText.getStringList("messages"); for (int i = 0; i < 4; i++) { Component com = component.get(i); - String json = com == null ? EMPTY_LINE_NBT : GsonComponentSerializer.gson().serialize(com); + String json = com == null + ? emptyJson + : "{\"text\":\"" + MiniMessage.miniMessage().serialize(com) + "\"}"; root.setString("Text" + (i + 1), json); - messages.add(json); // > 1.20 + messages.add(json); } - // ==== Apply the changes ==== - NBT.modify(sign, nbt -> { - nbt.mergeCompound(root); - }); + NBT.modify(sign, (Consumer) nbt -> nbt.mergeCompound(root)); } @Override public void setLore(@NotNull ItemStack stack, @NotNull Collection components) { - if (!stack.hasItemMeta()) { - return; - } + if (!stack.hasItemMeta()) return; ItemMeta meta = stack.getItemMeta(); - meta.setLore(components.stream().map(LegacyComponentSerializer.legacySection()::serialize).collect(Collectors.toList())); + meta.lore(components.stream().collect(Collectors.toList())); stack.setItemMeta(meta); } diff --git a/platform/quickshop-platform-spigot-v1_19_R1/.gitignore b/platform/quickshop-platform-spigot-v1_19_R1/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/quickshop-platform-spigot-v1_19_R1/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-spigot-v1_19_R1/pom.xml b/platform/quickshop-platform-spigot-v1_19_R1/pom.xml deleted file mode 100644 index 61c81da1d..000000000 --- a/platform/quickshop-platform-spigot-v1_19_R1/pom.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - - quickshop-platform-spigot-v1_19_R1 - jar - - quickshop-platform-spigot-v1_19_R1 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - net.md-5 - specialsource-maven-plugin - 2.0.2 - - - package - - remap - - remap-obf - - org.spigotmc:minecraft-server:1.19.1-R0.1-SNAPSHOT:txt:maps-mojang - true - org.spigotmc:spigot:1.19.1-R0.1-SNAPSHOT:jar:remapped-mojang - - true - remapped-obf - - - - package - - remap - - remap-spigot - - - ${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar - - org.spigotmc:minecraft-server:1.19.1-R0.1-SNAPSHOT:csrg:maps-spigot - org.spigotmc:spigot:1.19.1-R0.1-SNAPSHOT:jar:remapped-obf - - - - - - - - - src/main/resources - true - - - - - - - nms-repo - https://repo.codemc.io/repository/nms/ - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - - - - com.ghostchu - quickshop-platform-spigot-abstract - ${parent.version} - compile - - - org.spigotmc - spigot - 1.19.1-R0.1-SNAPSHOT - remapped-mojang - provided - - - de.tr7zw - item-nbt-api-plugin - 2.12.1 - provided - - - * - * - - - - - diff --git a/platform/quickshop-platform-spigot-v1_19_R1/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_1/Spigot1191Platform.java b/platform/quickshop-platform-spigot-v1_19_R1/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_1/Spigot1191Platform.java index c341a7b81..031b105ac 100644 --- a/platform/quickshop-platform-spigot-v1_19_R1/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_1/Spigot1191Platform.java +++ b/platform/quickshop-platform-spigot-v1_19_R1/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_1/Spigot1191Platform.java @@ -3,6 +3,7 @@ package com.ghostchu.quickshop.platform.spigot.v1_19_1; import com.ghostchu.quickshop.platform.Platform; import com.ghostchu.quickshop.platform.Util; import com.ghostchu.quickshop.platform.spigot.AbstractSpigotPlatform; +import java.util.Optional; import net.kyori.adventure.key.Key; import net.kyori.adventure.nbt.api.BinaryTagHolder; import net.kyori.adventure.text.event.HoverEvent; @@ -23,8 +24,6 @@ import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; -import java.util.Optional; - public class Spigot1191Platform extends AbstractSpigotPlatform implements Platform { public Spigot1191Platform(@NotNull Plugin plugin) { @@ -37,10 +36,12 @@ public class Spigot1191Platform extends AbstractSpigotPlatform implements Platfo Key key = Key.key(namespacedKey.toString()); BinaryTagHolder holder; if (Util.methodExists(BinaryTagHolder.class, "binaryTagHolder")) { - holder = BinaryTagHolder.binaryTagHolder(CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); + holder = BinaryTagHolder.binaryTagHolder( + CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); } else { //noinspection UnstableApiUsage - holder = BinaryTagHolder.of(CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); + holder = BinaryTagHolder.of( + CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); } return HoverEvent.showItem(key, stack.getAmount(), holder); } @@ -62,7 +63,8 @@ public class Spigot1191Platform extends AbstractSpigotPlatform implements Platfo if (material.isBlock()) { return CraftMagicNumbers.getBlock(material).getDescriptionId(); } else { - return postProcessingTranslationKey(CraftMagicNumbers.getItem(material).getDescriptionId()); + return postProcessingTranslationKey( + CraftMagicNumbers.getItem(material).getDescriptionId()); } } @@ -72,7 +74,8 @@ public class Spigot1191Platform extends AbstractSpigotPlatform implements Platfo @Override public @NotNull String getTranslationKey(@NotNull EntityType type) { - Optional> op = net.minecraft.world.entity.EntityType.byString(type.getKey().toString()); + Optional> op = + net.minecraft.world.entity.EntityType.byString(type.getKey().toString()); if (op.isPresent()) { return postProcessingTranslationKey(op.get().getDescriptionId()); } else { diff --git a/platform/quickshop-platform-spigot-v1_19_R2/.gitignore b/platform/quickshop-platform-spigot-v1_19_R2/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/quickshop-platform-spigot-v1_19_R2/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-spigot-v1_19_R2/pom.xml b/platform/quickshop-platform-spigot-v1_19_R2/pom.xml deleted file mode 100644 index 3315ffbaa..000000000 --- a/platform/quickshop-platform-spigot-v1_19_R2/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - - quickshop-platform-spigot-v1_19_R2 - jar - - quickshop-platform-spigot-v1_19_R2 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - net.md-5 - specialsource-maven-plugin - 2.0.2 - - - package - - remap - - remap-obf - - org.spigotmc:minecraft-server:1.19.3-R0.1-SNAPSHOT:txt:maps-mojang - true - org.spigotmc:spigot:1.19.3-R0.1-SNAPSHOT:jar:remapped-mojang - - true - remapped-obf - - - - package - - remap - - remap-spigot - - - ${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar - - org.spigotmc:minecraft-server:1.19.3-R0.1-SNAPSHOT:csrg:maps-spigot - org.spigotmc:spigot:1.19.3-R0.1-SNAPSHOT:jar:remapped-obf - - - - - - - - - src/main/resources - true - - - - - - - nms-repo - https://repo.codemc.io/repository/nms/ - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - - - - com.ghostchu - quickshop-platform-interface - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-abstract - ${parent.version} - compile - - - org.spigotmc - spigot - 1.19.3-R0.1-SNAPSHOT - remapped-mojang - provided - - - de.tr7zw - item-nbt-api-plugin - 2.12.1 - provided - - - * - * - - - - - diff --git a/platform/quickshop-platform-spigot-v1_19_R2/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_2/Spigot1193Platform.java b/platform/quickshop-platform-spigot-v1_19_R2/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_2/Spigot1193Platform.java index d87559a8c..357d4f74f 100644 --- a/platform/quickshop-platform-spigot-v1_19_R2/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_2/Spigot1193Platform.java +++ b/platform/quickshop-platform-spigot-v1_19_R2/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_2/Spigot1193Platform.java @@ -35,10 +35,12 @@ public class Spigot1193Platform extends AbstractSpigotPlatform implements Platfo Key key = Key.key(namespacedKey.toString()); BinaryTagHolder holder; if (Util.methodExists(BinaryTagHolder.class, "binaryTagHolder")) { - holder = BinaryTagHolder.binaryTagHolder(CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); + holder = BinaryTagHolder.binaryTagHolder( + CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); } else { //noinspection UnstableApiUsage - holder = BinaryTagHolder.of(CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); + holder = BinaryTagHolder.of( + CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); } return HoverEvent.showItem(key, stack.getAmount(), holder); } @@ -90,6 +92,7 @@ public class Spigot1193Platform extends AbstractSpigotPlatform implements Platfo CraftEnchantment craftEnchantment = (CraftEnchantment) enchantment; return postProcessingTranslationKey(craftEnchantment.getHandle().getDescriptionId()); } + @Override public @NotNull String getTranslationKey(@NotNull ItemStack stack) { return postProcessingTranslationKey(stack.getTranslationKey()); diff --git a/platform/quickshop-platform-spigot-v1_19_R3/.gitignore b/platform/quickshop-platform-spigot-v1_19_R3/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/platform/quickshop-platform-spigot-v1_19_R3/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/platform/quickshop-platform-spigot-v1_19_R3/pom.xml b/platform/quickshop-platform-spigot-v1_19_R3/pom.xml deleted file mode 100644 index 9cc428722..000000000 --- a/platform/quickshop-platform-spigot-v1_19_R3/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - ../../pom.xml - - - quickshop-platform-spigot-v1_19_R3 - jar - - quickshop-platform-spigot-v1_19_R3 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - net.md-5 - specialsource-maven-plugin - 2.0.2 - - - package - - remap - - remap-obf - - org.spigotmc:minecraft-server:1.19.4-R0.1-SNAPSHOT:txt:maps-mojang - true - org.spigotmc:spigot:1.19.4-R0.1-SNAPSHOT:jar:remapped-mojang - - true - remapped-obf - - - - package - - remap - - remap-spigot - - - ${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar - - org.spigotmc:minecraft-server:1.19.4-R0.1-SNAPSHOT:csrg:maps-spigot - org.spigotmc:spigot:1.19.4-R0.1-SNAPSHOT:jar:remapped-obf - - - - - - - - - src/main/resources - true - - - - - - - nms-repo - https://repo.codemc.io/repository/nms/ - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - - - - com.ghostchu - quickshop-platform-interface - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-abstract - ${parent.version} - compile - - - org.spigotmc - spigot - 1.19.4-R0.1-SNAPSHOT - remapped-mojang - provided - - - de.tr7zw - item-nbt-api-plugin - 2.12.1 - provided - - - * - * - - - - - diff --git a/platform/quickshop-platform-spigot-v1_19_R3/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_3/Spigot1194Platform.java b/platform/quickshop-platform-spigot-v1_19_R3/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_3/Spigot1194Platform.java index e3e536561..a3f3fae94 100644 --- a/platform/quickshop-platform-spigot-v1_19_R3/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_3/Spigot1194Platform.java +++ b/platform/quickshop-platform-spigot-v1_19_R3/src/main/java/com/ghostchu/quickshop/platform/spigot/v1_19_3/Spigot1194Platform.java @@ -35,10 +35,12 @@ public class Spigot1194Platform extends AbstractSpigotPlatform implements Platfo Key key = Key.key(namespacedKey.toString()); BinaryTagHolder holder; if (Util.methodExists(BinaryTagHolder.class, "binaryTagHolder")) { - holder = BinaryTagHolder.binaryTagHolder(CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); + holder = BinaryTagHolder.binaryTagHolder( + CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); } else { //noinspection UnstableApiUsage - holder = BinaryTagHolder.of(CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); + holder = BinaryTagHolder.of( + CraftItemStack.asNMSCopy(stack).save(new CompoundTag()).toString()); } return HoverEvent.showItem(key, stack.getAmount(), holder); } @@ -78,7 +80,7 @@ public class Spigot1194Platform extends AbstractSpigotPlatform implements Platfo @Override public @NotNull String getTranslationKey(@NotNull PotionEffectType potionEffectType) { - if(potionEffectType instanceof PotionEffectTypeWrapper wrapper){ + if (potionEffectType instanceof PotionEffectTypeWrapper wrapper) { potionEffectType = wrapper.getType(); } CraftPotionEffectType craftPotionEffectType = (CraftPotionEffectType) potionEffectType; @@ -90,6 +92,7 @@ public class Spigot1194Platform extends AbstractSpigotPlatform implements Platfo CraftEnchantment craftEnchantment = (CraftEnchantment) enchantment; return postProcessingTranslationKey(craftEnchantment.getHandle().getDescriptionId()); } + @Override public @NotNull String getTranslationKey(@NotNull ItemStack stack) { return postProcessingTranslationKey(stack.getTranslationKey()); diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 70db42ec7..000000000 --- a/pom.xml +++ /dev/null @@ -1,360 +0,0 @@ - - - - 4.0.0 - - com.ghostchu - quickshop-hikari - 5.2.0.7 - pom - quickshop-hikari - Another QuickShop fork - https://github.com/${developer}/${artifactId} - - - 17 - Ghost-chu - UTF-8 - - - - - GPL v3 License - https://www.gnu.org/licenses/ - repo - - - - - - Ghost_chu - Ghost chu - 2908803755@qq.com - https://www.ghostchu.com - Asia/Shanghai - - - - - scm:git:git@github.com:${developer}/${artifactId}.git - scm:git:git@github.com:${developer}/${artifactId}.git - https://github.com/${developer}/${artifactId} - HEAD - - - - https://github.com/${developer}/${name}/issues - GitHub Issues - - - - - md_5-releases - https://repo.md-5.net/content/repositories/releases/ - - - codemc-snapshots - https://repo.codemc.io/repository/maven-snapshots/ - - - - - GitHub Actions - https://github.com/${developer}/${artifactId}/actions/workflows/maven.yml - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - ${java.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.5.1 - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.6.2 - - UTF-8 - com.ghostchu.quickshop.nonquickshopstuff.* - ${java.version} - - - - - org.apache.maven.plugins - maven-clean-plugin - - - - - io.github.git-commit-id - git-commit-id-maven-plugin - 5.0.0 - - ${project.basedir}/.git - false - yyyy-MM-dd HH:mm:ss - git - json - - false - false - -dirty - - - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - package - - shade - - - QuickShop-OG-${project.version} - true - false - false - false - true - false - - - com.ghostchu:quickshop*:* - com.ghostchu.quickshop.compatibility:*:* - com.ghostchu.quickshop.addon:*:* - de.tr7zw:item-nbt-api:* - io.papermc:paperlib:* - org.bstats:* - - - - - io.papermc.lib. - com.ghostchu.quickshop.shade.io.papermc.lib. - - - de.tr7zw.changeme.nbtapi - com.ghostchu.quickshop.shade.de.tr7zw.changeme.nbtapi - - - org.bstats - com.ghostchu.quickshop.shade.org.bstats - - - de.themoep.minedown. - com.ghostchu.quickshop.shade.de.themoep.minedown - - - - - com.ghostchu.quickshop.bootstrap.Bootstrap - - - - - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/*.kotlin_module - META-INF/*.txt - META-INF/proguard/* - META-INF/services/* - META-INF/versions/9/* - *License* - *LICENSE* - - - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - false - -Xdoclint:none - - - - - - - - io.github.git-commit-id - git-commit-id-maven-plugin - - - - get-the-git-infos - initialize - - revision - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - org.codehaus.mojo - versions-maven-plugin - 2.16.1 - - true - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - copy-resources - initialize - - copy-resources - - - ${basedir}/target/extra-resources - - - src/main/resources - true - - * - - - - - - - - - - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - - - - - org.spigotmc - spigot-api - 1.20.4-R0.1-SNAPSHOT - provided - - - commons-lang - commons-lang - - - - - org.projectlombok - lombok - 1.18.30 - provided - - - org.jetbrains - annotations - 24.1.0 - provided - - - - - - - org.projectlombok - lombok - - - org.jetbrains - annotations - - - - - quickshop-common - quickshop-api - platform/quickshop-platform-interface - platform/quickshop-platform-spigot-abstract - platform/quickshop-platform-spigot-v1_19_R1 - platform/quickshop-platform-spigot-v1_19_R2 - platform/quickshop-platform-spigot-v1_19_R3 - platform/quickshop-platform-paper - quickshop-bukkit - compatibility/common - compatibility/clearlag - compatibility/nocheatplus - compatibility/worldguard - compatibility/worldedit - compatibility/openinv - addon/plan - addon/discount - addon/list - addon/shopitemonly - addon/limited - addon/dynmap - addon/bluemap - addon/displaycontrol - addon/reremake-migrator - - - - diff --git a/quickshop-api/.gitignore b/quickshop-api/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/quickshop-api/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/quickshop-api/pom.xml b/quickshop-api/pom.xml deleted file mode 100644 index 6e30b6766..000000000 --- a/quickshop-api/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - quickshop-hikari - com.ghostchu - 5.2.0.7 - - 4.0.0 - - quickshop-api - - - 17 - 17 - - - - - com.ghostchu - quickshop-common - ${parent.version} - compile - - - org.spigotmc - spigot-api - - - com.vdurmont - semver4j - 3.1.0 - - - \ No newline at end of file diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/CommonUtil.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/CommonUtil.java index e0aa5a761..374d6d50f 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/CommonUtil.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/CommonUtil.java @@ -4,8 +4,7 @@ import net.kyori.adventure.text.Component; import org.jetbrains.annotations.Nullable; public class CommonUtil { - private CommonUtil() { - } + private CommonUtil() {} public static boolean isEmptyComponent(@Nullable Component component) { if (component == null) { @@ -16,5 +15,4 @@ public class CommonUtil { } return component.equals(Component.text("")); } - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/GameVersion.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/GameVersion.java index 707c4b180..8093543ea 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/GameVersion.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/GameVersion.java @@ -79,7 +79,13 @@ public enum GameVersion { */ private final boolean signTextDyeSupport; - GameVersion(boolean coreSupports, boolean endOfLife, boolean virtualDisplaySupports, boolean newNmsName, boolean signGlowingSupport, boolean signTextDyeSupport) { + GameVersion( + boolean coreSupports, + boolean endOfLife, + boolean virtualDisplaySupports, + boolean newNmsName, + boolean signGlowingSupport, + boolean signTextDyeSupport) { this.coreSupports = coreSupports; this.endOfLife = endOfLife; this.virtualDisplaySupports = virtualDisplaySupports; @@ -88,7 +94,6 @@ public enum GameVersion { this.signTextDyeSupport = signTextDyeSupport; } - /** * Matches the version that QuickShop supports or not * @@ -104,5 +109,4 @@ public enum GameVersion { } return UNKNOWN; } - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopAPI.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopAPI.java index 1d7e1379c..639dcffc8 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopAPI.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopAPI.java @@ -6,21 +6,21 @@ import com.ghostchu.quickshop.api.inventory.InventoryWrapperRegistry; import com.ghostchu.quickshop.api.localization.text.TextManager; import com.ghostchu.quickshop.api.shop.*; import com.vdurmont.semver4j.Semver; +import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -import java.util.Map; - /** * The unique entry point to allow you to access most features of QuickShop */ public interface QuickShopAPI { static QuickShopAPI getInstance() { - RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(QuickShopProvider.class); + RegisteredServiceProvider provider = + Bukkit.getServicesManager().getRegistration(QuickShopProvider.class); if (provider == null) { throw new IllegalStateException("QuickShop hadn't loaded at this moment."); } @@ -28,7 +28,8 @@ public interface QuickShopAPI { } static Plugin getPluginInstance() { - RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(QuickShopProvider.class); + RegisteredServiceProvider provider = + Bukkit.getServicesManager().getRegistration(QuickShopProvider.class); if (provider == null) { throw new IllegalStateException("QuickShop hadn't loaded at this moment."); } @@ -61,7 +62,8 @@ public interface QuickShopAPI { * * @return registry */ - @NotNull InventoryWrapperRegistry getInventoryWrapperRegistry(); + @NotNull + InventoryWrapperRegistry getInventoryWrapperRegistry(); /** * Getting current using ItemMatcher impl diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopProvider.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopProvider.java index 6a9c08de4..feffeaded 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopProvider.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/QuickShopProvider.java @@ -9,6 +9,4 @@ public interface QuickShopProvider { @NotNull Plugin getInstance(); - - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/RankLimiter.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/RankLimiter.java index c06b5ab6e..9b6c8e8dd 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/RankLimiter.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/RankLimiter.java @@ -1,20 +1,19 @@ package com.ghostchu.quickshop.api; import com.ghostchu.quickshop.api.obj.QUser; +import java.util.Map; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -import java.util.Map; - public interface RankLimiter { - int getShopLimit(@NotNull QUser p); @Deprecated(forRemoval = true) @ApiStatus.Internal @ApiStatus.Obsolete - @NotNull Map getLimits(); + @NotNull + Map getLimits(); boolean isLimit(); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandContainer.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandContainer.java index fec6d3e28..cbc51aa6e 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandContainer.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandContainer.java @@ -2,6 +2,10 @@ package com.ghostchu.quickshop.api.command; import com.ghostchu.quickshop.api.CommonUtil; import com.ghostchu.quickshop.api.QuickShopAPI; +import java.lang.reflect.Method; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; import lombok.Builder; import lombok.Data; import lombok.Singular; @@ -12,11 +16,6 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.Method; -import java.util.List; -import java.util.function.Function; -import java.util.function.Supplier; - /** * Builds a CommandContainer that can be registered into CommandManager. * @@ -34,20 +33,28 @@ public class CommandContainer { */ @Singular private List selectivePermissions; + @Singular private List permissions; // E.g quickshop.unlimited + @NotNull private String prefix; // E.g /quickshop - @Nullable - private Function<@NotNull String, @Nullable Component> description; // Will show in the /quickshop help, provide an arg that pass a player locale code - private boolean disabled; //Set command is disabled or not. @Nullable - private Supplier disabledSupplier; //Set command is disabled or not. + private Function<@NotNull String, @Nullable Component> + description; // Will show in the /quickshop help, provide an arg that pass a player locale code + + private boolean disabled; // Set command is disabled or not. + @Nullable - private Supplier disablePlaceholder; //Set the text shown if command disabled + private Supplier disabledSupplier; // Set command is disabled or not. + @Nullable - private Function<@Nullable CommandSender, @NotNull Component> disableCallback; //Set the callback that should return a text to shown + private Supplier disablePlaceholder; // Set the text shown if command disabled + + @Nullable + private Function<@Nullable CommandSender, @NotNull Component> + disableCallback; // Set the callback that should return a text to shown private Class executorType; @@ -60,10 +67,16 @@ public class CommandContainer { public final @NotNull Component getDisableText(@NotNull CommandSender sender) { if (this.getDisableCallback() != null) { return this.getDisableCallback().apply(sender); - } else if (this.getDisablePlaceholder() != null && !CommonUtil.isEmptyComponent(this.getDisablePlaceholder().get())) { + } else if (this.getDisablePlaceholder() != null + && !CommonUtil.isEmptyComponent(this.getDisablePlaceholder().get())) { return this.getDisablePlaceholder().get(); } else { - return Component.empty().color(NamedTextColor.GRAY).append(QuickShopAPI.getInstance().getTextManager().of(sender, "command.feature-not-enabled").forLocale()); + return Component.empty() + .color(NamedTextColor.GRAY) + .append(QuickShopAPI.getInstance() + .getTextManager() + .of(sender, "command.feature-not-enabled") + .forLocale()); } } @@ -80,7 +93,9 @@ public class CommandContainer { public void bakeExecutorType() { for (Method declaredMethod : getExecutor().getClass().getMethods()) { if ("onCommand".equals(declaredMethod.getName()) || "onTabComplete".equals(declaredMethod.getName())) { - if (declaredMethod.getParameterCount() != 3 || declaredMethod.isSynthetic() || declaredMethod.isBridge()) { + if (declaredMethod.getParameterCount() != 3 + || declaredMethod.isSynthetic() + || declaredMethod.isBridge()) { continue; } executorType = declaredMethod.getParameterTypes()[0]; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandHandler.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandHandler.java index 51fd02d8e..a4abf8a3f 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandHandler.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandHandler.java @@ -2,6 +2,8 @@ package com.ghostchu.quickshop.api.command; import com.ghostchu.quickshop.api.QuickShopAPI; import com.ghostchu.quickshop.api.shop.Shop; +import java.util.*; +import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.NotImplementedException; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; @@ -10,9 +12,6 @@ import org.bukkit.util.BlockIterator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.concurrent.CompletableFuture; - /** * The command handler that processing sub commands under QS main command * @@ -104,11 +103,13 @@ public interface CommandHandler { */ @Deprecated(since = "4.2.0.0") default void onCommand(T sender, @NotNull String commandLabel, @NotNull String[] cmdArgs) { - throw new NotImplementedException("This method is deprecated, please use onCommand(T sender, @NotNull String commandLabel, @NotNull CommandParser parser) instead."); + throw new NotImplementedException( + "This method is deprecated, please use onCommand(T sender, @NotNull String commandLabel, @NotNull CommandParser parser) instead."); } @Nullable - default List onTabComplete_Internal(@NotNull T sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { + default List onTabComplete_Internal( + @NotNull T sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { StringJoiner joiner = new StringJoiner(" "); for (String s : cmdArg) { joiner.add(s); @@ -149,6 +150,7 @@ public interface CommandHandler { */ @Deprecated(since = "4.2.0.0") default List onTabComplete(@NotNull T sender, @NotNull String commandLabel, @NotNull String[] cmdArgs) { - throw new NotImplementedException("This method is deprecated, please use onTabComplete(T sender, @NotNull String commandLabel, @NotNull CommandParser parser) instead."); + throw new NotImplementedException( + "This method is deprecated, please use onTabComplete(T sender, @NotNull String commandLabel, @NotNull CommandParser parser) instead."); } } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandManager.java index c450f3b89..50c8b41e1 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandManager.java @@ -1,12 +1,11 @@ package com.ghostchu.quickshop.api.command; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; - /** * The manager that managing all sub-commands that registered * Also performing permission checks in there. @@ -17,7 +16,8 @@ public interface CommandManager { * * @return All registered {@link CommandContainer}s. */ - @NotNull List getRegisteredCommands(); + @NotNull + List getRegisteredCommands(); boolean onCommand( @NotNull CommandSender sender, @@ -25,7 +25,8 @@ public interface CommandManager { @NotNull String commandLabel, @NotNull String[] cmdArg); - @Nullable List onTabComplete( + @Nullable + List onTabComplete( @NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandParser.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandParser.java index 9d572d208..28b64cc68 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandParser.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandParser.java @@ -1,8 +1,7 @@ package com.ghostchu.quickshop.api.command; -import org.jetbrains.annotations.NotNull; - import java.util.*; +import org.jetbrains.annotations.NotNull; /** * CommandParser is a utility class for parsing command arguments. diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandProcesser.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandProcesser.java index 0f00a8719..b60c95c7d 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandProcesser.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/command/CommandProcesser.java @@ -1,13 +1,12 @@ package com.ghostchu.quickshop.api.command; +import java.util.Collections; +import java.util.List; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; - -//Preserved for backward compatibility +// Preserved for backward compatibility @Deprecated public interface CommandProcesser extends CommandHandler { @@ -20,5 +19,4 @@ public interface CommandProcesser extends CommandHandler { @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { return Collections.emptyList(); } - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/DatabaseHelper.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/DatabaseHelper.java index 3b58d9651..5cdb9047f 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/DatabaseHelper.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/DatabaseHelper.java @@ -5,15 +5,14 @@ import com.ghostchu.quickshop.api.database.bean.DataRecord; import com.ghostchu.quickshop.api.database.bean.ShopRecord; import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.quickshop.api.shop.Shop; -import org.apache.commons.lang3.tuple.Triple; -import org.bukkit.Location; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.sql.SQLException; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Location; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * Processing and handle most things about database ;) @@ -33,14 +32,16 @@ public interface DatabaseHelper { * @param player The player * @return */ - @NotNull CompletableFuture<@NotNull Integer> cleanMessageForPlayer(@NotNull UUID player); + @NotNull + CompletableFuture<@NotNull Integer> cleanMessageForPlayer(@NotNull UUID player); /** * Create a shop data record sand save into database * * @param shop The shop object */ - @NotNull CompletableFuture<@NotNull Long> createData(@NotNull Shop shop); + @NotNull + CompletableFuture<@NotNull Long> createData(@NotNull Shop shop); /** * Create a shop record in database @@ -68,7 +69,8 @@ public interface DatabaseHelper { * @return The data record, null for not exists * @throws SQLException something going wrong */ - @NotNull CompletableFuture<@Nullable DataRecord> getDataRecord(long dataId); + @NotNull + CompletableFuture<@Nullable DataRecord> getDataRecord(long dataId); /** * Async gets the player last use locale code from database @@ -91,7 +93,6 @@ public interface DatabaseHelper { */ CompletableFuture<@Nullable String> getPlayerName(@NotNull UUID uuid); - /** * Async gets the player last use username from database * @@ -105,17 +106,29 @@ public interface DatabaseHelper { * @param rec Record object that can be serialized by Gson. * @return */ - @NotNull CompletableFuture<@NotNull Integer> insertHistoryRecord(@NotNull Object rec); + @NotNull + CompletableFuture<@NotNull Integer> insertHistoryRecord(@NotNull Object rec); - @NotNull CompletableFuture<@NotNull Integer> insertMetricRecord(@NotNull ShopMetricRecord recordEntry); + @NotNull + CompletableFuture<@NotNull Integer> insertMetricRecord(@NotNull ShopMetricRecord recordEntry); - void insertTransactionRecord(@Nullable UUID from, @Nullable UUID to, double amount, @Nullable String currency, double taxAmount, @Nullable UUID taxAccount, @Nullable String error); + void insertTransactionRecord( + @Nullable UUID from, + @Nullable UUID to, + double amount, + @Nullable String currency, + double taxAmount, + @Nullable UUID taxAccount, + @Nullable String error); - @NotNull List listShops(boolean deleteIfCorrupt); + @NotNull + List listShops(boolean deleteIfCorrupt); - @NotNull List listShopsTaggedBy(@NotNull UUID tagger, @NotNull String tag); + @NotNull + List listShopsTaggedBy(@NotNull UUID tagger, @NotNull String tag); - @NotNull List listTags(@NotNull UUID tagger); + @NotNull + List listTags(@NotNull UUID tagger); CompletableFuture<@Nullable Integer> removeShopTag(@NotNull UUID tagger, @NotNull Long shopId, @NotNull String tag); @@ -131,7 +144,8 @@ public interface DatabaseHelper { * @param shopId The shop record id * @return The shop record */ - @NotNull CompletableFuture<@Nullable Long> locateShopDataId(long shopId); + @NotNull + CompletableFuture<@Nullable Long> locateShopDataId(long shopId); /** * Locate a shop record from database by location @@ -150,7 +164,8 @@ public interface DatabaseHelper { * @param dataId The data record id * @return */ - @NotNull CompletableFuture<@NotNull Integer> removeData(long dataId); + @NotNull + CompletableFuture<@NotNull Integer> removeData(long dataId); /** * Remove a shop data record from database @@ -158,8 +173,8 @@ public interface DatabaseHelper { * @param shopId The shop record id * @return */ - @NotNull CompletableFuture<@NotNull Integer> removeShop(long shopId); - + @NotNull + CompletableFuture<@NotNull Integer> removeShop(long shopId); /** * Remove a shop data mapping record from database @@ -170,7 +185,8 @@ public interface DatabaseHelper { * @param z Shop Z * @return */ - @NotNull CompletableFuture<@NotNull Integer> removeShopMap(@NotNull String world, int x, int y, int z); + @NotNull + CompletableFuture<@NotNull Integer> removeShopMap(@NotNull String world, int x, int y, int z); /** * Create a transaction message record and save into database @@ -180,7 +196,9 @@ public interface DatabaseHelper { * @param time System time * @return */ - @NotNull CompletableFuture<@NotNull Integer> saveOfflineTransactionMessage(@NotNull UUID player, @NotNull String message, long time); + @NotNull + CompletableFuture<@NotNull Integer> saveOfflineTransactionMessage( + @NotNull UUID player, @NotNull String message, long time); /** * Select all messages that saved in the database @@ -208,7 +226,8 @@ public interface DatabaseHelper { @NotNull SQLQuery selectTable(@NotNull String table) throws SQLException; - CompletableFuture updatePlayerProfile(@NotNull UUID uuid, @Nullable String locale, @NotNull String username); + CompletableFuture updatePlayerProfile( + @NotNull UUID uuid, @Nullable String locale, @NotNull String username); /** * Update player profiles in batch @@ -226,7 +245,8 @@ public interface DatabaseHelper { * @param stock The inventory stock * @return */ - @NotNull CompletableFuture<@NotNull Integer> updateExternalInventoryProfileCache(long shopId, int space, int stock); + @NotNull + CompletableFuture<@NotNull Integer> updateExternalInventoryProfileCache(long shopId, int space, int stock); /** * Update the shop profile to database @@ -235,5 +255,4 @@ public interface DatabaseHelper { * @return */ CompletableFuture updateShop(@NotNull Shop shop); - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/ShopMetricRecord.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/ShopMetricRecord.java index d8226abe6..33bfa377c 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/ShopMetricRecord.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/ShopMetricRecord.java @@ -16,7 +16,8 @@ public class ShopMetricRecord { private String player; @Builder - public ShopMetricRecord(long time, long shopId, ShopOperationEnum type, double total, double tax, int amount, QUser player) { + public ShopMetricRecord( + long time, long shopId, ShopOperationEnum type, double total, double tax, int amount, QUser player) { this.time = time; this.shopId = shopId; this.type = type; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/bean/DataRecord.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/bean/DataRecord.java index 170b38d51..d60734510 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/bean/DataRecord.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/database/bean/DataRecord.java @@ -1,11 +1,10 @@ package com.ghostchu.quickshop.api.database.bean; import com.ghostchu.quickshop.api.obj.QUser; +import java.util.Date; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Date; - public interface DataRecord { @NotNull Date getCreateTime(); diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/AbstractEconomy.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/AbstractEconomy.java index 436d61967..8b61fe0f4 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/AbstractEconomy.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/AbstractEconomy.java @@ -4,20 +4,18 @@ import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - /** * Abstract Economy Core */ public abstract class AbstractEconomy implements EconomyCore, Reloadable { - protected AbstractEconomy() { - } + protected AbstractEconomy() {} @Override public @NotNull String getName() { @@ -50,11 +48,12 @@ public abstract class AbstractEconomy implements EconomyCore, Reloadable { } else if (obj instanceof OfflinePlayer offlinePlayer) { return withdraw(offlinePlayer, amount, world, currency); } - throw new IllegalArgumentException("The obj argument can only accept one of those type: " + - "QUser = player quickshop user object, " + - "UUID = player uuid, String = player username, " + - "OfflinePlayer = player bukkit offline player object." + - " Your given: " + obj.getClass()); + throw new IllegalArgumentException( + "The obj argument can only accept one of those type: " + "QUser = player quickshop user object, " + + "UUID = player uuid, String = player username, " + + "OfflinePlayer = player bukkit offline player object." + + " Your given: " + + obj.getClass()); } @Override @@ -82,11 +81,12 @@ public abstract class AbstractEconomy implements EconomyCore, Reloadable { } else if (obj instanceof OfflinePlayer offlinePlayer) { return deposit(offlinePlayer, amount, world, currency); } - throw new IllegalArgumentException("The obj argument can only accept one of those type: " + - "QUser = player quickshop user object, " + - "UUID = player uuid, String = player username, " + - "OfflinePlayer = player bukkit offline player object." + - " Your given: " + obj.getClass()); + throw new IllegalArgumentException( + "The obj argument can only accept one of those type: " + "QUser = player quickshop user object, " + + "UUID = player uuid, String = player username, " + + "OfflinePlayer = player bukkit offline player object." + + " Your given: " + + obj.getClass()); } @Override @@ -115,15 +115,17 @@ public abstract class AbstractEconomy implements EconomyCore, Reloadable { } else if (obj instanceof OfflinePlayer offlinePlayer) { return getBalance(offlinePlayer, world, currency); } - throw new IllegalArgumentException("The obj argument can only accept one of those type: " + - "QUser = player quickshop user object, " + - "UUID = player uuid, String = player username, " + - "OfflinePlayer = player bukkit offline player object." + - " Your given: " + obj.getClass()); + throw new IllegalArgumentException( + "The obj argument can only accept one of those type: " + "QUser = player quickshop user object, " + + "UUID = player uuid, String = player username, " + + "OfflinePlayer = player bukkit offline player object." + + " Your given: " + + obj.getClass()); } @Override - public boolean transfer(@NotNull Object from, @NotNull Object to, double amount, @NotNull World world, @Nullable String currency) { + public boolean transfer( + @NotNull Object from, @NotNull Object to, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { return false; } @@ -152,7 +154,8 @@ public abstract class AbstractEconomy implements EconomyCore, Reloadable { * @return successed */ @Override - public boolean transfer(@NotNull UUID from, @NotNull UUID to, double amount, @NotNull World world, @Nullable String currency) { + public boolean transfer( + @NotNull UUID from, @NotNull UUID to, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { return false; } @@ -170,7 +173,8 @@ public abstract class AbstractEconomy implements EconomyCore, Reloadable { } @Override - public boolean transfer(@NotNull String from, @NotNull String to, double amount, @NotNull World world, @Nullable String currency) { + public boolean transfer( + @NotNull String from, @NotNull String to, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { return false; } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/Benefit.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/Benefit.java index e0a680314..8e6e35135 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/Benefit.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/Benefit.java @@ -1,9 +1,8 @@ package com.ghostchu.quickshop.api.economy; -import org.jetbrains.annotations.NotNull; - import java.util.Map; import java.util.UUID; +import org.jetbrains.annotations.NotNull; public interface Benefit { /** @@ -54,8 +53,7 @@ public interface Benefit { @NotNull String serialize(); - class BenefitExistsException extends Exception { - } + class BenefitExistsException extends Exception {} class BenefitOverflowException extends Exception { private final double overflow; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyCore.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyCore.java index de450ef1c..dbdb48925 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyCore.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyCore.java @@ -1,13 +1,12 @@ package com.ghostchu.quickshop.api.economy; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - /** * @author netherfoam Represents an economy. */ @@ -119,14 +118,16 @@ public interface EconomyCore { * * @return Impl name */ - @NotNull String getName(); + @NotNull + String getName(); /** * Getting Economy impl owned by * * @return Owned by */ - @NotNull Plugin getPlugin(); + @NotNull + Plugin getPlugin(); /** * Gets the currency does exists @@ -161,8 +162,8 @@ public interface EconomyCore { * @param world The transaction world * @return true if success (Payer had enough cash, receiver was able to receive the funds) */ - boolean transfer(@NotNull Object from, @NotNull Object to, double amount, @NotNull World world, @Nullable String currency); - + boolean transfer( + @NotNull Object from, @NotNull Object to, double amount, @NotNull World world, @Nullable String currency); /** * Transfers the given amount of money from Player1 to Player2 @@ -174,7 +175,8 @@ public interface EconomyCore { * @param world The transaction world * @return true if success (Payer had enough cash, receiver was able to receive the funds) */ - boolean transfer(@NotNull UUID from, @NotNull UUID to, double amount, @NotNull World world, @Nullable String currency); + boolean transfer( + @NotNull UUID from, @NotNull UUID to, double amount, @NotNull World world, @Nullable String currency); /** * Transfers the given amount of money from Player1 to Player2 @@ -186,8 +188,8 @@ public interface EconomyCore { * @param world The transaction world * @return true if success (Payer had enough cash, receiver was able to receive the funds) */ - boolean transfer(@NotNull String from, @NotNull String to, double amount, @NotNull World world, @Nullable String currency); - + boolean transfer( + @NotNull String from, @NotNull String to, double amount, @NotNull World world, @Nullable String currency); /** * Withdraws a given amount of money from the given username and turns it to thin air. @@ -232,5 +234,4 @@ public interface EconomyCore { * @return True if success, false if they didn't have enough cash */ boolean withdraw(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency); - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyTransaction.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyTransaction.java index 1fa430093..a8bf99973 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyTransaction.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyTransaction.java @@ -1,13 +1,12 @@ package com.ghostchu.quickshop.api.economy; import com.ghostchu.quickshop.api.operation.Operation; +import java.util.Deque; +import java.util.List; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Deque; -import java.util.List; - public interface EconomyTransaction { /** @@ -48,23 +47,28 @@ public interface EconomyTransaction { void setAmountAfterTax(double amountAfterTax); - @NotNull EconomyCore getCore(); + @NotNull + EconomyCore getCore(); void setCore(@NotNull EconomyCore core); - @Nullable String getCurrency(); + @Nullable + String getCurrency(); void setCurrency(@Nullable String currency); - @Nullable Object getFrom(); + @Nullable + Object getFrom(); void setFrom(@Nullable Object from); - @Nullable String getLastError(); + @Nullable + String getLastError(); void setLastError(@NotNull String lastError); - @NotNull Deque getProcessingStack(); + @NotNull + Deque getProcessingStack(); /** * Getting the tax in this transaction @@ -75,15 +79,18 @@ public interface EconomyTransaction { void setTax(double tax); - @Nullable Object getTaxer(); + @Nullable + Object getTaxer(); void setTaxer(@Nullable Object taxer); - @Nullable Object getTo(); + @Nullable + Object getTo(); void setTo(@Nullable Object to); - @NotNull World getWorld(); + @NotNull + World getWorld(); void setWorld(@NotNull World world); @@ -94,11 +101,11 @@ public interface EconomyTransaction { * @return A list contains all steps executed. If "continueWhenFailed" is false, it only contains all success steps before hit the error. Else all. */ @SuppressWarnings("UnusedReturnValue") - @NotNull List rollback(boolean continueWhenFailed); + @NotNull + List rollback(boolean continueWhenFailed); void setAllowLoan(boolean allowLoan); - interface TransactionCallback { /** * Calling while Transaction commit @@ -117,17 +124,14 @@ public interface EconomyTransaction { * * @param economyTransaction Transaction */ - default void onFailed(@NotNull EconomyTransaction economyTransaction) { - } + default void onFailed(@NotNull EconomyTransaction economyTransaction) {} /** * Calling while Transaction commit successfully * * @param economyTransaction Transaction */ - default void onSuccess(@NotNull EconomyTransaction economyTransaction) { - - } + default void onSuccess(@NotNull EconomyTransaction economyTransaction) {} /** * Calling while Tax processing failed @@ -136,9 +140,6 @@ public interface EconomyTransaction { * * @param economyTransaction Transaction */ - default void onTaxFailed(@NotNull EconomyTransaction economyTransaction) { - } - + default void onTaxFailed(@NotNull EconomyTransaction economyTransaction) {} } - -} \ No newline at end of file +} diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyType.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyType.java index 83cc53d15..fb79d3a6a 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyType.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/EconomyType.java @@ -11,7 +11,7 @@ public enum EconomyType { UNKNOWN(-1), VAULT(0), RESERVE(1), - //MIXED(2), + // MIXED(2), GEMS_ECONOMY(3), TNE(4); diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/DepositEconomyOperation.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/DepositEconomyOperation.java index 7e71851e1..c5c59a070 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/DepositEconomyOperation.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/DepositEconomyOperation.java @@ -18,7 +18,12 @@ public class DepositEconomyOperation implements Operation { private boolean committed = false; private boolean rollback = false; - public DepositEconomyOperation(@NotNull Object account, double amount, @NotNull World world, @Nullable String currency, @NotNull EconomyCore economyCore) { + public DepositEconomyOperation( + @NotNull Object account, + double amount, + @NotNull World world, + @Nullable String currency, + @NotNull EconomyCore economyCore) { this.account = account; this.amount = amount; this.world = world; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/WithdrawEconomyOperation.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/WithdrawEconomyOperation.java index 81910639e..ea29f9d00 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/WithdrawEconomyOperation.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/economy/operation/WithdrawEconomyOperation.java @@ -18,7 +18,12 @@ public class WithdrawEconomyOperation implements Operation { private boolean committed = false; private boolean rollback = false; - public WithdrawEconomyOperation(@NotNull Object account, double amount, @NotNull World world, @Nullable String currency, @NotNull EconomyCore economyCore) { + public WithdrawEconomyOperation( + @NotNull Object account, + double amount, + @NotNull World world, + @Nullable String currency, + @NotNull EconomyCore economyCore) { this.account = account; this.amount = amount; this.world = world; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/AbstractQSEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/AbstractQSEvent.java index e01fe53ca..28bf0d023 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/AbstractQSEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/AbstractQSEvent.java @@ -7,9 +7,6 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; -/** - * Parent about all events. - */ public abstract class AbstractQSEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); @@ -22,11 +19,6 @@ public abstract class AbstractQSEvent extends Event { super(async); } - /** - * Call event on Bukkit event bus and check if cancelled - * - * @return Returns true if cancelled, and false if didn't cancel - */ public boolean callCancellableEvent() { Bukkit.getPluginManager().callEvent(this); if (this instanceof Cancellable cancellable) { @@ -35,21 +27,22 @@ public abstract class AbstractQSEvent extends Event { return false; } - /** - * Fire event on Bukkit event bus - */ - public void callEvent() { + @Override + public boolean callEvent() { QuickShopAPI.getPluginInstance().getServer().getPluginManager().callEvent(this); + if (this instanceof Cancellable cancellable) { + return !cancellable.isCancelled(); + } + return true; } @NotNull @Override public HandlerList getHandlers() { - return getHandlerList(); + return HANDLERS; } public static HandlerList getHandlerList() { return HANDLERS; } - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/CalendarEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/CalendarEvent.java index a537c1f67..18087554d 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/CalendarEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/CalendarEvent.java @@ -9,7 +9,6 @@ import lombok.EqualsAndHashCode; */ @EqualsAndHashCode(callSuper = true) @Data - public class CalendarEvent extends AbstractQSEvent { private CalendarTriggerType calendarTriggerType; @@ -18,6 +17,13 @@ public class CalendarEvent extends AbstractQSEvent { } public enum CalendarTriggerType { - NOTHING_CHANGED, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR + NOTHING_CHANGED, + SECOND, + MINUTE, + HOUR, + DAY, + WEEK, + MONTH, + YEAR } } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/DisplayApplicableCheckEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/DisplayApplicableCheckEvent.java index 1f5721e7d..393fde455 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/DisplayApplicableCheckEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/DisplayApplicableCheckEvent.java @@ -1,7 +1,6 @@ package com.ghostchu.quickshop.api.event; import com.ghostchu.quickshop.api.shop.Shop; - import java.util.UUID; public class DisplayApplicableCheckEvent extends AbstractQSEvent { diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopAuthorizeCalculateEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopAuthorizeCalculateEvent.java index 5ca04ca57..1a3dff055 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopAuthorizeCalculateEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopAuthorizeCalculateEvent.java @@ -1,11 +1,10 @@ package com.ghostchu.quickshop.api.event; import com.ghostchu.quickshop.api.shop.Shop; +import java.util.UUID; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - /** * Call when shop authorize was calculated */ @@ -26,7 +25,12 @@ public class ShopAuthorizeCalculateEvent extends AbstractQSEvent { * * @param shop The shop bought from */ - public ShopAuthorizeCalculateEvent(@NotNull Shop shop, @NotNull UUID authorizer, @NotNull Plugin namespace, @NotNull String permission, boolean result) { + public ShopAuthorizeCalculateEvent( + @NotNull Shop shop, + @NotNull UUID authorizer, + @NotNull Plugin namespace, + @NotNull String permission, + boolean result) { this.shop = shop; this.authorizer = authorizer; this.namespace = namespace; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopClickEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopClickEvent.java index 9b4d4ba9f..0b4a86a82 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopClickEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopClickEvent.java @@ -13,6 +13,7 @@ public class ShopClickEvent extends AbstractQSEvent implements QSCancellable { @NotNull private final Shop shop; + private final Player player; private boolean cancelled; @@ -62,6 +63,4 @@ public class ShopClickEvent extends AbstractQSEvent implements QSCancellable { public boolean isCancelled() { return this.cancelled; } - - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopCreateSuccessEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopCreateSuccessEvent.java index 2a892c951..fa6647d70 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopCreateSuccessEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopCreateSuccessEvent.java @@ -15,7 +15,6 @@ public class ShopCreateSuccessEvent extends AbstractQSEvent { @NotNull private final Shop shop; - /** * Call when have a new shop was created. * @@ -27,7 +26,6 @@ public class ShopCreateSuccessEvent extends AbstractQSEvent { this.creator = creator; } - /** * Gets the creator of this shop * @@ -37,7 +35,6 @@ public class ShopCreateSuccessEvent extends AbstractQSEvent { return this.creator; } - /** * Gets the shop created * diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInfoPanelEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInfoPanelEvent.java index c108249f8..b718c53db 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInfoPanelEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInfoPanelEvent.java @@ -1,14 +1,13 @@ package com.ghostchu.quickshop.api.event; import com.ghostchu.quickshop.api.shop.Shop; +import java.util.UUID; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - /** * Calling when purchaser prepared to purchase a shop (click the shop) */ @@ -19,6 +18,7 @@ public class ShopInfoPanelEvent extends AbstractQSEvent implements QSCancellable @NotNull private final UUID purchaser; + @Nullable private final Player player; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInventoryChangedEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInventoryChangedEvent.java index 72db9d729..47884492b 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInventoryChangedEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopInventoryChangedEvent.java @@ -11,6 +11,7 @@ public class ShopInventoryChangedEvent extends AbstractQSEvent { @NotNull private final InventoryWrapper wrapper; + @NotNull private final InventoryWrapperManager manager; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPlayerGroupSetEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPlayerGroupSetEvent.java index 498e0d869..60d63c368 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPlayerGroupSetEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPlayerGroupSetEvent.java @@ -1,9 +1,8 @@ package com.ghostchu.quickshop.api.event; import com.ghostchu.quickshop.api.shop.Shop; -import org.jetbrains.annotations.NotNull; - import java.util.UUID; +import org.jetbrains.annotations.NotNull; /** * Fire when a player's group is set or changed. @@ -22,7 +21,8 @@ public class ShopPlayerGroupSetEvent extends AbstractQSEvent { * @param oldGroup The old group. * @param newGroup The new group. */ - public ShopPlayerGroupSetEvent(@NotNull Shop shop, @NotNull UUID player, @NotNull String oldGroup, @NotNull String newGroup) { + public ShopPlayerGroupSetEvent( + @NotNull Shop shop, @NotNull UUID player, @NotNull String oldGroup, @NotNull String newGroup) { this.shop = shop; this.player = player; this.oldGroup = oldGroup; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPurchaseEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPurchaseEvent.java index b83cadb06..bbdb65b55 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPurchaseEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopPurchaseEvent.java @@ -38,7 +38,12 @@ public class ShopPurchaseEvent extends AbstractQSEvent implements QSCancellable * @param amount The amount they're buying * @param total The total balance in this purchase */ - public ShopPurchaseEvent(@NotNull Shop shop, @NotNull QUser purchaser, @NotNull InventoryWrapper purchaserInventory, int amount, double total) { + public ShopPurchaseEvent( + @NotNull Shop shop, + @NotNull QUser purchaser, + @NotNull InventoryWrapper purchaserInventory, + int amount, + double total) { this.shop = shop; this.purchaser = purchaser; this.purchaserInventory = purchaserInventory; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopSuccessPurchaseEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopSuccessPurchaseEvent.java index a655d064c..8f2ce514f 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopSuccessPurchaseEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopSuccessPurchaseEvent.java @@ -23,8 +23,7 @@ public class ShopSuccessPurchaseEvent extends AbstractQSEvent { private final double tax; - private final double - total; // Don't use getter, we have important notice need told dev in javadoc. + private final double total; // Don't use getter, we have important notice need told dev in javadoc. /** * Builds a new shop purchase event @@ -38,7 +37,12 @@ public class ShopSuccessPurchaseEvent extends AbstractQSEvent { * @param total The money in this purchase */ public ShopSuccessPurchaseEvent( - @NotNull Shop shop, @NotNull QUser purchaser, @NotNull InventoryWrapper purchaserInventory, int amount, double total, double tax) { + @NotNull Shop shop, + @NotNull QUser purchaser, + @NotNull InventoryWrapper purchaserInventory, + int amount, + double total, + double tax) { this.shop = shop; this.purchaser = purchaser; this.purchaserInventory = purchaserInventory; @@ -76,7 +80,6 @@ public class ShopSuccessPurchaseEvent extends AbstractQSEvent { return this.total; } - /** * Gets the purchaser, that maybe is a online/offline/virtual player. * diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountChangeEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountChangeEvent.java index 1c155f239..24c66806f 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountChangeEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountChangeEvent.java @@ -12,6 +12,7 @@ import org.jetbrains.annotations.Nullable; public class ShopTaxAccountChangeEvent extends AbstractQSEvent implements QSCancellable { @Nullable private final QUser newTaxAccount; + @NotNull private final Shop shop; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountGettingEvent.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountGettingEvent.java index 1252af167..7ad3f7ad0 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountGettingEvent.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/ShopTaxAccountGettingEvent.java @@ -9,6 +9,7 @@ import org.jetbrains.annotations.Nullable; */ public class ShopTaxAccountGettingEvent extends AbstractQSEvent { private final Shop shop; + @Nullable private QUser taxAccount; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/package-info.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/package-info.java index c9a9ae5bc..37b466810 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/package-info.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/event/package-info.java @@ -1,4 +1,4 @@ /** * The QuickShop events that allow addons to listen to. */ -package com.ghostchu.quickshop.api.event; \ No newline at end of file +package com.ghostchu.quickshop.api.event; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/eventmanager/QuickEventManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/eventmanager/QuickEventManager.java index e22cd169e..4750e4e34 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/eventmanager/QuickEventManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/eventmanager/QuickEventManager.java @@ -1,11 +1,10 @@ package com.ghostchu.quickshop.api.eventmanager; +import java.util.function.Consumer; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; - /** * QuickEventManager allow user switch between bukkit and quickshop. * QuickShop's EventManager can filter the Plugin listeners and skip it when calling events @@ -17,5 +16,6 @@ public interface QuickEventManager { * @param event The event * @throws IllegalStateException Just like bukkit */ - void callEvent(@NotNull Event event, @Nullable Consumer callBeforePassToMonitor) throws IllegalStateException; + void callEvent(@NotNull Event event, @Nullable Consumer callBeforePassToMonitor) + throws IllegalStateException; } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapper.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapper.java index 5db2a3208..93cab77dd 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapper.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapper.java @@ -1,6 +1,9 @@ package com.ghostchu.quickshop.api.inventory; import com.ghostchu.quickshop.api.QuickShopAPI; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.inventory.InventoryHolder; @@ -8,10 +11,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * Wrapper to handle inventory/fake inventory/custom inventory etc. */ @@ -68,7 +67,12 @@ public interface InventoryWrapper extends Iterable { */ @NotNull default ItemStack[] createSnapshot() { - Logger.getLogger("QuickShop-Hikari").log(Level.WARNING, "InventoryWrapper provider " + getWrapperManager().getClass().getName() + " didn't override default InventoryWrapper#createSnapshot method, it may cause un-excepted behavior like item missing, mess order and heavy hit performance! Please report this issue to InventoryWrapper provider plugin author!"); + Logger.getLogger("QuickShop-Hikari") + .log( + Level.WARNING, + "InventoryWrapper provider " + + getWrapperManager().getClass().getName() + + " didn't override default InventoryWrapper#createSnapshot method, it may cause un-excepted behavior like item missing, mess order and heavy hit performance! Please report this issue to InventoryWrapper provider plugin author!"); List contents = new ArrayList<>(); for (ItemStack stack : this) { if (stack == null) { @@ -84,21 +88,24 @@ public interface InventoryWrapper extends Iterable { * * @return Wrapper Manager */ - @NotNull InventoryWrapperManager getWrapperManager(); + @NotNull + InventoryWrapperManager getWrapperManager(); /** * Gets the block or entity belonging to the open inventory * * @return The holder of the inventory; null if it has no holder. */ - @Nullable InventoryHolder getHolder(); + @Nullable + InventoryHolder getHolder(); /** * Gets the Inventory Type * * @return The Inventory Type */ - @NotNull InventoryWrapperType getInventoryType(); + @NotNull + InventoryWrapperType getInventoryType(); /** * Get the location of the block or entity which corresponds to this inventory. May return null if this container @@ -106,7 +113,8 @@ public interface InventoryWrapper extends Iterable { * * @return location or null if not applicable. */ - @Nullable Location getLocation(); + @Nullable + Location getLocation(); /** * Do valid check, check if this Inventory is valid. @@ -136,7 +144,8 @@ public interface InventoryWrapper extends Iterable { while (iterator.hasNext()) { ItemStack itemStack = iterator.next(); // TODO: Need lots of verification, it cause mismatch between items under non-Bukkit item matcher - if (itemStack != null && QuickShopAPI.getInstance().getItemMatcher().matches(itemStackToRemove, itemStack)) { + if (itemStack != null + && QuickShopAPI.getInstance().getItemMatcher().matches(itemStackToRemove, itemStack)) { int couldRemove = itemStack.getAmount(); int actuallyRemove = Math.min(itemStackToRemove.getAmount(), couldRemove); itemStack.setAmount(itemStack.getAmount() - actuallyRemove); @@ -165,7 +174,12 @@ public interface InventoryWrapper extends Iterable { * @return The result of rollback. */ default boolean restoreSnapshot(@NotNull ItemStack[] snapshot) { - Logger.getLogger("QuickShop-Hikari").log(Level.WARNING, "InventoryWrapper provider " + getWrapperManager().getClass().getName() + " didn't override default InventoryWrapper#restoreSnapshot method, it may cause un-excepted behavior like item missing, mess order and heavy hit performance! Please report this issue to InventoryWrapper provider plugin author!"); + Logger.getLogger("QuickShop-Hikari") + .log( + Level.WARNING, + "InventoryWrapper provider " + + getWrapperManager().getClass().getName() + + " didn't override default InventoryWrapper#restoreSnapshot method, it may cause un-excepted behavior like item missing, mess order and heavy hit performance! Please report this issue to InventoryWrapper provider plugin author!"); InventoryWrapperIterator it = iterator(); while (it.hasNext()) { it.remove(); @@ -198,7 +212,8 @@ public interface InventoryWrapper extends Iterable { continue AddProcess; } else { if (itemStack.isSimilar(itemStackToAdd)) { - int couldAdd = itemStack.getMaxStackSize() - Math.min(itemStack.getMaxStackSize(), itemStack.getAmount()); + int couldAdd = itemStack.getMaxStackSize() + - Math.min(itemStack.getMaxStackSize(), itemStack.getAmount()); int actuallyAdd = Math.min(itemStackToAdd.getAmount(), couldAdd); itemStack.setAmount(itemStack.getAmount() + actuallyAdd); int needsNow = itemStackToAdd.getAmount() - actuallyAdd; @@ -237,5 +252,4 @@ public interface InventoryWrapper extends Iterable { */ boolean changeItem(int index, ItemStack itemStack); } - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperIterator.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperIterator.java index a58ba85a8..cf097bc07 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperIterator.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperIterator.java @@ -1,18 +1,16 @@ package com.ghostchu.quickshop.api.inventory; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - import java.util.Iterator; import java.util.NoSuchElementException; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; /** * Iterator for InventoryWrapper */ public interface InventoryWrapperIterator extends Iterator { - /** * Return the default implementation for bukkit inventory * diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperManager.java index 7d953ad7d..22514345e 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperManager.java @@ -27,6 +27,4 @@ public interface InventoryWrapperManager { */ @NotNull String mklink(@NotNull InventoryWrapper wrapper) throws IllegalArgumentException; - - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperRegistry.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperRegistry.java index af18585c8..f59793ef7 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperRegistry.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/inventory/InventoryWrapperRegistry.java @@ -1,12 +1,11 @@ package com.ghostchu.quickshop.api.inventory; import com.google.common.collect.MapMaker; +import java.util.Map; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; - public class InventoryWrapperRegistry { private final Map registry = new MapMaker().makeMap(); @@ -27,10 +26,13 @@ public class InventoryWrapperRegistry { public void register(@NotNull Plugin plugin, @NotNull InventoryWrapperManager manager) { if (registry.containsKey(plugin.getName())) { - plugin.getLogger().warning("Nag Author: Plugin " + plugin.getName() + " already have a registered InventoryWrapperManager: " - + registry.get(plugin.getName()).getClass().getName() + - " but trying register another new manager: " + manager.getClass().getName() + - ". This may cause unexpected behavior! Replacing with new instance..."); + plugin.getLogger() + .warning("Nag Author: Plugin " + plugin.getName() + + " already have a registered InventoryWrapperManager: " + + registry.get(plugin.getName()).getClass().getName() + + " but trying register another new manager: " + + manager.getClass().getName() + + ". This may cause unexpected behavior! Replacing with new instance..."); } registry.put(plugin.getName(), manager); } @@ -38,6 +40,4 @@ public class InventoryWrapperRegistry { public void unregister(@NotNull Plugin plugin) { registry.remove(plugin.getName()); } - - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/ProxiedLocale.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/ProxiedLocale.java index 8962aab5a..1f6df8940 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/ProxiedLocale.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/ProxiedLocale.java @@ -7,6 +7,7 @@ import org.jetbrains.annotations.Nullable; public class ProxiedLocale { @Nullable private String origin; + private String relative; public ProxiedLocale(@Nullable String origin, String relative) { diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/Text.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/Text.java index 121419b91..399b8c8bc 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/Text.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/Text.java @@ -13,14 +13,16 @@ public interface Text { * @param locale The minecraft locale code (like en_us) * @return The text */ - @NotNull Component forLocale(@NotNull String locale); + @NotNull + Component forLocale(@NotNull String locale); /** * Getting the text for player locale * * @return Getting the text for player locale */ - @NotNull Component forLocale(); + @NotNull + Component forLocale(); /** * Getting this text is exists in the translation file diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextList.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextList.java index 5349f10f5..eb1bf790f 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextList.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextList.java @@ -1,10 +1,9 @@ package com.ghostchu.quickshop.api.localization.text; +import java.util.List; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; -import java.util.List; - /** * The Texts of a series of the translation. */ @@ -16,14 +15,16 @@ public interface TextList { * @param locale The minecraft locale code (like en_us) * @return The text */ - @NotNull List forLocale(@NotNull String locale); + @NotNull + List forLocale(@NotNull String locale); /** * Getting the text for player locale * * @return Getting the text for player locale */ - @NotNull List forLocale(); + @NotNull + List forLocale(); /** * Getting this text is exists in the translation file @@ -32,7 +33,6 @@ public interface TextList { */ boolean isPresent(); - /** * Send text to the player */ diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextManager.java index 1658f8a36..faf4363c5 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/localization/text/TextManager.java @@ -1,27 +1,31 @@ package com.ghostchu.quickshop.api.localization.text; import com.ghostchu.quickshop.api.obj.QUser; +import java.util.List; +import java.util.UUID; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; -import java.util.UUID; - /** * The TextManager that allow create user's locale specified message. */ public interface TextManager { - @NotNull Component[] convert(@Nullable Object... args); + @NotNull + Component[] convert(@Nullable Object... args); - @NotNull ProxiedLocale findRelativeLanguages(@Nullable String langCode); + @NotNull + ProxiedLocale findRelativeLanguages(@Nullable String langCode); - @NotNull ProxiedLocale findRelativeLanguages(@Nullable CommandSender sender); + @NotNull + ProxiedLocale findRelativeLanguages(@Nullable CommandSender sender); - @NotNull ProxiedLocale findRelativeLanguages(@Nullable UUID sender, boolean allowDbLoad); + @NotNull + ProxiedLocale findRelativeLanguages(@Nullable UUID sender, boolean allowDbLoad); - @NotNull ProxiedLocale findRelativeLanguages(@Nullable QUser qUser, boolean allowDbLoad); + @NotNull + ProxiedLocale findRelativeLanguages(@Nullable QUser qUser, boolean allowDbLoad); /** * Return the set of available Languages @@ -80,7 +84,6 @@ public interface TextManager { @NotNull Text of(@Nullable UUID sender, @NotNull String path, @Nullable Object... args); - /** * Getting the translation with path with player's locale (if available) * diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/obj/QUser.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/obj/QUser.java index bcaef71bd..4809bfcdc 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/obj/QUser.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/obj/QUser.java @@ -1,22 +1,26 @@ package com.ghostchu.quickshop.api.obj; +import java.util.Optional; +import java.util.UUID; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Optional; -import java.util.UUID; - public interface QUser { - @Nullable String getUsername(); + @Nullable + String getUsername(); - @NotNull Optional getUsernameOptional(); + @NotNull + Optional getUsernameOptional(); - @NotNull String getDisplay(); + @NotNull + String getDisplay(); - @Nullable UUID getUniqueId(); + @Nullable + UUID getUniqueId(); - @NotNull Optional getUniqueIdOptional(); + @NotNull + Optional getUniqueIdOptional(); boolean isRealPlayer(); diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/operation/Operation.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/operation/Operation.java index 666a149f8..1bbdc9800 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/operation/Operation.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/operation/Operation.java @@ -30,6 +30,5 @@ public interface Operation { * * @return true if successes */ - boolean rollback(); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/package-info.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/package-info.java index c191ec4c8..25a71fdf3 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/package-info.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/package-info.java @@ -1,4 +1,4 @@ /** * The QuickShop API package */ -package com.ghostchu.quickshop.api; \ No newline at end of file +package com.ghostchu.quickshop.api; diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/permission/PermissionProvider.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/permission/PermissionProvider.java index 7461475af..33dd7cf22 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/permission/PermissionProvider.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/permission/PermissionProvider.java @@ -34,5 +34,4 @@ public interface PermissionProvider { * @return hasPermission */ boolean hasPermission(@NotNull QUser sender, @NotNull String permission); - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/serialize/BlockPos.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/serialize/BlockPos.java index ceb764327..a7933cae0 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/serialize/BlockPos.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/serialize/BlockPos.java @@ -30,12 +30,10 @@ public final class BlockPos { return x; } - public int getY() { return y; } - public int getZ() { return z; } @@ -46,13 +44,12 @@ public final class BlockPos { @Override public String toString() { - return "BlockPos{" + - "version=" + version + - ", x=" + x + - ", y=" + y + - ", z=" + z + - ", world='" + world + '\'' + - '}'; + return "BlockPos{" + "version=" + + version + ", x=" + + x + ", y=" + + y + ", z=" + + z + ", world='" + + world + '\'' + '}'; } public static BlockPos deserialize(String string) { @@ -61,7 +58,8 @@ public final class BlockPos { if (split.length < 5) { throw new IllegalArgumentException("Invalid input string for deserialization"); } - return new BlockPos(Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), split[4]); + return new BlockPos( + Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), split[4]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse integer during deserialization", e); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Info.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Info.java index 58b159463..ba470e16b 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Info.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Info.java @@ -13,24 +13,28 @@ public interface Info { /** * @return ShopAction action, Get shop action. */ - @NotNull ShopAction getAction(); + @NotNull + ShopAction getAction(); void setAction(@NotNull ShopAction action); /** * @return ItemStack iStack, Get Shop's selling/buying item's ItemStack. */ - @NotNull ItemStack getItem(); + @NotNull + ItemStack getItem(); /** * @return Location loc, Get shop's location, */ - @NotNull Location getLocation(); + @NotNull + Location getLocation(); /** * @return Block signBlock, Get block of shop's sign, may return the null. */ - @Nullable Block getSignBlock(); + @Nullable + Block getSignBlock(); /** * Get shop is or not has changed. @@ -46,5 +50,4 @@ public interface Info { * @return Bypassed Protection Checks */ boolean isBypassed(); - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/InventoryTransaction.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/InventoryTransaction.java index a49daecd9..528885702 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/InventoryTransaction.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/InventoryTransaction.java @@ -2,13 +2,12 @@ package com.ghostchu.quickshop.api.shop; import com.ghostchu.quickshop.api.inventory.InventoryWrapper; import com.ghostchu.quickshop.api.operation.Operation; +import java.util.Deque; +import java.util.List; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Deque; -import java.util.List; - public interface InventoryTransaction { /** * Commit the transaction @@ -67,7 +66,8 @@ public interface InventoryTransaction { * @return A list contains all steps executed. If "continueWhenFailed" is false, it only contains all success steps before hit the error. Else all. */ @SuppressWarnings("UnusedReturnValue") - @NotNull List rollback(boolean continueWhenFailed); + @NotNull + List rollback(boolean continueWhenFailed); interface TransactionCallback { /** @@ -87,17 +87,13 @@ public interface InventoryTransaction { * * @param transaction Transaction */ - default void onFailed(@NotNull InventoryTransaction transaction) { - } + default void onFailed(@NotNull InventoryTransaction transaction) {} /** * Calling while Transaction commit successfully * * @param transaction Transaction */ - default void onSuccess(@NotNull InventoryTransaction transaction) { - } - - + default void onSuccess(@NotNull InventoryTransaction transaction) {} } } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ItemMatcher.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ItemMatcher.java index 609a51d0e..eb37668e2 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ItemMatcher.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ItemMatcher.java @@ -14,14 +14,16 @@ public interface ItemMatcher { * * @return Provider name */ - @NotNull String getName(); + @NotNull + String getName(); /** * Gets the ItemMatcher provider plugin instance * * @return Provider Plugin instance */ - @NotNull Plugin getPlugin(); + @NotNull + Plugin getPlugin(); /** * Tests ItemStacks is matches diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PlayerFinder.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PlayerFinder.java index de7971667..24674dbad 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PlayerFinder.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PlayerFinder.java @@ -1,28 +1,37 @@ package com.ghostchu.quickshop.api.shop; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface PlayerFinder { - @Nullable String uuid2Name(@NotNull UUID uuid); + @Nullable + String uuid2Name(@NotNull UUID uuid); - @Nullable String uuid2Name(@NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService); + @Nullable + String uuid2Name(@NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService); - @Nullable UUID name2Uuid(@NotNull String name); + @Nullable + UUID name2Uuid(@NotNull String name); - @Nullable UUID name2Uuid(@NotNull String name, boolean writeCache, @NotNull ExecutorService executorService); + @Nullable + UUID name2Uuid(@NotNull String name, boolean writeCache, @NotNull ExecutorService executorService); - @NotNull CompletableFuture uuid2NameFuture(@NotNull UUID uuid); + @NotNull + CompletableFuture uuid2NameFuture(@NotNull UUID uuid); - @NotNull CompletableFuture uuid2NameFuture(@NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService); + @NotNull + CompletableFuture uuid2NameFuture( + @NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService); - @NotNull CompletableFuture name2UuidFuture(@NotNull String name); + @NotNull + CompletableFuture name2UuidFuture(@NotNull String name); - @NotNull CompletableFuture name2UuidFuture(@NotNull String name, boolean writeCache, @NotNull ExecutorService executorService); + @NotNull + CompletableFuture name2UuidFuture( + @NotNull String name, boolean writeCache, @NotNull ExecutorService executorService); void cache(@NotNull UUID uuid, @NotNull String name); diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PriceLimiter.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PriceLimiter.java index 0dde09932..331cedad0 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PriceLimiter.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/PriceLimiter.java @@ -18,5 +18,7 @@ public interface PriceLimiter { * @param price the price * @return the result */ - @NotNull PriceLimiterCheckResult check(@NotNull CommandSender sender, @NotNull ItemStack stack, @Nullable String currency, double price); + @NotNull + PriceLimiterCheckResult check( + @NotNull CommandSender sender, @NotNull ItemStack stack, @Nullable String currency, double price); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Shop.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Shop.java index a7e85a4a8..3fae3f119 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Shop.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/Shop.java @@ -8,6 +8,10 @@ import com.ghostchu.quickshop.api.localization.text.ProxiedLocale; import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermissionGroup; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; import net.kyori.adventure.text.Component; import org.bukkit.Location; import org.bukkit.NamespacedKey; @@ -21,11 +25,6 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; - /** * A shop */ @@ -49,7 +48,8 @@ public interface Shop { * @param paramInt How many buyed? * @throws Exception Possible exception thrown if anything wrong. */ - void buy(@NotNull QUser buyer, @NotNull InventoryWrapper buyerInventory, @NotNull Location loc2Drop, int paramInt) throws Exception; + void buy(@NotNull QUser buyer, @NotNull InventoryWrapper buyerInventory, @NotNull Location loc2Drop, int paramInt) + throws Exception; /** * Check the display location, and teleport, respawn if needs. @@ -99,7 +99,8 @@ public interface Shop { * * @return Inventory */ - @Nullable InventoryWrapper getInventory(); + @Nullable + InventoryWrapper getInventory(); /** * Gets the InventoryWrapper provider name (the plugin name who register it), usually is QuickShop @@ -132,7 +133,6 @@ public interface Shop { @NotNull Location getLocation(); - /** * Get shop's owner QUser * @@ -199,7 +199,8 @@ public interface Shop { * * @return Random UUID */ - @NotNull UUID getRuntimeRandomUniqueId(); + @NotNull + UUID getRuntimeRandomUniqueId(); /** * Gets the Shop ID to identify the shop. @@ -260,7 +261,7 @@ public interface Shop { * Line 3: Price */ default List getSignText(@NotNull ProxiedLocale locale) { - //backward support + // backward support throw new UnsupportedOperationException(); } @@ -292,7 +293,6 @@ public interface Shop { * * @return Shop Tax Account, null if use general tax account */ - @Nullable QUser getTaxAccountActual(); @@ -417,7 +417,6 @@ public interface Shop { */ void onClick(@NotNull Player clicker); - @Deprecated() @ApiStatus.Internal void handleLoading(); @@ -508,8 +507,7 @@ public interface Shop { * Refresh shop sign and display item */ @Deprecated(forRemoval = true) - default void refresh() { - } + default void refresh() {} /** * Remove x ItemStack from the shop inventory @@ -551,7 +549,9 @@ public interface Shop { * @param paramInt How many sold? * @throws Exception Possible exception thrown if anything wrong. */ - void sell(@NotNull QUser seller, @NotNull InventoryWrapper sellerInventory, @NotNull Location loc2Drop, int paramInt) throws Exception; + void sell( + @NotNull QUser seller, @NotNull InventoryWrapper sellerInventory, @NotNull Location loc2Drop, int paramInt) + throws Exception; /** * Sets shop is dirty @@ -614,5 +614,4 @@ public interface Shop { * Sets the benefit in this shop */ void setShopBenefit(@NotNull Benefit benefit); - } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanel.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanel.java index 4f55e732b..67b40b7f1 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanel.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanel.java @@ -1,12 +1,11 @@ package com.ghostchu.quickshop.api.shop; +import java.util.List; import net.kyori.adventure.text.Component; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.List; - /** * The shop control panel impl. */ @@ -18,7 +17,8 @@ public interface ShopControlPanel { * @param shop The shop * @return The components, or empty list if nothing to show. Every component will be shown in a new line. */ - @NotNull List generate(@NotNull Player player, @NotNull Shop shop); + @NotNull + List generate(@NotNull Player player, @NotNull Shop shop); /** * Usually you don't need touch this :) @@ -44,5 +44,6 @@ public interface ShopControlPanel { * * @return Your plugin instance; */ - @NotNull Plugin getPlugin(); + @NotNull + Plugin getPlugin(); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanelManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanelManager.java index 2acf8af09..54cfcbcf6 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanelManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopControlPanelManager.java @@ -14,7 +14,6 @@ public interface ShopControlPanelManager { * @param player the player to open * @param shop the shop to open */ - void openControlPanel(@NotNull Player player, @NotNull Shop shop); /** @@ -36,6 +35,5 @@ public interface ShopControlPanelManager { * * @param panel the panel to unregister */ - void unregister(@NotNull ShopControlPanel panel); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopInfoStorage.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopInfoStorage.java index ae0e594a9..5334e38b8 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopInfoStorage.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopInfoStorage.java @@ -2,10 +2,9 @@ package com.ghostchu.quickshop.api.shop; import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.quickshop.api.serialize.BlockPos; -import lombok.Data; - import java.util.Map; import java.util.UUID; +import lombok.Data; /** * Minimal information about a shop. @@ -27,7 +26,21 @@ public class ShopInfoStorage { private final String symbolLink; private final Map permission; - public ShopInfoStorage(String world, BlockPos position, QUser owner, double price, String item, int unlimited, int shopType, String extra, String currency, boolean disableDisplay, QUser taxAccount, String inventoryWrapperName, String symbolLink, Map permission) { + public ShopInfoStorage( + String world, + BlockPos position, + QUser owner, + double price, + String item, + int unlimited, + int shopType, + String extra, + String currency, + boolean disableDisplay, + QUser taxAccount, + String inventoryWrapperName, + String symbolLink, + Map permission) { this.world = world; this.position = position; this.owner = owner.serialize(); diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopManager.java index 9103baa58..de2af20e4 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopManager.java @@ -3,6 +3,8 @@ package com.ghostchu.quickshop.api.shop; import com.ghostchu.quickshop.api.economy.AbstractEconomy; import com.ghostchu.quickshop.api.inventory.InventoryWrapper; import com.ghostchu.quickshop.api.obj.QUser; +import java.util.*; +import java.util.concurrent.CompletableFuture; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; @@ -12,9 +14,6 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.concurrent.CompletableFuture; - /** * The manager that managing shops */ @@ -66,14 +65,14 @@ public interface ShopManager { @NotNull Shop shop, int amount); -// /** -// * Adds a shop to the world. Does NOT require the chunk or world to be loaded Call shop.onLoad -// * by yourself -// * -// * @param world The name of the world -// * @param shop The shop to add -// */ -// void addShop(@NotNull String world, @NotNull Shop shop); + // /** + // * Adds a shop to the world. Does NOT require the chunk or world to be loaded Call shop.onLoad + // * by yourself + // * + // * @param world The name of the world + // * @param shop The shop to add + // */ + // void addShop(@NotNull String world, @NotNull Shop shop); void bakeShopRuntimeRandomUniqueIdCache(@NotNull Shop shop); @@ -91,7 +90,8 @@ public interface ShopManager { * @param bypassProtectCheck Should bypass protection check * @throws IllegalStateException If the shop owner offline */ - void createShop(@NotNull Shop shop, @Nullable Block signBlock, boolean bypassProtectCheck) throws IllegalStateException; + void createShop(@NotNull Shop shop, @Nullable Block signBlock, boolean bypassProtectCheck) + throws IllegalStateException; /** * Format the price use formatter @@ -101,7 +101,8 @@ public interface ShopManager { * @param world shop world * @return formated price */ - @NotNull String format(double d, @NotNull World world, @Nullable String currency); + @NotNull + String format(double d, @NotNull World world, @Nullable String currency); /** * Format the price use formatter @@ -110,14 +111,16 @@ public interface ShopManager { * @param shop The shop * @return formated price */ - @NotNull String format(double d, @NotNull Shop shop); + @NotNull + String format(double d, @NotNull Shop shop); /** * @return Returns the Map. Info contains what their last question etc was. * @deprecated Use getInteractiveManager() instead. */ @Deprecated(forRemoval = true) - @NotNull Map getActions(); + @NotNull + Map getActions(); /** * Returns all shops in the whole database, include unloaded. @@ -126,14 +129,16 @@ public interface ShopManager { * * @return All shop in the database */ - @NotNull List getAllShops(); + @NotNull + List getAllShops(); /** * Get all loaded shops. * * @return All loaded shops. */ - @NotNull Set getLoadedShops(); + @NotNull + Set getLoadedShops(); /** * Get a players all shops. @@ -143,7 +148,8 @@ public interface ShopManager { * @param playerUUID The player's uuid. * @return The list have this player's all shops. */ - @NotNull List getAllShops(@NotNull QUser playerUUID); + @NotNull + List getAllShops(@NotNull QUser playerUUID); /** * Get a players all shops. @@ -153,7 +159,8 @@ public interface ShopManager { * @param playerUUID The player's uuid. * @return The list have this player's all shops. */ - @NotNull List getAllShops(@NotNull UUID playerUUID); + @NotNull + List getAllShops(@NotNull UUID playerUUID); /** * Getting the Shop Price Limiter @@ -168,7 +175,8 @@ public interface ShopManager { * * @return The shop object */ - @Nullable Shop getShop(long shopId); + @Nullable + Shop getShop(long shopId); /** * Gets a shop in a specific location @@ -177,7 +185,8 @@ public interface ShopManager { * @param loc The location to get the shop from * @return The shop at that location */ - @Nullable Shop getShop(@NotNull Location loc); + @Nullable + Shop getShop(@NotNull Location loc); /** * Gets a shop in a specific location but via cache @@ -186,7 +195,8 @@ public interface ShopManager { * @param loc The location to get the shop from * @return The shop at that location but via cache */ - @Nullable Shop getShopViaCache(@NotNull Location loc); + @Nullable + Shop getShopViaCache(@NotNull Location loc); /** * Gets a shop in a specific location @@ -196,12 +206,14 @@ public interface ShopManager { * @param skipShopableChecking whether to check is shopable * @return The shop at that location */ - @Nullable Shop getShop(@NotNull Location loc, boolean skipShopableChecking); + @Nullable + Shop getShop(@NotNull Location loc, boolean skipShopableChecking); + @Nullable + Shop getShopFromRuntimeRandomUniqueId(@NotNull UUID runtimeRandomUniqueId); - @Nullable Shop getShopFromRuntimeRandomUniqueId(@NotNull UUID runtimeRandomUniqueId); - - @Nullable Shop getShopFromRuntimeRandomUniqueId(@NotNull UUID runtimeRandomUniqueId, boolean includeInvalid); + @Nullable + Shop getShopFromRuntimeRandomUniqueId(@NotNull UUID runtimeRandomUniqueId, boolean includeInvalid); /** * Gets a shop in a specific location Include the attached shop, e.g DoubleChest shop. @@ -209,7 +221,8 @@ public interface ShopManager { * @param loc The location to get the shop from * @return The shop at that location */ - @Nullable Shop getShopIncludeAttached(@Nullable Location loc); + @Nullable + Shop getShopIncludeAttached(@Nullable Location loc); /** * Gets a shop in a specific location Include the attached shop, e.g DoubleChest shop. but via cache @@ -217,8 +230,8 @@ public interface ShopManager { * @param loc The location to get the shop from * @return The shop at that location but via cache */ - @Nullable Shop getShopIncludeAttachedViaCache(@Nullable Location loc); - + @Nullable + Shop getShopIncludeAttachedViaCache(@Nullable Location loc); /** * Returns a new shop iterator object, allowing iteration over shops easily, instead of sorting @@ -226,14 +239,16 @@ public interface ShopManager { * * @return a new shop iterator object. */ - @NotNull Iterator getShopIterator(); + @NotNull + Iterator getShopIterator(); /** * Returns a map of World - Chunk - Shop * * @return a map of World - Chunk - Shop */ - @NotNull Map>> getShops(); + @NotNull + Map>> getShops(); /** * Returns a map of Shops @@ -242,7 +257,8 @@ public interface ShopManager { * used. * @return Shops */ - @Nullable Map getShops(@NotNull Chunk c); + @Nullable + Map getShops(@NotNull Chunk c); /** * Gets the shop at the world and specific chunk. @@ -252,7 +268,8 @@ public interface ShopManager { * @param chunkZ The chunk z coordinate * @return The shop at the world and specific chunk. */ - @Nullable Map getShops(@NotNull String world, int chunkX, int chunkZ); + @Nullable + Map getShops(@NotNull String world, int chunkX, int chunkZ); /** * Gets the shop at the world and specific chunk. @@ -260,7 +277,8 @@ public interface ShopManager { * @param shopChunk The shop chunk * @return The shop at the world and specific chunk. */ - @Nullable Map getShops(@NotNull ShopChunk shopChunk); + @Nullable + Map getShops(@NotNull ShopChunk shopChunk); /** * Returns a map of Chunk - Shop @@ -268,7 +286,8 @@ public interface ShopManager { * @param world The name of the world (case sensitive) to get the list of shops from * @return a map of Chunk - Shop */ - @Nullable Map> getShops(@NotNull String world); + @Nullable + Map> getShops(@NotNull String world); /** * Get the all shops in the world. @@ -276,7 +295,8 @@ public interface ShopManager { * @param world The world you want get the shops. * @return The list have this world all shops */ - @NotNull List getShopsInWorld(@NotNull World world); + @NotNull + List getShopsInWorld(@NotNull World world); /** * Get the all shops in the world. @@ -284,8 +304,8 @@ public interface ShopManager { * @param worldName The world you want get the shops. * @return The list have this world all shops */ - @NotNull List getShopsInWorld(@NotNull String worldName); - + @NotNull + List getShopsInWorld(@NotNull String worldName); /** * Get the tax of the shop @@ -393,7 +413,8 @@ public interface ShopManager { @NotNull ShopManager.InteractiveManager getInteractiveManager(); - @NotNull CompletableFuture<@NotNull List> queryTaggedShops(@NotNull UUID tagger, @NotNull String tag); + @NotNull + CompletableFuture<@NotNull List> queryTaggedShops(@NotNull UUID tagger, @NotNull String tag); CompletableFuture<@Nullable Integer> clearShopTags(@NotNull UUID tagger, @NotNull Shop shop); @@ -403,7 +424,8 @@ public interface ShopManager { CompletableFuture<@Nullable Integer> tagShop(@NotNull UUID tagger, @NotNull Shop shop, @NotNull String tag); - @NotNull List listTags(@NotNull UUID tagger); + @NotNull + List listTags(@NotNull UUID tagger); void deleteShop(@NotNull Shop shop); diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopModerator.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopModerator.java index 06e240299..a14601a48 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopModerator.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopModerator.java @@ -2,10 +2,9 @@ package com.ghostchu.quickshop.api.shop; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; -import org.jetbrains.annotations.NotNull; - import java.util.List; import java.util.UUID; +import org.jetbrains.annotations.NotNull; /** * Contains shop's moderators infomations, owner, staffs etc. @@ -67,7 +66,8 @@ public interface ShopModerator { * * @return Owner's UUID */ - @NotNull UUID getOwner(); + @NotNull + UUID getOwner(); /** * Set moderators owner (Shop Owner) @@ -81,7 +81,8 @@ public interface ShopModerator { * * @return Staffs */ - @NotNull List getStaffs(); + @NotNull + List getStaffs(); /** * Set moderators staffs @@ -115,6 +116,6 @@ public interface ShopModerator { boolean isStaff(@NotNull UUID player); @Override - @NotNull String toString(); - + @NotNull + String toString(); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopPermissionManager.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopPermissionManager.java index c6bb584d8..bfc0ad218 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopPermissionManager.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopPermissionManager.java @@ -1,11 +1,10 @@ package com.ghostchu.quickshop.api.shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - import java.util.Collection; import java.util.List; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; /** * Shop permission manager. @@ -17,7 +16,8 @@ public interface ShopPermissionManager { * * @return Groups. */ - @NotNull List getGroups(); + @NotNull + List getGroups(); /** * Gets the permission list of a group. diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopType.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopType.java index 1a758b419..20d136606 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopType.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/ShopType.java @@ -25,7 +25,6 @@ public enum ShopType { return null; } - public static @NotNull ShopType fromID(int id) { for (ShopType type : ShopType.values()) { if (type.id == id) { diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/cache/ShopCache.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/cache/ShopCache.java index ce8e73aa4..50ca5ee98 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/cache/ShopCache.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/cache/ShopCache.java @@ -8,11 +8,13 @@ import org.jetbrains.annotations.Nullable; public interface ShopCache { - @Nullable Shop get(@NotNull ShopCacheNamespacedKey namespacedKey, @NotNull Location location, boolean allowLoading); + @Nullable + Shop get(@NotNull ShopCacheNamespacedKey namespacedKey, @NotNull Location location, boolean allowLoading); void invalidateAll(@Nullable ShopCacheNamespacedKey namespacedKey); void invalidate(@Nullable ShopCacheNamespacedKey namespacedKey, @NotNull Location location); - @NotNull CacheStats getCacheStats(@NotNull ShopCacheNamespacedKey namespacedKey); + @NotNull + CacheStats getCacheStats(@NotNull ShopCacheNamespacedKey namespacedKey); } diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/display/DisplayType.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/display/DisplayType.java index 4f85f448d..5216e5aaf 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/display/DisplayType.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/display/DisplayType.java @@ -1,10 +1,9 @@ package com.ghostchu.quickshop.api.shop.display; -import org.jetbrains.annotations.NotNull; - import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.jetbrains.annotations.NotNull; public enum DisplayType { /* diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermission.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermission.java index 3af2bd7e9..6a5f00260 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermission.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermission.java @@ -2,9 +2,8 @@ package com.ghostchu.quickshop.api.shop.permission; import com.ghostchu.quickshop.api.QuickShopAPI; import com.ghostchu.quickshop.api.shop.ShopPermissionAudience; -import org.jetbrains.annotations.NotNull; - import java.util.Locale; +import org.jetbrains.annotations.NotNull; public enum BuiltInShopPermission implements ShopPermissionAudience { PURCHASE("purchase", "purchase"), diff --git a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermissionGroup.java b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermissionGroup.java index 96d685656..2f7893d67 100644 --- a/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermissionGroup.java +++ b/quickshop-api/src/main/java/com/ghostchu/quickshop/api/shop/permission/BuiltInShopPermissionGroup.java @@ -1,28 +1,41 @@ package com.ghostchu.quickshop.api.shop.permission; +import static com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission.*; + import com.ghostchu.quickshop.api.QuickShopAPI; import com.ghostchu.quickshop.api.shop.ShopPermissionAudience; import com.google.common.collect.ImmutableList; -import org.jetbrains.annotations.NotNull; - import java.util.List; import java.util.Locale; - -import static com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission.*; +import org.jetbrains.annotations.NotNull; public enum BuiltInShopPermissionGroup implements ShopPermissionAudience { BLOCKED("blocked", "blocked"), EVERYONE("everyone", "everyone", PURCHASE, SHOW_INFORMATION, PREVIEW_SHOP, SEARCH), - STAFF("staff", "staff", PURCHASE, SHOW_INFORMATION, PREVIEW_SHOP, SEARCH, ACCESS_INVENTORY, - TOGGLE_DISPLAY, SET_SHOPTYPE, SET_PRICE, SET_ITEM, SET_STACK_AMOUNT, - SET_CURRENCY, RECEIVE_ALERT, SET_BENEFIT), + STAFF( + "staff", + "staff", + PURCHASE, + SHOW_INFORMATION, + PREVIEW_SHOP, + SEARCH, + ACCESS_INVENTORY, + TOGGLE_DISPLAY, + SET_SHOPTYPE, + SET_PRICE, + SET_ITEM, + SET_STACK_AMOUNT, + SET_CURRENCY, + RECEIVE_ALERT, + SET_BENEFIT), ADMINISTRATOR("administrator", "administrator", BuiltInShopPermission.values()); private final String node; private final String descriptionKey; private final List permissions; - BuiltInShopPermissionGroup(@NotNull String node, @NotNull String descriptionKey, @NotNull BuiltInShopPermission... permissions) { + BuiltInShopPermissionGroup( + @NotNull String node, @NotNull String descriptionKey, @NotNull BuiltInShopPermission... permissions) { this.node = node; this.descriptionKey = descriptionKey; this.permissions = ImmutableList.copyOf(permissions); diff --git a/quickshop-bukkit/.gitignore b/quickshop-bukkit/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/quickshop-bukkit/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/quickshop-bukkit/pom.xml b/quickshop-bukkit/pom.xml deleted file mode 100644 index 3247d92b8..000000000 --- a/quickshop-bukkit/pom.xml +++ /dev/null @@ -1,315 +0,0 @@ - - - - 4.0.0 - - - com.ghostchu - quickshop-hikari - 5.2.0.7 - - - quickshop-bukkit - jar - QuickShop-OG - - - QuickShop-OG-${project.version} - - - - src/main/resources - true - - lang/messages.json - - - - ../crowdin - true - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 3.1.0 - - - copy-jar - package - - run - - - - - - - - - - - - - - - dmulloy2-repo - https://repo.dmulloy2.net/repository/public/ - - - essentials - https://repo.essentialsx.net/releases/ - - - placeholderapi - https://repo.extendedclip.com/content/repositories/placeholderapi/ - - - papermc - https://repo.papermc.io/repository/maven-public/ - - - CodeMC - https://repo.codemc.io/repository/maven-public/ - - - codemc-releases - https://repo.codemc.io/repository/maven-releases/ - - - md_5-snapshots - https://repo.md-5.net/content/repositories/snapshots/ - - - jitpack.io - https://www.jitpack.io - - - - - - org.spigotmc - spigot-api - - - com.ghostchu - quickshop-api - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_18_R1 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_18_R2 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_19_R1 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_19_R2 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_19_R3 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_20_R1 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_20_R2 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-spigot-v1_20_R3 - ${parent.version} - compile - - - com.ghostchu - quickshop-platform-paper - ${parent.version} - compile - - - com.comphenix.protocol - ProtocolLib - 5.0.0 - provided - - - com.github.MilkBowl - VaultAPI - 1.7.1 - provided - - - * - * - - - - - me.clip - placeholderapi - 2.11.5 - provided - - - * - * - - - - - me.xanium - GemsEconomy - system - 4.9.3-GCRemake-1.6 - ${project.basedir}/lib/GemsEconomy-4.9.2.jar - - - * - * - - - - - net.tnemc - EconomyCore - 0.1.2.6-Pre1 - provided - - - * - * - - - - - io.papermc - paperlib - LATEST - compile - - - net.tnemc - Reserve - 0.1.5.3-SNAPSHOT-4 - provided - - - * - * - - - - - com.h2database - h2 - 2.1.214 - provided - - - com.konghq - unirest-java - 3.14.5 - provided - - - com.github.juliomarcopineda - jdbc-stream - 0.1.1 - provided - - - net.sourceforge.csvjdbc - csvjdbc - 1.0.41 - provided - - - org.dom4j - dom4j - 2.1.4 - provided - - - net.essentialsx - EssentialsX - 2.20.1 - provided - - - paperlib - io.papermc - - - snakeyaml - org.yaml - - - error_prone_annotations - com.google.errorprone - - - checker-qual - org.checkerframework - - - - - com.ghostchu.crowdin - crowdinota - 1.0.3 - provided - - - org.bstats - bstats-bukkit - 3.0.2 - compile - - - com.rollbar - rollbar-java - 1.10.0 - provided - - - org.slf4j - slf4j-api - - - - - - diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BootError.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BootError.java index 91406ce1d..af688e879 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BootError.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BootError.java @@ -1,5 +1,6 @@ package com.ghostchu.quickshop; +import java.util.Arrays; import lombok.EqualsAndHashCode; import lombok.ToString; import org.bukkit.ChatColor; @@ -7,8 +8,6 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; -import java.util.Arrays; - /** * BootError class contains print errors on /quickshop command when plugin failed launched. * @@ -38,7 +37,7 @@ public class BootError { * * @param sender The sender you want output the errors. */ - public void printErrors(CommandSender sender) { //Do not use any method that not in CraftBukkit + public void printErrors(CommandSender sender) { // Do not use any method that not in CraftBukkit sender.sendMessage(ChatColor.RED + "#####################################################"); sender.sendMessage(ChatColor.RED + " QuickShop is disabled, Please fix any errors and restart"); for (String issue : errors) { @@ -46,5 +45,4 @@ public class BootError { } sender.sendMessage(ChatColor.RED + "#####################################################"); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuildInfo.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuildInfo.java index f27ce9b96..c32689a0e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuildInfo.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuildInfo.java @@ -1,15 +1,14 @@ package com.ghostchu.quickshop; import com.ghostchu.quickshop.util.logger.Log; +import java.io.InputStream; +import java.util.Objects; +import java.util.Properties; import lombok.Data; import lombok.SneakyThrows; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.InputStream; -import java.util.Objects; -import java.util.Properties; - /** * BuildInfo is utilities to help read BUILDINFO file that generated by CodeMC Jenkins. * @@ -36,33 +35,48 @@ public class BuildInfo { public static class GitInfo { private static final String DEFAULT_VALUE = "undefined"; + @Nullable private final String branch; + private final boolean dirty; + @Nullable private final String remoteOriginUrl; + @Nullable private final String id; + @Nullable private final String abbrev; + @Nullable private final String describe; + @Nullable private final String describeShort; + @Nullable private final String commitUsername; + @Nullable private final String commitEmail; + @Nullable private final String commitMessage; + @Nullable private final String commitDate; + @Nullable private final String buildTime; + @Nullable private final String buildVersion; + @Nullable private final String buildNumber; + @Nullable private final String tags; @@ -175,20 +189,25 @@ public class BuildInfo { private static final String DEFAULT_VALUE = "undefined"; private final boolean ci; private final int id; + @Nullable private final String idName; + @Nullable private final String tag; + @Nullable private final String url; + @Nullable private final String projectName; + @Nullable private final String projectUrl; + @Nullable private final String projectBaseName; - public JenkinsInfo(@NotNull Properties properties) { this.ci = "true".equalsIgnoreCase(properties.getProperty("jenkins.ci")); String idStr = properties.getProperty("ci.build.id"); @@ -259,5 +278,4 @@ public class BuildInfo { return ci; } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuiltInSolution.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuiltInSolution.java index bbdf265d4..4c1ab5ee9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuiltInSolution.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/BuiltInSolution.java @@ -8,8 +8,7 @@ import org.bukkit.ChatColor; */ public class BuiltInSolution { - private BuiltInSolution() { - } + private BuiltInSolution() {} /** * Call îf database failed to load. This checks the failure reason. @@ -17,7 +16,8 @@ public class BuiltInSolution { * @return The error reason. */ public static BootError databaseError() { - return new BootError(QuickShop.getInstance().logger(), + return new BootError( + QuickShop.getInstance().logger(), "Error connecting to the database!", "Please make sure your database service is running.", "and check the configuration in your config.yml"); @@ -32,23 +32,25 @@ public class BuiltInSolution { // Check if Vault is installed if (Bukkit.getPluginManager().getPlugin("Vault") == null) { // Vault is not installed - return new BootError(QuickShop.getInstance().logger(), + return new BootError( + QuickShop.getInstance().logger(), "Vault is not installed or loaded!", "Please make sure Vault is installed."); } // Vault is installed if (Bukkit.getPluginManager().getPlugin("CMI") != null) { // Found possible incompatible plugin - return new BootError(QuickShop.getInstance().logger(), + return new BootError( + QuickShop.getInstance().logger(), "No Economy plugin detected! Please make sure that you have a compatible economy", "plugin installed that is hooked into Vault and loads before QuickShop.", ChatColor.YELLOW + "Incompatibility detected: CMI Installed", "The use of the CMI Edition of Vault might fix this."); } - return new BootError(QuickShop.getInstance().logger(), + return new BootError( + QuickShop.getInstance().logger(), "No Economy plugin detected! Please make sure that you have a", "compatible economy plugin installed to get Vault working."); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/NbtApiInitializer.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/NbtApiInitializer.java index b43c58c7f..8dfa5ef51 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/NbtApiInitializer.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/NbtApiInitializer.java @@ -4,6 +4,13 @@ import com.ghostchu.quickshop.common.util.JsonUtil; import com.google.common.hash.Hashing; import com.google.gson.JsonSyntaxException; import com.google.gson.annotations.SerializedName; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import lombok.Data; @@ -14,21 +21,16 @@ import org.bukkit.plugin.InvalidDescriptionException; import org.bukkit.plugin.InvalidPluginException; import org.jetbrains.annotations.NotNull; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - public class NbtApiInitializer { public NbtApiInitializer(Logger logger) { if (checkNeedDownloadNbtApi()) { try { init(logger); } catch (Throwable e) { - logger.log(Level.WARNING, "Failed to download/install the NBT-API, please download and install it by manual. https://modrinth.com/plugin/nbtapi", e); + logger.log( + Level.WARNING, + "Failed to download/install the NBT-API, please download and install it by manual. https://modrinth.com/plugin/nbtapi", + e); logger.warning("Automatic installation failed, abort."); } } @@ -40,12 +42,12 @@ public class NbtApiInitializer { private void init(Logger logger) throws IOException, InvalidPluginException, InvalidDescriptionException { logger.info("QuickShop-Hikari needs NBT-API on Spigot platform, downloading it from Modrinth..."); - HttpResponse response = Unirest - .get("https://api.modrinth.com/v2/project/nbtapi/version") + HttpResponse response = Unirest.get("https://api.modrinth.com/v2/project/nbtapi/version") .header("Content-Type", "application/json") .asString(); if (!response.isSuccess()) { - throw new IOException("Failed to download NBT-API from Modrinth: " + response.getStatus() + " - " + response.getStatusText() + ": " + response.getBody()); + throw new IOException("Failed to download NBT-API from Modrinth: " + response.getStatus() + " - " + + response.getStatusText() + ": " + response.getBody()); } ResponseProject[] responseProjects; try { @@ -65,11 +67,14 @@ public class NbtApiInitializer { logger.info("Downloading NBT-API from Modrinth..."); HttpResponse fileHttpResponse = Unirest.get(dto.getUrl()).asFile(nbtapiTempFile.getAbsolutePath()); if (!fileHttpResponse.isSuccess()) { - throw new IOException("Failed to download NBT-API from Modrinth: " + fileHttpResponse.getStatus() + " - " + fileHttpResponse.getStatusText() + ": " + fileHttpResponse.getBody()); + throw new IOException("Failed to download NBT-API from Modrinth: " + fileHttpResponse.getStatus() + " - " + + fileHttpResponse.getStatusText() + ": " + fileHttpResponse.getBody()); } logger.info("Checking hash..."); - String downloadedHash = Hashing.sha512().hashBytes(Files.readAllBytes(nbtapiTempFile.toPath())).toString(); + String downloadedHash = Hashing.sha512() + .hashBytes(Files.readAllBytes(nbtapiTempFile.toPath())) + .toString(); if (!downloadedHash.equalsIgnoreCase(dto.getHashes().getSha512())) { logger.warning("Excepted: " + dto.getHashes().getSha512()); logger.warning("Actual: " + downloadedHash); @@ -116,36 +121,52 @@ public class NbtApiInitializer { static class ResponseProject { @SerializedName("id") private String id; + @SerializedName("project_id") private String projectId; + @SerializedName("author_id") private String authorId; + @SerializedName("featured") private Boolean featured; + @SerializedName("name") private String name; + @SerializedName("version_number") private String versionNumber; + @SerializedName("changelog") private String changelog; + @SerializedName("changelog_url") private Object changelogUrl; + @SerializedName("date_published") private String datePublished; + @SerializedName("downloads") private Integer downloads; + @SerializedName("version_type") private String versionType; + @SerializedName("status") private String status; + @SerializedName("requested_status") private Object requestedStatus; + @SerializedName("files") private List files; + @SerializedName("dependencies") private List dependencies; + @SerializedName("game_versions") private List gameVersions; + @SerializedName("loaders") private List loaders; @@ -154,14 +175,19 @@ public class NbtApiInitializer { public static class FilesDTO { @SerializedName("hashes") private HashesDTO hashes; + @SerializedName("url") private String url; + @SerializedName("filename") private String filename; + @SerializedName("primary") private Boolean primary; + @SerializedName("size") private Integer size; + @SerializedName("file_type") private Object fileType; @@ -170,10 +196,10 @@ public class NbtApiInitializer { public static class HashesDTO { @SerializedName("sha512") private String sha512; + @SerializedName("sha1") private String sha1; } } - } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShop.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShop.java index 1aebda803..28be5d1a3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShop.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShop.java @@ -63,6 +63,10 @@ import com.ghostchu.simplereloadlib.ReloadManager; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; import com.vdurmont.semver4j.Semver; +import java.io.File; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.CompletableFuture; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; @@ -81,11 +85,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; -import java.io.File; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.CompletableFuture; - public class QuickShop implements QuickShopAPI, Reloadable { /** * If running environment test @@ -102,21 +101,31 @@ public class QuickShop implements QuickShopAPI, Reloadable { * The manager to check permissions. */ private static PermissionManager permissionManager; + @Getter private final ReloadManager reloadManager = new ReloadManager(); + private final InventoryWrapperRegistry inventoryWrapperRegistry = new InventoryWrapperRegistry(); + @Getter private final InventoryWrapperManager inventoryWrapperManager = new BukkitInventoryWrapperManager(); + @Getter private final ShopControlPanelManager shopControlPanelManager = new SimpleShopControlPanelManager(this); + private final Map addonRegisteredMapping = new HashMap<>(); + @Getter private final QuickShopBukkit javaPlugin; + private final Logger logger; + @Getter private final Platform platform; + @Getter private final EconomyLoader economyLoader = new EconomyLoader(this); + @Getter private final PasteManager pasteManager = new PasteManager(); /* Public QuickShop API End */ @@ -126,9 +135,12 @@ public class QuickShop implements QuickShopAPI, Reloadable { private ItemMatcher itemMatcher; private SimpleShopManager shopManager; private SimpleTextManager textManager; + @Getter private SimpleShopPermissionManager shopPermissionManager; + private boolean priceChangeRequiresFee = false; + @Getter private DatabaseDriverType databaseDriverType = null; /** @@ -147,6 +159,7 @@ public class QuickShop implements QuickShopAPI, Reloadable { * Whether we should use display items or not */ private boolean display = true; + @Getter private int displayItemCheckTicks; /** @@ -154,6 +167,7 @@ public class QuickShop implements QuickShopAPI, Reloadable { */ @Getter private AbstractEconomy economy; + @Nullable @Getter private LogWatcher logWatcher; @@ -179,63 +193,90 @@ public class QuickShop implements QuickShopAPI, Reloadable { */ @Getter private UUID serverUniqueID; + private boolean setupDBonEnableding = false; /** * Rewrited shoploader, more faster. */ @Getter private ShopLoader shopLoader; + @Getter private DisplayAutoDespawnWatcher displayAutoDespawnWatcher; + @Getter private OngoingFeeWatcher ongoingFeeWatcher; + @Getter private SignUpdateWatcher signUpdateWatcher; + @Getter private boolean allowStack; + @Getter private EnvironmentChecker environmentChecker; + @Getter @Nullable private UpdateWatcher updateWatcher; + @Getter private BuildInfo buildInfo; + @Getter @Nullable private String currency = null; + @Getter private CalendarWatcher calendarWatcher; + @Getter private ShopPurger shopPurger; + private int loggingLocation = 0; + @Getter private InteractionController interactionController; + @Getter private SQLManager sqlManager; + @Getter @Nullable private QuickShopPAPI quickShopPAPI; + @Getter private ItemMarker itemMarker; + private Map translationMapping; + @Getter private PlayerFinder playerFinder; + @Getter private ShopItemBlackList shopItemBlackList; + @Getter private NexusManager nexusManager; + @Getter private ShopDataSaveWatcher shopSaveWatcher; + @Getter private SignHooker signHooker; + @Getter private BungeeListener bungeeListener; + private RankLimiter rankLimiter; + @Nullable @Getter private VirtualDisplayItemManager virtualDisplayItemManager; + @Getter private PrivacyController privacyController; + @Getter private MetricManager metricManager; @@ -268,7 +309,6 @@ public class QuickShop implements QuickShopAPI, Reloadable { return permissionManager; } - /** * Early than onEnable, make sure instance was loaded in first time. */ @@ -280,7 +320,7 @@ public class QuickShop implements QuickShopAPI, Reloadable { Util.setPlugin(this); logger.info("QuickShop {} - Early boot step - Booting up", javaPlugin.getFork()); getReloadManager().register(this); - //BEWARE THESE ONLY RUN ONCE + // BEWARE THESE ONLY RUN ONCE this.buildInfo = new BuildInfo(javaPlugin.getResource("BUILDINFO")); logger.info("Self testing..."); if (!runtimeCheck(EnvCheckEntry.Stage.ON_LOAD)) { @@ -305,17 +345,22 @@ public class QuickShop implements QuickShopAPI, Reloadable { private void registerService() { logger.info("Registering Bukkit Service: {}", QuickShopProvider.class.getName()); - Bukkit.getServicesManager().register(QuickShopProvider.class, new QuickShopProvider() { - @Override - public @NotNull QuickShopAPI getApiInstance() { - return instance; - } + Bukkit.getServicesManager() + .register( + QuickShopProvider.class, + new QuickShopProvider() { + @Override + public @NotNull QuickShopAPI getApiInstance() { + return instance; + } - @Override - public @NotNull Plugin getInstance() { - return javaPlugin; - } - }, javaPlugin, ServicePriority.High); + @Override + public @NotNull Plugin getInstance() { + return javaPlugin; + } + }, + javaPlugin, + ServicePriority.High); } private boolean runtimeCheck(@NotNull EnvCheckEntry.Stage stage) { @@ -323,9 +368,14 @@ public class QuickShop implements QuickShopAPI, Reloadable { ResultReport resultReport = environmentChecker.run(stage); StringJoiner joiner = new StringJoiner("\n", "", ""); if (resultReport.getFinalResult().ordinal() > CheckResult.WARNING.ordinal()) { - for (Entry result : resultReport.getResults().entrySet()) { + for (Entry result : + resultReport.getResults().entrySet()) { if (result.getValue().getResult().ordinal() > CheckResult.WARNING.ordinal()) { - joiner.add(String.format("- [%s/%s] %s", result.getValue().getResult().getDisplay(), result.getKey().name(), result.getValue().getResultMessage())); + joiner.add(String.format( + "- [%s/%s] %s", + result.getValue().getResult().getDisplay(), + result.getKey().name(), + result.getValue().getResultMessage())); } } } @@ -340,11 +390,10 @@ public class QuickShop implements QuickShopAPI, Reloadable { setupBootError(new BootError(logger, joiner.toString()), true); PluginCommand command = javaPlugin.getCommand("quickshop"); if (command != null) { - Util.mainThreadRun(() -> command.setTabCompleter(javaPlugin)); //Disable tab completer + Util.mainThreadRun(() -> command.setTabCompleter(javaPlugin)); // Disable tab completer } } - default -> { - } + default -> {} } return true; } @@ -356,27 +405,29 @@ public class QuickShop implements QuickShopAPI, Reloadable { try { javaPlugin.saveDefaultConfig(); } catch (IllegalArgumentException resourceNotFoundException) { - logger.error("Failed to save config.yml from jar, The binary file of QuickShop may be corrupted. Please re-download from our website."); + logger.error( + "Failed to save config.yml from jar, The binary file of QuickShop may be corrupted. Please re-download from our website."); } javaPlugin.reloadConfig(); if (getConfig().getInt("config-version", 0) == 0) { getConfig().set("config-version", 1); } /* It will generate a new UUID above updateConfig */ - this.serverUniqueID = UUID.fromString(Objects.requireNonNull(getConfig().getString("server-uuid", String.valueOf(UUID.randomUUID())))); + this.serverUniqueID = UUID.fromString( + Objects.requireNonNull(getConfig().getString("server-uuid", String.valueOf(UUID.randomUUID())))); updateConfig(); } - private void loadChatProcessor() { - - } + private void loadChatProcessor() {} private void loadTextManager() { logger.info("Loading translations (This may take a while)..."); try { this.textManager = new SimpleTextManager(this); } catch (NoSuchMethodError | NoClassDefFoundError e) { - logger.error("Failed to initialize text manager, the QuickShop doesn't compatible with your Server version. Did you up-to-date?", e); + logger.error( + "Failed to initialize text manager, the QuickShop doesn't compatible with your Server version. Did you up-to-date?", + e); Bukkit.getPluginManager().disablePlugin(javaPlugin); throw new IllegalStateException("Cannot initialize text manager"); } @@ -521,15 +572,14 @@ public class QuickShop implements QuickShopAPI, Reloadable { if (loggingLocation == 0) { this.getLogWatcher().log(JsonUtil.getGson().toJson(eventObject)); } else { - getDatabaseHelper().insertHistoryRecord(eventObject) - .thenAccept(result -> { - }) + getDatabaseHelper() + .insertHistoryRecord(eventObject) + .thenAccept(result -> {}) .exceptionally(throwable -> { Log.debug("Failed to log event: " + throwable.getMessage()); return null; }); } - } @Override @@ -567,7 +617,9 @@ public class QuickShop implements QuickShopAPI, Reloadable { } logger.info("Reading the configuration..."); initConfiguration(); - logger.info("Developers: {}", CommonUtil.list2String(javaPlugin.getDescription().getAuthors())); + logger.info( + "Developers: {}", + CommonUtil.list2String(javaPlugin.getDescription().getAuthors())); logger.info("Original author: Netherfoam, Timtower, KaiNoMood, sandtechnology"); logger.info("Let's start loading the plugin"); loadErrorReporter(); @@ -580,7 +632,7 @@ public class QuickShop implements QuickShopAPI, Reloadable { } catch (Exception e) { logger.warn("Failed to process virtual display item system", e); } - //Load the database + // Load the database try (PerfMonitor ignored = new PerfMonitor("Initialize database")) { initDatabase(); } @@ -599,14 +651,16 @@ public class QuickShop implements QuickShopAPI, Reloadable { loadCommandHandler(); this.shopManager = new SimpleShopManager(this); // Limit - //this.registerLimitRanks(); + // this.registerLimitRanks(); this.rankLimiter = new SimpleRankLimiter(this); // Limit end - if (getConfig().getInt("shop.finding.distance") > 100 && getConfig().getBoolean("shop.finding.exclude-out-of-stock")) { - logger.error("Shop find distance is too high with chunk loading feature turned on! It may cause lag! Pick a number below 100!"); + if (getConfig().getInt("shop.finding.distance") > 100 + && getConfig().getBoolean("shop.finding.exclude-out-of-stock")) { + logger.error( + "Shop find distance is too high with chunk loading feature turned on! It may cause lag! Pick a number below 100!"); } signUpdateWatcher = new SignUpdateWatcher(); - //shopContainerWatcher = new ShopContainerWatcher(); + // shopContainerWatcher = new ShopContainerWatcher(); shopSaveWatcher = new ShopDataSaveWatcher(this); shopSaveWatcher.runTaskTimerAsynchronously(javaPlugin, 0, 20L * 60L * 5L); /* Load all shops. */ @@ -637,10 +691,8 @@ public class QuickShop implements QuickShopAPI, Reloadable { runtimeCheck(EnvCheckEntry.Stage.AFTER_ON_ENABLE); } logger.info("QuickShop Loaded! " + enableTimer.stopAndGetTimePassed() + " ms."); - } - private void loadErrorReporter() { try { if (!getConfig().getBoolean("auto-report-errors")) { @@ -656,17 +708,19 @@ public class QuickShop implements QuickShopAPI, Reloadable { } private void loadItemMatcher() { - ItemMatcher defItemMatcher = switch (getConfig().getInt("matcher.work-type")) { - case 1 -> new BukkitItemMatcherImpl(this); - case 0 -> new QuickShopItemMatcherImpl(this); - default -> throw new IllegalStateException("Unexpected value: " + getConfig().getInt("matcher.work-type")); - }; + ItemMatcher defItemMatcher = + switch (getConfig().getInt("matcher.work-type")) { + case 1 -> new BukkitItemMatcherImpl(this); + case 0 -> new QuickShopItemMatcherImpl(this); + default -> throw new IllegalStateException( + "Unexpected value: " + getConfig().getInt("matcher.work-type")); + }; this.itemMatcher = ServiceInjector.getInjectedService(ItemMatcher.class, defItemMatcher); } private void loadVirtualDisplayItem() { if (this.display) { - //VirtualItem support + // VirtualItem support if (AbstractDisplayItem.getNowUsing() == DisplayType.VIRTUALITEM) { logger.info("Using Virtual Item display, loading ProtocolLib support..."); Plugin protocolLibPlugin = Bukkit.getPluginManager().getPlugin("ProtocolLib"); @@ -680,7 +734,8 @@ public class QuickShop implements QuickShopAPI, Reloadable { signHooker = null; } } else { - logger.warn("Failed to load ProtocolLib support, fallback to real item display and per-player shop info sign will automatically disable."); + logger.warn( + "Failed to load ProtocolLib support, fallback to real item display and per-player shop info sign will automatically disable."); signHooker = null; getConfig().set("shop.display-type", 0); javaPlugin.saveConfig(); @@ -702,9 +757,11 @@ public class QuickShop implements QuickShopAPI, Reloadable { private void registerDisplayAutoDespawn() { if (this.display && getConfig().getBoolean("shop.display-auto-despawn")) { this.displayAutoDespawnWatcher = new DisplayAutoDespawnWatcher(this); - //BUKKIT METHOD SHOULD ALWAYS EXECUTE ON THE SERVER MAIN THEAD - this.displayAutoDespawnWatcher.runTaskTimer(javaPlugin, 20, getConfig().getInt("shop.display-check-time")); // not worth async - logger.warn("Unrecommended use of display-auto-despawn. This feature may have a heavy impact on the server's performance!"); + // BUKKIT METHOD SHOULD ALWAYS EXECUTE ON THE SERVER MAIN THEAD + this.displayAutoDespawnWatcher.runTaskTimer( + javaPlugin, 20, getConfig().getInt("shop.display-check-time")); // not worth async + logger.warn( + "Unrecommended use of display-auto-despawn. This feature may have a heavy impact on the server's performance!"); } else { if (this.displayAutoDespawnWatcher != null) { this.displayAutoDespawnWatcher.cancel(); @@ -716,12 +773,12 @@ public class QuickShop implements QuickShopAPI, Reloadable { private void loadCommandHandler() { /* PreInit for BootError feature */ this.registerQuickShopCommands(); - } private void bakeShopsOwnerCache() { if (PackageUtil.parsePackageProperly("bakeuuids").asBoolean(false)) { - logger.info("Baking shops owner and moderators caches (This may take a while if you upgrade from old versions)..."); + logger.info( + "Baking shops owner and moderators caches (This may take a while if you upgrade from old versions)..."); Set waitingForBake = new HashSet<>(); this.shopManager.getAllShops().forEach(shop -> { UUID uuid = shop.getOwner().getUniqueIdIfRealPlayer().orElse(null); @@ -769,22 +826,29 @@ public class QuickShop implements QuickShopAPI, Reloadable { if (this.display && AbstractDisplayItem.getNowUsing() != DisplayType.VIRTUALITEM) { if (getDisplayItemCheckTicks() > 0) { if (getConfig().getInt("shop.display-items-check-ticks") < 3000) { - logger.error("Shop.display-items-check-ticks is too low! It may cause HUGE lag! Pick a number > 3000"); + logger.error( + "Shop.display-items-check-ticks is too low! It may cause HUGE lag! Pick a number > 3000"); } logger.info("Registering DisplayCheck task...."); - Bukkit.getScheduler().runTaskTimer(javaPlugin, () -> { - for (Shop shop : getShopManager().getLoadedShops()) { - //Shop may be deleted or unloaded when iterating - if (!shop.isLoaded()) { - continue; - } - shop.checkDisplay(); - } - }, 1L, getDisplayItemCheckTicks()); + Bukkit.getScheduler() + .runTaskTimer( + javaPlugin, + () -> { + for (Shop shop : getShopManager().getLoadedShops()) { + // Shop may be deleted or unloaded when iterating + if (!shop.isLoaded()) { + continue; + } + shop.checkDisplay(); + } + }, + 1L, + getDisplayItemCheckTicks()); } else if (getDisplayItemCheckTicks() == 0) { logger.info("shop.display-items-check-ticks was set to 0. Display Check has been disabled"); } else { - logger.error("shop.display-items-check-ticks has been set to an invalid value. Please use a value above 3000."); + logger.error( + "shop.display-items-check-ticks has been set to an invalid value. Please use a value above 3000."); } new DisplayProtectionListener(this).register(); } else { @@ -817,7 +881,7 @@ public class QuickShop implements QuickShopAPI, Reloadable { calendarWatcher = new CalendarWatcher(this); // shopVaildWatcher.runTaskTimer(this, 0, 20 * 60); // Nobody use it signUpdateWatcher.runTaskTimer(javaPlugin, 0, 10); - //shopContainerWatcher.runTaskTimer(this, 0, 5); // Nobody use it + // shopContainerWatcher.runTaskTimer(this, 0, 5); // Nobody use it if (logWatcher != null) { logWatcher.runTaskTimerAsynchronously(javaPlugin, 10, 10); logger.info("Log actions is enabled. Actions will be logged in the qs.log file!"); @@ -886,11 +950,14 @@ public class QuickShop implements QuickShopAPI, Reloadable { String driverClassName = Driver.class.getName(); Log.debug("Setting up H2 driver class name to: " + driverClassName); config.setDriverClassName(driverClassName); - config.setJdbcUrl("jdbc:h2:" + new File(javaPlugin.getDataFolder(), "shops").getCanonicalFile().getAbsolutePath() + ";MODE=MYSQL"); + config.setJdbcUrl("jdbc:h2:" + + new File(javaPlugin.getDataFolder(), "shops") + .getCanonicalFile() + .getAbsolutePath() + ";MODE=MYSQL"); this.sqlManager = new SQLManagerImpl(new HikariDataSource(config), "QuickShop-Hikari-SQLManager"); this.sqlManager.executeSQL("SET MODE=MYSQL"); // Switch to MySQL mode } - //this.sqlManager.setDebugMode(Util.isDevMode()); + // this.sqlManager.setDebugMode(Util.isDevMode()); this.sqlManager.setExecutorPool(QuickExecutor.getDatabaseExecutor()); // Make the database up to date this.databaseHelper = new SimpleDatabaseHelperV2(this, this.sqlManager, this.getDbPrefix()); @@ -909,19 +976,22 @@ public class QuickShop implements QuickShopAPI, Reloadable { public void registerQuickShopCommands() { commandManager = new SimpleCommandManager(this); List customCommands = getConfig().getStringList("custom-commands"); - Command quickShopCommand = new QuickShopCommand("quickshop", commandManager, new ArrayList<>(new HashSet<>(customCommands))); + Command quickShopCommand = + new QuickShopCommand("quickshop", commandManager, new ArrayList<>(new HashSet<>(customCommands))); try { platform.registerCommand("quickshop-hikari", quickShopCommand); } catch (Exception e) { logger.warn("Failed to register command aliases", e); } - Log.debug("QuickShop command registered with those aliases: " + CommonUtil.list2String(quickShopCommand.getAliases())); + Log.debug("QuickShop command registered with those aliases: " + + CommonUtil.list2String(quickShopCommand.getAliases())); } private void registerOngoingFee() { if (getConfig().getBoolean("shop.ongoing-fee.enable")) { ongoingFeeWatcher = new OngoingFeeWatcher(this); - ongoingFeeWatcher.runTaskTimerAsynchronously(javaPlugin, 0, getConfig().getInt("shop.ongoing-fee.ticks")); + ongoingFeeWatcher.runTaskTimerAsynchronously( + javaPlugin, 0, getConfig().getInt("shop.ongoing-fee.ticks")); logger.info("Ongoing fee feature is enabled."); } else { if (ongoingFeeWatcher != null) { @@ -960,10 +1030,12 @@ public class QuickShop implements QuickShopAPI, Reloadable { } if (getShopManager() != null) { logger.info("Saving all in-memory changed shops..."); - List> futures = getShopManager().getAllShops().stream().filter(Shop::isDirty).map(Shop::update).toList(); + List> futures = getShopManager().getAllShops().stream() + .filter(Shop::isDirty) + .map(Shop::update) + .toList(); CompletableFuture[] completableFutures = futures.toArray(new CompletableFuture[0]); - CompletableFuture.allOf(completableFutures) - .join(); + CompletableFuture.allOf(completableFutures).join(); } /* Remove all display items, and any dupes we can find */ if (shopManager != null) { @@ -1071,7 +1143,6 @@ public class QuickShop implements QuickShopAPI, Reloadable { * @return true if successful, false if the core is invalid or is not found, and vault cannot be * used. */ - public boolean load() { try (PerfMonitor ignored = new PerfMonitor("Loading Economy Bridge")) { return setupEconomy(); @@ -1080,7 +1151,8 @@ public class QuickShop implements QuickShopAPI, Reloadable { parent.sentryErrorReporter.ignoreThrow(); } parent.logger().error("Something went wrong while trying to load the economy system!"); - parent.logger().error("QuickShop was unable to hook into an economy system (Couldn't find Vault or Reserve)!"); + parent.logger() + .error("QuickShop was unable to hook into an economy system (Couldn't find Vault or Reserve)!"); parent.logger().error("QuickShop can NOT enable properly!"); parent.setupBootError(BuiltInSolution.econError(), false); parent.logger().error("Plugin Listeners have been disabled. Please fix this economy issue.", e); @@ -1089,12 +1161,13 @@ public class QuickShop implements QuickShopAPI, Reloadable { } private boolean setupEconomy() throws Exception { - AbstractEconomy abstractEconomy = switch (EconomyType.fromID(parent.getConfig().getInt("economy-type"))) { - case VAULT -> loadVault(); - case GEMS_ECONOMY -> loadGemsEconomy(); - case TNE -> loadTNE(); - default -> null; - }; + AbstractEconomy abstractEconomy = + switch (EconomyType.fromID(parent.getConfig().getInt("economy-type"))) { + case VAULT -> loadVault(); + case GEMS_ECONOMY -> loadGemsEconomy(); + case TNE -> loadTNE(); + default -> null; + }; abstractEconomy = ServiceInjector.getInjectedService(AbstractEconomy.class, abstractEconomy); if (abstractEconomy == null) { Log.debug("No economy bridge found."); @@ -1133,14 +1206,20 @@ public class QuickShop implements QuickShopAPI, Reloadable { } if (!Objects.requireNonNull(vault.getVault()).hasAccount(tax)) { Log.debug("Tax account doesn't exists: " + tax); - parent.logger().warn("QuickShop detected that no tax account exists and will try to create one. If you see any errors, please change the tax-account name in the config.yml to that of the Server owner."); + parent.logger() + .warn( + "QuickShop detected that no tax account exists and will try to create one. If you see any errors, please change the tax-account name in the config.yml to that of the Server owner."); if (vault.getVault().createPlayerAccount(tax)) { parent.logger().info("Tax account created."); } else { - parent.logger().warn("Cannot create tax-account, please change the tax-account name in the config.yml to that of the server owner"); + parent.logger() + .warn( + "Cannot create tax-account, please change the tax-account name in the config.yml to that of the server owner"); } if (!vault.getVault().hasAccount(tax)) { - parent.logger().warn("Player for the Tax-account has never played on this server before and we couldn't create an account. This may cause server lag or economy errors, therefore changing the name is recommended. You may ignore this warning if it doesn't cause any issues."); + parent.logger() + .warn( + "Player for the Tax-account has never played on this server before and we couldn't create an account. This may cause server lag or economy errors, therefore changing the name is recommended. You may ignore this warning if it doesn't cause any issues."); } } return vault; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShopBukkit.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShopBukkit.java index 84ac38763..4d1001f48 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShopBukkit.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/QuickShopBukkit.java @@ -4,17 +4,13 @@ import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.platform.Platform; import com.ghostchu.quickshop.platform.paper.PaperPlatform; import com.ghostchu.quickshop.platform.spigot.AbstractSpigotPlatform; -import com.ghostchu.quickshop.platform.spigot.v1_18_1.Spigot1181Platform; -import com.ghostchu.quickshop.platform.spigot.v1_18_2.Spigot1182Platform; import com.ghostchu.quickshop.platform.spigot.v1_19_1.Spigot1191Platform; import com.ghostchu.quickshop.platform.spigot.v1_19_2.Spigot1193Platform; import com.ghostchu.quickshop.platform.spigot.v1_19_3.Spigot1194Platform; -import com.ghostchu.quickshop.platform.spigot.v1_20_1.Spigot1201Platform; -import com.ghostchu.quickshop.platform.spigot.v1_20_2.Spigot1202Platform; -import com.ghostchu.quickshop.platform.spigot.v1_20_2.Spigot1203Platform; import com.ghostchu.quickshop.util.PackageUtil; import com.vdurmont.semver4j.Semver; import io.papermc.lib.PaperLib; +import java.util.logging.Level; import kong.unirest.Unirest; import net.kyori.adventure.Adventure; import net.kyori.adventure.platform.bukkit.BukkitAudiences; @@ -33,8 +29,6 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.logging.Level; - public class QuickShopBukkit extends JavaPlugin { private Platform platform; private Logger logger; @@ -126,20 +120,19 @@ public class QuickShopBukkit extends JavaPlugin { initNbtApi(); this.platform = switch (AbstractSpigotPlatform.getNMSVersion()) { - case "v1_18_R1" -> new Spigot1181Platform(this); - case "v1_18_R2" -> new Spigot1182Platform(this); case "v1_19_R1" -> new Spigot1191Platform(this); case "v1_19_R2" -> new Spigot1193Platform(this); case "v1_19_R3" -> new Spigot1194Platform(this); - case "v1_20_R1" -> new Spigot1201Platform(this); - case "v1_20_R2" -> new Spigot1202Platform(this); - case "v1_20_R3" -> new Spigot1203Platform(this); default -> { - getLogger().warning("This server running " + AbstractSpigotPlatform.getNMSVersion() + " not supported by Hikari. (Try update? or Use Paper's fork to get cross-platform compatibility.)"); + getLogger() + .warning( + "This server running " + AbstractSpigotPlatform.getNMSVersion() + + " not supported by Hikari. (Try update? or Use Paper's fork to get cross-platform compatibility.)"); Bukkit.getPluginManager().disablePlugin(this); - throw new IllegalStateException("This server running " + AbstractSpigotPlatform.getNMSVersion() + " not supported by Hikari. (Try update? or Use Paper's fork to get cross-platform compatibility.)"); - } - }; + throw new IllegalStateException( + "This server running " + AbstractSpigotPlatform.getNMSVersion() + + " not supported by Hikari. (Try update? or Use Paper's fork to get cross-platform compatibility.)"); + }}; } case 2 -> { getLogger().info("Platform detected: Paper"); @@ -205,15 +198,30 @@ public class QuickShopBukkit extends JavaPlugin { plugin.getLogger().info("Initialing Unirest..."); Unirest.config() .concurrency(10, 5) - .setDefaultHeader("User-Agent", "QuickShop/" + plugin.getFork() + "-" + plugin.getDescription().getVersion() + " Java/" + System.getProperty("java.version")); - Unirest.config().verifySsl(PackageUtil.parsePackageProperly("verifySSL").asBoolean()); + .setDefaultHeader( + "User-Agent", + "QuickShop/" + plugin.getFork() + "-" + + plugin.getDescription().getVersion() + " Java/" + + System.getProperty("java.version")); + Unirest.config() + .verifySsl(PackageUtil.parsePackageProperly("verifySSL").asBoolean()); if (PackageUtil.parsePackageProperly("proxyHost").isPresent()) { plugin.getLogger().info("Unirest proxy feature has been enabled."); - Unirest.config().proxy(PackageUtil.parsePackageProperly("proxyHost").asString("127.0.0.1"), PackageUtil.parsePackageProperly("proxyPort").asInteger(1080)); + Unirest.config() + .proxy( + PackageUtil.parsePackageProperly("proxyHost").asString("127.0.0.1"), + PackageUtil.parsePackageProperly("proxyPort").asInteger(1080)); } if (PackageUtil.parsePackageProperly("proxyUsername").isPresent()) { plugin.getLogger().info("Unirest proxy authentication activated."); - Unirest.config().proxy(PackageUtil.parsePackageProperly("proxyHost").asString("127.0.0.1"), PackageUtil.parsePackageProperly("proxyPort").asInteger(1080), PackageUtil.parsePackageProperly("proxyUsername").asString(""), PackageUtil.parsePackageProperly("proxyPassword").asString("")); + Unirest.config() + .proxy( + PackageUtil.parsePackageProperly("proxyHost").asString("127.0.0.1"), + PackageUtil.parsePackageProperly("proxyPort").asInteger(1080), + PackageUtil.parsePackageProperly("proxyUsername") + .asString(""), + PackageUtil.parsePackageProperly("proxyPassword") + .asString("")); } } } @@ -222,16 +230,31 @@ public class QuickShopBukkit extends JavaPlugin { public AdventureLibLoader(QuickShopBukkit plugin) { plugin.getLogger().info("Loading the Adventure Chat Processor..."); plugin.getLogger().info("Adventure API loaded from: " + CommonUtil.getClassPath(Adventure.class)); - plugin.getLogger().info("Adventure Bukkit Platform loaded from: " + CommonUtil.getClassPath(BukkitAudiences.class)); - plugin.getLogger().info("Adventure Text Serializer (Legacy) loaded from: " + CommonUtil.getClassPath(LegacyComponentSerializer.class)); - plugin.getLogger().info("Adventure Text Serializer (Gson) loaded from: " + CommonUtil.getClassPath(GsonComponentSerializer.class)); - plugin.getLogger().info("Adventure Text Serializer (Json) loaded from: " + CommonUtil.getClassPath(JSONComponentSerializer.class)); - plugin.getLogger().info("Adventure Text Serializer (BungeeChat) loaded from: " + CommonUtil.getClassPath(BungeeComponentSerializer.class)); - plugin.getLogger().info("Adventure Text Serializer (ViaVersion Facet) loaded from: " + CommonUtil.getClassPath(ViaFacet.class)); - plugin.getLogger().info("Adventure Text Serializer (ANSI) loaded from: " + CommonUtil.getClassPath(ANSIComponentSerializer.class)); - plugin.getLogger().info("Adventure Text Serializer (Plain) loaded from: " + CommonUtil.getClassPath(PlainTextComponentSerializer.class)); - plugin.getLogger().info("Adventure MiniMessage Lib loaded from: " + CommonUtil.getClassPath(MiniMessage.class)); - + plugin.getLogger() + .info("Adventure Bukkit Platform loaded from: " + CommonUtil.getClassPath(BukkitAudiences.class)); + plugin.getLogger() + .info("Adventure Text Serializer (Legacy) loaded from: " + + CommonUtil.getClassPath(LegacyComponentSerializer.class)); + plugin.getLogger() + .info("Adventure Text Serializer (Gson) loaded from: " + + CommonUtil.getClassPath(GsonComponentSerializer.class)); + plugin.getLogger() + .info("Adventure Text Serializer (Json) loaded from: " + + CommonUtil.getClassPath(JSONComponentSerializer.class)); + plugin.getLogger() + .info("Adventure Text Serializer (BungeeChat) loaded from: " + + CommonUtil.getClassPath(BungeeComponentSerializer.class)); + plugin.getLogger() + .info("Adventure Text Serializer (ViaVersion Facet) loaded from: " + + CommonUtil.getClassPath(ViaFacet.class)); + plugin.getLogger() + .info("Adventure Text Serializer (ANSI) loaded from: " + + CommonUtil.getClassPath(ANSIComponentSerializer.class)); + plugin.getLogger() + .info("Adventure Text Serializer (Plain) loaded from: " + + CommonUtil.getClassPath(PlainTextComponentSerializer.class)); + plugin.getLogger() + .info("Adventure MiniMessage Lib loaded from: " + CommonUtil.getClassPath(MiniMessage.class)); } } -} \ No newline at end of file +} diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/ServiceInjector.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/ServiceInjector.java index b5e429764..3ed52baa9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/ServiceInjector.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/ServiceInjector.java @@ -13,11 +13,11 @@ import org.jetbrains.annotations.Nullable; */ public class ServiceInjector { - private ServiceInjector() { - } + private ServiceInjector() {} public static @Nullable T getInjectedService(@NotNull Class clazz, T def) { - @Nullable RegisteredServiceProvider registeredServiceProvider = + @Nullable + RegisteredServiceProvider registeredServiceProvider = Bukkit.getServicesManager().getRegistration(clazz); if (registeredServiceProvider == null) { return def; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/SimpleRankLimiter.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/SimpleRankLimiter.java index 13d38dd6c..af281fbde 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/SimpleRankLimiter.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/SimpleRankLimiter.java @@ -6,15 +6,14 @@ import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.quickshop.util.paste.util.HTMLTable; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; public class SimpleRankLimiter implements Reloadable, RankLimiter, SubPasteItem { private final QuickShop plugin; @@ -23,6 +22,7 @@ public class SimpleRankLimiter implements Reloadable, RankLimiter, SubPasteItem * Whether or not to limit players shop amounts */ private boolean limit = false; + private int def = 0; public SimpleRankLimiter(QuickShop plugin) { @@ -33,7 +33,8 @@ public class SimpleRankLimiter implements Reloadable, RankLimiter, SubPasteItem } private void load() { - YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(new File(this.plugin.getDataFolder(), "config.yml")); + YamlConfiguration yamlConfiguration = + YamlConfiguration.loadConfiguration(new File(this.plugin.getDataFolder(), "config.yml")); ConfigurationSection limitCfg = yamlConfiguration.getConfigurationSection("limits"); if (limitCfg != null) { this.limit = limitCfg.getBoolean("use", false); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/bootstrap/Bootstrap.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/bootstrap/Bootstrap.java index cb79451f7..3e66eff61 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/bootstrap/Bootstrap.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/bootstrap/Bootstrap.java @@ -11,7 +11,8 @@ import javax.swing.*; public class Bootstrap { public static void main(String[] args) { System.out.println("QuickShop is a Spigot plugin."); - System.out.println("You cannot directly execute this jar file, please install it as server plugin following the tutorials."); + System.out.println( + "You cannot directly execute this jar file, please install it as server plugin following the tutorials."); System.out.println("https://www.spigotmc.org/wiki/spigot-installation."); if (java.awt.Desktop.isDesktopSupported()) { try { @@ -34,20 +35,30 @@ public class Bootstrap { private static void createAndShowGUI(boolean supportBrowse) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException | - InstantiationException e) { + } catch (ClassNotFoundException + | UnsupportedLookAndFeelException + | IllegalAccessException + | InstantiationException e) { e.printStackTrace(); } if (supportBrowse) { - JOptionPane.showMessageDialog(new JPanel(), "

QuickShop is a Spigot plugin.

" + - "

You cannot directly execute this jar file, please install it as server plugin following the tutorials." + - "

Press \"OK\" button to open Spigot's plugin installation tutorial.

" + - "", "QuickShop Alert", JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog( + new JPanel(), + "

QuickShop is a Spigot plugin.

" + + "

You cannot directly execute this jar file, please install it as server plugin following the tutorials." + + "

Press \"OK\" button to open Spigot's plugin installation tutorial.

" + + "", + "QuickShop Alert", + JOptionPane.ERROR_MESSAGE); } else { - JOptionPane.showMessageDialog(new JPanel(), "

QuickShop is a Spigot plugin.

" + - "

You cannot directly execute this jar file, please install it as server plugin following the tutorials." + - "

Please open the link https://www.spigotmc.org/wiki/spigot-installation/ in your browser to view.

" + - "", "QuickShop Alert", JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog( + new JPanel(), + "

QuickShop is a Spigot plugin.

" + + "

You cannot directly execute this jar file, please install it as server plugin following the tutorials." + + "

Please open the link https://www.spigotmc.org/wiki/spigot-installation/ in your browser to view.

" + + "", + "QuickShop Alert", + JOptionPane.ERROR_MESSAGE); } } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/QuickShopCommand.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/QuickShopCommand.java index 6bd5cc549..20251cf58 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/QuickShopCommand.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/QuickShopCommand.java @@ -1,14 +1,13 @@ package com.ghostchu.quickshop.command; import com.ghostchu.quickshop.api.command.CommandManager; +import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.command.defaults.BukkitCommand; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class QuickShopCommand extends BukkitCommand { private final CommandManager manager; @@ -24,7 +23,8 @@ public class QuickShopCommand extends BukkitCommand { @NotNull @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { + public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) + throws IllegalArgumentException { List items = this.manager.onTabComplete(sender, this, alias, args); if (items == null) { items = Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/SimpleCommandManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/SimpleCommandManager.java index e53e9d915..e59707ddf 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/SimpleCommandManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/SimpleCommandManager.java @@ -15,6 +15,13 @@ import com.ghostchu.quickshop.util.performance.PerfMonitor; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; import com.google.common.collect.ImmutableList; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.logging.Level; import lombok.Data; import org.bukkit.Sound; import org.bukkit.command.Command; @@ -26,19 +33,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.logging.Level; - @Data @SuppressWarnings("unchecked") public class SimpleCommandManager implements CommandManager, TabCompleter, CommandExecutor, SubPasteItem, Reloadable { private static final String[] EMPTY_ARGS = new String[0]; - private final List cmds = new CopyOnWriteArrayList<>(); //Because we open to allow register, so this should be thread-safe + private final List cmds = + new CopyOnWriteArrayList<>(); // Because we open to allow register, so this should be thread-safe private final QuickShop plugin; private final CommandContainer rootContainer; @@ -53,224 +53,190 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma .permission(null) .executor(new SubCommand_ROOT(plugin)) .build(); - registerCmd( - CommandContainer.builder() - .prefix("help") - .permission(null) - .executor(new SubCommand_Help(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("unlimited") - .permission("quickshop.unlimited") - .executor(new SubCommand_Unlimited(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silentunlimited") - .hidden(true) - .permission("quickshop.unlimited") - .executor(new SubCommand_SilentUnlimited(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("transfer") - .permission("quickshop.transfer") - .executor(new SubCommand_Transfer(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("setowner") - .permission("quickshop.setowner") - .executor(new SubCommand_SetOwner(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("owner") - .hidden(true) - .permission("quickshop.setowner") - .executor(new SubCommand_SetOwner(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("amount") - .permission(null) - .executor(new SubCommand_Amount(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("buy") - .permission("quickshop.create.buy") - .executor(new SubCommand_Buy(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("sell") - .permission("quickshop.create.sell") - .executor(new SubCommand_Sell(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silentbuy") - .hidden(true) - .permission("quickshop.create.buy") - .executor(new SubCommand_SilentBuy(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silentsell") - .hidden(true) - .permission("quickshop.create.sell") - .executor(new SubCommand_SilentSell(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("price") - .permission("quickshop.create.changeprice") - .executor(new SubCommand_Price(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("remove") - .permission(null) - .executor(new SubCommand_Remove(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silentremove") - .hidden(true) - .permission(null) - .executor(new SubCommand_SilentRemove(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("empty") - .permission("quickshop.empty") - .executor(new SubCommand_Empty(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("refill") - .permission("quickshop.refill") - .executor(new SubCommand_Refill(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silentempty") - .hidden(true) - .permission("quickshop.empty") - .executor(new SubCommand_SilentEmpty(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silentpreview") - .hidden(true) - .permission("quickshop.preview") - .executor(new SubCommand_SilentPreview(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("silenttoggledisplay") - .hidden(true) - .permission("quickshop.toggledisplay") - .executor(new SubCommand_SilentToggleDisplay(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("clean") - .permission("quickshop.clean") - .executor(new SubCommand_Clean(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("reload") - .permission("quickshop.reload") - .executor(new SubCommand_Reload(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("about") - .permission("quickshop.about") - .executor(new SubCommand_About(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("debug") - .permission("quickshop.debug") - .executor(new SubCommand_Debug(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("fetchmessage") - .permission("quickshop.fetchmessage") - .executor(new SubCommand_FetchMessage()) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("info") - .permission("quickshop.info") - .executor(new SubCommand_Info(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("paste") - .permission("quickshop.paste") - .executor(new SubCommand_Paste(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("staff") - .permission("quickshop.staff") - .executor(new SubCommand_Staff(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("create") - .permission("quickshop.create.cmd") - .permission("quickshop.create.sell") - .executor(new SubCommand_Create(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("find") - .permission("quickshop.find") - .executor(new SubCommand_Find(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("supercreate") - .permission("quickshop.create.admin") - .permission("quickshop.create.sell") - .executor(new SubCommand_SuperCreate(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("cleanghost") - .permission("quickshop.cleanghost") - .hidden(true) - .executor(new SubCommand_CleanGhost(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("reset") - .hidden(true) - .permission("quickshop.reset") - .executor(new SubCommand_Reset(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("recovery") - .hidden(true) - .permission("quickshop.recovery") - .executor(new SubCommand_Recovery(plugin)) - .build()); - registerCmd( - CommandContainer.builder() - .prefix("export") - .hidden(true) - .permission("quickshop.export") - .executor(new SubCommand_Export(plugin)) - .build()); + registerCmd(CommandContainer.builder() + .prefix("help") + .permission(null) + .executor(new SubCommand_Help(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("unlimited") + .permission("quickshop.unlimited") + .executor(new SubCommand_Unlimited(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silentunlimited") + .hidden(true) + .permission("quickshop.unlimited") + .executor(new SubCommand_SilentUnlimited(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("transfer") + .permission("quickshop.transfer") + .executor(new SubCommand_Transfer(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("setowner") + .permission("quickshop.setowner") + .executor(new SubCommand_SetOwner(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("owner") + .hidden(true) + .permission("quickshop.setowner") + .executor(new SubCommand_SetOwner(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("amount") + .permission(null) + .executor(new SubCommand_Amount(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("buy") + .permission("quickshop.create.buy") + .executor(new SubCommand_Buy(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("sell") + .permission("quickshop.create.sell") + .executor(new SubCommand_Sell(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silentbuy") + .hidden(true) + .permission("quickshop.create.buy") + .executor(new SubCommand_SilentBuy(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silentsell") + .hidden(true) + .permission("quickshop.create.sell") + .executor(new SubCommand_SilentSell(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("price") + .permission("quickshop.create.changeprice") + .executor(new SubCommand_Price(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("remove") + .permission(null) + .executor(new SubCommand_Remove(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silentremove") + .hidden(true) + .permission(null) + .executor(new SubCommand_SilentRemove(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("empty") + .permission("quickshop.empty") + .executor(new SubCommand_Empty(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("refill") + .permission("quickshop.refill") + .executor(new SubCommand_Refill(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silentempty") + .hidden(true) + .permission("quickshop.empty") + .executor(new SubCommand_SilentEmpty(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silentpreview") + .hidden(true) + .permission("quickshop.preview") + .executor(new SubCommand_SilentPreview(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("silenttoggledisplay") + .hidden(true) + .permission("quickshop.toggledisplay") + .executor(new SubCommand_SilentToggleDisplay(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("clean") + .permission("quickshop.clean") + .executor(new SubCommand_Clean(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("reload") + .permission("quickshop.reload") + .executor(new SubCommand_Reload(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("about") + .permission("quickshop.about") + .executor(new SubCommand_About(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("debug") + .permission("quickshop.debug") + .executor(new SubCommand_Debug(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("fetchmessage") + .permission("quickshop.fetchmessage") + .executor(new SubCommand_FetchMessage()) + .build()); + registerCmd(CommandContainer.builder() + .prefix("info") + .permission("quickshop.info") + .executor(new SubCommand_Info(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("paste") + .permission("quickshop.paste") + .executor(new SubCommand_Paste(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("staff") + .permission("quickshop.staff") + .executor(new SubCommand_Staff(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("create") + .permission("quickshop.create.cmd") + .permission("quickshop.create.sell") + .executor(new SubCommand_Create(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("find") + .permission("quickshop.find") + .executor(new SubCommand_Find(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("supercreate") + .permission("quickshop.create.admin") + .permission("quickshop.create.sell") + .executor(new SubCommand_SuperCreate(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("cleanghost") + .permission("quickshop.cleanghost") + .hidden(true) + .executor(new SubCommand_CleanGhost(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("reset") + .hidden(true) + .permission("quickshop.reset") + .executor(new SubCommand_Reset(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("recovery") + .hidden(true) + .permission("quickshop.recovery") + .executor(new SubCommand_Recovery(plugin)) + .build()); + registerCmd(CommandContainer.builder() + .prefix("export") + .hidden(true) + .permission("quickshop.export") + .executor(new SubCommand_Export(plugin)) + .build()); registerCmd(CommandContainer.builder() .prefix("size") .permission("quickshop.create.stacks") @@ -341,7 +307,6 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma .permission("quickshop.benefit") .executor(new SubCommand_Benefit(plugin)) .build()); - } /** @@ -378,41 +343,61 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma } } if (sender instanceof Player player && playSoundOnCommand) { - ((Player) sender) - .playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 80.0F, 1.0F); + ((Player) sender).playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 80.0F, 1.0F); } if (cmdArg.length == 0) { - //Handle main command + // Handle main command rootContainer.getExecutor().onCommand_Internal(capture(sender), commandLabel, EMPTY_ARGS); } else { - //Handle subcommand + // Handle subcommand String[] passThroughArgs = new String[cmdArg.length - 1]; System.arraycopy(cmdArg, 1, passThroughArgs, 0, passThroughArgs.length); for (CommandContainer container : cmds) { if (!container.getPrefix().equalsIgnoreCase(cmdArg[0])) { continue; } - if (container.isDisabled() || (container.getDisabledSupplier() != null && container.getDisabledSupplier().get())) { + if (container.isDisabled() + || (container.getDisabledSupplier() != null + && container.getDisabledSupplier().get())) { MsgUtil.sendDirectMessage(sender, container.getDisableText(sender)); return true; } if (!isAdapt(container, sender)) { - plugin.text().of(sender, "command-type-mismatch", container.getExecutorType().getSimpleName()).send(); + plugin.text() + .of( + sender, + "command-type-mismatch", + container.getExecutorType().getSimpleName()) + .send(); return true; } List requirePermissions = container.getPermissions(); List selectivePermissions = container.getSelectivePermissions(); - if (!checkPermissions(sender, commandLabel, passThroughArgs, requirePermissions, PermissionType.REQUIRE, Action.EXECUTE)) { + if (!checkPermissions( + sender, + commandLabel, + passThroughArgs, + requirePermissions, + PermissionType.REQUIRE, + Action.EXECUTE)) { plugin.text().of(sender, "no-permission").send(); return true; } - if (!checkPermissions(sender, commandLabel, passThroughArgs, selectivePermissions, PermissionType.SELECTIVE, Action.EXECUTE)) { + if (!checkPermissions( + sender, + commandLabel, + passThroughArgs, + selectivePermissions, + PermissionType.SELECTIVE, + Action.EXECUTE)) { plugin.text().of(sender, "no-permission").send(); return true; } Log.debug("Execute container: " + container.getPrefix() + " - " + cmdArg[0]); - try (PerfMonitor ignored = new PerfMonitor("Execute command " + container.getPrefix() + " " + CommonUtil.array2String(passThroughArgs), Duration.of(2, ChronoUnit.SECONDS))) { + try (PerfMonitor ignored = new PerfMonitor( + "Execute command " + container.getPrefix() + " " + CommonUtil.array2String(passThroughArgs), + Duration.of(2, ChronoUnit.SECONDS))) { container.getExecutor().onCommand_Internal(capture(sender), commandLabel, passThroughArgs); } return true; @@ -433,7 +418,13 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma return container.getExecutorType().isInstance(sender); } - private boolean checkPermissions(CommandSender sender, String commandLabel, String[] cmdArg, List permissionList, PermissionType permissionType, Action action) { + private boolean checkPermissions( + CommandSender sender, + String commandLabel, + String[] cmdArg, + List permissionList, + PermissionType permissionType, + Action action) { if (permissionList == null || permissionList.isEmpty()) { return true; } @@ -442,15 +433,14 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma if (requirePermission != null && !requirePermission.isEmpty() && !plugin.perm().hasPermission(sender, requirePermission)) { - Log.debug( - "Sender " - + sender.getName() - + " trying " + action.getName() + " the command: " - + commandLabel - + " " - + CommonUtil.array2String(cmdArg) - + ", but no permission " - + requirePermission); + Log.debug("Sender " + + sender.getName() + + " trying " + action.getName() + " the command: " + + commandLabel + + " " + + CommonUtil.array2String(cmdArg) + + ", but no permission " + + requirePermission); return false; } } @@ -464,15 +454,14 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma } } if (Util.isDevMode()) { - Log.debug( - "Sender " - + sender.getName() - + " trying " + action + " the command: " - + commandLabel - + " " - + CommonUtil.array2String(cmdArg) - + ", but does no have one of those permissions: " - + permissionList); + Log.debug("Sender " + + sender.getName() + + " trying " + action + " the command: " + + commandLabel + + " " + + CommonUtil.array2String(cmdArg) + + ", but does no have one of those permissions: " + + permissionList); } return false; } @@ -506,17 +495,28 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma } List requirePermissions = container.getPermissions(); List selectivePermissions = container.getSelectivePermissions(); - if (!checkPermissions(sender, commandLabel, passThroughArgs, requirePermissions, PermissionType.REQUIRE, Action.TAB_COMPLETE)) { + if (!checkPermissions( + sender, + commandLabel, + passThroughArgs, + requirePermissions, + PermissionType.REQUIRE, + Action.TAB_COMPLETE)) { return Collections.emptyList(); } - if (!checkPermissions(sender, commandLabel, passThroughArgs, selectivePermissions, PermissionType.SELECTIVE, Action.TAB_COMPLETE)) { + if (!checkPermissions( + sender, + commandLabel, + passThroughArgs, + selectivePermissions, + PermissionType.SELECTIVE, + Action.TAB_COMPLETE)) { return Collections.emptyList(); } if (Util.isDevMode()) { Log.debug("Tab-complete container: " + container.getPrefix()); } return container.getExecutor().onTabComplete_Internal(capture(sender), commandLabel, passThroughArgs); - } return Collections.emptyList(); } @@ -539,7 +539,11 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma cmds.removeIf(container::equals); cmds.add(container); cmds.sort(Comparator.comparing(CommandContainer::getPrefix)); - Log.debug(Level.INFO, "Registered subcommand: " + container.getPrefix() + " - " + container.getExecutor().getClass().getName(), Log.Caller.create()); + Log.debug( + Level.INFO, + "Registered subcommand: " + container.getPrefix() + " - " + + container.getExecutor().getClass().getName(), + Log.Caller.create()); } @Override @@ -563,7 +567,12 @@ public class SimpleCommandManager implements CommandManager, TabCompleter, Comma HTMLTable table = new HTMLTable(2); table.setTableTitle("Prefix", "Permissions", "Selective Permissions", "Executor Type", "Binding"); for (CommandContainer cmd : this.cmds) { - table.insert(cmd.getPrefix(), CommonUtil.list2String(cmd.getPermissions()), CommonUtil.list2String(cmd.getSelectivePermissions()), cmd.getExecutorType(), cmd.getExecutor().getClass().getName()); + table.insert( + cmd.getPrefix(), + CommonUtil.list2String(cmd.getPermissions()), + CommonUtil.list2String(cmd.getSelectivePermissions()), + cmd.getExecutorType(), + cmd.getExecutor().getClass().getName()); } return table.render(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_About.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_About.java index 919b6efde..7ed4b5e63 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_About.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_About.java @@ -10,6 +10,9 @@ import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import lombok.Data; @@ -22,10 +25,6 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.List; - public class SubCommand_About implements CommandHandler { private final QuickShop plugin; private final LegacyComponentSerializer serializer; @@ -38,54 +37,72 @@ public class SubCommand_About implements CommandHandler { @Override public void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - MsgUtil.sendDirectMessage(sender, serializer.deserialize(ChatColor.AQUA + "QuickShop " + ChatColor.YELLOW + QuickShop.getInstance().getFork())); - MsgUtil.sendDirectMessage(sender, serializer.deserialize(ChatColor.AQUA - + "Version " - + ChatColor.YELLOW - + ">> " - + ChatColor.GREEN - + QuickShop.getInstance().getVersion())); + MsgUtil.sendDirectMessage( + sender, + serializer.deserialize(ChatColor.AQUA + "QuickShop " + ChatColor.YELLOW + + QuickShop.getInstance().getFork())); + MsgUtil.sendDirectMessage( + sender, + serializer.deserialize(ChatColor.AQUA + + "Version " + + ChatColor.YELLOW + + ">> " + + ChatColor.GREEN + + QuickShop.getInstance().getVersion())); if (plugin.getBuildInfo().getGitInfo().getBranch().toUpperCase().contains("ORIGIN/LTS")) { - MsgUtil.sendDirectMessage(sender, serializer.deserialize( - ChatColor.AQUA + MsgUtil.sendDirectMessage( + sender, + serializer.deserialize(ChatColor.AQUA + "Release " + ChatColor.YELLOW + ">> " + ChatColor.GREEN - + serializer.serialize(plugin.text().of(sender, "updatenotify.label.lts").forLocale()))); + + serializer.serialize(plugin.text() + .of(sender, "updatenotify.label.lts") + .forLocale()))); } else if (plugin.getBuildInfo().getGitInfo().getBranch().toUpperCase().contains("ORIGIN/RELEASE")) { - MsgUtil.sendDirectMessage(sender, + MsgUtil.sendDirectMessage( + sender, serializer.deserialize(ChatColor.AQUA + "Release " + ChatColor.YELLOW + ">> " + ChatColor.GREEN - + serializer.serialize(plugin.text().of(sender, "updatenotify.label.stable").forLocale()))); + + serializer.serialize(plugin.text() + .of(sender, "updatenotify.label.stable") + .forLocale()))); } else { - MsgUtil.sendDirectMessage(sender, + MsgUtil.sendDirectMessage( + sender, serializer.deserialize(ChatColor.AQUA + "Release " + ChatColor.YELLOW + ">> " + ChatColor.GREEN - + serializer.serialize(plugin.text().of(sender, "updatenotify.label.unstable").forLocale()))); + + serializer.serialize(plugin.text() + .of(sender, "updatenotify.label.unstable") + .forLocale()))); } - MsgUtil.sendDirectMessage(sender, + MsgUtil.sendDirectMessage( + sender, serializer.deserialize(ChatColor.AQUA + "Developers " + ChatColor.YELLOW + ">> " + ChatColor.GREEN - + CommonUtil.list2String(plugin.getJavaPlugin().getDescription().getAuthors()))); + + CommonUtil.list2String( + plugin.getJavaPlugin().getDescription().getAuthors()))); MsgUtil.sendDirectMessage(sender, serializer.deserialize(ChatColor.GOLD + "Powered by Community")); MsgUtil.sendDirectMessage(sender, serializer.deserialize(ChatColor.RED + "Made with ❤")); Util.asyncThreadRun(() -> { try { String json = fetchKofi(); if (json != null) { - MsgUtil.sendDirectMessage(sender, serializer.deserialize(ChatColor.LIGHT_PURPLE + "Special thanks to those who support to QuickShop-Hikari on Ko-fi :)")); - List dto = JsonUtil.getGson().fromJson(json, new TypeToken>() { - }.getType()); + MsgUtil.sendDirectMessage( + sender, + serializer.deserialize(ChatColor.LIGHT_PURPLE + + "Special thanks to those who support to QuickShop-Hikari on Ko-fi :)")); + List dto = JsonUtil.getGson().fromJson(json, new TypeToken>() {}.getType()); Component message = Component.empty(); boolean first = true; for (KoFiDTO record : dto) { @@ -108,7 +125,8 @@ public class SubCommand_About implements CommandHandler { if (this.fetchCache != null && Instant.now().isBefore(this.fetchCache.getInstant())) { return this.fetchCache.getJson(); } - HttpResponse resp = Unirest.get("https://quickshop-kofi-proxy.ghostchu.workers.dev/").asString(); + HttpResponse resp = Unirest.get("https://quickshop-kofi-proxy.ghostchu.workers.dev/") + .asString(); if (resp.isSuccess()) { this.fetchCache = new KofiFetchCache(Instant.now().plus(12, ChronoUnit.HOURS), resp.getBody()); return this.fetchCache.getJson(); @@ -141,10 +159,13 @@ public class SubCommand_About implements CommandHandler { static class KoFiDTO { @SerializedName("id") private Integer id; + @SerializedName("time") private String time; + @SerializedName("type") private String type; + @SerializedName("name") private String name; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Amount.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Amount.java index 823e9aa32..cbef76824 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Amount.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Amount.java @@ -3,13 +3,12 @@ package com.ghostchu.quickshop.command.subcommand; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; +import java.util.Collections; +import java.util.List; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; - public class SubCommand_Amount implements CommandHandler { private final QuickShop plugin; @@ -37,7 +36,10 @@ public class SubCommand_Amount implements CommandHandler { @Override public List onTabComplete( @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - return parser.getArgs().size() == 1 ? Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.amount").forLocale())) : Collections.emptyList(); + return parser.getArgs().size() == 1 + ? Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize( + plugin.text().of(sender, "tabcomplete.amount").forLocale())) + : Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Benefit.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Benefit.java index 566097d5e..385fa50e6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Benefit.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Benefit.java @@ -10,17 +10,16 @@ import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.PackageUtil; import com.ghostchu.quickshop.util.Profile; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; - public class SubCommand_Benefit implements CommandHandler { private final QuickShop plugin; @@ -32,7 +31,9 @@ public class SubCommand_Benefit implements CommandHandler { @Override public void onCommand(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().isEmpty()) { - plugin.text().of(sender, "command-incorrect", "/quickshop benefit ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop benefit ") + .send(); return; } Shop shop = getLookingShop(sender); @@ -51,15 +52,17 @@ public class SubCommand_Benefit implements CommandHandler { case "add" -> addBenefit(sender, shop, parser); case "remove" -> removeBenefit(sender, shop, parser); case "query" -> queryBenefit(sender, shop, parser); - default -> - plugin.text().of(sender, "command-incorrect", "/quickshop benefit ").send(); + default -> plugin.text() + .of(sender, "command-incorrect", "/quickshop benefit ") + .send(); } - } private void addBenefit(Player sender, Shop shop, @NotNull CommandParser parser) { if (parser.getArgs().size() < 3) { - plugin.text().of(sender, "command-incorrect", "/quickshop benefit ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop benefit ") + .send(); return; } String player = parser.getArgs().get(1); @@ -82,40 +85,52 @@ public class SubCommand_Benefit implements CommandHandler { } if (!parser.getArgs().get(2).endsWith("%")) { // Force player enter '%' to avoid player type something like 0.01 for 1% - plugin.text().of(sender, "invalid-percentage", parser.getArgs().get(0)).send(); + plugin.text() + .of(sender, "invalid-percentage", parser.getArgs().get(0)) + .send(); return; } - String percentageStr = StringUtils.substringBeforeLast(parser.getArgs().get(2), "%"); + String percentageStr = + StringUtils.substringBeforeLast(parser.getArgs().get(2), "%"); Util.mainThreadRun(() -> { try { double percent = Double.parseDouble(percentageStr); if (Double.isInfinite(percent) || Double.isNaN(percent)) { - plugin.text().of(sender, "not-a-number", parser.getArgs().get(2)).send(); + plugin.text() + .of(sender, "not-a-number", parser.getArgs().get(2)) + .send(); return; } if (percent <= 0 || percent >= 100) { - plugin.text().of(sender, "argument-must-between", "percentage", ">0%", "<100%").send(); + plugin.text() + .of(sender, "argument-must-between", "percentage", ">0%", "<100%") + .send(); return; } Benefit benefit = shop.getShopBenefit(); benefit.addBenefit(uuid, percent / 100d); shop.setShopBenefit(benefit); - plugin.text().of(sender, "benefit-added", MsgUtil.formatPlayerProfile(new Profile(uuid, player), sender)).send(); + plugin.text() + .of(sender, "benefit-added", MsgUtil.formatPlayerProfile(new Profile(uuid, player), sender)) + .send(); } catch (NumberFormatException e) { plugin.text().of(sender, "not-a-number", percentageStr).send(); } catch (Benefit.BenefitOverflowException e) { - plugin.text().of(sender, "benefit-overflow", (e.getOverflow() * 100) + "%").send(); + plugin.text() + .of(sender, "benefit-overflow", (e.getOverflow() * 100) + "%") + .send(); } catch (Benefit.BenefitExistsException e) { plugin.text().of(sender, "benefit-exists").send(); } }); }); - } private void removeBenefit(Player sender, Shop shop, @NotNull CommandParser parser) { if (parser.getArgs().size() < 2) { - plugin.text().of(sender, "command-incorrect", "/quickshop benefit ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop benefit ") + .send(); return; } String player = parser.getArgs().get(1); @@ -132,20 +147,30 @@ public class SubCommand_Benefit implements CommandHandler { Benefit benefit = shop.getShopBenefit(); benefit.removeBenefit(uuid); shop.setShopBenefit(benefit); - plugin.text().of(sender, "benefit-removed", MsgUtil.formatPlayerProfile(new Profile(uuid, player), sender)).send(); + plugin.text() + .of(sender, "benefit-removed", MsgUtil.formatPlayerProfile(new Profile(uuid, player), sender)) + .send(); }); - } private void queryBenefit(Player sender, Shop shop, @NotNull CommandParser parser) { - plugin.text().of(sender, "benefit-query", shop.getShopBenefit().getRegistry().size()).send(); + plugin.text() + .of(sender, "benefit-query", shop.getShopBenefit().getRegistry().size()) + .send(); Util.asyncThreadRun(() -> { - for (Map.Entry entry : shop.getShopBenefit().getRegistry().entrySet()) { + for (Map.Entry entry : + shop.getShopBenefit().getRegistry().entrySet()) { String v = MsgUtil.decimalFormat(entry.getValue() * 100); - plugin.text().of(sender, "benefit-query-list", plugin.getPlayerFinder().uuid2Name(entry.getKey()), entry.getKey(), v + "%").send(); + plugin.text() + .of( + sender, + "benefit-query-list", + plugin.getPlayerFinder().uuid2Name(entry.getKey()), + entry.getKey(), + v + "%") + .send(); } }); - } @NotNull @@ -159,9 +184,10 @@ public class SubCommand_Benefit implements CommandHandler { return null; } if (parser.getArgs().size() == 3) { - return Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.percentage").forLocale())); + return Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize( + plugin.text().of(sender, "tabcomplete.percentage").forLocale())); } return Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Buy.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Buy.java index 40813a180..93b132826 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Buy.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Buy.java @@ -26,7 +26,9 @@ public class SubCommand_Buy implements CommandHandler { || plugin.perm().hasPermission(sender, "quickshop.create.control")) { shop.setShopType(ShopType.BUYING); shop.setSignText(plugin.text().findRelativeLanguages(sender)); - plugin.text().of(sender, "command.now-buying", Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(sender, "command.now-buying", Util.getItemStackName(shop.getItem())) + .send(); } else { plugin.text().of(sender, "not-managed-shop").send(); } @@ -34,6 +36,4 @@ public class SubCommand_Buy implements CommandHandler { } plugin.text().of(sender, "not-looking-at-shop").send(); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Clean.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Clean.java index 8965792ec..ec0fa932e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Clean.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Clean.java @@ -9,11 +9,10 @@ import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logging.container.ShopRemoveLog; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.List; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; public class SubCommand_Clean implements CommandHandler { @@ -32,9 +31,7 @@ public class SubCommand_Clean implements CommandHandler { for (Shop shop : plugin.getShopManager().getAllShops()) { try { - if (Util.isLoaded(shop.getLocation()) - && shop.isSelling() - && shop.getRemainingStock() == 0) { + if (Util.isLoaded(shop.getLocation()) && shop.isSelling() && shop.getRemainingStock() == 0) { pendingRemoval.add( shop); // Is selling, but has no stock, and is a chest shop, but is not a double shop. // Can be deleted safely. @@ -46,13 +43,14 @@ public class SubCommand_Clean implements CommandHandler { } for (Shop shop : pendingRemoval) { - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "/quickshop clean", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "/quickshop clean", + shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); } MsgUtil.clean(); plugin.text().of(sender, "command.cleaned", i).send(); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_CleanGhost.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_CleanGhost.java index fb1307605..8aeca7e21 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_CleanGhost.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_CleanGhost.java @@ -9,12 +9,11 @@ import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logging.container.ShopRemoveLog; import com.ghostchu.quickshop.util.performance.BatchBukkitExecutor; +import java.util.concurrent.atomic.AtomicInteger; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; -import java.util.concurrent.atomic.AtomicInteger; - public class SubCommand_CleanGhost implements CommandHandler { private final QuickShop plugin; @@ -39,42 +38,61 @@ public class SubCommand_CleanGhost implements CommandHandler { AtomicInteger deletionCounter = new AtomicInteger(0); BatchBukkitExecutor updateExecutor = new BatchBukkitExecutor<>(); updateExecutor.addTasks(plugin.getShopManager().getAllShops()); - updateExecutor.startHandle(plugin.getJavaPlugin(), (shop) -> { - if (shop == null) { - return; // WTF - } - if (shop.getOwner() == null) { - plugin.text().of(sender, "cleanghost-deleting", shop.getShopId(), "invalid owner data").send(); - plugin.getShopManager().deleteShop(shop); - deletionCounter.incrementAndGet(); - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "/quickshop cleanghost command", shop.saveToInfoStorage())); - return; - } - if (shop.getItem().getType() == Material.AIR) { - plugin.text().of(sender, "cleanghost-deleting", shop.getShopId(), "invalid item data").send(); - plugin.getShopManager().deleteShop(shop); - deletionCounter.incrementAndGet(); - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "/quickshop cleanghost command", shop.saveToInfoStorage())); - return; - } - if (!shop.getLocation().isWorldLoaded()) { - plugin.text().of(sender, "cleanghost-deleting", shop.getShopId(), "unloaded world").send(); - plugin.getShopManager().deleteShop(shop); - deletionCounter.incrementAndGet(); - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "/quickshop cleanghost command", shop.saveToInfoStorage())); - return; - } - if (!Util.canBeShop(shop.getLocation().getBlock())) { - plugin.text().of(sender, "cleanghost-deleting", shop.getShopId(), "invalid shop block").send(); - plugin.getShopManager().deleteShop(shop); - deletionCounter.incrementAndGet(); - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "/quickshop cleanghost command", shop.saveToInfoStorage())); - } - }).whenComplete((aVoid, throwable) -> - plugin.text().of(sender, "cleanghost-deleted", deletionCounter.get() - ).send()); - + updateExecutor + .startHandle(plugin.getJavaPlugin(), (shop) -> { + if (shop == null) { + return; // WTF + } + if (shop.getOwner() == null) { + plugin.text() + .of(sender, "cleanghost-deleting", shop.getShopId(), "invalid owner data") + .send(); + plugin.getShopManager().deleteShop(shop); + deletionCounter.incrementAndGet(); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "/quickshop cleanghost command", + shop.saveToInfoStorage())); + return; + } + if (shop.getItem().getType() == Material.AIR) { + plugin.text() + .of(sender, "cleanghost-deleting", shop.getShopId(), "invalid item data") + .send(); + plugin.getShopManager().deleteShop(shop); + deletionCounter.incrementAndGet(); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "/quickshop cleanghost command", + shop.saveToInfoStorage())); + return; + } + if (!shop.getLocation().isWorldLoaded()) { + plugin.text() + .of(sender, "cleanghost-deleting", shop.getShopId(), "unloaded world") + .send(); + plugin.getShopManager().deleteShop(shop); + deletionCounter.incrementAndGet(); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "/quickshop cleanghost command", + shop.saveToInfoStorage())); + return; + } + if (!Util.canBeShop(shop.getLocation().getBlock())) { + plugin.text() + .of(sender, "cleanghost-deleting", shop.getShopId(), "invalid shop block") + .send(); + plugin.getShopManager().deleteShop(shop); + deletionCounter.incrementAndGet(); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "/quickshop cleanghost command", + shop.saveToInfoStorage())); + } + }) + .whenComplete((aVoid, throwable) -> plugin.text() + .of(sender, "cleanghost-deleted", deletionCounter.get()) + .send()); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Create.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Create.java index 02cb3e8db..d75d1cfde 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Create.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Create.java @@ -7,6 +7,8 @@ import com.ghostchu.quickshop.api.shop.ShopAction; import com.ghostchu.quickshop.shop.SimpleInfo; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Collections; +import java.util.List; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.Material; import org.bukkit.block.Block; @@ -16,14 +18,10 @@ import org.bukkit.util.BlockIterator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; - public class SubCommand_Create implements CommandHandler { private final QuickShop plugin; - public SubCommand_Create(@NotNull QuickShop plugin) { this.plugin = plugin; } @@ -48,7 +46,9 @@ public class SubCommand_Create implements CommandHandler { plugin.text().of(sender, "item-not-exist", matName).send(); return; } - if (parser.getArgs().size() > 2 && plugin.perm().hasPermission(sender, "quickshop.create.stack") && plugin.isAllowStack()) { + if (parser.getArgs().size() > 2 + && plugin.perm().hasPermission(sender, "quickshop.create.stack") + && plugin.isAllowStack()) { try { int amount = Integer.parseInt(parser.getArgs().get(2)); if (amount < 1) { @@ -72,8 +72,16 @@ public class SubCommand_Create implements CommandHandler { continue; } // Send creation menu. - plugin.getShopManager().getInteractiveManager().put(sender.getUniqueId(), - new SimpleInfo(b.getLocation(), ShopAction.CREATE_SELL, item, b.getRelative(sender.getFacing().getOppositeFace()), false)); + plugin.getShopManager() + .getInteractiveManager() + .put( + sender.getUniqueId(), + new SimpleInfo( + b.getLocation(), + ShopAction.CREATE_SELL, + item, + b.getRelative(sender.getFacing().getOppositeFace()), + false)); plugin.getShopManager().handleChat(sender, price); return; } @@ -100,17 +108,20 @@ public class SubCommand_Create implements CommandHandler { public List onTabComplete( @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().size() == 1) { - return Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.price").forLocale())); + return Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of(sender, "tabcomplete.price").forLocale())); } if (sender.getInventory().getItemInMainHand().getType().isAir()) { if (parser.getArgs().size() == 2) { - return Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.item").forLocale())); + return Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of(sender, "tabcomplete.item").forLocale())); } if (parser.getArgs().size() == 3) { - return Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.amount").forLocale())); + return Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize( + plugin.text().of(sender, "tabcomplete.amount").forLocale())); } } return Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Currency.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Currency.java index 2db9c48bf..519d8b778 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Currency.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Currency.java @@ -9,13 +9,12 @@ import com.ghostchu.quickshop.api.shop.PriceLimiterStatus; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.util.Util; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - import java.util.Collections; import java.util.List; import java.util.Objects; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; public class SubCommand_Currency implements CommandHandler { @@ -40,21 +39,32 @@ public class SubCommand_Currency implements CommandHandler { plugin.text().of(sender, "currency-not-support").send(); return; } - if (!plugin.getEconomy().hasCurrency(Objects.requireNonNull(shop.getLocation().getWorld()), parser.getArgs().get(0))) { + if (!plugin.getEconomy() + .hasCurrency( + Objects.requireNonNull(shop.getLocation().getWorld()), + parser.getArgs().get(0))) { plugin.text().of(sender, "currency-not-exists").send(); return; } PriceLimiter limiter = plugin.getShopManager().getPriceLimiter(); - PriceLimiterCheckResult checkResult = limiter.check(sender, shop.getItem(), parser.getArgs().get(0), shop.getPrice()); + PriceLimiterCheckResult checkResult = + limiter.check(sender, shop.getItem(), parser.getArgs().get(0), shop.getPrice()); if (checkResult.getStatus() != PriceLimiterStatus.PASS) { - plugin.text().of(sender, "restricted-prices", Util.getItemStackName(shop.getItem()), - Component.text(checkResult.getMin()), - Component.text(checkResult.getMax())).send(); + plugin.text() + .of( + sender, + "restricted-prices", + Util.getItemStackName(shop.getItem()), + Component.text(checkResult.getMin()), + Component.text(checkResult.getMax())) + .send(); return; } shop.setCurrency(parser.getArgs().get(0)); - plugin.text().of(sender, "currency-set", parser.getArgs().get(0)).send(); + plugin.text() + .of(sender, "currency-set", parser.getArgs().get(0)) + .send(); return; } else { @@ -71,5 +81,4 @@ public class SubCommand_Currency implements CommandHandler { @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Database.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Database.java index 9d6fe80f4..9eaae3b6b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Database.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Database.java @@ -7,14 +7,13 @@ import com.ghostchu.quickshop.database.DataTables; import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; import com.ghostchu.quickshop.util.FastPlayerFinder; import com.ghostchu.quickshop.util.Util; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SubCommand_Database implements CommandHandler { private final QuickShop plugin; @@ -42,12 +41,15 @@ public class SubCommand_Database implements CommandHandler { case "trim" -> handleTrim(sender, subParams); case "purgelogs" -> purgeLogs(sender, subParams); case "purgeplayerscache" -> purgePlayersCache(sender, subParams); - default -> plugin.text().of(sender, "bad-command-usage-detailed", "trim").send(); + default -> plugin.text() + .of(sender, "bad-command-usage-detailed", "trim") + .send(); } } @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().size() < 2) { return List.of("trim"); } @@ -61,42 +63,47 @@ public class SubCommand_Database implements CommandHandler { } plugin.text().of(sender, "database.trim-start").send(); SimpleDatabaseHelperV2 databaseHelper = (SimpleDatabaseHelperV2) plugin.getDatabaseHelper(); - databaseHelper.purgeIsolated() - .thenAccept(i -> plugin.text().of(sender, "database.trim-complete", i).send()) + databaseHelper + .purgeIsolated() + .thenAccept(i -> + plugin.text().of(sender, "database.trim-complete", i).send()) .exceptionally(err -> { plugin.text().of(sender, "internal-error", err.getMessage()).send(); return null; }); - } -// -// private void handleStatus(@NotNull CommandSender sender) { -// DatabaseStatusHolder holder = plugin.getDatabaseMaintenanceWatcher().getResult(); -// if (holder == null) { -// plugin.text().of(sender, "database.scanning-sync").send(); -// plugin.getDatabaseMaintenanceWatcher().runTaskAsynchronously(plugin); -// return; -// } -// Component statusComponent = switch (holder.getStatus()) { -// case GOOD -> plugin.text().of(sender, "database.status-good").forLocale(); -// case MAINTENANCE_REQUIRED -> plugin.text().of(sender, "database.status-bad").forLocale(); -// }; -// ChatSheetPrinter printer = new ChatSheetPrinter(sender); -// printer.printHeader(); -// printer.printLine(plugin.text().of(sender, "database.status", statusComponent).forLocale()); -// printer.printLine(plugin.text().of(sender, "database.isolated").forLocale()); -// printer.printLine(plugin.text().of(sender, "database.isolated-data-ids", holder.getDataIds().getIsolated().size()).forLocale()); -// printer.printLine(plugin.text().of(sender, "database.isolated-shop-ids", holder.getShopIds().getIsolated().size()).forLocale()); -// if (holder.getStatus() == DatabaseStatusHolder.Status.MAINTENANCE_REQUIRED) { -// printer.printLine(plugin.text().of(sender, "database.suggestion.trim").forLocale()); -// } -// printer.printFooter(); -// } + // + // private void handleStatus(@NotNull CommandSender sender) { + // DatabaseStatusHolder holder = plugin.getDatabaseMaintenanceWatcher().getResult(); + // if (holder == null) { + // plugin.text().of(sender, "database.scanning-sync").send(); + // plugin.getDatabaseMaintenanceWatcher().runTaskAsynchronously(plugin); + // return; + // } + // Component statusComponent = switch (holder.getStatus()) { + // case GOOD -> plugin.text().of(sender, "database.status-good").forLocale(); + // case MAINTENANCE_REQUIRED -> plugin.text().of(sender, "database.status-bad").forLocale(); + // }; + // ChatSheetPrinter printer = new ChatSheetPrinter(sender); + // printer.printHeader(); + // printer.printLine(plugin.text().of(sender, "database.status", statusComponent).forLocale()); + // printer.printLine(plugin.text().of(sender, "database.isolated").forLocale()); + // printer.printLine(plugin.text().of(sender, "database.isolated-data-ids", + // holder.getDataIds().getIsolated().size()).forLocale()); + // printer.printLine(plugin.text().of(sender, "database.isolated-shop-ids", + // holder.getShopIds().getIsolated().size()).forLocale()); + // if (holder.getStatus() == DatabaseStatusHolder.Status.MAINTENANCE_REQUIRED) { + // printer.printLine(plugin.text().of(sender, "database.suggestion.trim").forLocale()); + // } + // printer.printFooter(); + // } private void purgeLogs(@NotNull CommandSender sender, @NotNull List subParams) { // TODO: Only purge before x days if (subParams.isEmpty()) { - plugin.text().of(sender, "command-incorrect", "/quickshop database purgelogs ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop database purgelogs ") + .send(); return; } if (subParams.size() < 2 || !"confirm".equalsIgnoreCase(subParams.get(1))) { @@ -112,19 +119,27 @@ public class SubCommand_Database implements CommandHandler { databaseHelper.purgeLogsRecords(calendar.getTime()).whenComplete((r, e) -> { if (e != null) { plugin.logger().warn("Failed to execute database purge.", e); - plugin.text().of(sender, "database.purge-done-with-error", r).send(); + plugin.text() + .of(sender, "database.purge-done-with-error", r) + .send(); } else { if (r == -1) { plugin.logger().warn("Failed to execute database purge, check the exception above."); - plugin.text().of(sender, "database.purge-done-with-error", r).send(); + plugin.text() + .of(sender, "database.purge-done-with-error", r) + .send(); } else { - plugin.text().of(sender, "database.purge-done-with-line", r).send(); + plugin.text() + .of(sender, "database.purge-done-with-line", r) + .send(); } } }); // Then we need also purge the isolated data after purge the logs. plugin.text().of(sender, "database.trim-start").send(); - databaseHelper.purgeIsolated().whenComplete((data, err) -> plugin.text().of(sender, "database.trim-complete", data).send()); + databaseHelper.purgeIsolated().whenComplete((data, err) -> plugin.text() + .of(sender, "database.trim-complete", data) + .send()); } catch (NumberFormatException e) { plugin.text().of(sender, "not-a-number", subParams.get(0)).send(); } @@ -135,12 +150,20 @@ public class SubCommand_Database implements CommandHandler { Util.asyncThreadRun(() -> DataTables.PLAYERS .createDelete() .build() - .executeAsync((lines) -> { - ((FastPlayerFinder) plugin.getPlayerFinder()).getNameCache().invalidateAll(); - plugin.text().of(sender, "database.purge-players-completed", lines).send(); - }, (error, sqlAction) -> { - plugin.logger().error("Failed to purge players caches!", error); - plugin.text().of(sender, "database.purge-players-error").send(); - })); + .executeAsync( + (lines) -> { + ((FastPlayerFinder) plugin.getPlayerFinder()) + .getNameCache() + .invalidateAll(); + plugin.text() + .of(sender, "database.purge-players-completed", lines) + .send(); + }, + (error, sqlAction) -> { + plugin.logger().error("Failed to purge players caches!", error); + plugin.text() + .of(sender, "database.purge-players-error") + .send(); + })); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Debug.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Debug.java index ad737d35d..0d39b88e6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Debug.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Debug.java @@ -10,15 +10,6 @@ import com.ghostchu.quickshop.shop.cache.SimpleShopCache; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.performance.BatchBukkitExecutor; import com.google.common.cache.Cache; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.RegisteredListener; -import org.jetbrains.annotations.NotNull; - import java.lang.reflect.Method; import java.time.Instant; import java.util.ArrayList; @@ -28,6 +19,14 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.RegisteredListener; +import org.jetbrains.annotations.NotNull; public class SubCommand_Debug implements CommandHandler { @@ -59,7 +58,9 @@ public class SubCommand_Debug implements CommandHandler { case "set-property" -> handleProperty(sender, subParams); case "await-profile-io-tasks" -> handleProfileIOTasksInfo(sender, subParams); case "reset-shop-caches" -> handleShopCacheResetting(sender, subParams); - default -> plugin.text().of(sender, "debug.arguments-invalid", parser.getArgs().get(0)).send(); + default -> plugin.text() + .of(sender, "debug.arguments-invalid", parser.getArgs().get(0)) + .send(); } } @@ -108,17 +109,16 @@ public class SubCommand_Debug implements CommandHandler { List remains = executorService.shutdownNow(); sender.sendMessage("Killed executor service with " + remains.size() + " unfinished tasks."); switch (subParams.get(0)) { - case "PRIMARY" -> - QuickExecutor.setPrimaryProfileIoExecutor(new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, queue)); - case "SECONDARY" -> - QuickExecutor.setSecondaryProfileIoExecutor(new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, queue)); - default -> { - } + case "PRIMARY" -> QuickExecutor.setPrimaryProfileIoExecutor( + new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, queue)); + case "SECONDARY" -> QuickExecutor.setSecondaryProfileIoExecutor( + new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, queue)); + default -> {} } - sender.sendMessage("Successfully re-launched executor service with 2 min, 32 max, 60sec K.A.T., unlimited capacity."); + sender.sendMessage( + "Successfully re-launched executor service with 2 min, 32 max, 60sec K.A.T., unlimited capacity."); } } - } private void handleProperty(CommandSender sender, List subParams) { @@ -188,9 +188,14 @@ public class SubCommand_Debug implements CommandHandler { private void handleShopsLoaderReload(CommandSender sender, List remove) { plugin.text().of(sender, "debug.force-shop-loader-reload").send(); List allShops = plugin.getShopManager().getAllShops(); - plugin.text().of(sender, "debug.force-shop-loader-reload-unloading-shops-from-memory", allShops.size()).send(); - plugin.getShopManager().getAllShops().forEach(shop -> plugin.getShopManager().unloadShop(shop)); - plugin.text().of(sender, "debug.force-shop-loader-reload-reloading-shop-loader").send(); + plugin.text() + .of(sender, "debug.force-shop-loader-reload-unloading-shops-from-memory", allShops.size()) + .send(); + plugin.getShopManager().getAllShops().forEach(shop -> plugin.getShopManager() + .unloadShop(shop)); + plugin.text() + .of(sender, "debug.force-shop-loader-reload-reloading-shop-loader") + .send(); plugin.getShopLoader().loadShops(); plugin.text().of(sender, "debug.force-shop-loader-reload-complete").send(); } @@ -200,10 +205,11 @@ public class SubCommand_Debug implements CommandHandler { List shops = new ArrayList<>(plugin.getShopManager().getLoadedShops()); shops.forEach(s -> plugin.getShopManager().unloadShop(s)); shops.forEach(s -> plugin.getShopManager().loadShop(s)); - plugin.text().of(sender, "debug.force-shop-reload-complete", shops.size()).send(); + plugin.text() + .of(sender, "debug.force-shop-reload-complete", shops.size()) + .send(); } - public void switchDebug(@NotNull CommandSender sender) { final boolean debug = plugin.getConfig().getBoolean("dev-mode"); @@ -238,7 +244,9 @@ public class SubCommand_Debug implements CommandHandler { plugin.text().of(sender, "not-looking-at-shop").send(); return; } - shop.getSigns().forEach(sign -> plugin.text().of(sender, "debug.sign-located", sign.getLocation()).send()); + shop.getSigns().forEach(sign -> plugin.text() + .of(sender, "debug.sign-located", sign.getLocation()) + .send()); } private void handleDatabase(@NotNull CommandSender sender, @NotNull List remove) { @@ -251,31 +259,48 @@ public class SubCommand_Debug implements CommandHandler { private void handleSignsUpdate(CommandSender sender, List remove) { if (remove.isEmpty()) { - plugin.text().of(sender, "debug.update-player-shops-signs-no-username-given").send(); + plugin.text() + .of(sender, "debug.update-player-shops-signs-no-username-given") + .send(); return; } - plugin.text().of(sender, "debug.update-player-shops-signs-create-async-task").send(); + plugin.text() + .of(sender, "debug.update-player-shops-signs-create-async-task") + .send(); plugin.getPlayerFinder().name2UuidFuture(remove.get(0)).whenComplete((uuid, throwable) -> { if (throwable != null) { - plugin.text().of(sender, "internal-error", throwable.getMessage()).send(); + plugin.text() + .of(sender, "internal-error", throwable.getMessage()) + .send(); return; } - plugin.text().of(sender, "debug.update-player-shops-player-selected", uuid).send(); + plugin.text() + .of(sender, "debug.update-player-shops-player-selected", uuid) + .send(); List shops = plugin.getShopManager().getAllShops(uuid); - plugin.text().of(sender, "debug.update-player-shops-player-shops", shops.size()).send(); + plugin.text() + .of(sender, "debug.update-player-shops-player-shops", shops.size()) + .send(); BatchBukkitExecutor updateExecutor = new BatchBukkitExecutor<>(); updateExecutor.addTasks(shops); - plugin.text().of(sender, "debug.update-player-shops-task-started", shops.size()).send(); - updateExecutor.startHandle(plugin.getJavaPlugin(), Shop::setSignText).whenComplete((aVoid, th) -> { - if (th != null) { - plugin.text().of(sender, "internal-error", th.getMessage()).send(); - return; - } - long usedTime = updateExecutor.getStartTime().until(Instant.now(), java.time.temporal.ChronoUnit.MILLIS); - plugin.text().of(sender, "debug.update-player-shops-complete", usedTime); - }); + plugin.text() + .of(sender, "debug.update-player-shops-task-started", shops.size()) + .send(); + updateExecutor + .startHandle(plugin.getJavaPlugin(), Shop::setSignText) + .whenComplete((aVoid, th) -> { + if (th != null) { + plugin.text() + .of(sender, "internal-error", th.getMessage()) + .send(); + return; + } + long usedTime = updateExecutor + .getStartTime() + .until(Instant.now(), java.time.temporal.ChronoUnit.MILLIS); + plugin.text().of(sender, "debug.update-player-shops-complete", usedTime); + }); }); - } public void printHandlerList(@NotNull CommandSender sender, String event) { @@ -286,16 +311,19 @@ public class SubCommand_Debug implements CommandHandler { final HandlerList list = (HandlerList) method.invoke(null, obj); for (RegisteredListener listener1 : list.getRegisteredListeners()) { - MsgUtil.sendDirectMessage(sender, - LegacyComponentSerializer.legacySection().deserialize(ChatColor.AQUA - + listener1.getPlugin().getName() - + ChatColor.YELLOW - + " # " - + ChatColor.GREEN - + listener1.getListener().getClass().getCanonicalName())); + MsgUtil.sendDirectMessage( + sender, + LegacyComponentSerializer.legacySection() + .deserialize(ChatColor.AQUA + + listener1.getPlugin().getName() + + ChatColor.YELLOW + + " # " + + ChatColor.GREEN + + listener1.getListener().getClass().getCanonicalName())); } } catch (Exception th) { - MsgUtil.sendDirectMessage(sender, Component.text("ERR " + th.getMessage()).color(NamedTextColor.RED)); + MsgUtil.sendDirectMessage( + sender, Component.text("ERR " + th.getMessage()).color(NamedTextColor.RED)); plugin.logger().warn("An error has occurred while getting the HandlerList", th); } } @@ -306,5 +334,4 @@ public class SubCommand_Debug implements CommandHandler { @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Empty.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Empty.java index fc5e04aff..3036d90f1 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Empty.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Empty.java @@ -31,6 +31,4 @@ public class SubCommand_Empty implements CommandHandler { plugin.text().of(sender, "not-looking-at-shop").send(); } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Export.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Export.java index 482259c88..5120207f3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Export.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Export.java @@ -6,12 +6,11 @@ import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.database.DatabaseIOUtil; import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; import com.ghostchu.quickshop.util.Util; -import org.bukkit.command.ConsoleCommandSender; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.sql.SQLException; +import org.bukkit.command.ConsoleCommandSender; +import org.jetbrains.annotations.NotNull; public class SubCommand_Export implements CommandHandler { private final QuickShop plugin; @@ -21,7 +20,8 @@ public class SubCommand_Export implements CommandHandler { } @Override - public synchronized void onCommand(@NotNull ConsoleCommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public synchronized void onCommand( + @NotNull ConsoleCommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { plugin.text().of(sender, "exporting-database").send(); File file = new File(QuickShop.getInstance().getDataFolder(), "export-" + System.currentTimeMillis() + ".zip"); @@ -35,8 +35,5 @@ public class SubCommand_Export implements CommandHandler { plugin.text().of(sender, "exporting-failed", e.getMessage()).send(); } }); - } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_FetchMessage.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_FetchMessage.java index f7e015b82..aab6607f4 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_FetchMessage.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_FetchMessage.java @@ -8,13 +8,10 @@ import org.jetbrains.annotations.NotNull; public class SubCommand_FetchMessage implements CommandHandler { - public SubCommand_FetchMessage() { - } + public SubCommand_FetchMessage() {} @Override public void onCommand(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { MsgUtil.flush(sender); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Find.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Find.java index 74e3a18c2..15cf86915 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Find.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Find.java @@ -9,6 +9,7 @@ import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; import io.papermc.lib.PaperLib; +import java.util.*; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.ChatColor; @@ -19,8 +20,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import java.util.*; - public class SubCommand_Find implements CommandHandler { private final QuickShop plugin; @@ -39,13 +38,12 @@ public class SubCommand_Find implements CommandHandler { final Location loc = sender.getLocation().clone(); final Vector playerVector = loc.toVector(); - //Combing command args + // Combing command args final StringBuilder sb = new StringBuilder(parser.getArgs().get(0)); for (int i = 1; i < parser.getArgs().size(); i++) { sb.append("_").append(parser.getArgs().get(i)); } - final String lookFor = sb.toString().toLowerCase(); final StringBuilder originLookForSb = new StringBuilder(parser.getArgs().get(0)); @@ -59,18 +57,18 @@ public class SubCommand_Find implements CommandHandler { final boolean allShops = plugin.getConfig().getBoolean("shop.finding.all"); final boolean excludeOutOfStock = plugin.getConfig().getBoolean("shop.finding.exclude-out-of-stock"); - //Rewrite by Ghost_chu - Use vector to replace old chunks finding. + // Rewrite by Ghost_chu - Use vector to replace old chunks finding. Map aroundShops = new HashMap<>(); - //Choose finding source + // Choose finding source Collection scanPool; if (allShops) { scanPool = plugin.getShopManager().getAllShops(); } else { scanPool = plugin.getShopManager().getLoadedShops(); } - //Calc distance between player and shop + // Calc distance between player and shop for (Shop shop : scanPool) { if (!Objects.equals(shop.getLocation().getWorld(), loc.getWorld())) { continue; @@ -84,10 +82,13 @@ public class SubCommand_Find implements CommandHandler { } Vector shopVector = shop.getLocation().toVector(); double distance = shopVector.distance(playerVector); - //Check distance + // Check distance if (distance <= maxDistance) { - //Collect valid shop that trading items we want - if (!ChatColor.stripColor(LegacyComponentSerializer.legacySection().serialize(Util.getItemStackName(shop.getItem()))).toLowerCase().contains(lookFor)) { + // Collect valid shop that trading items we want + if (!ChatColor.stripColor(LegacyComponentSerializer.legacySection() + .serialize(Util.getItemStackName(shop.getItem()))) + .toLowerCase() + .contains(lookFor)) { if (!shop.getItem().getType().name().toLowerCase().contains(lookFor)) { if (plugin.getItemMarker().get(originLookFor) == null) { continue; @@ -95,52 +96,66 @@ public class SubCommand_Find implements CommandHandler { } } if (excludeOutOfStock) { - if ((shop.isSelling() && shop.getRemainingStock() == 0) || (shop.isBuying() && shop.getRemainingSpace() == 0)) { + if ((shop.isSelling() && shop.getRemainingStock() == 0) + || (shop.isBuying() && shop.getRemainingSpace() == 0)) { continue; } } aroundShops.put(shop, distance); } } - //Check if no shops found + // Check if no shops found if (aroundShops.isEmpty()) { plugin.text().of(sender, "no-nearby-shop", lookFor).send(); return; } - //Okay now all shops is our wanted shop in Map + // Okay now all shops is our wanted shop in Map - List> sortedShops = aroundShops.entrySet().stream().sorted(Map.Entry.comparingByValue(Double::compare).reversed()).toList(); + List> sortedShops = aroundShops.entrySet().stream() + .sorted(Map.Entry.comparingByValue(Double::compare) + .reversed()) + .toList(); - //Function + // Function if (usingOldLogic) { Map.Entry closest = sortedShops.get(0); Location lookAt = closest.getKey().getLocation().clone().add(0.5, 0.5, 0.5); - PaperLib.teleportAsync(sender, Util.lookAt(sender.getEyeLocation(), lookAt).add(0, -1.62, 0), + PaperLib.teleportAsync( + sender, + Util.lookAt(sender.getEyeLocation(), lookAt).add(0, -1.62, 0), PlayerTeleportEvent.TeleportCause.UNKNOWN); - plugin.text().of(sender, "nearby-shop-this-way", closest.getValue().intValue()).send(); + plugin.text() + .of(sender, "nearby-shop-this-way", closest.getValue().intValue()) + .send(); } else { plugin.text().of(sender, "nearby-shop-header", lookFor).send(); for (Map.Entry shopDoubleEntry : sortedShops) { Shop shop = shopDoubleEntry.getKey(); Location location = shop.getLocation(); ItemStack previewItemStack = shop.getItem().clone(); - ItemPreviewComponentPrePopulateEvent previewComponentPrePopulateEvent = new ItemPreviewComponentPrePopulateEvent(previewItemStack, sender); + ItemPreviewComponentPrePopulateEvent previewComponentPrePopulateEvent = + new ItemPreviewComponentPrePopulateEvent(previewItemStack, sender); previewComponentPrePopulateEvent.callEvent(); previewItemStack = previewComponentPrePopulateEvent.getItemStack(); - // "nearby-shop-entry": "&a- Info:{0} &aPrice:&b{1} &ax:&b{2} &ay:&b{3} &az:&b{4} &adistance: &b{5} &ablock(s)" - Component entryComponent = plugin.text().of(sender, "nearby-shop-entry", - shop.getSignText(plugin.text().findRelativeLanguages(sender)).get(1), - shop.getSignText(plugin.text().findRelativeLanguages(sender)).get(3), + // "nearby-shop-entry": "&a- Info:{0} &aPrice:&b{1} &ax:&b{2} &ay:&b{3} &az:&b{4} &adistance: &b{5} + // &ablock(s)" + Component entryComponent = plugin.text() + .of( + sender, + "nearby-shop-entry", + shop.getSignText(plugin.text().findRelativeLanguages(sender)) + .get(1), + shop.getSignText(plugin.text().findRelativeLanguages(sender)) + .get(3), location.getBlockX(), location.getBlockY(), location.getBlockZ(), - shopDoubleEntry.getValue().intValue() - ).forLocale() + shopDoubleEntry.getValue().intValue()) + .forLocale() .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(previewItemStack)); MsgUtil.sendDirectMessage(sender, entryComponent); } - } } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Help.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Help.java index a69aaa83b..3ae6a7707 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Help.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Help.java @@ -5,13 +5,12 @@ import com.ghostchu.quickshop.api.command.CommandContainer; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.util.MsgUtil; +import java.util.List; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class SubCommand_Help implements CommandHandler { private final QuickShop plugin; @@ -21,12 +20,10 @@ public class SubCommand_Help implements CommandHandler { } @Override - public void onCommand( - @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { sendHelp(sender, commandLabel); } - private void sendHelp(@NotNull CommandSender s, @NotNull String commandLabel) { plugin.text().of(s, "command.description.title").send(); String locale = MsgUtil.getDefaultGameLanguageCode(); @@ -37,7 +34,7 @@ public class SubCommand_Help implements CommandHandler { for (CommandContainer container : plugin.getCommandManager().getRegisteredCommands()) { if (!container.isHidden()) { boolean passed = false; - //selectivePermissions + // selectivePermissions final List selectivePermissions = container.getSelectivePermissions(); if (selectivePermissions != null && !selectivePermissions.isEmpty()) { for (String selectivePermission : container.getSelectivePermissions()) { @@ -49,11 +46,13 @@ public class SubCommand_Help implements CommandHandler { } } } - //requirePermissions + // requirePermissions final List requirePermissions = container.getPermissions(); if (requirePermissions != null && !requirePermissions.isEmpty()) { for (String requirePermission : requirePermissions) { - if (requirePermission != null && !requirePermission.isEmpty() && !plugin.perm().hasPermission(s, requirePermission)) { + if (requirePermission != null + && !requirePermission.isEmpty() + && !plugin.perm().hasPermission(s, requirePermission)) { continue commandPrintingLoop; } } @@ -62,22 +61,36 @@ public class SubCommand_Help implements CommandHandler { if (!passed) { continue; } - Component commandDesc = plugin.text().of(s, "command.description." + container.getPrefix()).forLocale(); + Component commandDesc = plugin.text() + .of(s, "command.description." + container.getPrefix()) + .forLocale(); if (container.getDescription() != null) { commandDesc = container.getDescription().apply(locale); if (commandDesc == null) { - commandDesc = Component.text("Error: Subcommand " + container.getPrefix() + " # " + container.getClass().getCanonicalName() + " doesn't register the correct help description."); + commandDesc = Component.text("Error: Subcommand " + container.getPrefix() + " # " + + container.getClass().getCanonicalName() + + " doesn't register the correct help description."); } } - if (container.isDisabled() || (container.getDisabledSupplier() != null && container.getDisabledSupplier().get())) { + if (container.isDisabled() + || (container.getDisabledSupplier() != null + && container.getDisabledSupplier().get())) { if (plugin.perm().hasPermission(s, "quickshop.showdisabled")) { - plugin.text().of(s, "command.format-disabled", commandLabel, container.getPrefix(), container.getDisableText(s)).send(); + plugin.text() + .of( + s, + "command.format-disabled", + commandLabel, + container.getPrefix(), + container.getDisableText(s)) + .send(); } } else { - plugin.text().of(s, "command.format", commandLabel, container.getPrefix(), commandDesc).send(); + plugin.text() + .of(s, "command.format", commandLabel, container.getPrefix(), commandDesc) + .send(); } } } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Info.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Info.java index c213ede6c..8c97f5167 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Info.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Info.java @@ -6,14 +6,13 @@ import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.ShopChunk; import com.ghostchu.quickshop.util.MsgUtil; +import java.util.Map; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; -import java.util.Map; - public class SubCommand_Info implements CommandHandler { private final QuickShop plugin; @@ -49,18 +48,29 @@ public class SubCommand_Info implements CommandHandler { } } - MsgUtil.sendDirectMessage(sender, Component.text("QuickShop Statistics...").color(NamedTextColor.GOLD)); - MsgUtil.sendDirectMessage(sender, Component.text("Server UniqueId: " + plugin.getServerUniqueID()).color(NamedTextColor.GREEN)); - MsgUtil.sendDirectMessage(sender, Component.text((buying + selling) - + " shops in " - + chunks - + " chunks spread over " - + worlds - + " worlds.").color(NamedTextColor.GREEN)); - MsgUtil.sendDirectMessage(sender, Component.text(nostock - + " out-of-stock loaded shops (excluding doubles) which will be removed by /quickshop clean.").color(NamedTextColor.GREEN)); - MsgUtil.sendDirectMessage(sender, Component.text("QuickShop " + QuickShop.getInstance().getVersion()).color(NamedTextColor.GREEN)); + MsgUtil.sendDirectMessage( + sender, Component.text("QuickShop Statistics...").color(NamedTextColor.GOLD)); + MsgUtil.sendDirectMessage( + sender, + Component.text("Server UniqueId: " + plugin.getServerUniqueID()).color(NamedTextColor.GREEN)); + MsgUtil.sendDirectMessage( + sender, + Component.text((buying + selling) + + " shops in " + + chunks + + " chunks spread over " + + worlds + + " worlds.") + .color(NamedTextColor.GREEN)); + MsgUtil.sendDirectMessage( + sender, + Component.text( + nostock + + " out-of-stock loaded shops (excluding doubles) which will be removed by /quickshop clean.") + .color(NamedTextColor.GREEN)); + MsgUtil.sendDirectMessage( + sender, + Component.text("QuickShop " + QuickShop.getInstance().getVersion()) + .color(NamedTextColor.GREEN)); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Item.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Item.java index fd7ffdf4c..5f5183a81 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Item.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Item.java @@ -37,7 +37,11 @@ public class SubCommand_Item implements CommandHandler { plugin.text().of(sender, "command.no-trade-item").send(); return; } - if (plugin.getShopItemBlackList().isBlacklisted(itemStack) && !plugin.perm().hasPermission(sender, "quickshop.bypass." + itemStack.getType().name())) { + if (plugin.getShopItemBlackList().isBlacklisted(itemStack) + && !plugin.perm() + .hasPermission( + sender, + "quickshop.bypass." + itemStack.getType().name())) { plugin.text().of(sender, "blacklisted-item").send(); return; } @@ -47,16 +51,26 @@ public class SubCommand_Item implements CommandHandler { PriceLimiter limiter = plugin.getShopManager().getPriceLimiter(); PriceLimiterCheckResult checkResult = limiter.check(sender, itemStack, shop.getCurrency(), shop.getPrice()); if (checkResult.getStatus() != PriceLimiterStatus.PASS) { - plugin.text().of(sender, "restricted-prices", Util.getItemStackName(shop.getItem()), - Component.text(checkResult.getMin()), - Component.text(checkResult.getMax())).send(); + plugin.text() + .of( + sender, + "restricted-prices", + Util.getItemStackName(shop.getItem()), + Component.text(checkResult.getMin()), + Component.text(checkResult.getMax())) + .send(); return; } shop.setItem(itemStack); - plugin.text().of(sender, "command.trade-item-now", shop.getItem().getAmount(), Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of( + sender, + "command.trade-item-now", + shop.getItem().getAmount(), + Util.getItemStackName(shop.getItem())) + .send(); return; } plugin.text().of(sender, "not-looking-at-shop").send(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Lookup.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Lookup.java index acf8c2a43..ae6107daa 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Lookup.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Lookup.java @@ -4,15 +4,14 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.util.ItemMarker; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SubCommand_Lookup implements CommandHandler { private final QuickShop plugin; @@ -25,7 +24,9 @@ public class SubCommand_Lookup implements CommandHandler { public void onCommand(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { ItemStack item = sender.getInventory().getItemInMainHand(); if (parser.getArgs().isEmpty()) { - plugin.text().of(sender, "command-incorrect", "/quickshop lookup ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop lookup ") + .send(); return; } @@ -43,7 +44,9 @@ public class SubCommand_Lookup implements CommandHandler { } return; } - plugin.text().of(sender, "command-incorrect", "/quickshop lookup ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop lookup ") + .send(); return; } String itemRefName = parser.getArgs().get(1); @@ -56,28 +59,47 @@ public class SubCommand_Lookup implements CommandHandler { ItemMarker.OperationResult result = plugin.getItemMarker().save(itemRefName, item); switch (result) { - case SUCCESS -> plugin.text().of(sender, "lookup-item-created", itemRefName).send(); - case REGEXP_FAILURE -> - plugin.text().of(sender, "lookup-item-name-regex", ItemMarker.getNameRegExp(), parser.getArgs().get(1)).send(); - case NAME_CONFLICT -> plugin.text().of(sender, "lookup-item-exists", itemRefName).send(); - default -> plugin.text().of(sender, "internal-error", itemRefName).send(); + case SUCCESS -> plugin.text() + .of(sender, "lookup-item-created", itemRefName) + .send(); + case REGEXP_FAILURE -> plugin.text() + .of( + sender, + "lookup-item-name-regex", + ItemMarker.getNameRegExp(), + parser.getArgs().get(1)) + .send(); + case NAME_CONFLICT -> plugin.text() + .of(sender, "lookup-item-exists", itemRefName) + .send(); + default -> plugin.text() + .of(sender, "internal-error", itemRefName) + .send(); } } case "remove" -> { ItemMarker.OperationResult result = plugin.getItemMarker().remove(itemRefName); switch (result) { - case SUCCESS -> plugin.text().of(sender, "lookup-item-removed", itemRefName).send(); - case NOT_EXISTS -> plugin.text().of(sender, "lookup-item-not-found", itemRefName).send(); - default -> plugin.text().of(sender, "internal-error", itemRefName).send(); + case SUCCESS -> plugin.text() + .of(sender, "lookup-item-removed", itemRefName) + .send(); + case NOT_EXISTS -> plugin.text() + .of(sender, "lookup-item-not-found", itemRefName) + .send(); + default -> plugin.text() + .of(sender, "internal-error", itemRefName) + .send(); } } - default -> - plugin.text().of(sender, "command-incorrect", "/quickshop lookup ").send(); + default -> plugin.text() + .of(sender, "command-incorrect", "/quickshop lookup ") + .send(); } } @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().size() == 1) { return Arrays.asList("create", "remove", "test"); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Name.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Name.java index 30a4be989..5201e14c1 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Name.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Name.java @@ -9,14 +9,13 @@ import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.economy.SimpleEconomyTransaction; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Collections; +import java.util.List; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; - public class SubCommand_Name implements CommandHandler { private final QuickShop plugin; @@ -70,7 +69,13 @@ public class SubCommand_Name implements CommandHandler { .amount(fee) .build(); if (!transaction.checkBalance()) { - plugin.text().of(sender, "you-cant-afford-shop-naming", plugin.getShopManager().format(fee, shop.getLocation().getWorld(), plugin.getCurrency())).send(); + plugin.text() + .of( + sender, + "you-cant-afford-shop-naming", + plugin.getShopManager() + .format(fee, shop.getLocation().getWorld(), plugin.getCurrency())) + .send(); return; } } @@ -83,7 +88,9 @@ public class SubCommand_Name implements CommandHandler { shopName = namingEvent.getName(); if (transaction != null && !transaction.failSafeCommit()) { - plugin.text().of(sender, "economy-transaction-failed", transaction.getLastError()).send(); + plugin.text() + .of(sender, "economy-transaction-failed", transaction.getLastError()) + .send(); plugin.logger().error("EconomyTransaction Failed, last error: {}", transaction.getLastError()); return; } @@ -94,8 +101,11 @@ public class SubCommand_Name implements CommandHandler { @NotNull @Override - public List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - return parser.getArgs().size() == 1 ? Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.name").forLocale())) : Collections.emptyList(); + public List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + return parser.getArgs().size() == 1 + ? Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of(sender, "tabcomplete.name").forLocale())) + : Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Paste.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Paste.java index f9514ef33..5d959cbae 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Paste.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Paste.java @@ -9,12 +9,6 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.metric.MetricDataType; import com.ghostchu.quickshop.util.paste.Paste; import com.ghostchu.quickshop.util.paste.PasteGenerator; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.event.ClickEvent; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -23,14 +17,15 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import java.util.UUID; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; public class SubCommand_Paste implements CommandHandler { - private static final List warningPluginList = List.of( - "ConsoleSpamFix", - "ConsoleFilter", - "LogFilter" - ); + private static final List warningPluginList = List.of("ConsoleSpamFix", "ConsoleFilter", "LogFilter"); private final QuickShop plugin; public SubCommand_Paste(QuickShop plugin) { @@ -73,7 +68,9 @@ public class SubCommand_Paste implements CommandHandler { fwriter.write(string); fwriter.flush(); } - plugin.text().of(sender, "paste-created-local", file.getAbsolutePath()).send(); + plugin.text() + .of(sender, "paste-created-local", file.getAbsolutePath()) + .send(); return true; } catch (IOException e) { if (plugin.getSentryErrorReporter() != null) { @@ -86,21 +83,32 @@ public class SubCommand_Paste implements CommandHandler { } private boolean pasteToPastebin(@NotNull CommandSender sender) { - plugin.getPrivacyController().privacyReview(MetricDataType.DIAGNOSTIC, "Debug Paste", "User request to create a online debug paste", () -> { - final String string = Paste.paste(new PasteGenerator(sender).render()); - if (string != null) { - String url = "https://ghost-chu.github.io/quickshop-hikari-paste-viewer/?remote=" + URLEncoder.encode(string, StandardCharsets.UTF_8); - Component component = plugin.text().of(sender, "paste-created", url).forLocale(); - component = component.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, url)); - MsgUtil.sendDirectMessage(sender, component); - if ("zh_cn".equalsIgnoreCase(MsgUtil.getDefaultGameLanguageCode()) || Locale.getDefault().equals(Locale.CHINA)) { - plugin.text().of(sender, "paste-451").send(); - } - return; - } - }, () -> plugin.text().of(sender, "internet-paste-forbidden-privacy-reason").send()); + plugin.getPrivacyController() + .privacyReview( + MetricDataType.DIAGNOSTIC, + "Debug Paste", + "User request to create a online debug paste", + () -> { + final String string = Paste.paste(new PasteGenerator(sender).render()); + if (string != null) { + String url = "https://ghost-chu.github.io/quickshop-hikari-paste-viewer/?remote=" + + URLEncoder.encode(string, StandardCharsets.UTF_8); + Component component = plugin.text() + .of(sender, "paste-created", url) + .forLocale(); + component = + component.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, url)); + MsgUtil.sendDirectMessage(sender, component); + if ("zh_cn".equalsIgnoreCase(MsgUtil.getDefaultGameLanguageCode()) + || Locale.getDefault().equals(Locale.CHINA)) { + plugin.text().of(sender, "paste-451").send(); + } + return; + } + }, + () -> plugin.text() + .of(sender, "internet-paste-forbidden-privacy-reason") + .send()); return true; } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Permission.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Permission.java index 30d673ee5..96c6ead38 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Permission.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Permission.java @@ -7,13 +7,12 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermissionGroup; import com.ghostchu.quickshop.util.ChatSheetPrinter; import com.ghostchu.quickshop.util.Util; +import java.util.*; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - public class SubCommand_Permission implements CommandHandler { private final QuickShop plugin; @@ -68,7 +67,9 @@ public class SubCommand_Permission implements CommandHandler { switch (type) { case "user" -> { if (target == null) { - plugin.text().of(sender, "bad-command-usage-detailed", "set,list,unset").send(); + plugin.text() + .of(sender, "bad-command-usage-detailed", "set,list,unset") + .send(); return; } plugin.getPlayerFinder().name2UuidFuture(targetFinal).whenComplete((uuid, throwable) -> { @@ -83,19 +84,27 @@ public class SubCommand_Permission implements CommandHandler { switch (operationFinal) { case "set" -> { if (groupFinal == null) { - plugin.text().of(sender, "command-incorrect", "/quickshop permission user set ").send(); + plugin.text() + .of(sender, "command-incorrect", "/quickshop permission user set ") + .send(); return; } if (!plugin.getShopPermissionManager().hasGroup(groupFinal)) { - plugin.text().of(sender, "invalid-group", targetFinal).send(); + plugin.text() + .of(sender, "invalid-group", targetFinal) + .send(); return; } shop.setPlayerGroup(uuid, groupFinal); - plugin.text().of(sender, "successfully-set-player-group", targetFinal, groupFinal).send(); + plugin.text() + .of(sender, "successfully-set-player-group", targetFinal, groupFinal) + .send(); } case "unset" -> { shop.setPlayerGroup(uuid, BuiltInShopPermissionGroup.EVERYONE); - plugin.text().of(sender, "successfully-unset-player-group", targetFinal).send(); + plugin.text() + .of(sender, "successfully-unset-player-group", targetFinal) + .send(); } } }); @@ -105,24 +114,28 @@ public class SubCommand_Permission implements CommandHandler { switch (operation) { case "list" -> { sheet.printHeader(); - sheet.printLine(plugin.text().of(sender, "permission.header").forLocale()); + sheet.printLine( + plugin.text().of(sender, "permission.header").forLocale()); Util.asyncThreadRun(() -> { - for (Map.Entry map : shop.getPermissionAudiences().entrySet()) { + for (Map.Entry map : + shop.getPermissionAudiences().entrySet()) { String name = plugin.getPlayerFinder().uuid2Name(map.getKey()); if (name == null) { name = "unknown"; } - sheet.printLine(plugin.text().of(sender, "permission.table", name, map.getValue()).forLocale()); + sheet.printLine(plugin.text() + .of(sender, "permission.table", name, map.getValue()) + .forLocale()); } sheet.printFooter(); }); } } } - default -> plugin.text().of(sender, "bad-command-usage-detailed", "list").send(); + default -> plugin.text() + .of(sender, "bad-command-usage-detailed", "list") + .send(); } - - } /** @@ -134,7 +147,8 @@ public class SubCommand_Permission implements CommandHandler { * @return Candidate list */ @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().size() == 1) { return List.of("user", "group"); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Price.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Price.java index 6ac8d9bc2..6b2809e90 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Price.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Price.java @@ -11,15 +11,14 @@ import com.ghostchu.quickshop.economy.SimpleEconomyTransaction; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Collections; +import java.util.List; +import java.util.Objects; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - public class SubCommand_Price implements CommandHandler { private final QuickShop plugin; @@ -81,17 +80,36 @@ public class SubCommand_Price implements CommandHandler { switch (checkResult.getStatus()) { case PRICE_RESTRICTED -> { - plugin.text().of(sender, "restricted-prices", Util.getItemStackName(shop.getItem()), - Component.text(checkResult.getMin()), - Component.text(checkResult.getMax())).send(); + plugin.text() + .of( + sender, + "restricted-prices", + Util.getItemStackName(shop.getItem()), + Component.text(checkResult.getMin()), + Component.text(checkResult.getMax())) + .send(); return; } case REACHED_PRICE_MIN_LIMIT -> { - plugin.text().of(sender, "price-too-cheap", (format) ? MsgUtil.decimalFormat(checkResult.getMin()) : Double.toString(checkResult.getMin())).send(); + plugin.text() + .of( + sender, + "price-too-cheap", + (format) + ? MsgUtil.decimalFormat(checkResult.getMin()) + : Double.toString(checkResult.getMin())) + .send(); return; } case REACHED_PRICE_MAX_LIMIT -> { - plugin.text().of(sender, "price-too-high", (format) ? MsgUtil.decimalFormat(checkResult.getMax()) : Double.toString(checkResult.getMax())).send(); + plugin.text() + .of( + sender, + "price-too-high", + (format) + ? MsgUtil.decimalFormat(checkResult.getMax()) + : Double.toString(checkResult.getMax())) + .send(); return; } case NOT_A_WHOLE_NUMBER -> { @@ -109,28 +127,42 @@ public class SubCommand_Price implements CommandHandler { .currency(plugin.getCurrency()) .build(); if (!transaction.checkBalance()) { - plugin.text().of(sender, "you-cant-afford-to-change-price", plugin.getShopManager().format(fee, shop)).send(); + plugin.text() + .of( + sender, + "you-cant-afford-to-change-price", + plugin.getShopManager().format(fee, shop)) + .send(); return; } if (!transaction.failSafeCommit()) { - plugin.text().of(sender, "economy-transaction-failed", transaction.getLastError()).send(); + plugin.text() + .of(sender, "economy-transaction-failed", transaction.getLastError()) + .send(); return; } } - plugin.text().of(sender, - "fee-charged-for-price-change", plugin.getShopManager().format(fee, shop)).send(); + plugin.text() + .of( + sender, + "fee-charged-for-price-change", + plugin.getShopManager().format(fee, shop)) + .send(); // Update the shop shop.setPrice(price); shop.setSignText(plugin.text().findRelativeLanguages(sender)); - plugin.text().of(sender, - "price-is-now", plugin.getShopManager().format(shop.getPrice(), shop)).send(); + plugin.text() + .of(sender, "price-is-now", plugin.getShopManager().format(shop.getPrice(), shop)) + .send(); } @NotNull @Override public List onTabComplete( @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - return parser.getArgs().size() == 1 ? Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.price").forLocale())) : Collections.emptyList(); + return parser.getArgs().size() == 1 + ? Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of(sender, "tabcomplete.price").forLocale())) + : Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Purge.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Purge.java index 973c02814..fc53e6f57 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Purge.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Purge.java @@ -19,6 +19,4 @@ public class SubCommand_Purge implements CommandHandler { plugin.getShopPurger().purge(); plugin.text().of(sender, "shop-purged-start").send(); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ROOT.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ROOT.java index 25c0abd72..dcd5e293e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ROOT.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ROOT.java @@ -6,12 +6,11 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; public class SubCommand_ROOT implements CommandHandler { @@ -28,10 +27,12 @@ public class SubCommand_ROOT implements CommandHandler { @NotNull @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public List onTabComplete( + @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { final List candidate = new ArrayList<>(); for (CommandContainer container : plugin.getCommandManager().getRegisteredCommands()) { - if (!parser.getArgs().isEmpty() && !container.getPrefix().startsWith(parser.getArgs().get(0))) { + if (!parser.getArgs().isEmpty() + && !container.getPrefix().startsWith(parser.getArgs().get(0))) { continue; } @@ -43,25 +44,26 @@ public class SubCommand_ROOT implements CommandHandler { && !requirePermission.isEmpty() && !plugin.perm().hasPermission(sender, requirePermission)) { if (Util.isDevMode()) { - Log.debug( - "Player " - + sender.getName() - + " is trying to tab-complete the command: " - + commandLabel - + ", but doesn't have the permission: " - + requirePermission); + Log.debug("Player " + + sender.getName() + + " is trying to tab-complete the command: " + + commandLabel + + ", but doesn't have the permission: " + + requirePermission); } return Collections.emptyList(); } } } - if (!container.isHidden() && !(container.isDisabled() || (container.getDisabledSupplier() != null && container.getDisabledSupplier().get()))) { + if (!container.isHidden() + && !(container.isDisabled() + || (container.getDisabledSupplier() != null + && container.getDisabledSupplier().get()))) { candidate.add(container.getPrefix()); } } return candidate; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Recovery.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Recovery.java index 7cbb2c851..9f61f2d02 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Recovery.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Recovery.java @@ -7,11 +7,10 @@ import com.ghostchu.quickshop.database.DatabaseIOUtil; import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; -import org.bukkit.command.ConsoleCommandSender; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.sql.SQLException; +import org.bukkit.command.ConsoleCommandSender; +import org.jetbrains.annotations.NotNull; public class SubCommand_Recovery implements CommandHandler { @@ -22,14 +21,16 @@ public class SubCommand_Recovery implements CommandHandler } @Override - public void onCommand(@NotNull ConsoleCommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public void onCommand( + @NotNull ConsoleCommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { File file = new File(plugin.getDataFolder(), "recovery.zip"); if (!file.exists()) { plugin.text().of(sender, "importing-not-found", "recovery.zip").send(); return; } - if (parser.getArgs().isEmpty() || !"confirm".equalsIgnoreCase(parser.getArgs().get(0))) { + if (parser.getArgs().isEmpty() + || !"confirm".equalsIgnoreCase(parser.getArgs().get(0))) { plugin.text().of(sender, "importing-early-warning").send(); return; } @@ -38,7 +39,8 @@ public class SubCommand_Recovery implements CommandHandler Log.debug("Initializing database recovery..."); DatabaseIOUtil databaseIOUtil = new DatabaseIOUtil((SimpleDatabaseHelperV2) plugin.getDatabaseHelper()); Log.debug("Unloading all shops..."); - plugin.getShopManager().getAllShops().forEach(s -> plugin.getShopManager().unloadShop(s)); + plugin.getShopManager().getAllShops().forEach(s -> plugin.getShopManager() + .unloadShop(s)); Log.debug("Clean up in-memory data..."); plugin.getShopManager().clear(); Log.debug("Launching async thread for importing tables..."); @@ -49,7 +51,9 @@ public class SubCommand_Recovery implements CommandHandler Log.debug("Re-loading shop from database..."); Util.mainThreadRun(() -> { plugin.getShopLoader().loadShops(); - plugin.text().of(sender, "imported-database", "recovery.zip").send(); + plugin.text() + .of(sender, "imported-database", "recovery.zip") + .send(); }); } catch (SQLException | ClassNotFoundException e) { plugin.text().of(sender, "importing-failed", e.getMessage()).send(); @@ -57,5 +61,4 @@ public class SubCommand_Recovery implements CommandHandler } }); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Refill.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Refill.java index 45e506027..176b9f55b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Refill.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Refill.java @@ -4,14 +4,13 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; +import java.util.Collections; +import java.util.List; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.apache.commons.lang3.StringUtils; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; - public class SubCommand_Refill implements CommandHandler { private final QuickShop plugin; @@ -38,7 +37,9 @@ public class SubCommand_Refill implements CommandHandler { if (parser.getArgs().get(0).equals(plugin.getConfig().getString("shop.word-for-trade-all-items"))) { add = shop.getRemainingSpace(); } else { - plugin.text().of(sender, "not-a-number", parser.getArgs().get(0)).send(); + plugin.text() + .of(sender, "not-a-number", parser.getArgs().get(0)) + .send(); return; } } @@ -49,8 +50,12 @@ public class SubCommand_Refill implements CommandHandler { @NotNull @Override - public List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - return parser.getArgs().size() == 1 ? Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.amount").forLocale())) : Collections.emptyList(); + public List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + return parser.getArgs().size() == 1 + ? Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize( + plugin.text().of(sender, "tabcomplete.amount").forLocale())) + : Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reload.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reload.java index 7034769bb..bff2ac254 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reload.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reload.java @@ -5,12 +5,11 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadableContainer; +import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; -import java.util.Map; - public class SubCommand_Reload implements CommandHandler { private final QuickShop plugin; @@ -23,7 +22,8 @@ public class SubCommand_Reload implements CommandHandler { public void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { plugin.text().of(sender, "command.reloading").send(); plugin.getJavaPlugin().reloadConfig(); - Map container = plugin.getReloadManager().reload(); + Map container = + plugin.getReloadManager().reload(); sender.sendMessage(ChatColor.GOLD + "Reloaded " + container.size() + " modules."); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Remove.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Remove.java index 34a696193..dd8c4aabb 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Remove.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Remove.java @@ -28,10 +28,10 @@ public class SubCommand_Remove implements CommandHandler { if (shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.DELETE) || plugin.perm().hasPermission(sender, "quickshop.other.destroy")) { plugin.getShopManager().deleteShop(shop); - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(sender), "/quickshop remove command", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(sender), "/quickshop remove command", shop.saveToInfoStorage())); } else { plugin.text().of(sender, "no-permission").send(); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveAll.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveAll.java index 63bdc268c..f90802691 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveAll.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveAll.java @@ -1,5 +1,7 @@ package com.ghostchu.quickshop.command.subcommand; +import static com.ghostchu.quickshop.util.Util.getPlayerList; + import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; @@ -8,16 +10,13 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logging.container.ShopRemoveLog; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; - -import static com.ghostchu.quickshop.util.Util.getPlayerList; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SubCommand_RemoveAll implements CommandHandler { @@ -31,13 +30,15 @@ public class SubCommand_RemoveAll implements CommandHandler { public void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { CompletableFuture qUserFuture; if (parser.getArgs().size() == 1) { - qUserFuture = QUserImpl.createAsync(plugin.getPlayerFinder(), parser.getArgs().get(0)); + qUserFuture = QUserImpl.createAsync( + plugin.getPlayerFinder(), parser.getArgs().get(0)); } else { qUserFuture = QUserImpl.createAsync(plugin.getPlayerFinder(), sender); } qUserFuture .thenAccept(qUser -> { - QUser executor = QUserImpl.createAsync(plugin.getPlayerFinder(), sender).join(); + QUser executor = QUserImpl.createAsync(plugin.getPlayerFinder(), sender) + .join(); if (executor.equals(qUser)) { if (!plugin.perm().hasPermission(sender, "quickshop.removeall.self")) { plugin.text().of(sender, "no-permission").send(); @@ -58,22 +59,26 @@ public class SubCommand_RemoveAll implements CommandHandler { } Util.mainThreadRun(() -> { pendingRemoval.forEach(shop -> { - plugin.logEvent(new ShopRemoveLog(qUser, "Deleting shop " + shop + " as requested by the /quickshop removeall command.", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + qUser, + "Deleting shop " + shop + " as requested by the /quickshop removeall command.", + shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); }); - plugin.text().of(sender, "command.some-shops-removed", pendingRemoval.size()).send(); + plugin.text() + .of(sender, "command.some-shops-removed", pendingRemoval.size()) + .send(); }); - }) .exceptionally(err -> { plugin.text().of(sender, "internal-error", err.getMessage()).send(); return null; }); - } @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return parser.getArgs().size() <= 1 ? getPlayerList() : Collections.emptyList(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveWorld.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveWorld.java index fd4305623..aefcb0b7f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveWorld.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_RemoveWorld.java @@ -5,13 +5,12 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Objects; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; -import java.util.Objects; - public class SubCommand_RemoveWorld implements CommandHandler { private final QuickShop plugin; @@ -28,7 +27,9 @@ public class SubCommand_RemoveWorld implements CommandHandler { } World world = Bukkit.getWorld(parser.getArgs().get(0)); if (world == null) { - plugin.text().of(sender, "world-not-exists", parser.getArgs().get(0)).send(); + plugin.text() + .of(sender, "world-not-exists", parser.getArgs().get(0)) + .send(); return; } int shopsDeleted = 0; @@ -39,7 +40,8 @@ public class SubCommand_RemoveWorld implements CommandHandler { } } Log.debug("Successfully deleted all shops in world " + parser.getArgs().get(0) + "!"); - plugin.text().of(sender, "shops-removed-in-world", shopsDeleted, world.getName()).send(); + plugin.text() + .of(sender, "shops-removed-in-world", shopsDeleted, world.getName()) + .send(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reset.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reset.java index 02015e19e..3ff77e0c0 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reset.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Reset.java @@ -3,11 +3,10 @@ package com.ghostchu.quickshop.command.subcommand; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.util.List; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; public class SubCommand_Reset implements CommandHandler { @@ -18,7 +17,6 @@ public class SubCommand_Reset implements CommandHandler { this.plugin = plugin; } - @Override public void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().isEmpty()) { @@ -41,8 +39,8 @@ public class SubCommand_Reset implements CommandHandler { @NotNull @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public List onTabComplete( + @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return tabCompleteList; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Sell.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Sell.java index b3deec758..034d55892 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Sell.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Sell.java @@ -26,7 +26,9 @@ public class SubCommand_Sell implements CommandHandler { || plugin.perm().hasPermission(sender, "quickshop.other.control")) { shop.setShopType(ShopType.SELLING); shop.setSignText(plugin.text().findRelativeLanguages(sender)); - plugin.text().of(sender, "command.now-selling", Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(sender, "command.now-selling", Util.getItemStackName(shop.getItem())) + .send(); } else { plugin.text().of(sender, "not-managed-shop").send(); } @@ -34,5 +36,4 @@ public class SubCommand_Sell implements CommandHandler { plugin.text().of(sender, "not-looking-at-shop").send(); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SetOwner.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SetOwner.java index 5799bd31b..bfa2cf7ff 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SetOwner.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SetOwner.java @@ -1,5 +1,7 @@ package com.ghostchu.quickshop.command.subcommand; +import static com.ghostchu.quickshop.util.Util.getPlayerList; + import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; @@ -8,13 +10,10 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.Util; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - import java.util.Collections; import java.util.List; - -import static com.ghostchu.quickshop.util.Util.getPlayerList; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; public class SubCommand_SetOwner implements CommandHandler { @@ -48,20 +47,27 @@ public class SubCommand_SetOwner implements CommandHandler { plugin.text().of(sender, "unknown-player").send(); return; } - ShopOwnershipTransferEvent event = new ShopOwnershipTransferEvent(shop, shop.getOwner(), newShopOwner); + ShopOwnershipTransferEvent event = + new ShopOwnershipTransferEvent(shop, shop.getOwner(), newShopOwner); if (event.callCancellableEvent()) { return; } Util.mainThreadRun(() -> { shop.setOwner(newShopOwner); - plugin.text().of(sender, "command.new-owner", parser.getArgs().get(0)).send(); + plugin.text() + .of( + sender, + "command.new-owner", + parser.getArgs().get(0)) + .send(); }); }) .exceptionally(throwable -> { - plugin.text().of(sender, "internal-error", throwable.getMessage()).send(); + plugin.text() + .of(sender, "internal-error", throwable.getMessage()) + .send(); return null; }); - } @NotNull @@ -70,5 +76,4 @@ public class SubCommand_SetOwner implements CommandHandler { @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return parser.getArgs().size() <= 1 ? getPlayerList() : Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Size.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Size.java index d460b6697..eb8c22f2f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Size.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Size.java @@ -9,6 +9,8 @@ import com.ghostchu.quickshop.api.shop.PriceLimiterStatus; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.List; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.entity.Player; @@ -16,9 +18,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; - public class SubCommand_Size implements CommandHandler { private final QuickShop plugin; @@ -44,37 +43,57 @@ public class SubCommand_Size implements CommandHandler { if (shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_STACK_AMOUNT) || plugin.perm().hasPermission(sender, "quickshop.other.amount")) { if (amount <= 0) { - plugin.text().of(sender, "command.invalid-bulk-amount", amount).send(); + plugin.text() + .of(sender, "command.invalid-bulk-amount", amount) + .send(); return; } - if (amount > Util.getItemMaxStackSize(shop.getItem().getType()) && !plugin.getConfig().getBoolean("shop.disable-max-size-check-for-size-command", false)) { - plugin.text().of(sender, "command.invalid-bulk-amount", amount).send(); + if (amount > Util.getItemMaxStackSize(shop.getItem().getType()) + && !plugin.getConfig().getBoolean("shop.disable-max-size-check-for-size-command", false)) { + plugin.text() + .of(sender, "command.invalid-bulk-amount", amount) + .send(); return; } ItemStack pendingItemStack = shop.getItem().clone(); pendingItemStack.setAmount(amount); PriceLimiter limiter = plugin.getShopManager().getPriceLimiter(); - PriceLimiterCheckResult checkResult = limiter.check(sender, pendingItemStack, shop.getCurrency(), shop.getPrice()); + PriceLimiterCheckResult checkResult = + limiter.check(sender, pendingItemStack, shop.getCurrency(), shop.getPrice()); if (checkResult.getStatus() != PriceLimiterStatus.PASS) { - plugin.text().of(sender, "restricted-prices", Util.getItemStackName(shop.getItem()), - Component.text(checkResult.getMin()), - Component.text(checkResult.getMax())).send(); + plugin.text() + .of( + sender, + "restricted-prices", + Util.getItemStackName(shop.getItem()), + Component.text(checkResult.getMin()), + Component.text(checkResult.getMax())) + .send(); return; } shop.setItem(pendingItemStack); - plugin.text().of(sender, "command.bulk-size-now", shop.getItem().getAmount(), Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of( + sender, + "command.bulk-size-now", + shop.getItem().getAmount(), + Util.getItemStackName(shop.getItem())) + .send(); } else { plugin.text().of(sender, "not-managed-shop").send(); } } else { plugin.text().of(sender, "not-looking-at-shop").send(); } - - } @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - return parser.getArgs().size() == 1 ? Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.amount").forLocale())) : Collections.emptyList(); + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + return parser.getArgs().size() == 1 + ? Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize( + plugin.text().of(sender, "tabcomplete.amount").forLocale())) + : Collections.emptyList(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Staff.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Staff.java index 250f16788..b91938509 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Staff.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Staff.java @@ -9,6 +9,10 @@ import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermissionGroup; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.UUID; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.block.Block; @@ -16,11 +20,6 @@ import org.bukkit.entity.Player; import org.bukkit.util.BlockIterator; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - public class SubCommand_Staff implements CommandHandler { private final QuickShop plugin; @@ -38,28 +37,42 @@ public class SubCommand_Staff implements CommandHandler { final Shop shop = plugin.getShopManager().getShop(b.getLocation()); if (shop == null || (!shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.MANAGEMENT_PERMISSION) - && !plugin.perm().hasPermission(sender, "quickshop.other.staff"))) { + && !plugin.perm().hasPermission(sender, "quickshop.other.staff"))) { continue; } switch (parser.getArgs().size()) { case 1 -> { switch (parser.getArgs().get(0)) { case "clear" -> { - shop.playersCanAuthorize(BuiltInShopPermissionGroup.STAFF).forEach(staff -> shop.setPlayerGroup(staff, BuiltInShopPermissionGroup.EVERYONE)); + shop.playersCanAuthorize(BuiltInShopPermissionGroup.STAFF) + .forEach(staff -> shop.setPlayerGroup(staff, BuiltInShopPermissionGroup.EVERYONE)); plugin.text().of(sender, "shop-staff-cleared").send(); return; } case "list" -> { final List staffs = shop.playersCanAuthorize(BuiltInShopPermissionGroup.STAFF); if (staffs.isEmpty()) { - MsgUtil.sendDirectMessage(sender, plugin.text().of(sender, "tableformat.left_begin").forLocale() - .append(plugin.text().of(sender, "shop-staff-empty").forLocale())); + MsgUtil.sendDirectMessage( + sender, + plugin.text() + .of(sender, "tableformat.left_begin") + .forLocale() + .append(plugin.text() + .of(sender, "shop-staff-empty") + .forLocale())); return; } Util.asyncThreadRun(() -> { for (UUID uuid : staffs) { - MsgUtil.sendDirectMessage(sender, plugin.text().of(sender, "tableformat.left_begin").forLocale() - .append(Component.text(Optional.ofNullable(plugin.getPlayerFinder().uuid2Name(uuid)).orElse("Unknown")).color(NamedTextColor.GRAY))); + MsgUtil.sendDirectMessage( + sender, + plugin.text() + .of(sender, "tableformat.left_begin") + .forLocale() + .append(Component.text(Optional.ofNullable(plugin.getPlayerFinder() + .uuid2Name(uuid)) + .orElse("Unknown")) + .color(NamedTextColor.GRAY))); } }); @@ -73,19 +86,26 @@ public class SubCommand_Staff implements CommandHandler { } case 2 -> { String name = parser.getArgs().get(1); - plugin.getPlayerFinder().name2UuidFuture(parser.getArgs().get(1)) + plugin.getPlayerFinder() + .name2UuidFuture(parser.getArgs().get(1)) .thenAccept(uuid -> { BuiltInShopPermissionGroup permissionGroup = null; switch (parser.getArgs().get(0)) { case "add" -> { permissionGroup = BuiltInShopPermissionGroup.STAFF; - plugin.text().of(sender, "shop-staff-added", name).send(); + plugin.text() + .of(sender, "shop-staff-added", name) + .send(); } case "del" -> { permissionGroup = BuiltInShopPermissionGroup.EVERYONE; - plugin.text().of(sender, "shop-staff-deleted", name).send(); + plugin.text() + .of(sender, "shop-staff-deleted", name) + .send(); } - default -> plugin.text().of(sender, "command.wrong-args").send(); + default -> plugin.text() + .of(sender, "command.wrong-args") + .send(); } if (permissionGroup != null) { BuiltInShopPermissionGroup finalPermissionGroup = permissionGroup; @@ -94,7 +114,9 @@ public class SubCommand_Staff implements CommandHandler { }) .exceptionally(throwable -> { Log.debug("Failed set the user group: " + throwable.getMessage()); - plugin.text().of(sender, "internal-error", throwable.getMessage()).send(); + plugin.text() + .of(sender, "internal-error", throwable.getMessage()) + .send(); return null; }); return; @@ -105,7 +127,7 @@ public class SubCommand_Staff implements CommandHandler { } } } - //no match shop + // no match shop plugin.text().of(sender, "not-looking-at-shop").send(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SuperCreate.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SuperCreate.java index c556a87fa..ab0144d4c 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SuperCreate.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_SuperCreate.java @@ -6,6 +6,8 @@ import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.ShopAction; import com.ghostchu.quickshop.shop.SimpleInfo; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.List; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.Material; import org.bukkit.block.Block; @@ -14,9 +16,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.util.BlockIterator; import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.List; - public class SubCommand_SuperCreate implements CommandHandler { private final QuickShop plugin; @@ -43,10 +42,23 @@ public class SubCommand_SuperCreate implements CommandHandler { } // Send creation menu. - final SimpleInfo info = new SimpleInfo(b.getLocation(), ShopAction.CREATE_SELL, sender.getInventory().getItemInMainHand(), b.getRelative(sender.getFacing().getOppositeFace()), true); + final SimpleInfo info = new SimpleInfo( + b.getLocation(), + ShopAction.CREATE_SELL, + sender.getInventory().getItemInMainHand(), + b.getRelative(sender.getFacing().getOppositeFace()), + true); plugin.getShopManager().getInteractiveManager().put(sender.getUniqueId(), info); - plugin.text().of(sender, "how-much-to-trade-for", Util.getItemStackName(info.getItem()), plugin.isAllowStack() && plugin.perm().hasPermission(sender, "quickshop.create.stacks") ? item.getAmount() : 1).send(); + plugin.text() + .of( + sender, + "how-much-to-trade-for", + Util.getItemStackName(info.getItem()), + plugin.isAllowStack() && plugin.perm().hasPermission(sender, "quickshop.create.stacks") + ? item.getAmount() + : 1) + .send(); return; } plugin.text().of(sender, "not-looking-at-shop").send(); @@ -56,7 +68,10 @@ public class SubCommand_SuperCreate implements CommandHandler { @Override public List onTabComplete( @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { - return parser.getArgs().size() == 1 ? Collections.singletonList(LegacyComponentSerializer.legacySection().serialize(plugin.text().of(sender, "tabcomplete.amount").forLocale())) : Collections.emptyList(); + return parser.getArgs().size() == 1 + ? Collections.singletonList(LegacyComponentSerializer.legacySection() + .serialize( + plugin.text().of(sender, "tabcomplete.amount").forLocale())) + : Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_TaxAccount.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_TaxAccount.java index 3fc9d16b2..93819b4c6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_TaxAccount.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_TaxAccount.java @@ -5,11 +5,10 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.obj.QUserImpl; +import java.util.List; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class SubCommand_TaxAccount implements CommandHandler { private final QuickShop plugin; @@ -30,11 +29,19 @@ public class SubCommand_TaxAccount implements CommandHandler { QUserImpl.createAsync(plugin.getPlayerFinder(), parser.getArgs().get(0)) .thenAccept(qUser -> { shop.setTaxAccount(qUser); - plugin.text().of(sender, "taxaccount-set", parser.getArgs().get(0)).send(); + plugin.text() + .of(sender, "taxaccount-set", parser.getArgs().get(0)) + .send(); }) .exceptionally(throwable -> { - plugin.text().of(sender, "internal-error", throwable.getMessage()).send(); - plugin.logger().warn("Failed to get uuid of player " + parser.getArgs().get(0), throwable); + plugin.text() + .of(sender, "internal-error", throwable.getMessage()) + .send(); + plugin.logger() + .warn( + "Failed to get uuid of player " + + parser.getArgs().get(0), + throwable); return null; }); } else { @@ -48,5 +55,4 @@ public class SubCommand_TaxAccount implements CommandHandler { @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return null; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ToggleDisplay.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ToggleDisplay.java index 3549c082e..cd4d3d22d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ToggleDisplay.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_ToggleDisplay.java @@ -5,11 +5,10 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - import java.util.Collections; import java.util.List; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; public class SubCommand_ToggleDisplay implements CommandHandler { @@ -46,5 +45,4 @@ public class SubCommand_ToggleDisplay implements CommandHandler { @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return Collections.emptyList(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Transfer.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Transfer.java index 0f64d1852..87e14fabe 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Transfer.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Transfer.java @@ -10,30 +10,26 @@ import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.Util; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import lombok.Data; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - public class SubCommand_Transfer implements CommandHandler { private final QuickShop plugin; - private final Cache taskCache = CacheBuilder - .newBuilder() - .expireAfterWrite(60, TimeUnit.SECONDS) - .build(); + private final Cache taskCache = + CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS).build(); public SubCommand_Transfer(QuickShop plugin) { this.plugin = plugin; } - @Override public void onCommand(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { if (parser.getArgs().isEmpty()) { @@ -46,7 +42,9 @@ public class SubCommand_Transfer implements CommandHandler { PendingTransferTask task = taskCache.getIfPresent(sender.getUniqueId()); taskCache.invalidate(sender.getUniqueId()); if (task == null) { - plugin.text().of(sender, "transfer-no-pending-operation").send(); + plugin.text() + .of(sender, "transfer-no-pending-operation") + .send(); return; } task.commit(true); @@ -55,7 +53,9 @@ public class SubCommand_Transfer implements CommandHandler { PendingTransferTask task = taskCache.getIfPresent(sender.getUniqueId()); taskCache.invalidate(sender.getUniqueId()); if (task == null) { - plugin.text().of(sender, "transfer-no-pending-operation").send(); + plugin.text() + .of(sender, "transfer-no-pending-operation") + .send(); return; } task.cancel(true); @@ -83,7 +83,9 @@ public class SubCommand_Transfer implements CommandHandler { PendingTransferTask task = new PendingTransferTask(senderQUser, receiverQUser, shopsToTransfer); taskCache.put(uuid, task); plugin.text().of(sender, "transfer-sent", name).send(); - plugin.text().of(receiver, "transfer-request", sender.getName()).send(); + plugin.text() + .of(receiver, "transfer-request", sender.getName()) + .send(); plugin.text().of(receiver, "transfer-ask", 60).send(); }); } @@ -95,11 +97,21 @@ public class SubCommand_Transfer implements CommandHandler { return; } Util.asyncThreadRun(() -> { - QUser fromQUser = QUserImpl.createSync(QuickShop.getInstance().getPlayerFinder(), parser.getArgs().get(0)); - QUser targetQUser = QUserImpl.createSync(QuickShop.getInstance().getPlayerFinder(), parser.getArgs().get(1)); + QUser fromQUser = QUserImpl.createSync( + QuickShop.getInstance().getPlayerFinder(), + parser.getArgs().get(0)); + QUser targetQUser = QUserImpl.createSync( + QuickShop.getInstance().getPlayerFinder(), + parser.getArgs().get(1)); - Player fromPlayer = fromQUser.getUniqueIdIfRealPlayer().map(Bukkit::getPlayer).orElse(null); - Player targetPlayer = targetQUser.getUniqueIdIfRealPlayer().map(Bukkit::getPlayer).orElse(null); + Player fromPlayer = fromQUser + .getUniqueIdIfRealPlayer() + .map(Bukkit::getPlayer) + .orElse(null); + Player targetPlayer = targetQUser + .getUniqueIdIfRealPlayer() + .map(Bukkit::getPlayer) + .orElse(null); if (fromPlayer == null) { plugin.text().of(sender, "unknown-player", "fromPlayer").send(); @@ -113,15 +125,22 @@ public class SubCommand_Transfer implements CommandHandler { PendingTransferTask task = new PendingTransferTask(fromQUser, targetQUser, shopList); Util.mainThreadRun(() -> { task.commit(false); - plugin.text().of(sender, "command.transfer-success-other", shopList.size(), parser.getArgs().get(0), parser.getArgs().get(1)).send(); + plugin.text() + .of( + sender, + "command.transfer-success-other", + shopList.size(), + parser.getArgs().get(0), + parser.getArgs().get(1)) + .send(); }); }); - } } @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { List list = Util.getPlayerList(); list.add("accept"); list.add("deny"); @@ -142,8 +161,14 @@ public class SubCommand_Transfer implements CommandHandler { public void cancel(boolean sendMessage) { if (sendMessage) { - QuickShop.getInstance().text().of(from, "transfer-rejected-fromside", to).send(); - QuickShop.getInstance().text().of(to, "transfer-rejected-toside", from).send(); + QuickShop.getInstance() + .text() + .of(from, "transfer-rejected-fromside", to) + .send(); + QuickShop.getInstance() + .text() + .of(to, "transfer-rejected-toside", from) + .send(); } } @@ -156,8 +181,14 @@ public class SubCommand_Transfer implements CommandHandler { shop.setOwner(to); } if (sendMessage) { - QuickShop.getInstance().text().of(from, "transfer-accepted-fromside", to).send(); - QuickShop.getInstance().text().of(to, "transfer-accepted-toside", from).send(); + QuickShop.getInstance() + .text() + .of(from, "transfer-accepted-fromside", to) + .send(); + QuickShop.getInstance() + .text() + .of(to, "transfer-accepted-toside", from) + .send(); } } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Unlimited.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Unlimited.java index 4c053af42..5d5d32c1b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Unlimited.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/SubCommand_Unlimited.java @@ -40,5 +40,4 @@ public class SubCommand_Unlimited implements CommandHandler { plugin.text().of(sender, "unlimited-shop-owner-keeped").send(); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBase.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBase.java index 378c25c54..ccc94d651 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBase.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBase.java @@ -5,13 +5,12 @@ import com.ghostchu.quickshop.api.command.CommandHandler; import com.ghostchu.quickshop.api.command.CommandParser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.util.logger.Log; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.Collections; import java.util.List; import java.util.UUID; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class SubCommand_SilentBase implements CommandHandler { protected final QuickShop plugin; @@ -30,7 +29,7 @@ public abstract class SubCommand_SilentBase implements CommandHandler { try { uuid = UUID.fromString(parser.getArgs().get(0)); } catch (IllegalArgumentException e) { - //Not valid, return for doing nothing + // Not valid, return for doing nothing return; } @@ -45,7 +44,8 @@ public abstract class SubCommand_SilentBase implements CommandHandler { protected abstract void doSilentCommand(Player sender, @NotNull Shop shop, @NotNull CommandParser parser); @Override - public @Nullable List onTabComplete(@NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { + public @Nullable List onTabComplete( + @NotNull Player sender, @NotNull String commandLabel, @NotNull CommandParser parser) { return Collections.emptyList(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBuy.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBuy.java index 728d34314..81b706523 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBuy.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentBuy.java @@ -10,7 +10,6 @@ import com.ghostchu.quickshop.util.Util; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; - public class SubCommand_SilentBuy extends SubCommand_SilentBase { public SubCommand_SilentBuy(QuickShop plugin) { @@ -28,8 +27,8 @@ public class SubCommand_SilentBuy extends SubCommand_SilentBase { shop.setShopType(ShopType.BUYING); shop.setSignText(plugin.text().findRelativeLanguages(sender)); MsgUtil.sendControlPanelInfo(sender, shop); - plugin.text().of(sender, "command.now-buying", Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(sender, "command.now-buying", Util.getItemStackName(shop.getItem())) + .send(); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentEmpty.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentEmpty.java index b2eccb6a3..2e35aed39 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentEmpty.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentEmpty.java @@ -10,7 +10,6 @@ import com.ghostchu.quickshop.util.logger.Log; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; - public class SubCommand_SilentEmpty extends SubCommand_SilentBase { public SubCommand_SilentEmpty(QuickShop plugin) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentPreview.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentPreview.java index 6dbe8baf8..49880be96 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentPreview.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentPreview.java @@ -7,7 +7,6 @@ import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; - public class SubCommand_SilentPreview extends SubCommand_SilentBase { public SubCommand_SilentPreview(QuickShop plugin) { @@ -21,5 +20,4 @@ public class SubCommand_SilentPreview extends SubCommand_SilentBase { shop.openPreview(sender); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentRemove.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentRemove.java index b42001c96..59bf5db5b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentRemove.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentRemove.java @@ -23,7 +23,8 @@ public class SubCommand_SilentRemove extends SubCommand_SilentBase { return; } - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(sender), "/quickshop silentremove command", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(sender), "/quickshop silentremove command", shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentSell.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentSell.java index 6a84b7513..9ef133c19 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentSell.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentSell.java @@ -31,8 +31,8 @@ public class SubCommand_SilentSell extends SubCommand_SilentBase { shop.setShopType(ShopType.SELLING); shop.setSignText(plugin.text().findRelativeLanguages(sender)); MsgUtil.sendControlPanelInfo(sender, shop); - plugin.text().of(sender, - "command.now-selling", Util.getItemStackName(shop.getItem())).send(); - + plugin.text() + .of(sender, "command.now-selling", Util.getItemStackName(shop.getItem())) + .send(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentToggleDisplay.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentToggleDisplay.java index 6562d9fec..67269e1ea 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentToggleDisplay.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentToggleDisplay.java @@ -19,5 +19,4 @@ public class SubCommand_SilentToggleDisplay extends SubCommand_SilentBase { shop.setSignText(plugin.text().findRelativeLanguages(sender)); MsgUtil.sendControlPanelInfo(sender, shop); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentUnlimited.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentUnlimited.java index c5c31c0a5..8117c749e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentUnlimited.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/command/subcommand/silent/SubCommand_SilentUnlimited.java @@ -35,5 +35,4 @@ public class SubCommand_SilentUnlimited extends SubCommand_SilentBase { plugin.text().of(sender, "unlimited-shop-owner-keeped").send(); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DataTables.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DataTables.java index 01000eeb2..75bb10bc2 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DataTables.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DataTables.java @@ -8,15 +8,13 @@ import cc.carm.lib.easysql.api.enums.IndexType; import cc.carm.lib.easysql.api.function.SQLHandler; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public enum DataTables { - DATA("data", (table) -> { table.addAutoIncrementColumn("id", true); // SHOP DATA ID table.addColumn("owner", "VARCHAR(128) NOT NULL"); // SHOP DATA OWNER (ALL-ZERO if this is a server shop) @@ -25,7 +23,7 @@ public enum DataTables { table.addColumn("name", "TEXT"); // SHOP NAME table.addColumn("type", "INT NOT NULL DEFAULT 0"); // SHOP TYPE (see ShopType enum) - table.addColumn("currency", "VARCHAR(64)"); // CURRENCY (NULL means use the default currency) + table.addColumn("currency", "VARCHAR(64)"); // CURRENCY (NULL means use the default currency) table.addColumn("price", "DECIMAL(32,2) NOT NULL"); // SHOP ITEM PRICE // UNLIMITED STORAGE (means the shop can sell/buy unlimited amount of items) @@ -65,10 +63,10 @@ public enum DataTables { table.addColumn("shop", "INT UNSIGNED NOT NULL"); table.setIndex(IndexType.PRIMARY_KEY, null, "world", "x", "y", "z"); -// table.addForeignKey( -// "shop", "fk_qs_shop_map", SHOPS.getName(), "id", -// ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE -// ); + // table.addForeignKey( + // "shop", "fk_qs_shop_map", SHOPS.getName(), "id", + // ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE + // ); }), MESSAGES("message", (table) -> { @@ -173,14 +171,13 @@ public enum DataTables { private String prefix; private SQLManager manager; - DataTables(@NotNull String name, - @NotNull SQLHandler tableHandler) { + DataTables(@NotNull String name, @NotNull SQLHandler tableHandler) { this.name = name; this.tableHandler = tableHandler; } - public static void initializeTables(@NotNull SQLManager sqlManager, - @NotNull String tablePrefix) throws SQLException { + public static void initializeTables(@NotNull SQLManager sqlManager, @NotNull String tablePrefix) + throws SQLException { for (DataTables value : values()) { value.create(sqlManager, tablePrefix); } @@ -225,7 +222,8 @@ public enum DataTables { return this.createInsertBatch(this.manager); } - public @NotNull InsertBuilder> createInsertBatch(@NotNull SQLManager sqlManager) { + public @NotNull InsertBuilder> createInsertBatch( + @NotNull SQLManager sqlManager) { return sqlManager.createInsertBatch(this.getName()); } @@ -249,7 +247,8 @@ public enum DataTables { return this.createReplaceBatch(this.manager); } - public @NotNull ReplaceBuilder> createReplaceBatch(@NotNull SQLManager sqlManager) { + public @NotNull ReplaceBuilder> createReplaceBatch( + @NotNull SQLManager sqlManager) { return sqlManager.createReplaceBatch(this.getName()); } @@ -275,7 +274,8 @@ public enum DataTables { } boolean match = false; try { - try (Connection connection = manager.getConnection(); ResultSet rs = connection.getMetaData().getTables(null, null, "%", null)) { + try (Connection connection = manager.getConnection(); + ResultSet rs = connection.getMetaData().getTables(null, null, "%", null)) { while (rs.next()) { if (getName().equalsIgnoreCase(rs.getString("TABLE_NAME"))) { match = true; @@ -298,9 +298,7 @@ public enum DataTables { public boolean purgeTable(@NotNull SQLManager sqlManager) { try { - sqlManager.createDelete(this.getName()) - .addCondition("1=1") - .build().execute(); + sqlManager.createDelete(this.getName()).addCondition("1=1").build().execute(); return true; } catch (SQLException e) { Log.debug("Failed to purge table " + this.getName() + e); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DatabaseIOUtil.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DatabaseIOUtil.java index 75e69335f..c38327e6e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DatabaseIOUtil.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DatabaseIOUtil.java @@ -5,10 +5,6 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; -import lombok.Data; -import org.jetbrains.annotations.NotNull; -import org.relique.jdbc.csv.CsvDriver; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -18,6 +14,9 @@ import java.sql.*; import java.util.Arrays; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import lombok.Data; +import org.jetbrains.annotations.NotNull; +import org.relique.jdbc.csv.CsvDriver; @Data public class DatabaseIOUtil { @@ -95,13 +94,13 @@ public class DatabaseIOUtil { } } - public void importFromCSV(@NotNull File zipFile, @NotNull DataTables table) throws SQLException, ClassNotFoundException { + public void importFromCSV(@NotNull File zipFile, @NotNull DataTables table) + throws SQLException, ClassNotFoundException { Log.debug("Loading CsvDriver..."); Class.forName("org.relique.jdbc.csv.CsvDriver"); try (Connection conn = DriverManager.getConnection("jdbc:relique:csv:zip:" + zipFile); - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, - ResultSet.CONCUR_READ_ONLY); - ResultSet results = stmt.executeQuery("SELECT * FROM " + table.getName())) { + Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet results = stmt.executeQuery("SELECT * FROM " + table.getName())) { ResultSetMetaData metaData = results.getMetaData(); String[] columns = new String[metaData.getColumnCount()]; for (int i = 0; i < columns.length; i++) { @@ -114,11 +113,10 @@ public class DatabaseIOUtil { Log.debug("Copying column: " + columns[i]); values[i] = results.getObject(columns[i]); } - Log.debug("Inserting row: " + CommonUtil.array2String(Arrays.stream(values).map(Object::toString).toArray(String[]::new))); - table.createInsert() - .setColumnNames(columns) - .setParams(values) - .execute(); + Log.debug("Inserting row: " + + CommonUtil.array2String( + Arrays.stream(values).map(Object::toString).toArray(String[]::new))); + table.createInsert().setColumnNames(columns).setParams(values).execute(); } } } @@ -135,5 +133,4 @@ public class DatabaseIOUtil { CsvDriver.writeToCsv(set, stream, true); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/HikariUtil.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/HikariUtil.java index 789d26887..93c04e1c6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/HikariUtil.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/HikariUtil.java @@ -5,8 +5,7 @@ import com.ghostchu.quickshop.util.logger.Log; import org.bukkit.configuration.ConfigurationSection; public class HikariUtil { - private HikariUtil() { - } + private HikariUtil() {} public static cc.carm.lib.easysql.hikari.HikariConfig createHikariConfig() { cc.carm.lib.easysql.hikari.HikariConfig config = new cc.carm.lib.easysql.hikari.HikariConfig(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/MetricQuery.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/MetricQuery.java index eb8d95a7e..21192aae3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/MetricQuery.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/MetricQuery.java @@ -7,15 +7,14 @@ import com.ghostchu.quickshop.api.database.ShopOperationEnum; import com.ghostchu.quickshop.api.database.bean.DataRecord; import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.util.logger.Log; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import org.jetbrains.annotations.NotNull; - import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.ExecutionException; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import org.jetbrains.annotations.NotNull; public class MetricQuery { private final SimpleDatabaseHelperV2 databaseHelper; @@ -26,10 +25,14 @@ public class MetricQuery { this.plugin = plugin; } - public long queryServerPurchaseCount() { String sql = "SELECT COUNT(*) AS result FROM " + databaseHelper.getPrefix() + "log_purchase"; - try (SQLQuery query = databaseHelper.getManager().createQuery().withPreparedSQL(sql).setParams(Collections.emptyList()).execute()) { + try (SQLQuery query = databaseHelper + .getManager() + .createQuery() + .withPreparedSQL(sql) + .setParams(Collections.emptyList()) + .execute()) { ResultSet set = query.getResultSet(); if (set.next()) { return set.getInt("result"); @@ -44,15 +47,19 @@ public class MetricQuery { @NotNull public List queryTransactions(@NotNull Date startTime, long limit, boolean descending) { List list = new ArrayList<>(); - try (SQLQuery query = databaseHelper.getManager().createQuery() + try (SQLQuery query = databaseHelper + .getManager() + .createQuery() .inTable(databaseHelper.getPrefix() + "log_transaction") .addTimeCondition("time", startTime, null) .selectColumns() .setLimit(1000) - .orderBy("id", !descending).build().execute()) { + .orderBy("id", !descending) + .build() + .execute()) { ResultSet set = query.getResultSet(); while (set.next()) { - //"time", "shop", "data", "buyer", "type", "amount", "money", "tax" + // "time", "shop", "data", "buyer", "type", "amount", "money", "tax" ShopTransactionRecord record = new ShopTransactionRecord( set.getDate("time"), UUID.fromString(set.getString("from")), @@ -61,8 +68,7 @@ public class MetricQuery { set.getDouble("amount"), UUID.fromString(set.getString("tax_currency")), set.getDouble("tax_amount"), - set.getString("error") - ); + set.getString("error")); list.add(record); } } catch (SQLException e) { @@ -73,7 +79,8 @@ public class MetricQuery { } // Use LinkedHashMap forced because we need keep the order. - public @NotNull LinkedHashMap mapToDataRecord(@NotNull List metricRecords) throws ExecutionException, InterruptedException { + public @NotNull LinkedHashMap mapToDataRecord( + @NotNull List metricRecords) throws ExecutionException, InterruptedException { // map ShopMetricRecord#getShopId to DataRecord with blocking future LinkedHashMap dataRecords = new LinkedHashMap<>(); for (ShopMetricRecord metricRecord : metricRecords) { @@ -87,21 +94,24 @@ public class MetricQuery { dataRecords.put(metricRecord, dataRecord); } return dataRecords; - } @NotNull public List queryServerPurchaseRecords(@NotNull Date startTime, int limit, boolean descending) { List list = new ArrayList<>(); - try (SQLQuery query = databaseHelper.getManager().createQuery() + try (SQLQuery query = databaseHelper + .getManager() + .createQuery() .inTable(databaseHelper.getPrefix() + "log_purchase") .addTimeCondition("time", startTime, null) .selectColumns() .setLimit(limit) - .orderBy("id", !descending).build().execute()) { + .orderBy("id", !descending) + .build() + .execute()) { ResultSet set = query.getResultSet(); while (set.next()) { - //"time", "shop", "data", "buyer", "type", "amount", "money", "tax" + // "time", "shop", "data", "buyer", "type", "amount", "money", "tax" ShopMetricRecord record = ShopMetricRecord.builder() .time(set.getDate("time").getTime()) .shopId(set.getLong("shop")) diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/SimpleDatabaseHelperV2.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/SimpleDatabaseHelperV2.java index 099c4dec6..e22ddf14a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/SimpleDatabaseHelperV2.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/SimpleDatabaseHelperV2.java @@ -21,6 +21,10 @@ import com.ghostchu.quickshop.shop.ContainerShop; import com.ghostchu.quickshop.util.PackageUtil; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.performance.PerfMonitor; +import java.sql.*; +import java.util.*; +import java.util.Date; +import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.tuple.Triple; import org.bukkit.Location; @@ -28,11 +32,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; -import java.sql.*; -import java.util.Date; -import java.util.*; -import java.util.concurrent.CompletableFuture; - /** * A Util to execute all SQLs. */ @@ -48,11 +47,12 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { private final int LATEST_DATABASE_VERSION = 14; - public SimpleDatabaseHelperV2(@NotNull QuickShop plugin, @NotNull SQLManager manager, @NotNull String prefix) throws Exception { + public SimpleDatabaseHelperV2(@NotNull QuickShop plugin, @NotNull SQLManager manager, @NotNull String prefix) + throws Exception { this.plugin = plugin; this.manager = manager; this.prefix = prefix; - //manager.setDebugMode(Util.isDevMode()); + // manager.setDebugMode(Util.isDevMode()); checkTables(); checkColumns(); checkDatabaseVersion(); @@ -64,7 +64,10 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { } int databaseVersion = getDatabaseVersion(); if (databaseVersion > LATEST_DATABASE_VERSION) { - throw new IllegalStateException("Database schema version " + databaseVersion + " is newer than this support max supported schema version " + LATEST_DATABASE_VERSION + ", downgrading the QuickShop-Hikari without restore the database from backup is disallowed cause it will break the data."); + throw new IllegalStateException( + "Database schema version " + databaseVersion + + " is newer than this support max supported schema version " + LATEST_DATABASE_VERSION + + ", downgrading the QuickShop-Hikari without restore the database from backup is disallowed cause it will break the data."); } } @@ -76,7 +79,6 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { } } - /** * Verifies that all required columns exist. */ @@ -85,7 +87,9 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { try (PerfMonitor ignored = new PerfMonitor("Perform database schema upgrade")) { new DatabaseUpgrade(this).upgrade(); if (getDatabaseVersion() != LATEST_DATABASE_VERSION) { - plugin.logger().warn("Database not upgrade to latest schema, or the developer forget update the version number, please report this to developer."); + plugin.logger() + .warn( + "Database not upgrade to latest schema, or the developer forget update the version number, please report this to developer."); } } plugin.logger().info("Finished!"); @@ -97,7 +101,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { .addCondition("key", "database_version") .selectColumns("value") .setLimit(1) - .build().execute()) { + .build() + .execute()) { ResultSet result = query.getResultSet(); if (!result.next()) { return -1; // Default latest version @@ -117,42 +122,56 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { .executeFuture(lines -> lines); } - public CompletableFuture purgeIsolated() { - return CompletableFuture.supplyAsync(() -> { - List shop2ShopMapIds = listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.SHOP_MAP, "shop"); - List shop2LogPurchaseIds = listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.LOG_PURCHASE, "shop"); - List shop2LogChangesIds = listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.LOG_CHANGES, "shop"); - List shop2Tags = listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.TAGS, "shop"); - List shopAllIds = CommonUtil.linkLists(shop2LogChangesIds, shop2LogPurchaseIds, shop2Tags); - List shopIsolatedFinal = new ArrayList<>(shop2ShopMapIds); - shopIsolatedFinal.retainAll(shopAllIds); - shopIsolatedFinal.forEach(isolatedShopId -> { - try { - DataTables.SHOPS.createDelete().addCondition("id", isolatedShopId).build().execute(); - } catch (SQLException e) { - Log.debug("Failed to delete: " + e.getMessage()); - } - }); - List data2ShopIds = listAllANotExistsInB(DataTables.DATA, "id", DataTables.SHOPS, "data"); - List data2LogPurchaseIds = listAllANotExistsInB(DataTables.DATA, "id", DataTables.LOG_PURCHASE, "data"); - List dataIsolatedFinal = new ArrayList<>(data2ShopIds); - dataIsolatedFinal.retainAll(data2LogPurchaseIds); - dataIsolatedFinal.forEach(isolatedDataId -> { - try { - DataTables.DATA.createDelete().addCondition("id", isolatedDataId).build().execute(); - } catch (SQLException e) { - Log.debug("Failed to delete: " + e.getMessage()); - } - }); - return shopIsolatedFinal.size() + dataIsolatedFinal.size(); - }, QuickExecutor.getCommonExecutor()); + return CompletableFuture.supplyAsync( + () -> { + List shop2ShopMapIds = + listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.SHOP_MAP, "shop"); + List shop2LogPurchaseIds = + listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.LOG_PURCHASE, "shop"); + List shop2LogChangesIds = + listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.LOG_CHANGES, "shop"); + List shop2Tags = listAllANotExistsInB(DataTables.SHOPS, "id", DataTables.TAGS, "shop"); + List shopAllIds = CommonUtil.linkLists(shop2LogChangesIds, shop2LogPurchaseIds, shop2Tags); + List shopIsolatedFinal = new ArrayList<>(shop2ShopMapIds); + shopIsolatedFinal.retainAll(shopAllIds); + shopIsolatedFinal.forEach(isolatedShopId -> { + try { + DataTables.SHOPS + .createDelete() + .addCondition("id", isolatedShopId) + .build() + .execute(); + } catch (SQLException e) { + Log.debug("Failed to delete: " + e.getMessage()); + } + }); + List data2ShopIds = listAllANotExistsInB(DataTables.DATA, "id", DataTables.SHOPS, "data"); + List data2LogPurchaseIds = + listAllANotExistsInB(DataTables.DATA, "id", DataTables.LOG_PURCHASE, "data"); + List dataIsolatedFinal = new ArrayList<>(data2ShopIds); + dataIsolatedFinal.retainAll(data2LogPurchaseIds); + dataIsolatedFinal.forEach(isolatedDataId -> { + try { + DataTables.DATA + .createDelete() + .addCondition("id", isolatedDataId) + .build() + .execute(); + } catch (SQLException e) { + Log.debug("Failed to delete: " + e.getMessage()); + } + }); + return shopIsolatedFinal.size() + dataIsolatedFinal.size(); + }, + QuickExecutor.getCommonExecutor()); } @NotNull public List listAllANotExistsInB(DataTables aTable, String aId, DataTables bTable, String bId) { List isolatedIds = new ArrayList<>(); - String SQL = "SELECT " + aId + " FROM " + aTable.getName() + " WHERE " + aId + " NOT IN (SELECT " + bId + " FROM " + bTable.getName() + ")"; + String SQL = "SELECT " + aId + " FROM " + aTable.getName() + " WHERE " + aId + " NOT IN (SELECT " + bId + + " FROM " + bTable.getName() + ")"; try (SQLQuery query = manager.createQuery().withPreparedSQL(SQL).execute()) { ResultSet rs = query.getResultSet(); while (rs.next()) { @@ -160,7 +179,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { isolatedIds.add(id); } } catch (SQLException e) { - plugin.logger().warn("Failed to list all " + aTable.getName() + " not exists in " + bTable.getName() + "!", e); + plugin.logger() + .warn("Failed to list all " + aTable.getName() + " not exists in " + bTable.getName() + "!", e); } return isolatedIds; } @@ -177,7 +197,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { private void upgradeBenefit() { fastBackup(); try { - getManager().alterTable(DataTables.DATA.getName()) + getManager() + .alterTable(DataTables.DATA.getName()) .addColumn("benefit", "MEDIUMTEXT") .execute(); } catch (SQLException e) { @@ -192,53 +213,60 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { private void upgradePlayers() { fastBackup(); try { - getManager().alterTable(DataTables.PLAYERS.getName()) + getManager() + .alterTable(DataTables.PLAYERS.getName()) .modifyColumn("locale", "VARCHAR(255)") .execute(); - getManager().alterTable(DataTables.PLAYERS.getName()) + getManager() + .alterTable(DataTables.PLAYERS.getName()) .addColumn("cachedName", "VARCHAR(255)") .execute(); } catch (SQLException e) { - Log.debug("Failed to add cachedName or modify locale column in " + DataTables.DATA.getName() + "! Err:" + e.getMessage()); + Log.debug("Failed to add cachedName or modify locale column in " + DataTables.DATA.getName() + "! Err:" + + e.getMessage()); } } private void upgradeUniqueIdsField() { fastBackup(); CompletableFuture.allOf( - manager.alterTable(DataTables.DATA.getName()) - .modifyColumn("owner", "VARCHAR(128) NOT NULL") - .executeFuture(), - manager.alterTable(DataTables.DATA.getName()) - .modifyColumn("tax_account", "VARCHAR(64)") - .executeFuture(), - manager.alterTable(DataTables.LOG_PURCHASE.getName()) - .modifyColumn("buyer", "VARCHAR(128) NOT NULL") - .executeFuture(), - manager.alterTable(DataTables.LOG_TRANSACTION.getName()) - .modifyColumn("from", "VARCHAR(128) NOT NULL") - .executeFuture(), - manager.alterTable(DataTables.LOG_TRANSACTION.getName()) - .modifyColumn("to", "VARCHAR(128) NOT NULL") - .executeFuture(), - manager.alterTable(DataTables.LOG_TRANSACTION.getName()) - .modifyColumn("tax_account", "VARCHAR(64)") - .executeFuture()).join(); + manager.alterTable(DataTables.DATA.getName()) + .modifyColumn("owner", "VARCHAR(128) NOT NULL") + .executeFuture(), + manager.alterTable(DataTables.DATA.getName()) + .modifyColumn("tax_account", "VARCHAR(64)") + .executeFuture(), + manager.alterTable(DataTables.LOG_PURCHASE.getName()) + .modifyColumn("buyer", "VARCHAR(128) NOT NULL") + .executeFuture(), + manager.alterTable(DataTables.LOG_TRANSACTION.getName()) + .modifyColumn("from", "VARCHAR(128) NOT NULL") + .executeFuture(), + manager.alterTable(DataTables.LOG_TRANSACTION.getName()) + .modifyColumn("to", "VARCHAR(128) NOT NULL") + .executeFuture(), + manager.alterTable(DataTables.LOG_TRANSACTION.getName()) + .modifyColumn("tax_account", "VARCHAR(64)") + .executeFuture()) + .join(); } private void upgradeWorldNameLength() { fastBackup(); manager.alterTable(DataTables.SHOP_MAP.getName()) .modifyColumn("world", "VARCHAR(255) NOT NULL") - .executeFuture().join(); + .executeFuture() + .join(); } private void upgradeTablesEncoding() { fastBackup(); for (DataTables value : DataTables.values()) { if (value.isExists(manager, prefix)) { - Integer integer = manager.executeSQL("ALTER TABLE `" + value.getName() + "` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"); - Log.debug("Changing the table " + value.getName() + " charset to utf8mb4, returns " + integer + " lines changed."); + Integer integer = manager.executeSQL("ALTER TABLE `" + value.getName() + + "` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"); + Log.debug("Changing the table " + value.getName() + " charset to utf8mb4, returns " + integer + + " lines changed."); } else { Log.debug("Table " + value.getName() + " not exists, skipping."); } @@ -252,7 +280,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override @NotNull public CompletableFuture<@NotNull Integer> cleanMessage(long weekAgo) { - return DataTables.MESSAGES.createDelete() + return DataTables.MESSAGES + .createDelete() .addTimeCondition("time", -1L, weekAgo) .build() .executeFuture(lines -> lines); @@ -260,9 +289,11 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull CompletableFuture<@NotNull Integer> cleanMessageForPlayer(@NotNull UUID player) { - return DataTables.MESSAGES.createDelete() + return DataTables.MESSAGES + .createDelete() .addCondition("receiver", player.toString()) - .build().executeFuture(lines -> lines); + .build() + .executeFuture(lines -> lines); } @Override @@ -271,10 +302,12 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { return queryDataId(simpleDataRecord).thenCompose(id -> { if (id == null) { Map map = simpleDataRecord.generateParams(); - return DataTables.DATA.createInsert() + return DataTables.DATA + .createInsert() .setColumnNames(new ArrayList<>(map.keySet())) .setParams(map.values()) - .returnGeneratedKey(Long.class).executeFuture(i -> i); + .returnGeneratedKey(Long.class) + .executeFuture(i -> i); } else { return CompletableFuture.completedFuture(id); } @@ -285,7 +318,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @NotNull public CompletableFuture<@NotNull Long> createShop(long dataId) { Validate.isTrue(dataId > 0, "Data ID must be greater than 0!"); - return DataTables.SHOPS.createInsert() + return DataTables.SHOPS + .createInsert() .setColumnNames("data") .setParams(dataId) .returnGeneratedKey(Long.class) @@ -295,9 +329,11 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public CompletableFuture<@NotNull Void> createShopMap(long shopId, @NotNull Location location) { Validate.isTrue(shopId > 0, "Shop ID must be greater than 0!"); - return DataTables.SHOP_MAP.createReplace() + return DataTables.SHOP_MAP + .createReplace() .setColumnNames("world", "x", "y", "z", "shop") - .setParams(location.getWorld().getName(), + .setParams( + location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), @@ -307,7 +343,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull CompletableFuture<@Nullable DataRecord> getDataRecord(long dataId) { - return DataTables.DATA.createQuery() + return DataTables.DATA + .createQuery() .addCondition("id", dataId) .setLimit(1) .build() @@ -323,19 +360,19 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override @NotNull public CompletableFuture<@Nullable String> getPlayerLocale(@NotNull UUID uuid) { - return DataTables.PLAYERS.createQuery() + return DataTables.PLAYERS + .createQuery() .addCondition("uuid", uuid.toString()) .selectColumns("locale") .setLimit(1) .build() .executeFuture(sqlQuery -> { - ResultSet set = sqlQuery.getResultSet(); - if (set.next()) { - return set.getString("locale"); - } - return null; - } - ); + ResultSet set = sqlQuery.getResultSet(); + if (set.next()) { + return set.getString("locale"); + } + return null; + }); } @Override @@ -349,41 +386,42 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public CompletableFuture<@Nullable String> getPlayerName(@NotNull UUID uuid) { - return DataTables.PLAYERS.createQuery() + return DataTables.PLAYERS + .createQuery() .addCondition("uuid", uuid.toString()) .selectColumns("cachedName") .setLimit(1) .build() .executeFuture(sqlQuery -> { - ResultSet set = sqlQuery.getResultSet(); - if (set.next()) { - return set.getString("cachedName"); - } - return null; - } - ); + ResultSet set = sqlQuery.getResultSet(); + if (set.next()) { + return set.getString("cachedName"); + } + return null; + }); } @Override public CompletableFuture<@Nullable UUID> getPlayerUUID(@NotNull String name) { - return DataTables.PLAYERS.createQuery() + return DataTables.PLAYERS + .createQuery() .addCondition("cachedName", name) .selectColumns("uuid") .setLimit(1) .build() .executeFuture(sqlQuery -> { - ResultSet set = sqlQuery.getResultSet(); - if (set.next()) { - return UUID.fromString(set.getString("uuid")); - } - return null; - } - ); + ResultSet set = sqlQuery.getResultSet(); + if (set.next()) { + return UUID.fromString(set.getString("uuid")); + } + return null; + }); } @Override public @NotNull CompletableFuture<@NotNull Integer> insertHistoryRecord(@NotNull Object rec) { - return DataTables.LOG_OTHERS.createInsert() + return DataTables.LOG_OTHERS + .createInsert() .setColumnNames("type", "data") .setParams(rec.getClass().getName(), JsonUtil.getGson().toJson(rec)) .executeFuture(lines -> lines); @@ -399,10 +437,17 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { DataTables.LOG_PURCHASE .createInsert() .setColumnNames("time", "shop", "data", "buyer", "type", "amount", "money", "tax") - .setParams(new Date(metricRecord.getTime()), metricRecord.getShopId() - , dataId, metricRecord.getPlayer(), metricRecord.getType().name(), - metricRecord.getAmount(), metricRecord.getTotal(), metricRecord.getTax()) - .executeFuture(lines -> lines).whenComplete((line, err2) -> { + .setParams( + new Date(metricRecord.getTime()), + metricRecord.getShopId(), + dataId, + metricRecord.getPlayer(), + metricRecord.getType().name(), + metricRecord.getAmount(), + metricRecord.getTotal(), + metricRecord.getTax()) + .executeFuture(lines -> lines) + .whenComplete((line, err2) -> { if (err2 != null) { future.completeExceptionally(err2); } @@ -410,21 +455,36 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { }); }); return future; - } @Override - public void insertTransactionRecord(@Nullable UUID from, @Nullable UUID to, double amount, @Nullable String currency, double taxAmount, @Nullable UUID taxAccount, @Nullable String error) { + public void insertTransactionRecord( + @Nullable UUID from, + @Nullable UUID to, + double amount, + @Nullable String currency, + double taxAmount, + @Nullable UUID taxAccount, + @Nullable String error) { if (from == null) { from = CommonUtil.getNilUniqueId(); } if (to == null) { to = CommonUtil.getNilUniqueId(); } - DataTables.LOG_TRANSACTION.createInsert() + DataTables.LOG_TRANSACTION + .createInsert() .setColumnNames("from", "to", "currency", "amount", "tax_amount", "tax_account", "error") - .setParams(from.toString(), to.toString(), currency, amount, taxAmount, taxAccount == null ? null : taxAccount.toString(), error) - .executeAsync(handler -> Log.debug("Operation completed, insertTransactionRecord, " + handler + " lines affected")); + .setParams( + from.toString(), + to.toString(), + currency, + amount, + taxAmount, + taxAccount == null ? null : taxAccount.toString(), + error) + .executeAsync(handler -> + Log.debug("Operation completed, insertTransactionRecord, " + handler + " lines affected")); } @Override @@ -456,10 +516,12 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull List listShopsTaggedBy(@NotNull UUID tagger, @NotNull String tag) { List shopIds = new ArrayList<>(); - try (SQLQuery query = DataTables.TAGS.createQuery() + try (SQLQuery query = DataTables.TAGS + .createQuery() .addCondition("tagger", tagger.toString()) .addCondition("tag", tag) - .build().execute()) { + .build() + .execute()) { ResultSet set = query.getResultSet(); shopIds.add(set.getLong("shop")); } catch (SQLException e) { @@ -471,9 +533,11 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull List listTags(@NotNull UUID tagger) { List tags = new ArrayList<>(); - try (SQLQuery query = DataTables.TAGS.createQuery() + try (SQLQuery query = DataTables.TAGS + .createQuery() .addCondition("tagger", tagger.toString()) - .build().execute()) { + .build() + .execute()) { ResultSet set = query.getResultSet(); tags.add(set.getString("tag")); } catch (SQLException e) { @@ -483,32 +547,42 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { } @Override - public CompletableFuture<@Nullable Integer> removeShopTag(@NotNull UUID tagger, @NotNull Long shopId, @NotNull String tag) { - return DataTables.TAGS.createDelete() + public CompletableFuture<@Nullable Integer> removeShopTag( + @NotNull UUID tagger, @NotNull Long shopId, @NotNull String tag) { + return DataTables.TAGS + .createDelete() .addCondition("tagger", tagger.toString()) .addCondition("shop", shopId) - .addCondition("tag", tag).build().executeFuture(i -> i); + .addCondition("tag", tag) + .build() + .executeFuture(i -> i); } @Override public CompletableFuture<@Nullable Integer> removeShopAllTag(@NotNull UUID tagger, @NotNull Long shopId) { - return DataTables.TAGS.createDelete() + return DataTables.TAGS + .createDelete() .addCondition("tagger", tagger.toString()) .addCondition("shop", shopId) - .build().executeFuture(i -> i); + .build() + .executeFuture(i -> i); } @Override public CompletableFuture<@Nullable Integer> removeTagFromShops(@NotNull UUID tagger, @NotNull String tag) { - return DataTables.TAGS.createDelete() + return DataTables.TAGS + .createDelete() .addCondition("tagger", tagger.toString()) .addCondition("tag", tag) - .build().executeFuture(i -> i); + .build() + .executeFuture(i -> i); } @Override - public @NotNull CompletableFuture<@Nullable Integer> tagShop(@NotNull UUID tagger, @NotNull Long shopId, @NotNull String tag) { - return DataTables.TAGS.createInsert() + public @NotNull CompletableFuture<@Nullable Integer> tagShop( + @NotNull UUID tagger, @NotNull Long shopId, @NotNull String tag) { + return DataTables.TAGS + .createInsert() .setColumnNames("tagger", "shop", "tag") .setParams(tagger.toString(), shopId, tag) .executeFuture(i -> i); @@ -516,7 +590,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull CompletableFuture<@Nullable Long> locateShopDataId(long shopId) { - return DataTables.SHOPS.createQuery() + return DataTables.SHOPS + .createQuery() .addCondition("id", shopId) .setLimit(1) .build() @@ -532,13 +607,15 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override @NotNull public CompletableFuture<@Nullable Long> locateShopId(@NotNull String world, int x, int y, int z) { - return DataTables.SHOP_MAP.createQuery() + return DataTables.SHOP_MAP + .createQuery() .addCondition("world", world) .addCondition("x", x) .addCondition("y", y) .addCondition("z", z) .setLimit(1) - .build().executeFuture(query -> { + .build() + .executeFuture(query -> { ResultSet result = query.getResultSet(); if (result.next()) { return result.getLong("shop"); @@ -551,23 +628,24 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull CompletableFuture<@NotNull Integer> removeData(long dataId) { Validate.isTrue(dataId > 0, "Data ID must be greater than 0!"); - return DataTables.DATA.createDelete() - .addCondition("id", dataId) - .build().executeFuture(lines -> lines); + return DataTables.DATA.createDelete().addCondition("id", dataId).build().executeFuture(lines -> lines); } @Override public @NotNull CompletableFuture<@NotNull Integer> removeShop(long shopId) { Validate.isTrue(shopId > 0, "Shop ID must be greater than 0!"); - return DataTables.SHOPS.createDelete() + return DataTables.SHOPS + .createDelete() .addCondition("id", shopId) - .build().executeFuture(lines -> lines); + .build() + .executeFuture(lines -> lines); } @Override public @NotNull CompletableFuture<@NotNull Integer> removeShopMap(@NotNull String world, int x, int y, int z) { // TODO: Execute isolated data check in async thread - return DataTables.SHOP_MAP.createDelete() + return DataTables.SHOP_MAP + .createDelete() .addCondition("world", world) .addCondition("x", x) .addCondition("y", y) @@ -577,8 +655,10 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { } @Override - public @NotNull CompletableFuture<@NotNull Integer> saveOfflineTransactionMessage(@NotNull UUID player, @NotNull String message, long time) { - return DataTables.MESSAGES.createInsert() + public @NotNull CompletableFuture<@NotNull Integer> saveOfflineTransactionMessage( + @NotNull UUID player, @NotNull String message, long time) { + return DataTables.MESSAGES + .createInsert() .setColumnNames("receiver", "time", "content") .setParams(player.toString(), new Date(time), message) .executeFuture(lines -> lines); @@ -591,7 +671,8 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull CompletableFuture> selectPlayerMessages(UUID player) { - return DataTables.MESSAGES.createQuery() + return DataTables.MESSAGES + .createQuery() .addCondition("receiver", player.toString()) .selectColumns() .build() @@ -608,17 +689,16 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { @Override public @NotNull SQLQuery selectTable(@NotNull String table) throws SQLException { - return manager.createQuery() - .inTable(prefix + table) - .build() - .execute(); + return manager.createQuery().inTable(prefix + table).build().execute(); } @Override @NotNull - public CompletableFuture<@NotNull Integer> updatePlayerProfile(@NotNull UUID uuid, @Nullable String locale, @NotNull String username) { + public CompletableFuture<@NotNull Integer> updatePlayerProfile( + @NotNull UUID uuid, @Nullable String locale, @NotNull String username) { if (locale != null) { - return DataTables.PLAYERS.createReplace() + return DataTables.PLAYERS + .createReplace() .setColumnNames("uuid", "locale", "cachedName") .setParams(uuid.toString(), locale, username) .executeFuture(lines -> lines); @@ -628,16 +708,19 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { if (cachedLocale == null) { cachedLocale = "en_us"; } - return DataTables.PLAYERS.createReplace() + return DataTables.PLAYERS + .createReplace() .setColumnNames("uuid", "locale", "cachedName") .setParams(uuid.toString(), cachedLocale, username) - .executeFuture(lines -> lines).join(); + .executeFuture(lines -> lines) + .join(); }); } } @Override - public CompletableFuture updatePlayerProfileInBatch(List> uuidLocaleUsername) { + public CompletableFuture updatePlayerProfileInBatch( + List> uuidLocaleUsername) { List specificLocale = new ArrayList<>(); List> unspecificLocale = new ArrayList<>(); @@ -645,28 +728,37 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { if (user.getMiddle() == null) { unspecificLocale.add(user); } else { - specificLocale.add(new Object[]{user.getLeft(), user.getMiddle(), user.getRight()}); + specificLocale.add(new Object[] {user.getLeft(), user.getMiddle(), user.getRight()}); } } - var action = new PreparedSQLBatchUpdateActionImpl<>((SQLManagerImpl) getManager(), Integer.class, - "INSERT INTO " + DataTables.PLAYERS.getName() + "(uuid, locale, cachedName) VALUES (?, ?, ?) " + - "ON DUPLICATE KEY UPDATE cachedName = ?" - ); + var action = new PreparedSQLBatchUpdateActionImpl<>( + (SQLManagerImpl) getManager(), + Integer.class, + "INSERT INTO " + DataTables.PLAYERS.getName() + "(uuid, locale, cachedName) VALUES (?, ?, ?) " + + "ON DUPLICATE KEY UPDATE cachedName = ?"); for (Triple data : unspecificLocale) { action.addParamsBatch(data.getLeft().toString(), "en_us", data.getRight(), data.getRight()); } - return DataTables.PLAYERS.createReplaceBatch().setColumnNames("uuid", "locale", "cachedName") + return DataTables.PLAYERS + .createReplaceBatch() + .setColumnNames("uuid", "locale", "cachedName") .setAllParams(specificLocale) - .executeFuture(lines -> lines.stream().mapToInt(Integer::intValue).sum()) - .thenCombine(action.executeFuture(lines -> lines.stream().mapToInt(Integer::intValue).sum()), Integer::sum); + .executeFuture( + lines -> lines.stream().mapToInt(Integer::intValue).sum()) + .thenCombine( + action.executeFuture(lines -> + lines.stream().mapToInt(Integer::intValue).sum()), + Integer::sum); } @Override - public @NotNull CompletableFuture<@NotNull Integer> updateExternalInventoryProfileCache(long shopId, int space, int stock) { + public @NotNull CompletableFuture<@NotNull Integer> updateExternalInventoryProfileCache( + long shopId, int space, int stock) { Validate.isTrue(shopId > 0, "Shop ID must be greater than 0!"); - return DataTables.EXTERNAL_CACHE.createReplace() + return DataTables.EXTERNAL_CACHE + .createReplace() .setColumnNames("shop", "space", "stock") .setParams(shopId, space, stock) .executeFuture(lines -> lines); @@ -679,18 +771,21 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { // check if datarecord exists long shopId = shop.getShopId(); if (shopId < 1) { - Log.debug("Warning: Failed to update shop because the shop id locate result for " + loc + ", because the query shopId is " + shopId); + Log.debug("Warning: Failed to update shop because the shop id locate result for " + loc + + ", because the query shopId is " + shopId); return null; } return queryDataId(simpleDataRecord).thenCompose(dataId -> { if (dataId != null) { - return DataTables.SHOPS.createUpdate() + return DataTables.SHOPS + .createUpdate() .addCondition("id", shopId) .setColumnValues("data", dataId) .build() .executeFuture(); } else { - return createData(shop).thenCompose(createdDataId -> DataTables.SHOPS.createUpdate() + return createData(shop).thenCompose(createdDataId -> DataTables.SHOPS + .createUpdate() .addCondition("id", shopId) .setColumnValues("data", createdDataId) .build() @@ -708,37 +803,42 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { for (Map.Entry entry : lookupParams.entrySet()) { builder.addCondition(entry.getKey(), entry.getValue()); } - return builder.build() - .executeFuture(query -> { - ResultSet set = query.getResultSet(); - if (set.next()) { - long id = set.getLong("id"); - Log.debug("Found data record with id " + id + " for record " + simpleDataRecord); - return id; - } - Log.debug("No data record found for record basic data: " + simpleDataRecord); - return null; - }); - - + return builder.build().executeFuture(query -> { + ResultSet set = query.getResultSet(); + if (set.next()) { + long id = set.getLong("id"); + Log.debug("Found data record with id " + id + " for record " + simpleDataRecord); + return id; + } + Log.debug("No data record found for record basic data: " + simpleDataRecord); + return null; + }); } public CompletableFuture purgeLogsRecords(@Nullable Date endDate) { return CompletableFuture.supplyAsync(() -> { int linesAffected = 0; try { - linesAffected += DataTables.LOG_TRANSACTION.createDelete() + linesAffected += DataTables.LOG_TRANSACTION + .createDelete() .addTimeCondition("time", null, endDate) - .build().execute(); - linesAffected += DataTables.LOG_CHANGES.createDelete() + .build() + .execute(); + linesAffected += DataTables.LOG_CHANGES + .createDelete() .addTimeCondition("time", null, endDate) - .build().execute(); - linesAffected += DataTables.LOG_PURCHASE.createDelete() + .build() + .execute(); + linesAffected += DataTables.LOG_PURCHASE + .createDelete() .addTimeCondition("time", null, endDate) - .build().execute(); - linesAffected += DataTables.LOG_OTHERS.createDelete() + .build() + .execute(); + linesAffected += DataTables.LOG_OTHERS + .createDelete() .addTimeCondition("time", null, endDate) - .build().execute(); + .build() + .execute(); return linesAffected; } catch (SQLException e) { plugin.logger().warn("Failed to purge logs records", e); @@ -761,7 +861,9 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { } String query = "SELECT * FROM " + table + " LIMIT 1"; boolean match = false; - try (Connection connection = manager.getConnection(); PreparedStatement ps = connection.prepareStatement(query); ResultSet rs = ps.executeQuery()) { + try (Connection connection = manager.getConnection(); + PreparedStatement ps = connection.prepareStatement(query); + ResultSet rs = ps.executeQuery()) { ResultSetMetaData metaData = rs.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { if (metaData.getColumnLabel(i).equals(column)) { @@ -775,7 +877,6 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { return match; // Uh, wtf. } - /** * Returns true if the table exists * @@ -799,7 +900,6 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { return match; } - static class DatabaseUpgrade { private final SimpleDatabaseHelperV2 parent; private final String prefix; @@ -880,7 +980,6 @@ public class SimpleDatabaseHelperV2 implements DatabaseHelper { } } - private record ShopInfo(long shopID, String world, int x, int y, int z) implements InfoRecord { @Override public long getShopId() { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/IsolatedScanResult.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/IsolatedScanResult.java index e20f408c2..cad95e58d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/IsolatedScanResult.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/IsolatedScanResult.java @@ -1,8 +1,7 @@ package com.ghostchu.quickshop.database.bean; -import lombok.Data; - import java.util.List; +import lombok.Data; @Data public class IsolatedScanResult { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/SimpleDataRecord.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/SimpleDataRecord.java index 432f1a48a..3bfa7e93d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/SimpleDataRecord.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/bean/SimpleDataRecord.java @@ -5,15 +5,14 @@ import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.quickshop.api.shop.PlayerFinder; import com.ghostchu.quickshop.common.util.QuickExecutor; import com.ghostchu.quickshop.obj.QUserImpl; -import lombok.Data; -import org.jetbrains.annotations.NotNull; - import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import lombok.Data; +import org.jetbrains.annotations.NotNull; @Data public class SimpleDataRecord implements DataRecord { @@ -34,7 +33,22 @@ public class SimpleDataRecord implements DataRecord { private final String benefit; - public SimpleDataRecord(QUser owner, String item, String name, int type, String currency, double price, boolean unlimited, boolean hologram, QUser taxAccount, String permissions, String extra, String inventoryWrapper, String inventorySymbolLink, Date createTime, String benefit) { + public SimpleDataRecord( + QUser owner, + String item, + String name, + int type, + String currency, + double price, + boolean unlimited, + boolean hologram, + QUser taxAccount, + String permissions, + String extra, + String inventoryWrapper, + String inventorySymbolLink, + Date createTime, + String benefit) { this.owner = owner; this.item = item; this.name = name; @@ -53,7 +67,8 @@ public class SimpleDataRecord implements DataRecord { } public SimpleDataRecord(PlayerFinder finder, ResultSet set) throws SQLException { - this.owner = QUserImpl.deserialize(finder, set.getString("owner"), QuickExecutor.getSecondaryProfileIoExecutor()); + this.owner = + QUserImpl.deserialize(finder, set.getString("owner"), QuickExecutor.getSecondaryProfileIoExecutor()); this.item = set.getString("item"); this.name = set.getString("name"); this.type = set.getInt("type"); @@ -62,7 +77,9 @@ public class SimpleDataRecord implements DataRecord { this.unlimited = set.getBoolean("unlimited"); this.hologram = set.getBoolean("hologram"); String taxAccountString = set.getString("tax_account"); - this.taxAccount = taxAccountString == null ? null : QUserImpl.deserialize(finder, taxAccountString, QuickExecutor.getSecondaryProfileIoExecutor()); + this.taxAccount = taxAccountString == null + ? null + : QUserImpl.deserialize(finder, taxAccountString, QuickExecutor.getSecondaryProfileIoExecutor()); this.permissions = set.getString("permissions"); this.extra = set.getString("extra"); this.inventorySymbolLink = set.getString("inv_symbol_link"); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_GemsEconomy.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_GemsEconomy.java index 69d19a377..5180919ed 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_GemsEconomy.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_GemsEconomy.java @@ -5,6 +5,7 @@ import com.ghostchu.quickshop.api.economy.AbstractEconomy; import com.ghostchu.quickshop.util.economyformatter.BuiltInEconomyFormatter; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.util.UUID; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -16,14 +17,13 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - @ToString public class Economy_GemsEconomy extends AbstractEconomy { private final QuickShop plugin; private final BuiltInEconomyFormatter formatter; private boolean allowLoan; + @Getter @Setter private GemsEconomyAPI api; @@ -37,7 +37,6 @@ public class Economy_GemsEconomy extends AbstractEconomy { setupEconomy(); } - private void init() { this.allowLoan = plugin.getConfig().getBoolean("shop.allow-economy-loan"); } @@ -78,7 +77,6 @@ public class Economy_GemsEconomy extends AbstractEconomy { return this.api.getCurrency(currency); } - @Override public boolean deposit(@NotNull String name, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { @@ -114,7 +112,8 @@ public class Economy_GemsEconomy extends AbstractEconomy { * @return True if success (Should be almost always) */ @Override - public boolean deposit(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean deposit( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { return deposit(trader.getUniqueId(), amount, world, currency); } @@ -207,7 +206,8 @@ public class Economy_GemsEconomy extends AbstractEconomy { * @return True if success, false if they didn't have enough cash */ @Override - public boolean withdraw(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean withdraw( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { return withdraw(trader.getUniqueId(), amount, world, currency); } @@ -261,11 +261,8 @@ public class Economy_GemsEconomy extends AbstractEconomy { return this.api != null; } - @Override public @NotNull Plugin getPlugin() { return this.plugin.getJavaPlugin(); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Reserve.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Reserve.java index f06088ec2..f92a7b3d8 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Reserve.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Reserve.java @@ -3,6 +3,9 @@ package com.ghostchu.quickshop.economy; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.economy.AbstractEconomy; import com.ghostchu.quickshop.util.economyformatter.BuiltInEconomyFormatter; +import java.math.BigDecimal; +import java.util.Objects; +import java.util.UUID; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -16,10 +19,6 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.math.BigDecimal; -import java.util.Objects; -import java.util.UUID; - /** * @author creatorfromhell */ @@ -74,9 +73,11 @@ public class Economy_Reserve extends AbstractEconomy { * @return true if success (Payer had enough cash, receiver was able to receive the funds) */ @Override - public boolean transfer(@NotNull UUID from, @NotNull UUID to, double amount, @NotNull World world, @Nullable String currency) { + public boolean transfer( + @NotNull UUID from, @NotNull UUID to, double amount, @NotNull World world, @Nullable String currency) { try { - return Objects.requireNonNull(reserve).transferHoldings(from, to, BigDecimal.valueOf(amount), world.getName(), currency); + return Objects.requireNonNull(reserve) + .transferHoldings(from, to, BigDecimal.valueOf(amount), world.getName(), currency); } catch (Exception throwable) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); @@ -87,9 +88,11 @@ public class Economy_Reserve extends AbstractEconomy { } @Override - public boolean transfer(@NotNull String from, @NotNull String to, double amount, @NotNull World world, @Nullable String currency) { + public boolean transfer( + @NotNull String from, @NotNull String to, double amount, @NotNull World world, @Nullable String currency) { try { - return Objects.requireNonNull(reserve).transferHoldings(from, to, BigDecimal.valueOf(amount), world.getName(), currency); + return Objects.requireNonNull(reserve) + .transferHoldings(from, to, BigDecimal.valueOf(amount), world.getName(), currency); } catch (Exception throwable) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); @@ -120,7 +123,8 @@ public class Economy_Reserve extends AbstractEconomy { @Override public boolean deposit(@NotNull String name, double amount, @NotNull World world, @Nullable String currency) { try { - return Objects.requireNonNull(reserve).addHoldings(name, BigDecimal.valueOf(amount), world.getName(), currency); + return Objects.requireNonNull(reserve) + .addHoldings(name, BigDecimal.valueOf(amount), world.getName(), currency); } catch (Exception throwable) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); @@ -140,7 +144,8 @@ public class Economy_Reserve extends AbstractEconomy { @Override public boolean deposit(@NotNull UUID name, double amount, @NotNull World world, @Nullable String currency) { try { - return Objects.requireNonNull(reserve).addHoldings(name, BigDecimal.valueOf(amount), world.getName(), currency); + return Objects.requireNonNull(reserve) + .addHoldings(name, BigDecimal.valueOf(amount), world.getName(), currency); } catch (Exception throwable) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); @@ -150,9 +155,9 @@ public class Economy_Reserve extends AbstractEconomy { } } - @Override - public boolean deposit(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean deposit( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { return deposit(trader.getUniqueId(), amount, world, currency); } @@ -178,7 +183,9 @@ public class Economy_Reserve extends AbstractEconomy { @Override public double getBalance(@NotNull String name, @NotNull World world, @Nullable String currency) { try { - return Objects.requireNonNull(reserve).getHoldings(name, world.getName(), currency).doubleValue(); + return Objects.requireNonNull(reserve) + .getHoldings(name, world.getName(), currency) + .doubleValue(); } catch (Exception throwable) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); @@ -205,7 +212,9 @@ public class Economy_Reserve extends AbstractEconomy { @Override public double getBalance(@NotNull UUID name, @NotNull World world, @Nullable String currency) { try { - return Objects.requireNonNull(reserve).getHoldings(name, world.getName(), currency).doubleValue(); + return Objects.requireNonNull(reserve) + .getHoldings(name, world.getName(), currency) + .doubleValue(); } catch (Exception throwable) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); @@ -220,7 +229,6 @@ public class Economy_Reserve extends AbstractEconomy { return getBalance(player.getUniqueId(), world, currency); } - /** * Withdraws a given amount of money from the given username and turns it to thin air. * @@ -242,11 +250,11 @@ public class Economy_Reserve extends AbstractEconomy { } @Override - public boolean withdraw(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean withdraw( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { return withdraw(trader.getUniqueId(), amount, world, currency); } - /** * Gets the currency does exists * @@ -286,10 +294,8 @@ public class Economy_Reserve extends AbstractEconomy { return reserve != null; } - @Override public @NotNull Plugin getPlugin() { return plugin.getJavaPlugin(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_TNE.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_TNE.java index 02c9b9e96..e170bb7d6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_TNE.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_TNE.java @@ -4,6 +4,9 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.economy.AbstractEconomy; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -26,10 +29,6 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.math.BigDecimal; -import java.util.Optional; -import java.util.UUID; - @ToString public class Economy_TNE extends AbstractEconomy { @@ -69,21 +68,25 @@ public class Economy_TNE extends AbstractEconomy { return TNECore.eco().currency().getDefaultCurrency(world.getName()); } - private boolean runTransaction(final Account account, final Currency currency, final String world, final BigDecimal amount, final String type, final boolean counter) { + private boolean runTransaction( + final Account account, + final Currency currency, + final String world, + final BigDecimal amount, + final String type, + final boolean counter) { - //Set up our holdings' modifier. - final HoldingsModifier modifier = new HoldingsModifier(world, - currency.getUid(), - amount); + // Set up our holdings' modifier. + final HoldingsModifier modifier = new HoldingsModifier(world, currency.getUid(), amount); - //Setup our transaction. + // Setup our transaction. final Transaction transaction = new Transaction(type) .to(account, ((counter) ? modifier.counter() : modifier)) .processor(EconomyManager.baseProcessor()) .source(new PluginSource("QuickShop")); try { - //Process our transaction. + // Process our transaction. final TransactionResult result = transaction.process(); if (result.isSuccessful()) { return true; @@ -113,7 +116,8 @@ public class Economy_TNE extends AbstractEconomy { if (account.isPresent() && currencyOpt.isPresent()) { - return runTransaction(account.get(), currencyOpt.get(), world.getName(), BigDecimal.valueOf(amount), "give", false); + return runTransaction( + account.get(), currencyOpt.get(), world.getName(), BigDecimal.valueOf(amount), "give", false); } return false; } @@ -141,15 +145,16 @@ public class Economy_TNE extends AbstractEconomy { * @return True if success (Should be almost always) */ @Override - public boolean deposit(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean deposit( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { return false; } - //We should forward this method to the UUID one instead of doing another OfflinePlayer lookup here just to send it to the TNE UUID method. + // We should forward this method to the UUID one instead of doing another OfflinePlayer lookup here just to send + // it to the TNE UUID method. return deposit(trader.getUniqueId(), amount, world, currency); } - /** * Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50 Dollars 5 Cents * @@ -169,8 +174,13 @@ public class Economy_TNE extends AbstractEconomy { return "Error"; } - return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), - currencyObj.getUid(), BigDecimal.valueOf(balance), EconomyManager.NORMAL)); + return CurrencyFormatter.format( + null, + new HoldingsEntry( + TNECore.eco().region().defaultRegion(), + currencyObj.getUid(), + BigDecimal.valueOf(balance), + EconomyManager.NORMAL)); } @Override @@ -182,12 +192,13 @@ public class Economy_TNE extends AbstractEconomy { final Optional currencyOpt = TNECore.eco().currency().findCurrency(currency); if (account.isPresent() && currencyOpt.isPresent()) { - return account.get().getHoldingsTotal(world.getName(), currencyOpt.get().getUid()).doubleValue(); + return account.get() + .getHoldingsTotal(world.getName(), currencyOpt.get().getUid()) + .doubleValue(); } return 0.0; } - /** * Fetches the balance of the given account {@link UUID unique identifier}. * @@ -272,7 +283,8 @@ public class Economy_TNE extends AbstractEconomy { if (account.isPresent() && currencyOpt.isPresent()) { - return runTransaction(account.get(), currencyOpt.get(), world.getName(), BigDecimal.valueOf(amount), "take", true); + return runTransaction( + account.get(), currencyOpt.get(), world.getName(), BigDecimal.valueOf(amount), "take", true); } return false; } @@ -299,7 +311,8 @@ public class Economy_TNE extends AbstractEconomy { * @return True if success, false if they didn't have enough cash */ @Override - public boolean withdraw(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean withdraw( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { return withdraw(trader.getUniqueId().toString(), amount, world, currency); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Vault.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Vault.java index f21b59eb7..6a4f057d0 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Vault.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/Economy_Vault.java @@ -1,6 +1,5 @@ package com.ghostchu.quickshop.economy; - import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.economy.AbstractEconomy; import com.ghostchu.quickshop.common.util.CommonUtil; @@ -8,6 +7,9 @@ import com.ghostchu.quickshop.util.economyformatter.BuiltInEconomyFormatter; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.util.Objects; +import java.util.UUID; +import java.util.logging.Level; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -24,10 +26,6 @@ import org.bukkit.plugin.RegisteredServiceProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Objects; -import java.util.UUID; -import java.util.logging.Level; - @SuppressWarnings("deprecation") @ToString public class Economy_Vault extends AbstractEconomy implements Listener { @@ -37,14 +35,15 @@ public class Economy_Vault extends AbstractEconomy implements Listener { private final QuickShop plugin; private final BuiltInEconomyFormatter formatter; private boolean allowLoan; + @Getter @Setter @Nullable private net.milkbowl.vault.economy.Economy vault; + @Nullable private String lastError = null; - public Economy_Vault(@NotNull QuickShop plugin) { super(); this.plugin = plugin; @@ -60,7 +59,8 @@ public class Economy_Vault extends AbstractEconomy implements Listener { private boolean setupEconomy() { if (!CommonUtil.isClassAvailable("net.milkbowl.vault.economy.Economy")) { - return false; // QUICKSHOP-YS I can't believe it broken almost a year and nobody found it, my sentry exploded. + return false; // QUICKSHOP-YS I can't believe it broken almost a year and nobody found it, my sentry + // exploded. } RegisteredServiceProvider economyProvider; try { @@ -78,15 +78,12 @@ public class Economy_Vault extends AbstractEconomy implements Listener { } if (this.vault.getName() == null || this.vault.getName().isEmpty()) { - plugin - .logger() + plugin.logger() .warn( "Current economy plugin not correct process all request, this usually cause by irregular code, you should report this issue to your economy plugin author or use other economy plugin."); - plugin - .logger() - .warn( - "This is technical information, please send this to economy plugin author: " - + "VaultEconomyProvider.getName() return a null or empty."); + plugin.logger() + .warn("This is technical information, please send this to economy plugin author: " + + "VaultEconomyProvider.getName() return a null or empty."); } else { plugin.logger().info("Using economy system: " + this.vault.getName()); } @@ -106,7 +103,8 @@ public class Economy_Vault extends AbstractEconomy implements Listener { return true; } this.lastError = getProviderName() + ": " + response.type.name() + " - " + response.errorMessage; - Log.transaction(Level.WARNING, "Deposit player " + name + " failed, Vault response: " + response.errorMessage); + Log.transaction( + Level.WARNING, "Deposit player " + name + " failed, Vault response: " + response.errorMessage); return false; } catch (Exception t) { if (plugin.getSentryErrorReporter() != null) { @@ -124,11 +122,11 @@ public class Economy_Vault extends AbstractEconomy implements Listener { return false; } return deposit(Bukkit.getOfflinePlayer(name), amount, world, currency); - } @Override - public boolean deposit(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean deposit( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { return false; } @@ -138,14 +136,18 @@ public class Economy_Vault extends AbstractEconomy implements Listener { return true; } this.lastError = getProviderName() + ": " + response.type.name() + " - " + response.errorMessage; - Log.transaction(Level.WARNING, "Deposit player " + trader.getUniqueId() + " failed, Vault response: " + response.errorMessage); + Log.transaction( + Level.WARNING, + "Deposit player " + trader.getUniqueId() + " failed, Vault response: " + response.errorMessage); return false; } catch (Exception t) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); } if (trader.getName() == null) { - plugin.logger().warn("Deposit failed and player name is NULL, Player uuid: " + trader.getUniqueId() + ". Provider (" + getProviderName() + ")"); + plugin.logger() + .warn("Deposit failed and player name is NULL, Player uuid: " + trader.getUniqueId() + + ". Provider (" + getProviderName() + ")"); return false; } plugin.logger().warn("Failure - deposit - " + trader + " - " + amount + " - " + world + " - " + currency); @@ -201,7 +203,6 @@ public class Economy_Vault extends AbstractEconomy implements Listener { return 0.0; } return getBalance(Bukkit.getOfflinePlayer(name), world, currency); - } @Override @@ -271,7 +272,8 @@ public class Economy_Vault extends AbstractEconomy implements Listener { return true; } this.lastError = getProviderName() + ": " + response.type.name() + " - " + response.errorMessage; - Log.transaction(Level.WARNING, "Withdraw player " + name + " failed, Vault response: " + response.errorMessage); + Log.transaction( + Level.WARNING, "Withdraw player " + name + " failed, Vault response: " + response.errorMessage); return false; } catch (Exception t) { if (plugin.getSentryErrorReporter() != null) { @@ -292,7 +294,8 @@ public class Economy_Vault extends AbstractEconomy implements Listener { } @Override - public boolean withdraw(@NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { + public boolean withdraw( + @NotNull OfflinePlayer trader, double amount, @NotNull World world, @Nullable String currency) { if (!isValid()) { return false; } @@ -305,14 +308,19 @@ public class Economy_Vault extends AbstractEconomy implements Listener { return true; } this.lastError = getProviderName() + ": " + response.type.name() + " - " + response.errorMessage; - Log.transaction(Level.WARNING, "Withdraw player " + trader.getUniqueId() + " failed, Vault response: " + response.errorMessage); + Log.transaction( + Level.WARNING, + "Withdraw player " + trader.getUniqueId() + " failed, Vault response: " + response.errorMessage); return false; } catch (Exception t) { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); } if (trader.getName() == null) { - plugin.logger().warn("Withdraw failed and player name is NULL, Player uuid: {}", trader.getUniqueId() + ", Provider: " + getProviderName()); + plugin.logger() + .warn( + "Withdraw failed and player name is NULL, Player uuid: {}", + trader.getUniqueId() + ", Provider: " + getProviderName()); return false; } plugin.logger().warn("Failure - withdraw - " + trader + " - " + amount + " - " + world + " - " + currency); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleBenefit.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleBenefit.java index 1efe050a4..90346fcee 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleBenefit.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleBenefit.java @@ -3,13 +3,12 @@ package com.ghostchu.quickshop.economy; import com.ghostchu.quickshop.api.economy.Benefit; import com.ghostchu.quickshop.common.util.JsonUtil; import com.google.gson.reflect.TypeToken; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SimpleBenefit implements Benefit { private final Map benefits; @@ -27,8 +26,7 @@ public class SimpleBenefit implements Benefit { if (StringUtils.isEmpty(json)) { return new SimpleBenefit(); } - Map map = JsonUtil.regular().fromJson(json, new TypeToken>() { - }.getType()); + Map map = JsonUtil.regular().fromJson(json, new TypeToken>() {}.getType()); return new SimpleBenefit(map); } @@ -51,7 +49,8 @@ public class SimpleBenefit implements Benefit { } @Override - public void addBenefit(@NotNull UUID player, double benefit) throws BenefitOverflowException, BenefitExistsException { + public void addBenefit(@NotNull UUID player, double benefit) + throws BenefitOverflowException, BenefitExistsException { double overflow = getOverflow(benefit); if (overflow != 0) { throw new BenefitOverflowException(overflow); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleEconomyTransaction.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleEconomyTransaction.java index 7f83d80d0..c3eac43eb 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleEconomyTransaction.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/economy/SimpleEconomyTransaction.java @@ -12,15 +12,14 @@ import com.ghostchu.quickshop.common.util.CalculateUtil; import com.ghostchu.quickshop.common.util.JsonUtil; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.performance.PerfMonitor; +import java.util.*; +import java.util.logging.Level; import lombok.Builder; import lombok.ToString; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.logging.Level; - /** * Transaction * A secure way to transfer the money between players. @@ -30,29 +29,38 @@ import java.util.logging.Level; public class SimpleEconomyTransaction implements EconomyTransaction { @JsonUtil.Hidden private final QuickShop plugin = QuickShop.getInstance(); + private final Deque processingStack = new LinkedList<>(); + @Nullable private Object from; + @Nullable private Object to; + private double amount; + @NotNull @JsonUtil.Hidden private EconomyCore core; + private double amountAfterTax; private double tax; + @Nullable private Object taxer; + private boolean allowLoan; private World world; + @Nullable private String currency; + @Nullable private String lastError = null; private Benefit benefit; - /** * Create a transaction * @@ -64,27 +72,38 @@ public class SimpleEconomyTransaction implements EconomyTransaction { * @param taxAccount tax account * @param taxModifier tax modifier */ - @Builder - public SimpleEconomyTransaction(@Nullable Object from, @Nullable Object to, double amount, double taxModifier, @Nullable Object taxAccount, EconomyCore core, Boolean allowLoan, @NotNull World world, @Nullable String currency, boolean neverFail, @Nullable Benefit benefit) { + public SimpleEconomyTransaction( + @Nullable Object from, + @Nullable Object to, + double amount, + double taxModifier, + @Nullable Object taxAccount, + EconomyCore core, + Boolean allowLoan, + @NotNull World world, + @Nullable String currency, + boolean neverFail, + @Nullable Benefit benefit) { this.from = from; this.to = to; this.core = core == null ? QuickShop.getInstance().getEconomy() : core; this.amount = amount; this.taxer = taxAccount; - this.allowLoan = Objects.requireNonNullElseGet(allowLoan, () -> plugin.getConfig().getBoolean("shop.allow-economy-loan", false)); + this.allowLoan = Objects.requireNonNullElseGet( + allowLoan, () -> plugin.getConfig().getBoolean("shop.allow-economy-loan", false)); this.world = world; this.currency = currency; this.benefit = benefit; if (this.benefit == null) { this.benefit = new SimpleBenefit(); } - if (Double.doubleToLongBits(taxModifier) != Double.doubleToLongBits(0.0d)) { //Calc total money and apply tax + if (Double.doubleToLongBits(taxModifier) != Double.doubleToLongBits(0.0d)) { // Calc total money and apply tax this.amountAfterTax = CalculateUtil.multiply(CalculateUtil.subtract(1, taxModifier), amount); } else { this.amountAfterTax = amount; } - this.tax = CalculateUtil.subtract(amount, amountAfterTax); //Calc total tax + this.tax = CalculateUtil.subtract(amount, amountAfterTax); // Calc total tax if (from == null && to == null) { lastError = "From and To cannot be null in same time."; throw new IllegalArgumentException("From and To cannot be null in same time."); @@ -111,7 +130,10 @@ public class SimpleEconomyTransaction implements EconomyTransaction { * @param economyTransaction Transaction */ default void onFailed(@NotNull SimpleEconomyTransaction economyTransaction) { - Log.transaction(Level.WARNING, "Transaction failed: " + economyTransaction.getLastError() + ", transaction: " + economyTransaction); + Log.transaction( + Level.WARNING, + "Transaction failed: " + economyTransaction.getLastError() + ", transaction: " + + economyTransaction); } /** @@ -131,9 +153,11 @@ public class SimpleEconomyTransaction implements EconomyTransaction { * @param economyTransaction Transaction */ default void onTaxFailed(@NotNull SimpleEconomyTransaction economyTransaction) { - Log.transaction(Level.WARNING, "Tax Transaction failed: " + economyTransaction.getLastError() + ", transaction: " + economyTransaction); + Log.transaction( + Level.WARNING, + "Tax Transaction failed: " + economyTransaction.getLastError() + ", transaction: " + + economyTransaction); } - } /** @@ -159,7 +183,8 @@ public class SimpleEconomyTransaction implements EconomyTransaction { */ @Override public boolean commit(@NotNull TransactionCallback callback) { - Log.transaction("Transaction begin: Regular Commit --> " + from + " => " + to + "; Amount: " + amount + " Total(after tax): " + amountAfterTax + " Tax: " + tax + ", EconomyCore: " + core.getName()); + Log.transaction("Transaction begin: Regular Commit --> " + from + " => " + to + "; Amount: " + amount + + " Total(after tax): " + amountAfterTax + " Tax: " + tax + ", EconomyCore: " + core.getName()); if (!callback.onCommit(this)) { this.lastError = "Plugin cancelled this transaction."; return false; @@ -170,13 +195,16 @@ public class SimpleEconomyTransaction implements EconomyTransaction { return false; } if (from != null && !this.executeOperation(new WithdrawEconomyOperation(from, amount, world, currency, core))) { - this.lastError = "Failed to withdraw " + amount + " from player " + from + " account. LastError: " + core.getLastError(); + this.lastError = "Failed to withdraw " + amount + " from player " + from + " account. LastError: " + + core.getLastError(); callback.onFailed(this); return false; } if (benefit.isEmpty()) { - if (to != null && !this.executeOperation(new DepositEconomyOperation(to, amountAfterTax, world, currency, core))) { - this.lastError = "Failed to deposit " + amountAfterTax + " to player " + to + " account. LastError: " + core.getLastError(); + if (to != null + && !this.executeOperation(new DepositEconomyOperation(to, amountAfterTax, world, currency, core))) { + this.lastError = "Failed to deposit " + amountAfterTax + " to player " + to + " account. LastError: " + + core.getLastError(); callback.onFailed(this); return false; } @@ -187,9 +215,12 @@ public class SimpleEconomyTransaction implements EconomyTransaction { double payout = 0d; for (Map.Entry entry : benefit.getRegistry().entrySet()) { payout += entry.getValue(); - Log.transaction("Benefit for " + entry.getKey() + ", value: " + entry.getValue() + ". Payout = " + payout); - if (!this.executeOperation(new DepositEconomyOperation(entry.getKey(), amountAfterTax * entry.getValue(), world, currency, core))) { - this.lastError = "Failed to deposit " + amountAfterTax * entry.getValue() + " to player " + to + " account. LastError: " + core.getLastError(); + Log.transaction( + "Benefit for " + entry.getKey() + ", value: " + entry.getValue() + ". Payout = " + payout); + if (!this.executeOperation(new DepositEconomyOperation( + entry.getKey(), amountAfterTax * entry.getValue(), world, currency, core))) { + this.lastError = "Failed to deposit " + amountAfterTax * entry.getValue() + " to player " + to + + " account. LastError: " + core.getLastError(); callback.onFailed(this); return false; } @@ -197,23 +228,27 @@ public class SimpleEconomyTransaction implements EconomyTransaction { double ownerCanGet = CalculateUtil.multiply(amountAfterTax, (1 - payout)); Log.transaction("Benefit for owner remaining: " + ownerCanGet); if (ownerCanGet > 0) { - if (to != null && !this.executeOperation(new DepositEconomyOperation(to, ownerCanGet, world, currency, core))) { - this.lastError = "Failed to deposit " + ownerCanGet + " to player " + to + " account. LastError: " + core.getLastError(); + if (to != null + && !this.executeOperation( + new DepositEconomyOperation(to, ownerCanGet, world, currency, core))) { + this.lastError = "Failed to deposit " + ownerCanGet + " to player " + to + " account. LastError: " + + core.getLastError(); callback.onFailed(this); return false; } } callback.onSuccess(this); } - if (tax > 0 && taxer != null && !this.executeOperation(new DepositEconomyOperation(taxer, tax, world, currency, core))) { + if (tax > 0 + && taxer != null + && !this.executeOperation(new DepositEconomyOperation(taxer, tax, world, currency, core))) { this.lastError = "Failed to deposit tax account: " + tax + ". LastError: " + core.getLastError(); callback.onTaxFailed(this); - //Tax never should failed. + // Tax never should failed. } return true; } - @Override public void setFrom(@Nullable Object from) { this.from = from; @@ -319,7 +354,8 @@ public class SimpleEconomyTransaction implements EconomyTransaction { */ @Override public boolean failSafeCommit() { - Log.transaction("Transaction begin: FailSafe Commit --> " + from + " => " + to + "; Amount: " + amount + ", EconomyCore: " + core.getName()); + Log.transaction("Transaction begin: FailSafe Commit --> " + from + " => " + to + "; Amount: " + amount + + ", EconomyCore: " + core.getName()); boolean result = commit(); if (!result) { Log.transaction(Level.WARNING, "Fail-safe commit failed, starting rollback: " + lastError); @@ -338,8 +374,7 @@ public class SimpleEconomyTransaction implements EconomyTransaction { try (PerfMonitor ignored = new PerfMonitor("Economy Transaction - Commit")) { return this.commit(new SimpleTransactionCallback() { @Override - public void onSuccess(@NotNull SimpleEconomyTransaction economyTransaction) { - } + public void onSuccess(@NotNull SimpleEconomyTransaction economyTransaction) {} }); } } @@ -393,9 +428,19 @@ public class SimpleEconomyTransaction implements EconomyTransaction { } catch (Exception exception) { if (continueWhenFailed) { operations.add(operation); - plugin.logger().warn("Failed to rollback transaction: {}; Operation: {}; Transaction: {}; Skipping...", core.getLastError(), operation, this); + plugin.logger() + .warn( + "Failed to rollback transaction: {}; Operation: {}; Transaction: {}; Skipping...", + core.getLastError(), + operation, + this); } else { - plugin.logger().warn("Failed to rollback transaction: {}; Operation: {}; Transaction: {}", core.getLastError(), operation, this); + plugin.logger() + .warn( + "Failed to rollback transaction: {}; Operation: {}; Transaction: {}", + core.getLastError(), + operation, + this); break; } } @@ -419,11 +464,14 @@ public class SimpleEconomyTransaction implements EconomyTransaction { processingStack.push(operation); return true; } catch (Exception exception) { - plugin.logger().warn("Failed to execute operation: {}; Operation: {}; Transaction: {}", core.getLastError(), operation, this); + plugin.logger() + .warn( + "Failed to execute operation: {}; Operation: {}; Transaction: {}", + core.getLastError(), + operation, + this); this.lastError = "Failed to execute operation: " + core.getLastError() + "; Operation: " + operation; return false; } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/BukkitEventManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/BukkitEventManager.java index dcab5374d..800fafde9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/BukkitEventManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/BukkitEventManager.java @@ -1,13 +1,12 @@ package com.ghostchu.quickshop.eventmanager; import com.ghostchu.quickshop.api.eventmanager.QuickEventManager; +import java.util.function.Consumer; import org.bukkit.Bukkit; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; - /** * A simple impl for Bukkit original EventManager * diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/QSEventManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/QSEventManager.java index 206c93366..6d6b00f4a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/QSEventManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/eventmanager/QSEventManager.java @@ -6,6 +6,10 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.logging.Level; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.event.*; @@ -18,11 +22,6 @@ import org.bukkit.plugin.RegisteredListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; -import java.util.logging.Level; - public class QSEventManager implements QuickEventManager, Listener, Reloadable { private final QuickShop plugin; private final List ignoredListener = new ArrayList<>(); @@ -35,23 +34,21 @@ public class QSEventManager implements QuickEventManager, Listener, Reloadable { private synchronized void rescan() { this.ignoredListener.clear(); - plugin - .getConfig() + plugin.getConfig() .getStringList("shop.protection-checking-listener-blacklist") - .forEach( - input -> { - if (StringUtils.isEmpty(input)) { - return; - } - try { - Class clazz = Class.forName(input); - this.ignoredListener.add(new ListenerContainer(clazz, input)); - Log.debug("Successfully added blacklist: [BINDING] " + clazz.getName()); - } catch (Exception ignored) { - this.ignoredListener.add(new ListenerContainer(null, input)); - Log.debug("Successfully added blacklist: [DYNAMIC] " + input); - } - }); + .forEach(input -> { + if (StringUtils.isEmpty(input)) { + return; + } + try { + Class clazz = Class.forName(input); + this.ignoredListener.add(new ListenerContainer(clazz, input)); + Log.debug("Successfully added blacklist: [BINDING] " + clazz.getName()); + } catch (Exception ignored) { + this.ignoredListener.add(new ListenerContainer(null, input)); + Log.debug("Successfully added blacklist: [DYNAMIC] " + input); + } + }); } @Override @@ -59,13 +56,11 @@ public class QSEventManager implements QuickEventManager, Listener, Reloadable { if (event.isAsynchronous()) { if (Thread.holdsLock(Bukkit.getPluginManager())) { throw new IllegalStateException( - event.getEventName() - + " cannot be triggered asynchronously from inside synchronized code."); + event.getEventName() + " cannot be triggered asynchronously from inside synchronized code."); } if (Bukkit.getServer().isPrimaryThread()) { throw new IllegalStateException( - event.getEventName() - + " cannot be triggered asynchronously from primary server thread."); + event.getEventName() + " cannot be triggered asynchronously from primary server thread."); } } else { if (!Bukkit.getServer().isPrimaryThread()) { @@ -75,8 +70,7 @@ public class QSEventManager implements QuickEventManager, Listener, Reloadable { } if (callBeforePassToMonitor == null) { - callBeforePassToMonitor = empty -> { - }; + callBeforePassToMonitor = empty -> {}; } fireEvent(event, callBeforePassToMonitor); @@ -124,14 +118,16 @@ public class QSEventManager implements QuickEventManager, Listener, Reloadable { ex.getMessage())); } } catch (Throwable ex) { - Bukkit - .getLogger() + Bukkit.getLogger() .log( Level.SEVERE, "Could not pass event " + event.getEventName() + " to " - + registration.getPlugin().getDescription().getFullName(), + + registration + .getPlugin() + .getDescription() + .getFullName(), ex); } } @@ -162,6 +158,7 @@ public class QSEventManager implements QuickEventManager, Listener, Reloadable { class ListenerContainer { @Nullable private final Class clazz; + @NotNull private final String clazzName; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/AbstractProtectionListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/AbstractProtectionListener.java index c57b4ed46..e4db479f2 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/AbstractProtectionListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/AbstractProtectionListener.java @@ -29,7 +29,9 @@ public abstract class AbstractProtectionListener extends AbstractQSListener { */ @Nullable public Shop getShopNature(@NotNull Location location, boolean includeAttached) { - return includeAttached ? plugin.getShopManager().getShopIncludeAttached(location) : plugin.getShopManager().getShop(location); + return includeAttached + ? plugin.getShopManager().getShopIncludeAttached(location) + : plugin.getShopManager().getShop(location); } /** @@ -41,7 +43,9 @@ public abstract class AbstractProtectionListener extends AbstractQSListener { */ @Nullable public Shop getShopPlayer(@NotNull Location location, boolean includeAttached) { - return includeAttached ? plugin.getShopManager().getShopIncludeAttached(location) : plugin.getShopManager().getShop(location); + return includeAttached + ? plugin.getShopManager().getShopIncludeAttached(location) + : plugin.getShopManager().getShop(location); } /** @@ -58,7 +62,5 @@ public abstract class AbstractProtectionListener extends AbstractQSListener { } else { return plugin.getShopManager().getShopViaCache(location); } - } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BlockListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BlockListener.java index 7c6727252..55c3c1be6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BlockListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BlockListener.java @@ -44,7 +44,8 @@ public class BlockListener extends AbstractProtectionListener { } private void init() { - this.updateSignWhenInventoryMoving = super.getPlugin().getConfig().getBoolean("shop.update-sign-when-inventory-moving", true); + this.updateSignWhenInventoryMoving = + super.getPlugin().getConfig().getBoolean("shop.update-sign-when-inventory-moving", true); } /* @@ -62,7 +63,8 @@ public class BlockListener extends AbstractProtectionListener { } // If they're either survival or the owner, they can break it if (p.getGameMode() == GameMode.CREATIVE - && (shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.DELETE) || plugin.perm().hasPermission(p, "quickshop.other.destory"))) { + && (shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.DELETE) + || plugin.perm().hasPermission(p, "quickshop.other.destory"))) { // Check SuperTool if (p.getInventory().getItemInMainHand().getType() == Material.GOLDEN_AXE) { if (getPlugin().getConfig().getBoolean("shop.disable-super-tool")) { @@ -80,12 +82,14 @@ public class BlockListener extends AbstractProtectionListener { } // Cancel their current menu... Doesnt cancel other's menu's. - final Info action = super.getPlugin().getShopManager().getInteractiveManager().get(p.getUniqueId()); + final Info action = + super.getPlugin().getShopManager().getInteractiveManager().get(p.getUniqueId()); if (action != null) { action.setAction(ShopAction.CANCELLED); } - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(p), "BlockBreak(player)", shop.saveToInfoStorage())); + plugin.logEvent( + new ShopRemoveLog(QUserImpl.createFullFilled(p), "BlockBreak(player)", shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); plugin.text().of(p, "success-removed-shop").send(); } else if (Util.isWallSign(b.getType())) { @@ -97,7 +101,7 @@ public class BlockListener extends AbstractProtectionListener { // (accidents happen) if (p.getGameMode() == GameMode.CREATIVE && (shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.DELETE) - || plugin.perm().hasPermission(p, "quickshop.other.destory"))) { + || plugin.perm().hasPermission(p, "quickshop.other.destory"))) { // Check SuperTool if (p.getInventory().getItemInMainHand().getType() == Material.GOLDEN_AXE) { if (getPlugin().getConfig().getBoolean("shop.disable-super-tool")) { @@ -106,7 +110,8 @@ public class BlockListener extends AbstractProtectionListener { return; } plugin.text().of(p, "break-shop-use-supertool").send(); - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(p), "BlockBreak(player)", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(p), "BlockBreak(player)", shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); return; } @@ -115,8 +120,9 @@ public class BlockListener extends AbstractProtectionListener { plugin.text().of(p, "no-creative-break", component).send(); return; } - //Allow Shop owner break the shop sign(for sign replacement) - if (getPlugin().getConfig().getBoolean("shop.allow-owner-break-shop-sign") && p.getUniqueId().equals(shop.getOwner().getUniqueId())) { + // Allow Shop owner break the shop sign(for sign replacement) + if (getPlugin().getConfig().getBoolean("shop.allow-owner-break-shop-sign") + && p.getUniqueId().equals(shop.getOwner().getUniqueId())) { return; } Log.debug("Player cannot break the shop information sign."); @@ -180,31 +186,34 @@ public class BlockListener extends AbstractProtectionListener { } Block chest = null; - //Chest combine mechanic based checking + // Chest combine mechanic based checking if (player.isSneaking()) { Block blockAgainst = e.getBlockAgainst(); - if (blockAgainst.getType() == Material.CHEST && placingBlock.getFace(blockAgainst) != BlockFace.UP && placingBlock.getFace(blockAgainst) != BlockFace.DOWN && !Util.isDoubleChest(blockAgainst.getBlockData())) { + if (blockAgainst.getType() == Material.CHEST + && placingBlock.getFace(blockAgainst) != BlockFace.UP + && placingBlock.getFace(blockAgainst) != BlockFace.DOWN + && !Util.isDoubleChest(blockAgainst.getBlockData())) { chest = e.getBlockAgainst(); } else { return; } } else { - //Get all chest in vertical Location + // Get all chest in vertical Location BlockFace placingChestFacing = ((Directional) (placingBlock.getBlockData())).getFacing(); for (BlockFace face : Util.getVerticalFacing()) { - //just check the right side and left side + // just check the right side and left side if (!face.equals(placingChestFacing) && !face.equals(placingChestFacing.getOppositeFace())) { Block nearByBlock = placingBlock.getRelative(face); BlockData nearByBlockData = nearByBlock.getBlockData(); if (nearByBlock.getType() == Material.CHEST - //non double chest + // non double chest && !Util.isDoubleChest(nearByBlockData) - //same facing + // same facing && placingChestFacing == ((Directional) nearByBlockData).getFacing()) { if (chest == null) { chest = nearByBlock; } else { - //when multiply chests competed, minecraft will always combine with right side + // when multiply chests competed, minecraft will always combine with right side if (placingBlock.getFace(nearByBlock) == Util.getRightSide(placingChestFacing)) { chest = nearByBlock; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BungeeListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BungeeListener.java index 3f3b717bb..238be3f47 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BungeeListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/BungeeListener.java @@ -76,7 +76,8 @@ public class BungeeListener extends AbstractQSListener implements PluginMessageL return; } String chatMessage = in.readUTF(); - Log.debug("Handling the plugin channel " + channel + " with sub channel " + subChannel + " on player " + player.getName() + " for message: " + chatMessage); + Log.debug("Handling the plugin channel " + channel + " with sub channel " + subChannel + " on player " + + player.getName() + " for message: " + chatMessage); plugin.getShopManager().handleChat(player, chatMessage); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChatListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChatListener.java index 123fa3e30..f7d33e922 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChatListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChatListener.java @@ -5,13 +5,12 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.performance.PerfMonitor; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.time.Duration; +import java.time.temporal.ChronoUnit; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; -import java.time.Duration; -import java.time.temporal.ChronoUnit; - /** * @author Netherfoam */ @@ -24,11 +23,14 @@ public class ChatListener extends AbstractQSListener { @EventHandler(priority = EventPriority.LOWEST) public void onChat(AsyncPlayerChatEvent e) { if (e.isCancelled() && plugin.getConfig().getBoolean("shop.ignore-cancel-chat-event")) { - Log.debug("Ignored a chat event (Cancelled by another plugin, you can force process by turn on ignore-cancel-chat-event)"); + Log.debug( + "Ignored a chat event (Cancelled by another plugin, you can force process by turn on ignore-cancel-chat-event)"); return; } - if (!plugin.getShopManager().getInteractiveManager().containsKey(e.getPlayer().getUniqueId())) { + if (!plugin.getShopManager() + .getInteractiveManager() + .containsKey(e.getPlayer().getUniqueId())) { return; } try (PerfMonitor ignored = new PerfMonitor("HandleChat", Duration.of(3, ChronoUnit.SECONDS))) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChunkListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChunkListener.java index bcdebe5d7..f6407a38e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChunkListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ChunkListener.java @@ -8,6 +8,9 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.performance.PerfMonitor; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Map; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -17,10 +20,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.Map; - public class ChunkListener extends AbstractQSListener { public ChunkListener(QuickShop plugin) { @@ -37,8 +36,10 @@ public class ChunkListener extends AbstractQSListener { return; } cleanDisplayItems(e.getChunk()); - String chunkName = e.getChunk().getWorld().getName() + ", X=" + e.getChunk().getX() + ", Z=" + e.getChunk().getZ(); - try (PerfMonitor ignored = new PerfMonitor("Load shops in chunk [" + chunkName + "]", Duration.of(500, ChronoUnit.MILLIS))) { + String chunkName = e.getChunk().getWorld().getName() + ", X=" + + e.getChunk().getX() + ", Z=" + e.getChunk().getZ(); + try (PerfMonitor ignored = + new PerfMonitor("Load shops in chunk [" + chunkName + "]", Duration.of(500, ChronoUnit.MILLIS))) { for (Shop shop : inChunk.values()) { plugin.getShopManager().loadShop(shop); } @@ -53,7 +54,8 @@ public class ChunkListener extends AbstractQSListener { if (entity instanceof Item itemEntity) { if (AbstractDisplayItem.checkIsGuardItemStack(itemEntity.getItemStack())) { itemEntity.remove(); - Log.debug("Removed shop display item at " + itemEntity.getLocation() + " while chunk loading, pending for regenerate."); + Log.debug("Removed shop display item at " + itemEntity.getLocation() + + " while chunk loading, pending for regenerate."); } } } @@ -66,7 +68,8 @@ public class ChunkListener extends AbstractQSListener { return; } for (Shop shop : inChunk.values()) { - try (PerfMonitor ignored = new PerfMonitor("Unload shops in chunk " + e.getChunk(), Duration.of(500, ChronoUnit.MILLIS))) { + try (PerfMonitor ignored = + new PerfMonitor("Unload shops in chunk " + e.getChunk(), Duration.of(500, ChronoUnit.MILLIS))) { if (shop.isLoaded()) { plugin.getShopManager().unloadShop(shop); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/DisplayProtectionListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/DisplayProtectionListener.java index 93665d01b..19935070b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/DisplayProtectionListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/DisplayProtectionListener.java @@ -46,12 +46,11 @@ public class DisplayProtectionListener extends AbstractProtectionListener { @Nullable Location loc = event.getInventory().getLocation(); @Nullable InventoryHolder holder = event.getInventory().getHolder(); event.setCancelled(true); - sendAlert( - "[DisplayGuard] Something " - + holder - + " at " - + loc - + " trying pickup the DisplayItem, you should teleport to that location and to check detail.."); + sendAlert("[DisplayGuard] Something " + + holder + + " at " + + loc + + " trying pickup the DisplayItem, you should teleport to that location and to check detail.."); Util.inventoryCheck(new BukkitInventoryWrapper(event.getInventory())); } @@ -94,10 +93,9 @@ public class DisplayProtectionListener extends AbstractProtectionListener { } event.getHook().remove(); event.setCancelled(true); - sendAlert( - "[DisplayGuard] Player " - + event.getPlayer().getName() - + " trying hook item use Fishing Rod, QuickShop already removed it."); + sendAlert("[DisplayGuard] Player " + + event.getPlayer().getName() + + " trying hook item use Fishing Rod, QuickShop already removed it."); Util.inventoryCheck(new BukkitInventoryWrapper(event.getPlayer().getInventory())); } @@ -111,10 +109,9 @@ public class DisplayProtectionListener extends AbstractProtectionListener { } event.setCancelled(true); Util.inventoryCheck(new BukkitInventoryWrapper(event.getPlayer().getInventory())); - sendAlert( - "[DisplayGuard] Player " - + event.getPlayer().getName() - + " trying mainipulate armorstand contains displayItem."); + sendAlert("[DisplayGuard] Player " + + event.getPlayer().getName() + + " trying mainipulate armorstand contains displayItem."); } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @@ -128,10 +125,9 @@ public class DisplayProtectionListener extends AbstractProtectionListener { if (AbstractDisplayItem.checkIsGuardItemStack(itemEntity.getItemStack())) { event.setCancelled(true); event.getEntity().remove(); - sendAlert( - "[DisplayGuard] Somebody want dupe the display by Portal at " - + event.getFrom() - + " , QuickShop already cancel it."); + sendAlert("[DisplayGuard] Somebody want dupe the display by Portal at " + + event.getFrom() + + " , QuickShop already cancel it."); } } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/InternalListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/InternalListener.java index 3234ade1a..68c02c040 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/InternalListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/InternalListener.java @@ -13,20 +13,17 @@ import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; +import java.util.Objects; +import java.util.concurrent.TimeUnit; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.jetbrains.annotations.NotNull; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - - public class InternalListener extends AbstractQSListener { private final QuickShop plugin; - private final Cache countUpdateCache = CacheBuilder - .newBuilder() + private final Cache countUpdateCache = CacheBuilder.newBuilder() .weakKeys() .expireAfterAccess(5, TimeUnit.MINUTES) .maximumSize(100) @@ -59,12 +56,21 @@ public class InternalListener extends AbstractQSListener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void shopCreate(ShopCreateEvent event) { - if (isForbidden(event.getShop().getLocation().getBlock().getType(), event.getShop().getItem().getType())) { - event.setCancelled(true, plugin.text().of(event.getCreator(), "forbidden-vanilla-behavior").forLocale()); + if (isForbidden( + event.getShop().getLocation().getBlock().getType(), + event.getShop().getItem().getType())) { + event.setCancelled( + true, + plugin.text() + .of(event.getCreator(), "forbidden-vanilla-behavior") + .forLocale()); return; } if (loggingAction) { - plugin.logEvent(new ShopCreationLog(event.getCreator(), event.getShop().saveToInfoStorage(), new BlockPos(event.getShop().getLocation()))); + plugin.logEvent(new ShopCreationLog( + event.getCreator(), + event.getShop().saveToInfoStorage(), + new BlockPos(event.getShop().getLocation()))); } } @@ -78,7 +84,10 @@ public class InternalListener extends AbstractQSListener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void shopDelete(ShopDeleteEvent event) { if (loggingAction) { - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "Shop removed", event.getShop().saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "Shop removed", + event.getShop().saveToInfoStorage())); } } @@ -92,47 +101,86 @@ public class InternalListener extends AbstractQSListener { return; } countUpdateCache.put(event.getShop(), new SpaceCache(event.getSpace(), event.getStock())); - plugin.getDatabaseHelper().updateExternalInventoryProfileCache(event.getShop().getShopId(), event.getSpace(), event.getStock()) + plugin.getDatabaseHelper() + .updateExternalInventoryProfileCache(event.getShop().getShopId(), event.getSpace(), event.getStock()) .exceptionally(err -> { - Log.debug("Error updating external inventory profile cache for shop " + event.getShop().getShopId() + ": " + err.getMessage()); + Log.debug("Error updating external inventory profile cache for shop " + + event.getShop().getShopId() + ": " + err.getMessage()); return 0; }); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void shopPrePurchase(ShopPurchaseEvent event) { - if (isForbidden(event.getShop().getLocation().getBlock().getType(), event.getShop().getItem().getType())) { - event.setCancelled(true, plugin.text().of(event.getPurchaser(), "forbidden-vanilla-behavior").forLocale()); + if (isForbidden( + event.getShop().getLocation().getBlock().getType(), + event.getShop().getItem().getType())) { + event.setCancelled( + true, + plugin.text() + .of(event.getPurchaser(), "forbidden-vanilla-behavior") + .forLocale()); return; } if (loggingBalance) { - plugin.logEvent(new PlayerEconomyPreCheckLog(true, event.getPurchaser(), plugin.getEconomy().getBalance(event.getPurchaser(), event.getShop().getLocation().getWorld(), event.getShop().getCurrency()))); - plugin.logEvent(new PlayerEconomyPreCheckLog(true, event.getShop().getOwner(), plugin.getEconomy().getBalance(event.getShop().getOwner(), event.getShop().getLocation().getWorld(), event.getShop().getCurrency()))); + plugin.logEvent(new PlayerEconomyPreCheckLog( + true, + event.getPurchaser(), + plugin.getEconomy() + .getBalance( + event.getPurchaser(), + event.getShop().getLocation().getWorld(), + event.getShop().getCurrency()))); + plugin.logEvent(new PlayerEconomyPreCheckLog( + true, + event.getShop().getOwner(), + plugin.getEconomy() + .getBalance( + event.getShop().getOwner(), + event.getShop().getLocation().getWorld(), + event.getShop().getCurrency()))); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void shopPriceChanges(ShopPriceChangeEvent event) { if (loggingAction) { - plugin.logEvent(new ShopPriceChangedLog(event.getShop().saveToInfoStorage(), event.getOldPrice(), event.getNewPrice())); + plugin.logEvent(new ShopPriceChangedLog( + event.getShop().saveToInfoStorage(), event.getOldPrice(), event.getNewPrice())); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void shopPurchase(ShopSuccessPurchaseEvent event) { if (loggingAction) { - plugin.logEvent(new ShopPurchaseLog(event.getShop().saveToInfoStorage(), + plugin.logEvent(new ShopPurchaseLog( + event.getShop().saveToInfoStorage(), event.getShop().getShopType(), event.getPurchaser(), - LegacyComponentSerializer.legacySection().serialize(Util.getItemStackName(event.getShop().getItem())), + LegacyComponentSerializer.legacySection() + .serialize(Util.getItemStackName(event.getShop().getItem())), Util.serialize(event.getShop().getItem()), event.getAmount(), event.getBalance(), event.getTax())); } if (loggingBalance) { - plugin.logEvent(new PlayerEconomyPreCheckLog(false, event.getPurchaser(), plugin.getEconomy().getBalance(event.getPurchaser(), event.getShop().getLocation().getWorld(), event.getShop().getCurrency()))); - plugin.logEvent(new PlayerEconomyPreCheckLog(false, event.getShop().getOwner(), plugin.getEconomy().getBalance(event.getShop().getOwner(), event.getShop().getLocation().getWorld(), event.getShop().getCurrency()))); + plugin.logEvent(new PlayerEconomyPreCheckLog( + false, + event.getPurchaser(), + plugin.getEconomy() + .getBalance( + event.getPurchaser(), + event.getShop().getLocation().getWorld(), + event.getShop().getCurrency()))); + plugin.logEvent(new PlayerEconomyPreCheckLog( + false, + event.getShop().getOwner(), + plugin.getEconomy() + .getBalance( + event.getShop().getOwner(), + event.getShop().getLocation().getWorld(), + event.getShop().getCurrency()))); } if (event.getPurchaser().equals(event.getShop().getOwner())) { plugin.text().of(event.getPurchaser(), "shop-owner-self-trade").send(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/LockListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/LockListener.java index e85453527..e01cce1b2 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/LockListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/LockListener.java @@ -7,6 +7,8 @@ import com.ghostchu.quickshop.util.Util; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.google.common.cache.CacheBuilder; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; @@ -19,14 +21,10 @@ import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.jetbrains.annotations.NotNull; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - public class LockListener extends AbstractProtectionListener { private static final Object EMPTY_OBJECT = new Object(); - private final com.google.common.cache.Cache lockCoolDown = CacheBuilder.newBuilder() - .expireAfterAccess(1, TimeUnit.SECONDS) - .build(); + private final com.google.common.cache.Cache lockCoolDown = + CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.SECONDS).build(); public LockListener(@NotNull final QuickShop plugin) { super(plugin); @@ -186,5 +184,4 @@ public class LockListener extends AbstractProtectionListener { super.unregister(); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/PlayerListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/PlayerListener.java index 22f80f107..2331bc645 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/PlayerListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/PlayerListener.java @@ -22,6 +22,13 @@ import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.AbstractMap; +import java.util.Date; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.*; import org.bukkit.block.Block; @@ -43,14 +50,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.AbstractMap; -import java.util.Date; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - public class PlayerListener extends AbstractQSListener { private final ExpiringSet adventureWorkaround = new ExpiringSet<>(1, TimeUnit.SECONDS); private final ExpiringSet rateLimit = new ExpiringSet<>(125, TimeUnit.MILLISECONDS); @@ -72,8 +71,8 @@ public class PlayerListener extends AbstractQSListener { // ----Adventure dupe click workaround end---- Block focused = event.getPlayer().getTargetBlockExact(5); if (focused != null) { - PlayerInteractEvent interactEvent - = new PlayerInteractEvent(event.getPlayer(), + PlayerInteractEvent interactEvent = new PlayerInteractEvent( + event.getPlayer(), focused.getType() == Material.AIR ? Action.LEFT_CLICK_AIR : Action.LEFT_CLICK_BLOCK, event.getPlayer().getInventory().getItemInMainHand(), focused, @@ -97,7 +96,8 @@ public class PlayerListener extends AbstractQSListener { } // ----Adventure dupe click workaround end---- if (rateLimit.contains(e.getPlayer().getUniqueId())) { - Log.debug("Player " + e.getPlayer().getName() + " click the blocks too fast and reached the rate limit, ignoring the event..."); + Log.debug("Player " + e.getPlayer().getName() + + " click the blocks too fast and reached the rate limit, ignoring the event..."); return; } rateLimit.add(e.getPlayer().getUniqueId()); @@ -111,15 +111,23 @@ public class PlayerListener extends AbstractQSListener { InteractionController.Interaction interaction = null; if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { if (e.getPlayer().isSneaking()) { - interaction = shopSearched.getValue() == ClickType.SIGN ? InteractionController.Interaction.SNEAKING_RIGHT_CLICK_SIGN : InteractionController.Interaction.SNEAKING_RIGHT_CLICK_SHOPBLOCK; + interaction = shopSearched.getValue() == ClickType.SIGN + ? InteractionController.Interaction.SNEAKING_RIGHT_CLICK_SIGN + : InteractionController.Interaction.SNEAKING_RIGHT_CLICK_SHOPBLOCK; } else { - interaction = shopSearched.getValue() == ClickType.SIGN ? InteractionController.Interaction.STANDING_RIGHT_CLICK_SIGN : InteractionController.Interaction.STANDING_RIGHT_CLICK_SHOPBLOCK; + interaction = shopSearched.getValue() == ClickType.SIGN + ? InteractionController.Interaction.STANDING_RIGHT_CLICK_SIGN + : InteractionController.Interaction.STANDING_RIGHT_CLICK_SHOPBLOCK; } } else if (e.getAction() == Action.LEFT_CLICK_BLOCK) { if (e.getPlayer().isSneaking()) { - interaction = shopSearched.getValue() == ClickType.SIGN ? InteractionController.Interaction.SNEAKING_LEFT_CLICK_SIGN : InteractionController.Interaction.SNEAKING_LEFT_CLICK_SHOPBLOCK; + interaction = shopSearched.getValue() == ClickType.SIGN + ? InteractionController.Interaction.SNEAKING_LEFT_CLICK_SIGN + : InteractionController.Interaction.SNEAKING_LEFT_CLICK_SHOPBLOCK; } else { - interaction = shopSearched.getValue() == ClickType.SIGN ? InteractionController.Interaction.STANDING_LEFT_CLICK_SIGN : InteractionController.Interaction.STANDING_LEFT_CLICK_SHOPBLOCK; + interaction = shopSearched.getValue() == ClickType.SIGN + ? InteractionController.Interaction.STANDING_LEFT_CLICK_SIGN + : InteractionController.Interaction.STANDING_LEFT_CLICK_SHOPBLOCK; } } if (interaction == null) { @@ -127,7 +135,8 @@ public class PlayerListener extends AbstractQSListener { } if (Util.isDevMode()) { Log.debug("Click: " + interaction.name()); - Log.debug("Behavior Mapping: " + plugin.getInteractionController().getBehavior(interaction).name()); + Log.debug("Behavior Mapping: " + + plugin.getInteractionController().getBehavior(interaction).name()); } switch (plugin.getInteractionController().getBehavior(interaction)) { case CONTROL_PANEL -> { @@ -140,7 +149,9 @@ public class PlayerListener extends AbstractQSListener { } case TRADE_INTERACTION -> { if (shopSearched.getKey() == null) { - if (e.getItem() != null && createShop(e.getPlayer(), e.getClickedBlock(), e.getBlockFace(), e.getHand(), e.getItem())) { + if (e.getItem() != null + && createShop( + e.getPlayer(), e.getClickedBlock(), e.getBlockFace(), e.getHand(), e.getItem())) { e.setCancelled(true); e.setUseInteractedBlock(Event.Result.DENY); e.setUseItemInHand(Event.Result.DENY); @@ -223,7 +234,8 @@ public class PlayerListener extends AbstractQSListener { attached = Util.getSecondHalf(b); if (attached != null) { Shop secondHalfShop = plugin.getShopManager().getShop(attached.getLocation()); - if (secondHalfShop != null && !p.getUniqueId().equals(secondHalfShop.getOwner().getUniqueId())) { + if (secondHalfShop != null + && !p.getUniqueId().equals(secondHalfShop.getOwner().getUniqueId())) { // If player not the owner of the shop, make him select the second half of the // shop // Otherwise owner will be able to create new double chest shop @@ -242,7 +254,12 @@ public class PlayerListener extends AbstractQSListener { shop.setSignText(plugin.text().findRelativeLanguages(p)); } - public boolean createShop(@NotNull Player player, @Nullable Block block, @NotNull BlockFace blockFace, @NotNull EquipmentSlot hand, @NotNull ItemStack item) { + public boolean createShop( + @NotNull Player player, + @Nullable Block block, + @NotNull BlockFace blockFace, + @NotNull EquipmentSlot hand, + @NotNull ItemStack item) { QUser qUser = QUserImpl.createFullFilled(player); if (block == null) { return false; // This shouldn't happen because we have checked action type. @@ -276,15 +293,16 @@ public class PlayerListener extends AbstractQSListener { return false; } // Double chest creation permission check - if (Util.isDoubleChest(block.getBlockData()) && - !plugin.perm().hasPermission(player, "quickshop.create.double")) { + if (Util.isDoubleChest(block.getBlockData()) + && !plugin.perm().hasPermission(player, "quickshop.create.double")) { plugin.text().of(player, "no-double-chests").send(); return false; } // Blacklist check if (plugin.getShopItemBlackList().isBlacklisted(stack) && !plugin.perm() - .hasPermission(player, "quickshop.bypass." + stack.getType().name())) { + .hasPermission( + player, "quickshop.bypass." + stack.getType().name())) { plugin.text().of(player, "blacklisted-item").send(); return false; } @@ -327,10 +345,15 @@ public class PlayerListener extends AbstractQSListener { return false; } plugin.getShopManager().getInteractiveManager().put(player.getUniqueId(), info); - plugin.text().of(player, "how-much-to-trade-for", Util.getItemStackName(stack), - plugin.isAllowStack() && - plugin.perm().hasPermission(player, "quickshop.create.stacks") - ? stack.getAmount() : 1).send(); + plugin.text() + .of( + player, + "how-much-to-trade-for", + Util.getItemStackName(stack), + plugin.isAllowStack() && plugin.perm().hasPermission(player, "quickshop.create.stacks") + ? stack.getAmount() + : 1) + .send(); return false; } @@ -353,7 +376,8 @@ public class PlayerListener extends AbstractQSListener { final double price = shop.getPrice(); final Inventory playerInventory = p.getInventory(); final String tradeAllWord = plugin.getConfig().getString("shop.word-for-trade-all-items", "all"); - final double ownerBalance = eco.getBalance(shop.getOwner(), shop.getLocation().getWorld(), shop.getCurrency()); + final double ownerBalance = + eco.getBalance(shop.getOwner(), shop.getLocation().getWorld(), shop.getCurrency()); int items = getPlayerCanSell(shop, ownerBalance, price, new BukkitInventoryWrapper(playerInventory)); ShopManager.InteractiveManager actions = plugin.getShopManager().getInteractiveManager(); if (shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.PURCHASE) @@ -362,7 +386,9 @@ public class PlayerListener extends AbstractQSListener { actions.put(p.getUniqueId(), info); if (!direct) { if (shop.isStackingShop()) { - plugin.text().of(p, "how-many-sell-stack", shop.getItem().getAmount(), items, tradeAllWord).send(); + plugin.text() + .of(p, "how-many-sell-stack", shop.getItem().getAmount(), items, tradeAllWord) + .send(); } else { plugin.text().of(p, "how-many-sell", items, tradeAllWord).send(); } @@ -376,7 +402,8 @@ public class PlayerListener extends AbstractQSListener { if (arg == 0) { return true; } - plugin.getShopManager().actionBuying(p, new BukkitInventoryWrapper(p.getInventory()), eco, info, shop, arg); + plugin.getShopManager() + .actionBuying(p, new BukkitInventoryWrapper(p.getInventory()), eco, info, shop, arg); } } return true; @@ -402,7 +429,8 @@ public class PlayerListener extends AbstractQSListener { final Inventory playerInventory = p.getInventory(); final String tradeAllWord = plugin.getConfig().getString("shop.word-for-trade-all-items", "all"); ShopManager.InteractiveManager actions = plugin.getShopManager().getInteractiveManager(); - final double traderBalance = eco.getBalance(p.getUniqueId(), shop.getLocation().getWorld(), shop.getCurrency()); + final double traderBalance = + eco.getBalance(p.getUniqueId(), shop.getLocation().getWorld(), shop.getCurrency()); int itemAmount = getPlayerCanBuy(shop, traderBalance, price, new BukkitInventoryWrapper(playerInventory)); if (shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.PURCHASE) || plugin.perm().hasPermission(p, "quickshop.other.use")) { @@ -410,9 +438,13 @@ public class PlayerListener extends AbstractQSListener { actions.put(p.getUniqueId(), info); if (!direct) { if (shop.isStackingShop()) { - plugin.text().of(p, "how-many-buy-stack", shop.getItem().getAmount(), itemAmount, tradeAllWord).send(); + plugin.text() + .of(p, "how-many-buy-stack", shop.getItem().getAmount(), itemAmount, tradeAllWord) + .send(); } else { - plugin.text().of(p, "how-many-buy", itemAmount, tradeAllWord).send(); + plugin.text() + .of(p, "how-many-buy", itemAmount, tradeAllWord) + .send(); } } else { int arg; @@ -424,7 +456,8 @@ public class PlayerListener extends AbstractQSListener { if (arg == 0) { return true; } - plugin.getShopManager().actionSelling(p, new BukkitInventoryWrapper(p.getInventory()), eco, info, shop, arg); + plugin.getShopManager() + .actionSelling(p, new BukkitInventoryWrapper(p.getInventory()), eco, info, shop, arg); } } return true; @@ -436,10 +469,13 @@ public class PlayerListener extends AbstractQSListener { } } - private int getPlayerCanSell(@NotNull Shop shop, double ownerBalance, double price, @NotNull InventoryWrapper playerInventory) { + private int getPlayerCanSell( + @NotNull Shop shop, double ownerBalance, double price, @NotNull InventoryWrapper playerInventory) { boolean isContainerCountingNeeded = shop.isUnlimited(); if (shop.isFreeShop()) { - return isContainerCountingNeeded ? Util.countItems(playerInventory, shop) : Math.min(shop.getRemainingSpace(), Util.countItems(playerInventory, shop)); + return isContainerCountingNeeded + ? Util.countItems(playerInventory, shop) + : Math.min(shop.getRemainingSpace(), Util.countItems(playerInventory, shop)); } int items = Util.countItems(playerInventory, shop); @@ -463,13 +499,10 @@ public class PlayerListener extends AbstractQSListener { private int buyingShopAllCalc(@NotNull AbstractEconomy eco, @NotNull Shop shop, @NotNull Player p) { int amount; - int shopHaveSpaces = - Util.countSpace(shop.getInventory(), shop); + int shopHaveSpaces = Util.countSpace(shop.getInventory(), shop); int invHaveItems = Util.countItems(new BukkitInventoryWrapper(p.getInventory()), shop); // Check if shop owner has enough money - double ownerBalance = eco - .getBalance(shop.getOwner(), shop.getLocation().getWorld(), - shop.getCurrency()); + double ownerBalance = eco.getBalance(shop.getOwner(), shop.getLocation().getWorld(), shop.getCurrency()); int ownerCanAfford; if (shop.getPrice() != 0) { ownerCanAfford = (int) (ownerBalance / shop.getPrice()); @@ -491,33 +524,45 @@ public class PlayerListener extends AbstractQSListener { if (amount < 1) { // typed 'all' but the auto set amount is 0 if (shopHaveSpaces == 0) { // when typed 'all' but the shop doesn't have any empty space - plugin.text().of(p, "shop-has-no-space", shopHaveSpaces, - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(p, "shop-has-no-space", shopHaveSpaces, Util.getItemStackName(shop.getItem())) + .send(); return 0; } if (ownerCanAfford == 0 - && (!shop.isUnlimited() - || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners"))) { + && (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners"))) { // when typed 'all' but the shop owner doesn't have enough money to buy at least 1 // item (and shop isn't unlimited or pay-unlimited is true) - plugin.text().of(p, "the-owner-cant-afford-to-buy-from-you", - plugin.getShopManager().format(shop.getPrice(), shop.getLocation().getWorld(), - shop.getCurrency()), - plugin.getShopManager().format(ownerBalance, shop.getLocation().getWorld(), - shop.getCurrency())).send(); + plugin.text() + .of( + p, + "the-owner-cant-afford-to-buy-from-you", + plugin.getShopManager() + .format( + shop.getPrice(), + shop.getLocation().getWorld(), + shop.getCurrency()), + plugin.getShopManager() + .format(ownerBalance, shop.getLocation().getWorld(), shop.getCurrency())) + .send(); return 0; } // when typed 'all' but player doesn't have any items to sell - plugin.text().of(p, "you-dont-have-that-many-items", amount, Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(p, "you-dont-have-that-many-items", amount, Util.getItemStackName(shop.getItem())) + .send(); return 0; } return amount; } - private int getPlayerCanBuy(@NotNull Shop shop, double traderBalance, double price, @NotNull InventoryWrapper playerInventory) { + private int getPlayerCanBuy( + @NotNull Shop shop, double traderBalance, double price, @NotNull InventoryWrapper playerInventory) { boolean isContainerCountingNeeded = shop.isUnlimited(); if (shop.isFreeShop()) { // Free shop - return isContainerCountingNeeded ? Util.countSpace(playerInventory, shop) : Math.min(shop.getRemainingStock(), Util.countSpace(playerInventory, shop)); + return isContainerCountingNeeded + ? Util.countSpace(playerInventory, shop) + : Math.min(shop.getRemainingStock(), Util.countSpace(playerInventory, shop)); } int itemAmount = Math.min(Util.countSpace(playerInventory, shop), (int) Math.floor(traderBalance / price)); if (!isContainerCountingNeeded) { @@ -542,29 +587,31 @@ public class PlayerListener extends AbstractQSListener { } // typed 'all', check if player has enough money than price * amount double price = shop.getPrice(); - double balance = eco.getBalance(p.getUniqueId(), shop.getLocation().getWorld(), - shop.getCurrency()); + double balance = eco.getBalance(p.getUniqueId(), shop.getLocation().getWorld(), shop.getCurrency()); amount = Math.min(amount, (int) Math.floor(balance / price)); if (amount < 1) { // typed 'all' but the auto set amount is 0 // when typed 'all' but player can't buy any items if (!shop.isUnlimited() && shopHaveItems < 1) { // but also the shop's stock is 0 - plugin.text().of(p, "shop-stock-too-low", - shop.getRemainingStock(), - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(p, "shop-stock-too-low", shop.getRemainingStock(), Util.getItemStackName(shop.getItem())) + .send(); return 0; } else { // when if player's inventory is full if (invHaveSpaces <= 0) { - plugin.text().of(p, "not-enough-space", - invHaveSpaces).send(); + plugin.text().of(p, "not-enough-space", invHaveSpaces).send(); return 0; } - plugin.text().of(p, "you-cant-afford-to-buy", - plugin.getShopManager().format(price, shop.getLocation().getWorld(), - shop.getCurrency()), - plugin.getShopManager().format(balance, shop.getLocation().getWorld(), - shop.getCurrency())).send(); + plugin.text() + .of( + p, + "you-cant-afford-to-buy", + plugin.getShopManager() + .format(price, shop.getLocation().getWorld(), shop.getCurrency()), + plugin.getShopManager() + .format(balance, shop.getLocation().getWorld(), shop.getCurrency())) + .send(); } return 0; } @@ -573,7 +620,9 @@ public class PlayerListener extends AbstractQSListener { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onDyeing(PlayerInteractEvent e) { - if (e.getAction() != Action.RIGHT_CLICK_BLOCK || e.getItem() == null || !Util.isDyes(e.getItem().getType())) { + if (e.getAction() != Action.RIGHT_CLICK_BLOCK + || e.getItem() == null + || !Util.isDyes(e.getItem().getType())) { return; } final Block block = e.getClickedBlock(); @@ -581,7 +630,8 @@ public class PlayerListener extends AbstractQSListener { return; } final Block attachedBlock = Util.getAttached(block); - if (attachedBlock == null || plugin.getShopManager().getShopIncludeAttached(attachedBlock.getLocation()) == null) { + if (attachedBlock == null + || plugin.getShopManager().getShopIncludeAttached(attachedBlock.getLocation()) == null) { return; } e.setCancelled(true); @@ -610,8 +660,8 @@ public class PlayerListener extends AbstractQSListener { if (location == null) { return; /// ignored as workaround, GH-303 } - //Cannot tick distance manager while unloading playerchunks - //https://github.com/pl3xgaming/Purpur/issues/631 + // Cannot tick distance manager while unloading playerchunks + // https://github.com/pl3xgaming/Purpur/issues/631 if (!Util.isLoaded(location)) { return; } @@ -625,8 +675,14 @@ public class PlayerListener extends AbstractQSListener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onJoin(PlayerLocaleChangeEvent e) { - Log.debug("Player " + e.getPlayer().getName() + " using new locale " + e.getLocale() + ": " + LegacyComponentSerializer.legacySection().serialize(plugin.text().of(e.getPlayer(), "file-test").forLocale(e.getLocale()))); - plugin.getDatabaseHelper().updatePlayerProfile(e.getPlayer().getUniqueId(), e.getLocale(), e.getPlayer().getName()) + Log.debug("Player " + e.getPlayer().getName() + " using new locale " + e.getLocale() + ": " + + LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of(e.getPlayer(), "file-test").forLocale(e.getLocale()))); + plugin.getDatabaseHelper() + .updatePlayerProfile( + e.getPlayer().getUniqueId(), + e.getLocale(), + e.getPlayer().getName()) .exceptionally(throwable -> { Log.debug("Failed to set player locale: " + throwable.getMessage()); return null; @@ -636,7 +692,8 @@ public class PlayerListener extends AbstractQSListener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onJoin(PlayerJoinEvent e) { // Notify the player any messages they were sent - plugin.getPlayerFinder().cache(e.getPlayer().getUniqueId(), e.getPlayer().getName()); + plugin.getPlayerFinder() + .cache(e.getPlayer().getUniqueId(), e.getPlayer().getName()); if (plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) { MsgUtil.flush(e.getPlayer()); } @@ -646,9 +703,17 @@ public class PlayerListener extends AbstractQSListener { public void onJoinEasterEgg(PlayerJoinEvent e) { if (plugin.perm().hasPermission(e.getPlayer(), "quickshop.alert")) { Date date = new Date(); - LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - if ((localDate.getMonthValue() == 4 && localDate.getDayOfMonth() == 1) || PackageUtil.parsePackageProperly("april-rickandroll").asBoolean()) { - Bukkit.getScheduler().runTaskLater(plugin.getJavaPlugin(), (() -> plugin.text().of(e.getPlayer(), "april-rick-and-roll-easter-egg").send()), 80L); + LocalDate localDate = + date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + if ((localDate.getMonthValue() == 4 && localDate.getDayOfMonth() == 1) + || PackageUtil.parsePackageProperly("april-rickandroll").asBoolean()) { + Bukkit.getScheduler() + .runTaskLater( + plugin.getJavaPlugin(), + (() -> plugin.text() + .of(e.getPlayer(), "april-rick-and-roll-easter-egg") + .send()), + 80L); } } } @@ -678,7 +743,11 @@ public class PlayerListener extends AbstractQSListener { public void onPlayerQuit(PlayerQuitEvent e) { // Remove them from the menu plugin.getShopManager().getInteractiveManager().remove(e.getPlayer().getUniqueId()); - plugin.getDatabaseHelper().updatePlayerProfile(e.getPlayer().getUniqueId(), e.getPlayer().getLocale(), e.getPlayer().getName()) + plugin.getDatabaseHelper() + .updatePlayerProfile( + e.getPlayer().getUniqueId(), + e.getPlayer().getLocale(), + e.getPlayer().getName()) .exceptionally(throwable -> { Log.debug("Failed to set player locale: " + throwable.getMessage()); return null; @@ -695,7 +764,9 @@ public class PlayerListener extends AbstractQSListener { */ @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onMove(PlayerMoveEvent e) { - final Info info = plugin.getShopManager().getInteractiveManager().get(e.getPlayer().getUniqueId()); + final Info info = plugin.getShopManager() + .getInteractiveManager() + .get(e.getPlayer().getUniqueId()); if (info == null) { return; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ShopProtectionListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ShopProtectionListener.java index 2e28d63b2..193dfc316 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ShopProtectionListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/ShopProtectionListener.java @@ -27,7 +27,8 @@ import org.jetbrains.annotations.Nullable; public class ShopProtectionListener extends AbstractProtectionListener { - private final NamespacedKey hopperKey = new NamespacedKey(QuickShop.getInstance().getJavaPlugin(), "hopper-persistent-data"); + private final NamespacedKey hopperKey = + new NamespacedKey(QuickShop.getInstance().getJavaPlugin(), "hopper-persistent-data"); private boolean hopperProtect; private boolean hopperOwnerExclude; @@ -53,7 +54,10 @@ public class ShopProtectionListener extends AbstractProtectionListener { if (plugin.getConfig().getBoolean("protect.explode")) { e.setCancelled(true); } else { - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "Exploding", false), "BlockBreak(explode)", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "Exploding", false), + "BlockBreak(explode)", + shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); } } @@ -105,7 +109,10 @@ public class ShopProtectionListener extends AbstractProtectionListener { if (plugin.getConfig().getBoolean("protect.explode")) { e.setCancelled(true); } else { - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "EntityExploding", false), "BlockBreak(explode)", shop.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "EntityExploding", false), + "BlockBreak(explode)", + shop.saveToInfoStorage())); plugin.getShopManager().deleteShop(shop); } } @@ -128,9 +135,11 @@ public class ShopProtectionListener extends AbstractProtectionListener { } if (this.hopperOwnerExclude) { if (event.getDestination().getHolder() instanceof Hopper hopper) { - HopperPersistentData hopperPersistentData = hopper.getPersistentDataContainer().get(hopperKey, HopperPersistentDataType.INSTANCE); + HopperPersistentData hopperPersistentData = + hopper.getPersistentDataContainer().get(hopperKey, HopperPersistentDataType.INSTANCE); if (hopperPersistentData != null) { - if (shop.playerAuthorize(hopperPersistentData.getPlayer(), BuiltInShopPermission.ACCESS_INVENTORY)) { + if (shop.playerAuthorize( + hopperPersistentData.getPlayer(), BuiltInShopPermission.ACCESS_INVENTORY)) { return; } } @@ -142,7 +151,11 @@ public class ShopProtectionListener extends AbstractProtectionListener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onPlaceHopper(BlockPlaceEvent e) { if (e.getBlockPlaced().getState() instanceof Hopper hopper) { - hopper.getPersistentDataContainer().set(hopperKey, HopperPersistentDataType.INSTANCE, new HopperPersistentData(e.getPlayer().getUniqueId())); + hopper.getPersistentDataContainer() + .set( + hopperKey, + HopperPersistentDataType.INSTANCE, + new HopperPersistentData(e.getPlayer().getUniqueId())); hopper.update(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/WorldListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/WorldListener.java index 337759206..93db45091 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/WorldListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/listener/WorldListener.java @@ -5,6 +5,9 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.ShopChunk; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; @@ -13,10 +16,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; - public class WorldListener extends AbstractQSListener { public WorldListener(QuickShop plugin) { @@ -87,7 +86,7 @@ public class WorldListener extends AbstractQSListener { continue; } for (final Shop shop : inChunk.values()) { - if (shop.isLoaded()) { //Don't unload already unloaded shops. + if (shop.isLoaded()) { // Don't unload already unloaded shops. shop.handleUnloading(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/LanguageFilesManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/LanguageFilesManager.java index 8d0de1b97..0e310d150 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/LanguageFilesManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/LanguageFilesManager.java @@ -1,15 +1,14 @@ package com.ghostchu.quickshop.localization.text; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.configuration.file.FileConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - // No to-do anymore! This used for not only messages.yml! Keep the extent ability! public class LanguageFilesManager { - //distributionPath->[localeCode->OTA files] + // distributionPath->[localeCode->OTA files] private final Map locale2ContentMapping = new ConcurrentHashMap<>(); /** @@ -42,7 +41,8 @@ public class LanguageFilesManager { } } - private void mergeMissing(@NotNull FileConfiguration alreadyRegistered, @NotNull FileConfiguration newConfiguration) { + private void mergeMissing( + @NotNull FileConfiguration alreadyRegistered, @NotNull FileConfiguration newConfiguration) { for (String key : newConfiguration.getKeys(true)) { if (newConfiguration.isConfigurationSection(key)) { continue; @@ -104,6 +104,4 @@ public class LanguageFilesManager { public void reset() { this.locale2ContentMapping.clear(); } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/SimpleTextManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/SimpleTextManager.java index dcbfb7a78..9d6da23c9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/SimpleTextManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/SimpleTextManager.java @@ -23,6 +23,17 @@ import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; import kong.unirest.Unirest; import lombok.SneakyThrows; import net.kyori.adventure.text.Component; @@ -43,18 +54,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem { private static final String DEFAULT_LOCALE = "en_us"; private static final String LOCALE_MAPPING_SYNTAX = "locale"; @@ -64,10 +63,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem // > private final LanguageFilesManager languageFilesManager = new LanguageFilesManager(); private final Set availableLanguages = new LinkedHashSet<>(); - private final Cache languagesCache = - CacheBuilder.newBuilder().expireAfterAccess(30, TimeUnit.MINUTES).recordStats().build(); + private final Cache languagesCache = CacheBuilder.newBuilder() + .expireAfterAccess(30, TimeUnit.MINUTES) + .recordStats() + .build(); private final String crowdinHost; private TagResolver[] tagResolvers; + @Nullable private CrowdinOTA crowdinOTA; @@ -75,11 +77,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem this.plugin = plugin; plugin.getReloadManager().register(this); plugin.getPasteManager().register(plugin.getJavaPlugin(), this); - this.crowdinHost = PackageUtil.parsePackageProperly("crowdinHost").asString("https://crowdinota.hikari.r2.quickshop-powered.top"); + this.crowdinHost = PackageUtil.parsePackageProperly("crowdinHost") + .asString("https://crowdinota.hikari.r2.quickshop-powered.top"); if (PackageUtil.parsePackageProperly("enableCrowdinOTA").asBoolean(true)) { try { plugin.logger().info("Please wait us fetch the translation updates from Crowdin OTA service..."); - this.crowdinOTA = new CrowdinOTA(crowdinHost, new File(Util.getCacheFolder(), "crowdin-ota"), Unirest.primaryInstance()); + this.crowdinOTA = new CrowdinOTA( + crowdinHost, new File(Util.getCacheFolder(), "crowdin-ota"), Unirest.primaryInstance()); } catch (Exception e) { plugin.logger().warn("Cannot initialize the CrowdinOTA instance!", e); } @@ -94,7 +98,7 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem */ public void load() { plugin.logger().info("Loading up translations from Crowdin OTA, this may need a while..."); - //TODO: This will break the message processing system in-game until loading finished, need to fix it. + // TODO: This will break the message processing system in-game until loading finished, need to fix it. this.reset(); initTagResolvers(); // first, we need load built-in fallback translation. @@ -108,7 +112,10 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem if (fileInstance != null) { for (String crowdinCode : fileInstance.getAvailableLocales()) { String content = fileInstance.getLocaleContentByCrowdinCode(crowdinCode); - String mcCode = crowdinOTA.mapLanguageCode(crowdinCode, LOCALE_MAPPING_SYNTAX).toLowerCase(Locale.ROOT).replace("-", "_"); + String mcCode = crowdinOTA + .mapLanguageCode(crowdinCode, LOCALE_MAPPING_SYNTAX) + .toLowerCase(Locale.ROOT) + .replace("-", "_"); if (content == null) { plugin.logger().warn("Failed to load translation for {}, the content is null.", mcCode); continue; @@ -131,7 +138,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem // and don't forget fix missing languageFilesManager.fillMissing(loadBuiltInFallback()); // finally, load override translations - Collection pending = getOverrideLocales(languageFilesManager.getDistributions().keySet()); + Collection pending = + getOverrideLocales(languageFilesManager.getDistributions().keySet()); Log.debug("Pending: " + Arrays.toString(pending.toArray())); pending.forEach(locale -> { File file = getOverrideLocaleFile(locale); @@ -175,7 +183,6 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem postProcessors.add(new ForceReplaceFillerProcessor()); } postProcessors.add(new PlaceHolderApiProcessor()); - } private void initTagResolvers() { @@ -272,7 +279,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem if (zipFile.canReadEntryData(entry)) { try { YamlConfiguration configuration = new YamlConfiguration(); - configuration.loadFromString(new String(zipFile.getInputStream(entry).readAllBytes(), StandardCharsets.UTF_8)); + configuration.loadFromString( + new String(zipFile.getInputStream(entry).readAllBytes(), StandardCharsets.UTF_8)); availableLang.put(locale.toLowerCase(Locale.ROOT).replace("-", "_"), configuration); Log.debug("Bundled language file: " + locale + " at " + entry.getName() + " loaded."); } catch (IOException | InvalidConfigurationException e) { @@ -285,7 +293,6 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem plugin.logger().warn("Failed to load bundled translation, jar invalid", e); return new HashMap<>(); } - } /** @@ -381,7 +388,7 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem @Override @NotNull public ProxiedLocale findRelativeLanguages(@Nullable String langCode) { - //langCode may null when some plugins providing fake player + // langCode may null when some plugins providing fake player if (langCode == null || langCode.isEmpty()) { return new ProxiedLocale(langCode, DEFAULT_LOCALE); } @@ -462,7 +469,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem FileConfiguration configuration = languageFilesManager.getDistribution(locale); if (configuration == null) { configuration = new YamlConfiguration(); - configuration.loadFromString(languageFilesManager.getDistribution(DEFAULT_LOCALE).saveToString()); + configuration.loadFromString( + languageFilesManager.getDistribution(DEFAULT_LOCALE).saveToString()); } configuration.set(path, text); languageFilesManager.deploy(locale, configuration); @@ -481,7 +489,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem return findRelativeLanguages(MsgUtil.getDefaultGameLanguageCode()); } try { - return findRelativeLanguages(plugin.getDatabaseHelper().getPlayerLocale(sender).get()); + return findRelativeLanguages( + plugin.getDatabaseHelper().getPlayerLocale(sender).get()); } catch (InterruptedException | ExecutionException e) { Log.debug("Failed to get player locale from database, fallback to default locale: " + e.getMessage()); return findRelativeLanguages(MsgUtil.getDefaultGameLanguageCode()); @@ -505,7 +514,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem */ @Override public @NotNull Text of(@NotNull String path, @Nullable Object... args) { - return new Text(this, (CommandSender) null, languageFilesManager.getDistributions(), path, tagResolvers, convert(args)); + return new Text( + this, (CommandSender) null, languageFilesManager.getDistributions(), path, tagResolvers, convert(args)); } /** @@ -608,7 +618,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem } if (String.class.equals(clazz)) { if (obj instanceof String) { - components[i] = LegacyComponentSerializer.legacySection().deserialize((String) obj); + components[i] = + LegacyComponentSerializer.legacySection().deserialize((String) obj); } continue; } @@ -638,7 +649,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem */ @Override public @NotNull TextList ofList(@NotNull String path, Object... args) { - return new TextList(this, (CommandSender) null, languageFilesManager.getDistributions(), path, tagResolvers, convert(args)); + return new TextList( + this, (CommandSender) null, languageFilesManager.getDistributions(), path, tagResolvers, convert(args)); } /** @@ -665,7 +677,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem } @Override - public com.ghostchu.quickshop.api.localization.text.@NotNull TextList ofList(@Nullable QUser sender, @NotNull String path, @Nullable Object... args) { + public com.ghostchu.quickshop.api.localization.text.@NotNull TextList ofList( + @Nullable QUser sender, @NotNull String path, @Nullable Object... args) { return new TextList(this, sender, languageFilesManager.getDistributions(), path, tagResolvers, convert(args)); } @@ -690,7 +703,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem private final Component[] args; private final TagResolver[] tagResolvers; - private TextList(SimpleTextManager manager, CommandSender sender, Map mapping, String path, TagResolver[] tagResolvers, Component... args) { + private TextList( + SimpleTextManager manager, + CommandSender sender, + Map mapping, + String path, + TagResolver[] tagResolvers, + Component... args) { this.manager = manager; this.sender = sender; this.mapping = mapping; @@ -699,7 +718,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem this.args = args; } - private TextList(SimpleTextManager manager, UUID sender, Map mapping, String path, TagResolver[] tagResolvers, Component... args) { + private TextList( + SimpleTextManager manager, + UUID sender, + Map mapping, + String path, + TagResolver[] tagResolvers, + Component... args) { this.manager = manager; if (sender != null) { this.sender = Bukkit.getPlayer(sender); @@ -712,7 +737,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem this.args = args; } - public TextList(SimpleTextManager manager, QUser sender, Map mapping, String path, TagResolver[] tagResolvers, Component... args) { + public TextList( + SimpleTextManager manager, + QUser sender, + Map mapping, + String path, + TagResolver[] tagResolvers, + Component... args) { this.manager = manager; if (sender != null) { this.sender = sender.getBukkitPlayer().orElse(null); @@ -734,13 +765,16 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem @Override @NotNull public List forLocale(@NotNull String locale) { - FileConfiguration index = mapping.get(manager.findRelativeLanguages(locale).getLocale()); + FileConfiguration index = + mapping.get(manager.findRelativeLanguages(locale).getLocale()); if (index == null) { - Log.debug("Fallback " + locale + " to default game-language locale caused by QuickShop doesn't support this locale"); + Log.debug("Fallback " + locale + + " to default game-language locale caused by QuickShop doesn't support this locale"); String languageCode = MsgUtil.getDefaultGameLanguageCode(); if (languageCode.equals(locale)) { Log.debug("Fallback Missing Language Key: " + path + ", report to QuickShop!"); - return Collections.singletonList(LegacyComponentSerializer.legacySection().deserialize(path)); + return Collections.singletonList( + LegacyComponentSerializer.legacySection().deserialize(path)); } else { return forLocale(languageCode); } @@ -748,9 +782,12 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem List str = index.getStringList(path); if (str.isEmpty()) { Log.debug("Fallback Missing Language Key: " + path + ", report to QuickShop!"); - return Collections.singletonList(LegacyComponentSerializer.legacySection().deserialize(path)); + return Collections.singletonList( + LegacyComponentSerializer.legacySection().deserialize(path)); } - List components = str.stream().map(s -> manager.plugin.getPlatform().miniMessage().deserialize(s, tagResolvers)).toList(); + List components = str.stream() + .map(s -> manager.plugin.getPlatform().miniMessage().deserialize(s, tagResolvers)) + .toList(); return postProcess(components); } } @@ -783,7 +820,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem } else { locale = MsgUtil.getDefaultGameLanguageCode(); } - FileConfiguration index = mapping.get(manager.findRelativeLanguages(locale).getLocale()); + FileConfiguration index = + mapping.get(manager.findRelativeLanguages(locale).getLocale()); return index != null; } @@ -814,7 +852,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem try { texts.add(postProcessor.process(s, sender, args)); } catch (Throwable th) { - Log.debug("Failed to post processing text: " + s + " caused by " + th.getMessage() + " handler: " + postProcessor.getClass().getName()); + Log.debug("Failed to post processing text: " + s + " caused by " + th.getMessage() + + " handler: " + postProcessor.getClass().getName()); } } } @@ -830,7 +869,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem private final Component[] args; private final TagResolver[] tagResolvers; - private Text(SimpleTextManager manager, CommandSender sender, Map mapping, String path, TagResolver[] tagResolvers, Component... args) { + private Text( + SimpleTextManager manager, + CommandSender sender, + Map mapping, + String path, + TagResolver[] tagResolvers, + Component... args) { this.manager = manager; this.sender = sender; this.mapping = mapping; @@ -839,7 +884,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem this.args = args; } - private Text(SimpleTextManager manager, UUID sender, Map mapping, String path, TagResolver[] tagResolvers, Component... args) { + private Text( + SimpleTextManager manager, + UUID sender, + Map mapping, + String path, + TagResolver[] tagResolvers, + Component... args) { this.manager = manager; if (sender != null) { this.sender = Bukkit.getPlayer(sender); @@ -852,7 +903,13 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem this.args = args; } - public Text(SimpleTextManager manager, QUser sender, Map mapping, String path, TagResolver[] tagResolvers, Component... args) { + public Text( + SimpleTextManager manager, + QUser sender, + Map mapping, + String path, + TagResolver[] tagResolvers, + Component... args) { this.manager = manager; if (sender != null) { this.sender = sender.getBukkitPlayer().orElse(null); @@ -874,10 +931,12 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem @Override @NotNull public Component forLocale(@NotNull String locale) { - FileConfiguration index = mapping.get(manager.findRelativeLanguages(locale).getLocale()); + FileConfiguration index = + mapping.get(manager.findRelativeLanguages(locale).getLocale()); if (index == null) { Log.debug("Index for " + locale + " is null"); - Log.debug("Fallback " + locale + " to default game-language locale caused by QuickShop doesn't support this locale"); + Log.debug("Fallback " + locale + + " to default game-language locale caused by QuickShop doesn't support this locale"); if (MsgUtil.getDefaultGameLanguageCode().equals(locale)) { Log.debug("Fallback Missing Language Key: " + path + ", report to QuickShop!"); return LegacyComponentSerializer.legacySection().deserialize(path); @@ -930,7 +989,8 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem } else { locale = MsgUtil.getDefaultGameLanguageCode(); } - FileConfiguration index = mapping.get(manager.findRelativeLanguages(locale).getLocale()); + FileConfiguration index = + mapping.get(manager.findRelativeLanguages(locale).getLocale()); return index != null; } @@ -958,12 +1018,12 @@ public class SimpleTextManager implements TextManager, Reloadable, SubPasteItem try { text = postProcessor.process(text, sender, args); } catch (Exception e) { - Log.debug("Error occurred while processing text: " + PlainTextComponentSerializer.plainText().serialize(text) + " caused by" + e.getMessage() + ", handler: " + postProcessor.getClass().getName()); + Log.debug("Error occurred while processing text: " + + PlainTextComponentSerializer.plainText().serialize(text) + " caused by" + e.getMessage() + + ", handler: " + postProcessor.getClass().getName()); } } return text; } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/postprocessing/impl/PlaceHolderApiProcessor.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/postprocessing/impl/PlaceHolderApiProcessor.java index 1fd38b7a2..c3e016f04 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/postprocessing/impl/PlaceHolderApiProcessor.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/localization/text/postprocessing/impl/PlaceHolderApiProcessor.java @@ -24,5 +24,4 @@ public class PlaceHolderApiProcessor implements PostProcessor { } return text; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/metric/MetricListener.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/metric/MetricListener.java index bad381ee3..1bec7c647 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/metric/MetricListener.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/metric/MetricListener.java @@ -21,16 +21,15 @@ public class MetricListener extends AbstractQSListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onCreate(ShopCreateSuccessEvent event) { - plugin.getDatabaseHelper().insertMetricRecord( - ShopMetricRecord.builder() - .time(System.currentTimeMillis()) - .shopId(event.getShop().getShopId()) - .player(event.getCreator()) - .tax(0.0d) - .total(plugin.getConfig().getDouble("shop.cost")) - .type(ShopOperationEnum.CREATE) - .build() - ) + plugin.getDatabaseHelper() + .insertMetricRecord(ShopMetricRecord.builder() + .time(System.currentTimeMillis()) + .shopId(event.getShop().getShopId()) + .player(event.getCreator()) + .tax(0.0d) + .total(plugin.getConfig().getDouble("shop.cost")) + .type(ShopOperationEnum.CREATE) + .build()) .exceptionally(e -> { Log.debug("Failed to insert shop metric record: " + e.getMessage()); return 0; @@ -39,35 +38,35 @@ public class MetricListener extends AbstractQSListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onDelete(ShopDeleteEvent event) { - plugin.getDatabaseHelper().insertMetricRecord( - ShopMetricRecord.builder() - .time(System.currentTimeMillis()) - .shopId(event.getShop().getShopId()) - .player(event.getShop().getOwner()) - .tax(0.0d) - .total(plugin.getConfig().getBoolean("shop.refund") ? plugin.getConfig().getDouble("shop.cost", 0.0d) : 0.0d) - .type(ShopOperationEnum.DELETE) - .build() - ) + plugin.getDatabaseHelper() + .insertMetricRecord(ShopMetricRecord.builder() + .time(System.currentTimeMillis()) + .shopId(event.getShop().getShopId()) + .player(event.getShop().getOwner()) + .tax(0.0d) + .total( + plugin.getConfig().getBoolean("shop.refund") + ? plugin.getConfig().getDouble("shop.cost", 0.0d) + : 0.0d) + .type(ShopOperationEnum.DELETE) + .build()) .exceptionally(e -> { Log.debug("Failed to insert shop metric record: " + e.getMessage()); return 0; }); - } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onDelete(ShopOngoingFeeEvent event) { - plugin.getDatabaseHelper().insertMetricRecord( - ShopMetricRecord.builder() - .time(System.currentTimeMillis()) - .shopId(event.getShop().getShopId()) - .player(event.getShop().getOwner()) - .tax(0.0d) - .total(event.getCost()) - .type(ShopOperationEnum.ONGOING_FEE) - .build() - ) + plugin.getDatabaseHelper() + .insertMetricRecord(ShopMetricRecord.builder() + .time(System.currentTimeMillis()) + .shopId(event.getShop().getShopId()) + .player(event.getShop().getOwner()) + .tax(0.0d) + .total(event.getCost()) + .type(ShopOperationEnum.ONGOING_FEE) + .build()) .exceptionally(e -> { Log.debug("Failed to insert shop metric record: " + e.getMessage()); return 0; @@ -76,17 +75,16 @@ public class MetricListener extends AbstractQSListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onPurchase(ShopSuccessPurchaseEvent event) { - plugin.getDatabaseHelper().insertMetricRecord( - ShopMetricRecord.builder() - .time(System.currentTimeMillis()) - .shopId(event.getShop().getShopId()) - .player(event.getPurchaser()) - .tax(event.getTax()) - .total(event.getBalanceWithoutTax()) - .type(wrapShopOperation(event.getShop())) - .amount(event.getAmount()) - .build() - ) + plugin.getDatabaseHelper() + .insertMetricRecord(ShopMetricRecord.builder() + .time(System.currentTimeMillis()) + .shopId(event.getShop().getShopId()) + .player(event.getPurchaser()) + .tax(event.getTax()) + .total(event.getBalanceWithoutTax()) + .type(wrapShopOperation(event.getShop())) + .amount(event.getAmount()) + .build()) .exceptionally(e -> { Log.debug("Failed to insert shop metric record: " + e.getMessage()); return 0; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/mock/MckFileConfiguration.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/mock/MckFileConfiguration.java index e3e773a4d..e6eebd68a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/mock/MckFileConfiguration.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/mock/MckFileConfiguration.java @@ -13,13 +13,11 @@ public class MckFileConfiguration extends FileConfiguration { } @Override - public void loadFromString(@NotNull String s) { - } + public void loadFromString(@NotNull String s) {} @NotNull @Override protected String buildHeader() { return ""; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/obj/QUserImpl.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/obj/QUserImpl.java index 980d01ef6..3fedadc92 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/obj/QUserImpl.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/obj/QUserImpl.java @@ -7,6 +7,13 @@ import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.common.util.JsonUtil; import com.ghostchu.quickshop.common.util.QuickExecutor; import com.ghostchu.quickshop.util.logger.Log; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; @@ -15,19 +22,13 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.nio.charset.StandardCharsets; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.logging.Level; - public final class QUserImpl implements QUser { @JsonUtil.Hidden private final PlayerFinder finder; + @JsonUtil.Hidden private final ExecutorService executorService; + private String username; private UUID uniqueId; private boolean realPlayer; @@ -67,7 +68,6 @@ public final class QUserImpl implements QUser { } else { parseFromUsernameFromRealPlayer(string); } - } private void parseFromUsernameFromRealPlayer(String string) { @@ -89,7 +89,8 @@ public final class QUserImpl implements QUser { private void parseFromUUID(String string) { this.realPlayer = true; this.uniqueId = UUID.fromString(string); - this.finder.uuid2NameFuture(this.uniqueId, true, executorService) + this.finder + .uuid2NameFuture(this.uniqueId, true, executorService) .thenAccept(result -> { this.username = result; endCheck(); @@ -102,7 +103,11 @@ public final class QUserImpl implements QUser { private void endCheck() { if (this.username != null && CommonUtil.isUUID(this.username)) { - QuickShop.getInstance().logger().warn("Warning! The username of QUser is a uuid! This may cause some problems!", new IllegalStateException("The username of QUser is a uuid!")); + QuickShop.getInstance() + .logger() + .warn( + "Warning! The username of QUser is a uuid! This may cause some problems!", + new IllegalStateException("The username of QUser is a uuid!")); } } @@ -234,19 +239,27 @@ public final class QUserImpl implements QUser { } public static CompletableFuture createAsync(@NotNull PlayerFinder finder, @NotNull String string) { - return CompletableFuture.supplyAsync(() -> new QUserImpl(finder, string, QuickExecutor.getPrimaryProfileIoExecutor()), QuickExecutor.getCommonExecutor()); + return CompletableFuture.supplyAsync( + () -> new QUserImpl(finder, string, QuickExecutor.getPrimaryProfileIoExecutor()), + QuickExecutor.getCommonExecutor()); } public static CompletableFuture createAsync(@NotNull PlayerFinder finder, @NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> new QUserImpl(finder, uuid, QuickExecutor.getPrimaryProfileIoExecutor()), QuickExecutor.getCommonExecutor()); + return CompletableFuture.supplyAsync( + () -> new QUserImpl(finder, uuid, QuickExecutor.getPrimaryProfileIoExecutor()), + QuickExecutor.getCommonExecutor()); } - public static CompletableFuture createAsync(@NotNull PlayerFinder finder, @NotNull String string, @NotNull ExecutorService executorService) { - return CompletableFuture.supplyAsync(() -> new QUserImpl(finder, string, executorService), QuickExecutor.getCommonExecutor()); + public static CompletableFuture createAsync( + @NotNull PlayerFinder finder, @NotNull String string, @NotNull ExecutorService executorService) { + return CompletableFuture.supplyAsync( + () -> new QUserImpl(finder, string, executorService), QuickExecutor.getCommonExecutor()); } - public static CompletableFuture createAsync(@NotNull PlayerFinder finder, @NotNull UUID uuid, @NotNull ExecutorService executorService) { - return CompletableFuture.supplyAsync(() -> new QUserImpl(finder, uuid, executorService), QuickExecutor.getCommonExecutor()); + public static CompletableFuture createAsync( + @NotNull PlayerFinder finder, @NotNull UUID uuid, @NotNull ExecutorService executorService) { + return CompletableFuture.supplyAsync( + () -> new QUserImpl(finder, uuid, executorService), QuickExecutor.getCommonExecutor()); } public static QUser createFullFilled(UUID uuid, String username, boolean realPlayer) { @@ -257,13 +270,15 @@ public final class QUserImpl implements QUser { return new QUserImpl(player.getUniqueId(), player.getName(), true); } - public static QUser createSync(@NotNull PlayerFinder finder, @NotNull String string, @NotNull ExecutorService executorService) { + public static QUser createSync( + @NotNull PlayerFinder finder, @NotNull String string, @NotNull ExecutorService executorService) { return new QUserImpl(finder, string, executorService); } - public static QUser createSync(@NotNull PlayerFinder finder, @NotNull UUID uuid, @NotNull ExecutorService executorService) { + public static QUser createSync( + @NotNull PlayerFinder finder, @NotNull UUID uuid, @NotNull ExecutorService executorService) { return new QUserImpl(finder, uuid, executorService); - //return QUSER_CACHE.get(uuid, () -> new QUserImpl(finder, uuid)); + // return QUSER_CACHE.get(uuid, () -> new QUserImpl(finder, uuid)); } public static QUser createSync(@NotNull PlayerFinder finder, @NotNull String string) { @@ -272,10 +287,11 @@ public final class QUserImpl implements QUser { public static QUser createSync(@NotNull PlayerFinder finder, @NotNull UUID uuid) { return new QUserImpl(finder, uuid, QuickExecutor.getPrimaryProfileIoExecutor()); - //return QUSER_CACHE.get(uuid, () -> new QUserImpl(finder, uuid)); + // return QUSER_CACHE.get(uuid, () -> new QUserImpl(finder, uuid)); } - public static CompletableFuture createAsync(@NotNull PlayerFinder finder, @NotNull CommandSender sender, ExecutorService executorService) { + public static CompletableFuture createAsync( + @NotNull PlayerFinder finder, @NotNull CommandSender sender, ExecutorService executorService) { if (sender instanceof Player player) { return CompletableFuture.supplyAsync(() -> createFullFilled(player)); } @@ -285,10 +301,12 @@ public final class QUserImpl implements QUser { if (sender instanceof ConsoleCommandSender) { return CompletableFuture.supplyAsync(() -> createFullFilled(CommonUtil.getNilUniqueId(), "CONSOLE", false)); } - return CompletableFuture.supplyAsync(() -> createFullFilled(CommonUtil.getNilUniqueId(), sender.getName(), false)); + return CompletableFuture.supplyAsync( + () -> createFullFilled(CommonUtil.getNilUniqueId(), sender.getName(), false)); } - public static QUser createSync(@NotNull PlayerFinder finder, @NotNull CommandSender sender, ExecutorService executorService) { + public static QUser createSync( + @NotNull PlayerFinder finder, @NotNull CommandSender sender, ExecutorService executorService) { if (sender instanceof Player player) { return createFullFilled(player); } @@ -301,7 +319,6 @@ public final class QUserImpl implements QUser { return createFullFilled(CommonUtil.getNilUniqueId(), sender.getName(), false); } - public static CompletableFuture createAsync(@NotNull PlayerFinder finder, @NotNull CommandSender sender) { return createAsync(finder, sender, QuickExecutor.getPrimaryProfileIoExecutor()); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPICache.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPICache.java index 7efdd0a41..4512ae3f1 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPICache.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPICache.java @@ -9,14 +9,13 @@ import com.ghostchu.simplereloadlib.Reloadable; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; -import lombok.Data; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.Optional; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; +import lombok.Data; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PAPICache implements Reloadable { private QuickShop plugin; @@ -38,9 +37,11 @@ public class PAPICache implements Reloadable { } @NotNull - public Optional getCached(@NotNull UUID player, @NotNull String args, @NotNull BiFunction loader) { + public Optional getCached( + @NotNull UUID player, @NotNull String args, @NotNull BiFunction loader) { try (PerfMonitor ignored = new PerfMonitor("PlaceHolder API Handling")) { - return performCaches.get(compileUniqueKey(player, args), () -> Optional.ofNullable(loader.apply(player, args))); + return performCaches.get( + compileUniqueKey(player, args), () -> Optional.ofNullable(loader.apply(player, args))); } catch (ExecutionException ex) { plugin.logger().warn("Failed to get cache for " + player + " " + args, ex); return Optional.empty(); @@ -61,23 +62,27 @@ public class PAPICache implements Reloadable { } private long getLoadedPlayerShops(@NotNull UUID uuid) { - return plugin.getShopManager().getLoadedShops().stream().filter(shop -> { - UUID souid = shop.getOwner().getUniqueId(); - if (souid == null) { - return false; - } - return souid.equals(uuid); - }).count(); + return plugin.getShopManager().getLoadedShops().stream() + .filter(shop -> { + UUID souid = shop.getOwner().getUniqueId(); + if (souid == null) { + return false; + } + return souid.equals(uuid); + }) + .count(); } private long getLoadedPlayerShops(@NotNull String name) { - return plugin.getShopManager().getLoadedShops().stream().filter(shop -> { - String sousrname = shop.getOwner().getUsername(); - if (sousrname == null) { - return false; - } - return name.equals(sousrname); - }).count(); + return plugin.getShopManager().getLoadedShops().stream() + .filter(shop -> { + String sousrname = shop.getOwner().getUsername(); + if (sousrname == null) { + return false; + } + return name.equals(sousrname); + }) + .count(); } private long getPlayerShopsInventoryUnavailable(@NotNull UUID uuid) { @@ -124,6 +129,4 @@ public class PAPICache implements Reloadable { this.queryString = queryString; } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPIManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPIManager.java index 335b79e58..2de6c3c16 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPIManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/PAPIManager.java @@ -9,14 +9,13 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.paste.GuavaCacheRender; import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.quickshop.util.paste.util.HTMLTable; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; import java.util.UUID; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PAPIManager implements SubPasteItem { private final QuickShop plugin; @@ -39,7 +38,8 @@ public class PAPIManager implements SubPasteItem { public void register(@NotNull PAPISubHandler handler) { for (PAPISubHandler registered : handlers) { if (registered.getPrefix().equals(handler.getPrefix())) { - throw new IllegalStateException("The prefix " + handler.getPrefix() + " is already registered by " + registered.getClass().getName() + "!"); + throw new IllegalStateException("The prefix " + handler.getPrefix() + " is already registered by " + + registered.getClass().getName() + "!"); } } handlers.add(handler); @@ -62,16 +62,17 @@ public class PAPIManager implements SubPasteItem { public String handle(@NotNull OfflinePlayer player, @NotNull String params) { UUID playerUniqueId = player.getUniqueId(); return cache.getCached(playerUniqueId, params, (uuid, parms) -> { - for (PAPISubHandler handler : handlers) { - Log.debug("Comparing with " + handler.getPrefix() + " and " + params); - if (params.startsWith(handler.getPrefix())) { - Log.debug("Match! Handling..."); - return handler.handle(player, params); - } - } - Log.debug("No PAPI handler hit"); - return null; - }).orElse(null); + for (PAPISubHandler handler : handlers) { + Log.debug("Comparing with " + handler.getPrefix() + " and " + params); + if (params.startsWith(handler.getPrefix())) { + Log.debug("Match! Handling..."); + return handler.handle(player, params); + } + } + Log.debug("No PAPI handler hit"); + return null; + }) + .orElse(null); } @Override diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/MetadataPAPI.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/MetadataPAPI.java index d5e3c7f86..8a2fec973 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/MetadataPAPI.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/MetadataPAPI.java @@ -31,5 +31,4 @@ public class MetadataPAPI implements PAPISubHandler { default -> null; }; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/PurchasesPAPI.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/PurchasesPAPI.java index a3d2fa7bc..78720454a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/PurchasesPAPI.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/PurchasesPAPI.java @@ -8,15 +8,14 @@ import com.ghostchu.quickshop.database.MetricQuery; import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.papi.PAPISubHandler; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.Locale; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PurchasesPAPI implements PAPISubHandler { private final QuickShop plugin; @@ -61,7 +60,8 @@ public class PurchasesPAPI implements PAPISubHandler { } ShopType shopType = ShopType.fromString(type.toUpperCase(Locale.ROOT)); int recentDays = Integer.parseInt(days); - Date startTime = new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); + Date startTime = + new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); long count = this.query.queryServerPurchaseRecords(startTime, -1, false).stream() .filter(record -> { if (shopType == null) { @@ -74,7 +74,8 @@ public class PurchasesPAPI implements PAPISubHandler { return record.getType() == ShopOperationEnum.PURCHASE_BUYING_SHOP; } return false; - }).count(); + }) + .count(); return String.valueOf(count); } @@ -90,7 +91,8 @@ public class PurchasesPAPI implements PAPISubHandler { } ShopType shopType = ShopType.fromString(type.toUpperCase(Locale.ROOT)); int recentDays = Integer.parseInt(days); - Date startTime = new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); + Date startTime = + new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); long count = this.query.queryServerPurchaseRecords(startTime, -1, false).stream() .filter(record -> { if (shopType == null) { @@ -107,7 +109,8 @@ public class PurchasesPAPI implements PAPISubHandler { .filter(record -> { QUser qUser = QUserImpl.createSync(plugin.getPlayerFinder(), record.getPlayer()); return player.getUniqueId().equals(qUser.getUniqueId()); - }).count(); + }) + .count(); return String.valueOf(count); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/ShopManagerPAPI.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/ShopManagerPAPI.java index 12e9cc1f0..7e5c9637d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/ShopManagerPAPI.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/ShopManagerPAPI.java @@ -5,13 +5,12 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.ShopManager; import com.ghostchu.quickshop.api.shop.ShopType; import com.ghostchu.quickshop.papi.PAPISubHandler; +import java.util.List; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; -import java.util.UUID; - public class ShopManagerPAPI implements PAPISubHandler { private final QuickShop plugin; private final ShopManager shopManager; @@ -79,14 +78,20 @@ public class ShopManagerPAPI implements PAPISubHandler { return null; } List allShops = shopManager.getAllShops(); - return String.valueOf(switch (passThroughArgsChild[0]) { - case "all" -> allShops.size(); - case "selling" -> allShops.stream().filter(shop -> shop.getShopType() == ShopType.SELLING).count(); - case "buying" -> allShops.stream().filter(shop -> shop.getShopType() == ShopType.BUYING).count(); - case "loaded" -> shopManager.getLoadedShops().size(); - case "unloaded" -> allShops.size() - shopManager.getLoadedShops().size(); - default -> null; - }); + return String.valueOf( + switch (passThroughArgsChild[0]) { + case "all" -> allShops.size(); + case "selling" -> allShops.stream() + .filter(shop -> shop.getShopType() == ShopType.SELLING) + .count(); + case "buying" -> allShops.stream() + .filter(shop -> shop.getShopType() == ShopType.BUYING) + .count(); + case "loaded" -> shopManager.getLoadedShops().size(); + case "unloaded" -> allShops.size() + - shopManager.getLoadedShops().size(); + default -> null; + }); } @Nullable @@ -95,13 +100,20 @@ public class ShopManagerPAPI implements PAPISubHandler { return null; } List belongToPlayers = shopManager.getAllShops(player); - return String.valueOf(switch (passThroughArgsChild[0]) { - case "all" -> belongToPlayers.size(); - case "selling" -> belongToPlayers.stream().filter(shop -> shop.getShopType() == ShopType.SELLING).count(); - case "buying" -> belongToPlayers.stream().filter(shop -> shop.getShopType() == ShopType.BUYING).count(); - case "loaded" -> shopManager.getLoadedShops().size(); - case "unloaded" -> belongToPlayers.stream().filter(shop -> !shop.isLoaded()).count(); - default -> null; - }); + return String.valueOf( + switch (passThroughArgsChild[0]) { + case "all" -> belongToPlayers.size(); + case "selling" -> belongToPlayers.stream() + .filter(shop -> shop.getShopType() == ShopType.SELLING) + .count(); + case "buying" -> belongToPlayers.stream() + .filter(shop -> shop.getShopType() == ShopType.BUYING) + .count(); + case "loaded" -> shopManager.getLoadedShops().size(); + case "unloaded" -> belongToPlayers.stream() + .filter(shop -> !shop.isLoaded()) + .count(); + default -> null; + }); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/TransactionAmountPAPI.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/TransactionAmountPAPI.java index 48d0e21c1..fe4b3188f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/TransactionAmountPAPI.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/papi/impl/TransactionAmountPAPI.java @@ -9,15 +9,14 @@ import com.ghostchu.quickshop.database.MetricQuery; import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; import com.ghostchu.quickshop.obj.QUserImpl; import com.ghostchu.quickshop.papi.PAPISubHandler; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.Locale; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class TransactionAmountPAPI implements PAPISubHandler { private final QuickShop plugin; @@ -62,7 +61,8 @@ public class TransactionAmountPAPI implements PAPISubHandler { } ShopType shopType = ShopType.fromString(type.toUpperCase(Locale.ROOT)); int recentDays = Integer.parseInt(days); - Date startTime = new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); + Date startTime = + new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); long count = this.query.queryServerPurchaseRecords(startTime, -1, false).stream() .filter(record -> { if (shopType == null) { @@ -76,7 +76,8 @@ public class TransactionAmountPAPI implements PAPISubHandler { } return false; }) - .mapToLong(ShopMetricRecord::getAmount).sum(); + .mapToLong(ShopMetricRecord::getAmount) + .sum(); return String.valueOf(count); } @@ -92,7 +93,8 @@ public class TransactionAmountPAPI implements PAPISubHandler { } ShopType shopType = ShopType.fromString(type.toUpperCase(Locale.ROOT)); int recentDays = Integer.parseInt(days); - Date startTime = new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); + Date startTime = + new Date(Instant.now().minus(Duration.ofDays(recentDays)).toEpochMilli()); long count = this.query.queryServerPurchaseRecords(startTime, -1, false).stream() .filter(record -> { if (shopType == null) { @@ -110,7 +112,8 @@ public class TransactionAmountPAPI implements PAPISubHandler { QUser qUser = QUserImpl.createSync(plugin.getPlayerFinder(), record.getPlayer()); return player.getUniqueId().equals(qUser.getUniqueId()); }) - .mapToLong(ShopMetricRecord::getAmount).sum(); + .mapToLong(ShopMetricRecord::getAmount) + .sum(); return String.valueOf(count); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/BukkitPermsProvider.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/BukkitPermsProvider.java index ad1cc3b64..8fd338f9a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/BukkitPermsProvider.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/BukkitPermsProvider.java @@ -43,5 +43,4 @@ public class BukkitPermsProvider implements PermissionProvider { } return player.hasPermission(permission); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionInformationContainer.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionInformationContainer.java index dab600d2f..0d2fee9b5 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionInformationContainer.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionInformationContainer.java @@ -20,7 +20,11 @@ public class PermissionInformationContainer { @Nullable private String otherInfos; - public PermissionInformationContainer(@NotNull CommandSender sender, @NotNull String permission, @Nullable String groupName, @Nullable String otherInfos) { + public PermissionInformationContainer( + @NotNull CommandSender sender, + @NotNull String permission, + @Nullable String groupName, + @Nullable String otherInfos) { this.sender = sender; this.permission = permission; this.groupName = groupName; @@ -35,5 +39,4 @@ public class PermissionInformationContainer { public boolean isConsole() { return sender instanceof Server; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionManager.java index 0d30a5865..ef582a790 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/PermissionManager.java @@ -41,7 +41,10 @@ public class PermissionManager { } return result; } catch (Exception th) { - plugin.logger().warn("Failed to processing permission response, This might or not a bug, we not sure, but you can report to both permission provider plugin author or QuickShop devs about this error", th); + plugin.logger() + .warn( + "Failed to processing permission response, This might or not a bug, we not sure, but you can report to both permission provider plugin author or QuickShop devs about this error", + th); return false; } } @@ -61,10 +64,11 @@ public class PermissionManager { } return result; } catch (Exception th) { - plugin.logger().warn("Failed to processing permission response, This might or not a bug, we not sure, but you can report to both permission provider plugin author or QuickShop devs about this error", th); + plugin.logger() + .warn( + "Failed to processing permission response, This might or not a bug, we not sure, but you can report to both permission provider plugin author or QuickShop devs about this error", + th); return false; } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/VaultPermissionProvider.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/VaultPermissionProvider.java index 07f066a6e..060e82766 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/VaultPermissionProvider.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/permission/VaultPermissionProvider.java @@ -69,8 +69,6 @@ public class VaultPermissionProvider implements PermissionProvider { return new PermissionInformationContainer(sender, permission, null, "User is Console"); } OfflinePlayer offlinePlayer = (OfflinePlayer) sender; - return new PermissionInformationContainer( - sender, permission, api.getPrimaryGroup(null, offlinePlayer), null); + return new PermissionInformationContainer(sender, permission, api.getPrimaryGroup(null, offlinePlayer), null); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ContainerShop.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ContainerShop.java index c9c98ed5d..419392845 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ContainerShop.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ContainerShop.java @@ -30,6 +30,10 @@ import com.ghostchu.quickshop.util.performance.PerfMonitor; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; import io.papermc.lib.PaperLib; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.concurrent.CompletableFuture; import lombok.EqualsAndHashCode; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; @@ -50,11 +54,6 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.concurrent.CompletableFuture; - /** * ChestShop core */ @@ -63,84 +62,105 @@ public class ContainerShop implements Shop, Reloadable { // We use deprecated method to create a fake quickshop-reremake namespace to trick bukkit to access legacy data. @SuppressWarnings({"AliDeprecation", "deprecation"}) private static final NamespacedKey LEGACY_SHOP_NAMESPACED_KEY = new NamespacedKey("quickshop", "shopsign"); + private static final String LEGACY_SHOP_SIGN_RECOGNIZE_PATTERN = "§d§o "; + @NotNull private final Location location; + private final YamlConfiguration extra; + @EqualsAndHashCode.Exclude private final QuickShop plugin; + @EqualsAndHashCode.Exclude private final UUID runtimeRandomUniqueId = UUID.randomUUID(); + @NotNull private final Map playerGroup; + private long shopId; private QUser owner; private double price; private ShopType shopType; private boolean unlimited; + @NotNull private ItemStack item; + @NotNull private ItemStack originalItem; + @Nullable @EqualsAndHashCode.Exclude private AbstractDisplayItem displayItem; + @EqualsAndHashCode.Exclude private volatile boolean isLoaded = false; + @EqualsAndHashCode.Exclude private final boolean isDeleted = false; + @EqualsAndHashCode.Exclude private volatile boolean createBackup = false; + @EqualsAndHashCode.Exclude private InventoryPreview inventoryPreview = null; + @EqualsAndHashCode.Exclude private boolean dirty; + @EqualsAndHashCode.Exclude private boolean updating = false; + @Nullable private String currency; + private boolean disableDisplay; private QUser taxAccount; + @NotNull private String inventoryWrapperProvider; + @EqualsAndHashCode.Exclude private InventoryWrapper inventoryWrapper; + @NotNull private String symbolLink; + @Nullable private String shopName; @NotNull private Benefit benefit; -// ContainerShop(@NotNull ContainerShop s) { -// Util.ensureThread(false); -// this.shopId = s.shopId; -// this.shopType = s.shopType; -// this.item = s.item.clone(); -// this.originalItem = s.originalItem.clone(); -// this.location = s.location.clone(); -// this.plugin = s.plugin; -// this.unlimited = s.unlimited; -// this.owner = s.owner; -// this.price = s.price; -// this.isLoaded = s.isLoaded; -// this.isDeleted = s.isDeleted; -// this.createBackup = s.createBackup; -// this.extra = s.extra; -// this.dirty = true; -// this.inventoryPreview = null; -// this.currency = s.currency; -// this.disableDisplay = s.disableDisplay; -// this.taxAccount = s.taxAccount; -// this.inventoryWrapper = s.inventoryWrapper; -// this.inventoryWrapperProvider = s.inventoryWrapperProvider; -// this.symbolLink = s.symbolLink; -// this.shopName = s.shopName; -// this.playerGroup = s.playerGroup; -// this.benefit = s.benefit; -// } - + // ContainerShop(@NotNull ContainerShop s) { + // Util.ensureThread(false); + // this.shopId = s.shopId; + // this.shopType = s.shopType; + // this.item = s.item.clone(); + // this.originalItem = s.originalItem.clone(); + // this.location = s.location.clone(); + // this.plugin = s.plugin; + // this.unlimited = s.unlimited; + // this.owner = s.owner; + // this.price = s.price; + // this.isLoaded = s.isLoaded; + // this.isDeleted = s.isDeleted; + // this.createBackup = s.createBackup; + // this.extra = s.extra; + // this.dirty = true; + // this.inventoryPreview = null; + // this.currency = s.currency; + // this.disableDisplay = s.disableDisplay; + // this.taxAccount = s.taxAccount; + // this.inventoryWrapper = s.inventoryWrapper; + // this.inventoryWrapperProvider = s.inventoryWrapperProvider; + // this.symbolLink = s.symbolLink; + // this.shopName = s.shopName; + // this.playerGroup = s.playerGroup; + // this.benefit = s.benefit; + // } /** * Adds a new shop. You need call ShopManager#loadShop if you create from outside of @@ -180,7 +200,6 @@ public class ContainerShop implements Shop, Reloadable { this.price = price; this.benefit = shopBenefit; - // Upgrade the shop moderator this.owner = owner; this.item = item.clone(); @@ -193,9 +212,9 @@ public class ContainerShop implements Shop, Reloadable { if (item.hasItemMeta()) { ItemMeta meta = item.getItemMeta(); if (meta.hasDisplayName() && meta.getDisplayName().matches("\\{.*}")) { - //https://hub.spigotmc.org/jira/browse/SPIGOT-5964 + // https://hub.spigotmc.org/jira/browse/SPIGOT-5964 meta.setDisplayName(meta.getDisplayName()); - //Correct both items + // Correct both items item.setItemMeta(meta); this.item.setItemMeta(meta); } @@ -267,8 +286,9 @@ public class ContainerShop implements Shop, Reloadable { * @param amount The amount to buy */ @Override - public void buy(@NotNull QUser buyer, @NotNull InventoryWrapper buyerInventory, - @NotNull Location loc2Drop, int amount) throws Exception { + public void buy( + @NotNull QUser buyer, @NotNull InventoryWrapper buyerInventory, @NotNull Location loc2Drop, int amount) + throws Exception { Util.ensureThread(false); amount = amount * item.getAmount(); if (amount < 0) { @@ -276,8 +296,7 @@ public class ContainerShop implements Shop, Reloadable { return; } if (this.isUnlimited()) { - SimpleInventoryTransaction transaction = SimpleInventoryTransaction - .builder() + SimpleInventoryTransaction transaction = SimpleInventoryTransaction.builder() .from(buyerInventory) .to(null) // To void .item(this.getItem()) @@ -287,17 +306,19 @@ public class ContainerShop implements Shop, Reloadable { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); } - throw new IllegalStateException("Failed to commit transaction! Economy Error Response:" + transaction.getLastError()); + throw new IllegalStateException( + "Failed to commit transaction! Economy Error Response:" + transaction.getLastError()); } } else { InventoryWrapper chestInv = this.getInventory(); if (chestInv == null) { - plugin.logger().warn("Failed to process buy, reason: {} x{} to shop {}: Inventory null.", item, amount, this); - Log.debug("Failed to process buy, reason: " + item + " x" + amount + " to shop " + this + ": Inventory null."); + plugin.logger() + .warn("Failed to process buy, reason: {} x{} to shop {}: Inventory null.", item, amount, this); + Log.debug("Failed to process buy, reason: " + item + " x" + amount + " to shop " + this + + ": Inventory null."); return; } - SimpleInventoryTransaction transaction = SimpleInventoryTransaction - .builder() + SimpleInventoryTransaction transaction = SimpleInventoryTransaction.builder() .from(buyerInventory) .to(chestInv) // To void .item(this.getItem()) @@ -307,17 +328,19 @@ public class ContainerShop implements Shop, Reloadable { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); } - throw new IllegalStateException("Failed to commit transaction! Economy Error Response:" + transaction.getLastError()); + throw new IllegalStateException( + "Failed to commit transaction! Economy Error Response:" + transaction.getLastError()); } } - //Update sign + // Update sign this.setSignText(plugin.text().findRelativeLanguages(buyer, false)); } @Override public void checkDisplay() { Util.ensureThread(false); - boolean displayStatus = plugin.isDisplayEnabled() && !isDisableDisplay() && this.isLoaded() && !this.isDeleted(); + boolean displayStatus = + plugin.isDisplayEnabled() && !isDisableDisplay() && this.isLoaded() && !this.isDeleted(); if (!displayStatus) { if (this.displayItem != null) { this.displayItem.remove(); @@ -338,11 +361,14 @@ public class ContainerShop implements Shop, Reloadable { yield new RealDisplayItem(this); } } - default -> new RealDisplayItem(this); - }; + default -> new RealDisplayItem(this);}; } } catch (Throwable anyError) { - plugin.logger().warn("Failed to init the displayItem for shop {}, the display now disabled for this shop. Did you have ProtocolLib installed?", this, anyError); + plugin.logger() + .warn( + "Failed to init the displayItem for shop {}, the display now disabled for this shop. Did you have ProtocolLib installed?", + this, + anyError); return; } } @@ -367,7 +393,8 @@ public class ContainerShop implements Shop, Reloadable { @Override public void claimShopSign(@NotNull Sign sign) { if (!sign.getPersistentDataContainer().has(Shop.SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE)) { - sign.getPersistentDataContainer().set(Shop.SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE, saveToShopSignStorage()); + sign.getPersistentDataContainer() + .set(Shop.SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE, saveToShopSignStorage()); sign.update(); } } @@ -432,7 +459,8 @@ public class ContainerShop implements Shop, Reloadable { try { inventoryWrapper = locateInventory(symbolLink); } catch (Exception e) { - Log.debug("Cannot locate the Inventory with symbol link: " + symbolLink + ", provider: " + inventoryWrapperProvider); + Log.debug("Cannot locate the Inventory with symbol link: " + symbolLink + ", provider: " + + inventoryWrapperProvider); return null; } } @@ -447,7 +475,10 @@ public class ContainerShop implements Shop, Reloadable { } else { plugin.getShopManager().unregisterShop(this, false); } - plugin.logEvent(new ShopRemoveLog(QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), "Inventory Invalid", this.saveToInfoStorage())); + plugin.logEvent(new ShopRemoveLog( + QUserImpl.createFullFilled(CommonUtil.getNilUniqueId(), "SYSTEM", false), + "Inventory Invalid", + this.saveToInfoStorage())); Log.debug("Inventory doesn't exist anymore: " + this + " shop was deleted."); return null; } @@ -689,11 +720,10 @@ public class ContainerShop implements Shop, Reloadable { public void setShopType(@NotNull ShopType newShopType) { Util.ensureThread(false); if (this.shopType == newShopType) { - return; //Ignore if there actually no changes + return; // Ignore if there actually no changes } if (Util.fireCancellableEvent(new ShopTypeChangeEvent(this, this.shopType, newShopType))) { - Log.debug( - "Some addon cancelled shop type changes, target shop: " + this); + Log.debug("Some addon cancelled shop type changes, target shop: " + this); return; } this.shopType = newShopType; @@ -705,10 +735,10 @@ public class ContainerShop implements Shop, Reloadable { public List getSignText(@NotNull ProxiedLocale locale) { Util.ensureThread(false); List lines = new ArrayList<>(); - //Line 1 + // Line 1 String headerKey = inventoryAvailable() ? "signs.header-available" : "signs.header-unavailable"; lines.add(plugin.text().of(headerKey, this.ownerName(false, locale)).forLocale(locale.getLocale())); - //Line 2 + // Line 2 String tradingStringKey; String noRemainingStringKey; int shopRemaining; @@ -730,36 +760,56 @@ public class ContainerShop implements Shop, Reloadable { noRemainingStringKey = "MissingKey for shop type:" + shopType; } } - Component line2 = switch (shopRemaining) { - //Unlimited - case -1 -> - plugin.text().of(tradingStringKey, plugin.text().of("signs.unlimited").forLocale(locale.getLocale())).forLocale(locale.getLocale()); - //No remaining - case 0 -> plugin.text().of(noRemainingStringKey).forLocale(locale.getLocale()); - //Has remaining - default -> plugin.text().of(tradingStringKey, Component.text(shopRemaining)).forLocale(locale.getLocale()); - }; + Component line2 = + switch (shopRemaining) { + // Unlimited + case -1 -> plugin.text() + .of( + tradingStringKey, + plugin.text().of("signs.unlimited").forLocale(locale.getLocale())) + .forLocale(locale.getLocale()); + // No remaining + case 0 -> plugin.text().of(noRemainingStringKey).forLocale(locale.getLocale()); + // Has remaining + default -> plugin.text() + .of(tradingStringKey, Component.text(shopRemaining)) + .forLocale(locale.getLocale()); + }; lines.add(line2); - //line 3 - if (plugin.getConfig().getBoolean("shop.force-use-item-original-name") || !this.getItem().hasItemMeta() || !this.getItem().getItemMeta().hasDisplayName()) { + // line 3 + if (plugin.getConfig().getBoolean("shop.force-use-item-original-name") + || !this.getItem().hasItemMeta() + || !this.getItem().getItemMeta().hasDisplayName()) { Component left = plugin.text().of("signs.item-left").forLocale(locale.getLocale()); Component right = plugin.text().of("signs.item-right").forLocale(locale.getLocale()); Component itemName = Util.getItemStackName(getItem()); lines.add(left.append(itemName).append(right)); } else { - lines.add(plugin.text().of("signs.item-left").forLocale(locale.getLocale()).append(Util.getItemStackName(getItem()).append(plugin.text().of("signs.item-right").forLocale(locale.getLocale())))); + lines.add(plugin.text() + .of("signs.item-left") + .forLocale(locale.getLocale()) + .append(Util.getItemStackName(getItem()) + .append(plugin.text().of("signs.item-right").forLocale(locale.getLocale())))); } - //line 4 + // line 4 Component line4; if (this.isStackingShop()) { - line4 = plugin.text().of("signs.stack-price", - plugin.getShopManager().format(this.getPrice(), this), - item.getAmount(), - Util.getItemStackName(item)).forLocale(locale.getLocale()); + line4 = plugin.text() + .of( + "signs.stack-price", + plugin.getShopManager().format(this.getPrice(), this), + item.getAmount(), + Util.getItemStackName(item)) + .forLocale(locale.getLocale()); } else { - line4 = plugin.text().of("signs.price", LegacyComponentSerializer.legacySection().deserialize(plugin.getShopManager().format(this.getPrice(), this))).forLocale(locale.getLocale()); + line4 = plugin.text() + .of( + "signs.price", + LegacyComponentSerializer.legacySection() + .deserialize(plugin.getShopManager().format(this.getPrice(), this))) + .forLocale(locale.getLocale()); } lines.add(line4); @@ -800,7 +850,6 @@ public class ContainerShop implements Shop, Reloadable { return signs; } - @Override @Nullable public QUser getTaxAccount() { @@ -815,7 +864,6 @@ public class ContainerShop implements Shop, Reloadable { ShopTaxAccountGettingEvent event = new ShopTaxAccountGettingEvent(this, uuid); event.callEvent(); return event.getTaxAccount(); - } @Override @@ -906,7 +954,6 @@ public class ContainerShop implements Shop, Reloadable { return this.isLoaded; } - @Override public boolean isSelling() { return this.shopType == ShopType.SELLING; @@ -940,10 +987,12 @@ public class ContainerShop implements Shop, Reloadable { } // Check for exists shop sign (modern) - ShopSignStorage shopSignStorage = sign.getPersistentDataContainer().get(SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE); + ShopSignStorage shopSignStorage = + sign.getPersistentDataContainer().get(SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE); if (shopSignStorage == null) { // Try to read Reremake sign namespaced key - shopSignStorage = sign.getPersistentDataContainer().get(LEGACY_SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE); + shopSignStorage = sign.getPersistentDataContainer() + .get(LEGACY_SHOP_NAMESPACED_KEY, ShopSignPersistentDataType.INSTANCE); } if (shopSignStorage == null) { // Try more hard to read Reremake sign namespaced key @@ -952,7 +1001,11 @@ public class ContainerShop implements Shop, Reloadable { } } if (shopSignStorage != null) { - return shopSignStorage.equals(getLocation().getWorld().getName(), getLocation().getBlockX(), getLocation().getBlockY(), getLocation().getBlockZ()); + return shopSignStorage.equals( + getLocation().getWorld().getName(), + getLocation().getBlockX(), + getLocation().getBlockY(), + getLocation().getBlockZ()); } return false; } @@ -1039,12 +1092,19 @@ public class ContainerShop implements Shop, Reloadable { try (PerfMonitor ignored = new PerfMonitor("Shop Inventory Locate", Duration.of(1, ChronoUnit.SECONDS))) { inventoryWrapper = locateInventory(symbolLink); } catch (Exception e) { - plugin.logger().warn("Failed to load shop: {}: {}: {}", symbolLink, e.getClass().getName(), e.getMessage()); + plugin.logger() + .warn( + "Failed to load shop: {}: {}: {}", + symbolLink, + e.getClass().getName(), + e.getMessage()); if (plugin.getConfig().getBoolean("debug.delete-corrupt-shops")) { plugin.logger().warn("Deleting corrupt shop..."); plugin.getShopManager().deleteShop(this); } else { - plugin.logger().warn("Unloading shops from memory, set `debug.delete-corrupt-shops` to true to delete corrupted shops."); + plugin.logger() + .warn( + "Unloading shops from memory, set `debug.delete-corrupt-shops` to true to delete corrupted shops."); plugin.getShopManager().deleteShop(this); } return; @@ -1053,8 +1113,8 @@ public class ContainerShop implements Shop, Reloadable { return; } this.isLoaded = true; - //disable schedule check due to performance issue - //plugin.getShopContainerWatcher().scheduleCheck(this); + // disable schedule check due to performance issue + // plugin.getShopContainerWatcher().scheduleCheck(this); try (PerfMonitor ignored = new PerfMonitor("Shop Display Check", Duration.of(1, ChronoUnit.SECONDS))) { checkDisplay(); } @@ -1091,7 +1151,6 @@ public class ContainerShop implements Shop, Reloadable { inventoryPreview = new InventoryPreview(plugin, getItem().clone(), player.getLocale()); } inventoryPreview.show(player); - } @Override @@ -1101,17 +1160,18 @@ public class ContainerShop implements Shop, Reloadable { name = plugin.text().of("admin-shop").forLocale(locale.getLocale()); } else { String playerName = this.getOwner().getUsername(); -// if (plugin.getConfig().getBoolean("shop.async-owner-name-fetch", false)) { -// CompletableFuture future = CompletableFuture -// .supplyAsync(() -> plugin.getPlayerFinder().uuid2Name(owner), QuickExecutor.getCommonExecutor()); -// try { -// playerName = future.get(20, TimeUnit.MILLISECONDS); -// } catch (InterruptedException | ExecutionException | TimeoutException e) { -// playerName = "N/A"; -// } -// } else { -// playerName = plugin.getPlayerFinder().uuid2Name(this.getOwner()); -// } + // if (plugin.getConfig().getBoolean("shop.async-owner-name-fetch", false)) { + // CompletableFuture future = CompletableFuture + // .supplyAsync(() -> plugin.getPlayerFinder().uuid2Name(owner), + // QuickExecutor.getCommonExecutor()); + // try { + // playerName = future.get(20, TimeUnit.MILLISECONDS); + // } catch (InterruptedException | ExecutionException | TimeoutException e) { + // playerName = "N/A"; + // } + // } else { + // playerName = plugin.getPlayerFinder().uuid2Name(this.getOwner()); + // } if (playerName == null) { name = plugin.text().of("unknown-owner").forLocale(locale.getLocale()); } else { @@ -1119,14 +1179,21 @@ public class ContainerShop implements Shop, Reloadable { } } if (getOwner().isRealPlayer()) { - name = name.hoverEvent( - plugin.text().of("real-player-component-hover", getOwner().getUniqueId(), getOwner().getUsername(), getOwner().getDisplay()).forLocale(locale.getLocale()) - ); + name = name.hoverEvent(plugin.text() + .of( + "real-player-component-hover", + getOwner().getUniqueId(), + getOwner().getUsername(), + getOwner().getDisplay()) + .forLocale(locale.getLocale())); } else { - name = name.hoverEvent( - plugin.text().of("virtual-player-component-hover", getOwner().getUniqueId(), getOwner().getUsername(), getOwner().getDisplay()).forLocale(locale.getLocale()) - ); - + name = name.hoverEvent(plugin.text() + .of( + "virtual-player-component-hover", + getOwner().getUniqueId(), + getOwner().getUsername(), + getOwner().getDisplay()) + .forLocale(locale.getLocale())); } ShopOwnerNameGettingEvent event = new ShopOwnerNameGettingEvent(this, getOwner(), name); event.callEvent(); @@ -1155,16 +1222,17 @@ public class ContainerShop implements Shop, Reloadable { @Override public boolean playerAuthorize(@NotNull UUID player, @NotNull Plugin namespace, @NotNull String permission) { if (player.equals(getOwner().getUniqueId())) { - Log.permission("Check permission " + namespace.getName().toLowerCase(Locale.ROOT) + "." + permission + " for " + player + " -> " + "true"); + Log.permission("Check permission " + namespace.getName().toLowerCase(Locale.ROOT) + "." + permission + + " for " + player + " -> " + "true"); return true; } String group = getPlayerGroup(player); boolean r = plugin.getShopPermissionManager().hasPermission(group, namespace, permission); ShopAuthorizeCalculateEvent event = new ShopAuthorizeCalculateEvent(this, player, namespace, permission, r); event.callEvent(); - Log.permission("Check permission " + namespace.getName().toLowerCase(Locale.ROOT) + "." + permission + ": " + player + " -> " + event.getResult()); + Log.permission("Check permission " + namespace.getName().toLowerCase(Locale.ROOT) + "." + permission + ": " + + player + " -> " + event.getResult()); return event.getResult(); - } /** @@ -1186,7 +1254,10 @@ public class ContainerShop implements Shop, Reloadable { @Override public List playersCanAuthorize(@NotNull BuiltInShopPermissionGroup permissionGroup) { - return playerGroup.entrySet().stream().filter(entry -> entry.getValue().equals(permissionGroup.getNamespacedNode())).map(Map.Entry::getKey).toList(); + return playerGroup.entrySet().stream() + .filter(entry -> entry.getValue().equals(permissionGroup.getNamespacedNode())) + .map(Map.Entry::getKey) + .toList(); } @Override @@ -1195,14 +1266,16 @@ public class ContainerShop implements Shop, Reloadable { for (Map.Entry uuidStringEntry : this.playerGroup.entrySet()) { String group = uuidStringEntry.getValue(); boolean r = plugin.getShopPermissionManager().hasPermission(group, namespace, permission); - ShopAuthorizeCalculateEvent event = new ShopAuthorizeCalculateEvent(this, uuidStringEntry.getKey(), namespace, permission, r); + ShopAuthorizeCalculateEvent event = + new ShopAuthorizeCalculateEvent(this, uuidStringEntry.getKey(), namespace, permission, r); event.callEvent(); r = event.getResult(); if (r) { result.add(uuidStringEntry.getKey()); } } - Log.permission("Check permission " + namespace.getName().toLowerCase(Locale.ROOT) + "." + permission + ": " + CommonUtil.list2String(result.stream().map(UUID::toString).toList())); + Log.permission("Check permission " + namespace.getName().toLowerCase(Locale.ROOT) + "." + permission + ": " + + CommonUtil.list2String(result.stream().map(UUID::toString).toList())); return result; } @@ -1222,7 +1295,12 @@ public class ContainerShop implements Shop, Reloadable { int itemMaxStackSize = Util.getItemMaxStackSize(item.getType()); InventoryWrapper inv = this.getInventory(); if (inv == null) { - plugin.logger().warn("Failed to process item remove, reason: {} x{} to shop {}: Inventory null.", item, amount, this); + plugin.logger() + .warn( + "Failed to process item remove, reason: {} x{} to shop {}: Inventory null.", + item, + amount, + this); return; } int remains = amount; @@ -1242,13 +1320,21 @@ public class ContainerShop implements Shop, Reloadable { @Override public ShopInfoStorage saveToInfoStorage() { - return new ShopInfoStorage(getLocation().getWorld().getName(), - new BlockPos(getLocation()), this.owner, this.price, - Util.serialize(this.originalItem), isUnlimited() ? 1 : 0 - , getShopType().toID(), - saveExtraToYaml(), this.currency, this.disableDisplay, - this.taxAccount, inventoryWrapperProvider, - saveToSymbolLink(), this.playerGroup); + return new ShopInfoStorage( + getLocation().getWorld().getName(), + new BlockPos(getLocation()), + this.owner, + this.price, + Util.serialize(this.originalItem), + isUnlimited() ? 1 : 0, + getShopType().toID(), + saveExtraToYaml(), + this.currency, + this.disableDisplay, + this.taxAccount, + inventoryWrapperProvider, + saveToSymbolLink(), + this.playerGroup); } @Override @@ -1266,8 +1352,9 @@ public class ContainerShop implements Shop, Reloadable { * @param amount The amount to sell */ @Override - public void sell(@NotNull QUser seller, @NotNull InventoryWrapper sellerInventory, - @NotNull Location loc2Drop, int amount) throws Exception { + public void sell( + @NotNull QUser seller, @NotNull InventoryWrapper sellerInventory, @NotNull Location loc2Drop, int amount) + throws Exception { Util.ensureThread(false); amount = item.getAmount() * amount; if (amount < 0) { @@ -1276,8 +1363,7 @@ public class ContainerShop implements Shop, Reloadable { } // Items to drop on floor if (this.isUnlimited()) { - SimpleInventoryTransaction transaction = SimpleInventoryTransaction - .builder() + SimpleInventoryTransaction transaction = SimpleInventoryTransaction.builder() .from(null) .to(sellerInventory) // To void .item(this.getItem()) @@ -1287,7 +1373,8 @@ public class ContainerShop implements Shop, Reloadable { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); } - throw new IllegalStateException("Failed to commit transaction! Economy Error Response:" + transaction.getLastError()); + throw new IllegalStateException( + "Failed to commit transaction! Economy Error Response:" + transaction.getLastError()); } } else { InventoryWrapper chestInv = this.getInventory(); @@ -1295,8 +1382,7 @@ public class ContainerShop implements Shop, Reloadable { plugin.logger().warn("Failed to process sell, reason: {} to shop {}: Inventory null.", item, amount); return; } - SimpleInventoryTransaction transactionTake = SimpleInventoryTransaction - .builder() + SimpleInventoryTransaction transactionTake = SimpleInventoryTransaction.builder() .from(chestInv) .to(sellerInventory) // To void .item(this.getItem()) @@ -1306,7 +1392,8 @@ public class ContainerShop implements Shop, Reloadable { if (plugin.getSentryErrorReporter() != null) { plugin.getSentryErrorReporter().ignoreThrow(); } - throw new IllegalStateException("Failed to commit transaction! Economy Error Response:" + transactionTake.getLastError()); + throw new IllegalStateException( + "Failed to commit transaction! Economy Error Response:" + transactionTake.getLastError()); } this.setSignText(plugin.getTextManager().findRelativeLanguages(seller, false)); } @@ -1333,7 +1420,8 @@ public class ContainerShop implements Shop, Reloadable { public void setInventory(@NotNull InventoryWrapper wrapper, @NotNull InventoryWrapperManager manager) { String provider = plugin.getInventoryWrapperRegistry().find(manager); if (provider == null) { - throw new IllegalArgumentException("The manager " + manager.getClass().getName() + " not registered in registry."); + throw new IllegalArgumentException( + "The manager " + manager.getClass().getName() + " not registered in registry."); } this.inventoryWrapper = wrapper; this.inventoryWrapperProvider = provider; @@ -1380,7 +1468,8 @@ public class ContainerShop implements Shop, Reloadable { if (!Util.isLoaded(this.location)) { return; } - this.setSignText(getSignText(plugin.getTextManager().findRelativeLanguages(MsgUtil.getDefaultGameLanguageCode()))); + this.setSignText( + getSignText(plugin.getTextManager().findRelativeLanguages(MsgUtil.getDefaultGameLanguageCode()))); } /** @@ -1405,13 +1494,17 @@ public class ContainerShop implements Shop, Reloadable { sign.setGlowingText(isGlowing); } sign.update(true); - //plugin.getPlatform().setLine(sign, i, lines.get(i)); + // plugin.getPlatform().setLine(sign, i, lines.get(i)); plugin.getPlatform().setLines(sign, lines); new ShopSignUpdateEvent(this, sign).callEvent(); } if (plugin.getSignHooker() != null) { Log.debug("Start sign broadcast..."); - Bukkit.getScheduler().runTaskLater(plugin.getJavaPlugin(), () -> plugin.getSignHooker().updatePerPlayerShopSignBroadcast(getLocation(), this), 2); + Bukkit.getScheduler() + .runTaskLater( + plugin.getJavaPlugin(), + () -> plugin.getSignHooker().updatePerPlayerShopSignBroadcast(getLocation(), this), + 2); Log.debug("Sign broadcast completed."); } } @@ -1450,16 +1543,17 @@ public class ContainerShop implements Shop, Reloadable { return CompletableFuture.completedFuture(null); } updating = true; - return plugin.getDatabaseHelper().updateShop(this) - .whenComplete((result, throwable) -> { - updating = false; - if (throwable == null) { - this.dirty = false; - } else { - plugin.logger().warn( - "Could not update a shop in the database! Changes will revert after a reboot!", throwable); - } - }); + return plugin.getDatabaseHelper().updateShop(this).whenComplete((result, throwable) -> { + updating = false; + if (throwable == null) { + this.dirty = false; + } else { + plugin.logger() + .warn( + "Could not update a shop in the database! Changes will revert after a reboot!", + throwable); + } + }); } @Override @@ -1489,8 +1583,7 @@ public class ContainerShop implements Shop, Reloadable { getInventoryWrapperProvider(), saveToSymbolLink(), new Date(), - getShopBenefit().serialize() - ); + getShopBenefit().serialize()); } /** @@ -1526,13 +1619,17 @@ public class ContainerShop implements Shop, Reloadable { } InventoryWrapperManager manager = plugin.getInventoryWrapperRegistry().get(getInventoryWrapperProvider()); if (manager == null) { - throw new IllegalStateException("Failed load shop data, the InventoryWrapper provider " + getInventoryWrapperProvider() + " invalid or failed to load!"); + throw new IllegalStateException("Failed load shop data, the InventoryWrapper provider " + + getInventoryWrapperProvider() + " invalid or failed to load!"); } try { // this.symbolLink = manager.mklink(inventoryWrapper); return manager.locate(symbolLink); } catch (Exception e) { - throw new IllegalStateException("Failed load shop data, the InventoryWrapper provider " + getInventoryWrapperProvider() + " returns error: " + e.getMessage(), e); + throw new IllegalStateException( + "Failed load shop data, the InventoryWrapper provider " + getInventoryWrapperProvider() + + " returns error: " + e.getMessage(), + e); } } @@ -1547,24 +1644,33 @@ public class ContainerShop implements Shop, Reloadable { } private ShopSignStorage saveToShopSignStorage() { - return new ShopSignStorage(getLocation().getWorld().getName(), getLocation().getBlockX(), getLocation().getBlockY(), getLocation().getBlockZ()); + return new ShopSignStorage( + getLocation().getWorld().getName(), + getLocation().getBlockX(), + getLocation().getBlockY(), + getLocation().getBlockZ()); } @Override public String toString() { - return "Shop " + - (location.getWorld() == null ? "unloaded world" : location.getWorld().getName()) + - "(" + - location.getBlockX() + - ", " + - location.getBlockY() + - ", " + - location.getBlockZ() + - ")" + - " Owner: " + LegacyComponentSerializer.legacySection().serialize(this.ownerName(false, MsgUtil.getDefaultGameLanguageLocale())) + " - " + getOwner() + - ", Unlimited: " + isUnlimited() + - ", Item: " + LegacyComponentSerializer.legacySection().serialize(Util.getItemStackName(getItem())) + - ", Price: " + getPrice(); + return "Shop " + + (location.getWorld() == null + ? "unloaded world" + : location.getWorld().getName()) + + "(" + + location.getBlockX() + + ", " + + location.getBlockY() + + ", " + + location.getBlockZ() + + ")" + + " Owner: " + + LegacyComponentSerializer.legacySection() + .serialize(this.ownerName(false, MsgUtil.getDefaultGameLanguageLocale())) + + " - " + getOwner() + ", Unlimited: " + + isUnlimited() + ", Item: " + + LegacyComponentSerializer.legacySection().serialize(Util.getItemStackName(getItem())) + ", Price: " + + getPrice(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InteractionController.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InteractionController.java index 4d38c832e..466c78b35 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InteractionController.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InteractionController.java @@ -5,15 +5,14 @@ import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.quickshop.util.paste.util.HTMLTable; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.EnumMap; import java.util.Map; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; public class InteractionController implements Reloadable, SubPasteItem { @@ -41,8 +40,12 @@ public class InteractionController implements Reloadable, SubPasteItem { for (Interaction value : Interaction.values()) { try { behaviorMap.put(value, InteractionBehavior.valueOf(config.getString(value.name()))); - if (value.isRightLick() && value.isShopBlock() && InteractionBehavior.valueOf(config.getString(value.name())) != InteractionBehavior.NONE) { - plugin.logger().warn("Define a action for right shopblock clicking may prevent player from opening the shop container!"); + if (value.isRightLick() + && value.isShopBlock() + && InteractionBehavior.valueOf(config.getString(value.name())) != InteractionBehavior.NONE) { + plugin.logger() + .warn( + "Define a action for right shopblock clicking may prevent player from opening the shop container!"); } } catch (IllegalArgumentException e) { plugin.logger().warn("Failed to load interaction behavior for {}! Using NONE behavior!", value.name()); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InventoryPreview.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InventoryPreview.java index 450f99b3b..c1ca1c576 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InventoryPreview.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/InventoryPreview.java @@ -6,6 +6,9 @@ import com.ghostchu.quickshop.shop.datatype.PreviewGuiPersistentDataType; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.holder.QuickShopPreviewGUIHolder; import com.ghostchu.quickshop.util.logger.Log; +import java.util.ArrayList; +import java.util.Collections; +import java.util.UUID; import lombok.EqualsAndHashCode; import lombok.ToString; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; @@ -22,10 +25,6 @@ import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.UUID; - /** * A class to create a GUI item preview quickly */ @@ -33,10 +32,12 @@ import java.util.UUID; @ToString public class InventoryPreview implements Listener { - private static final NamespacedKey NAMESPACED_KEY = new NamespacedKey(QuickShop.getInstance().getJavaPlugin(), "preview-item"); + private static final NamespacedKey NAMESPACED_KEY = + new NamespacedKey(QuickShop.getInstance().getJavaPlugin(), "preview-item"); private final ItemStack itemStack; private final QuickShop plugin = QuickShop.getInstance(); private String previewStr; + @Nullable private Inventory inventory; @@ -55,7 +56,8 @@ public class InventoryPreview implements Listener { } else { itemMeta = Bukkit.getItemFactory().getItemMeta(itemStack.getType()); } - previewStr = LegacyComponentSerializer.legacySection().serialize(plugin.text().of("quickshop-gui-preview").forLocale(locale)); + previewStr = LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of("quickshop-gui-preview").forLocale(locale)); if (StringUtils.isEmpty(previewStr)) { previewStr = ChatColor.RED + "FIXME: Do not set quickshop-gui-preview to null or empty string."; } @@ -66,7 +68,8 @@ public class InventoryPreview implements Listener { itemMeta.setLore(Collections.singletonList(previewStr)); } - itemMeta.getPersistentDataContainer().set(NAMESPACED_KEY, PreviewGuiPersistentDataType.INSTANCE, UUID.randomUUID()); + itemMeta.getPersistentDataContainer() + .set(NAMESPACED_KEY, PreviewGuiPersistentDataType.INSTANCE, UUID.randomUUID()); this.itemStack.setItemMeta(itemMeta); } } @@ -99,12 +102,15 @@ public class InventoryPreview implements Listener { } if (inventory == null) { final int size = 9; - inventory = Bukkit.createInventory(new QuickShopPreviewGUIHolder(), size, LegacyComponentSerializer.legacySection().serialize(plugin.text().of(player, "menu.preview").forLocale())); + inventory = Bukkit.createInventory( + new QuickShopPreviewGUIHolder(), + size, + LegacyComponentSerializer.legacySection() + .serialize(plugin.text().of(player, "menu.preview").forLocale())); for (int i = 0; i < size; i++) { inventory.setItem(i, itemStack); } } player.openInventory(inventory); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopLoader.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopLoader.java index 520356d62..8cde23184 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopLoader.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopLoader.java @@ -17,6 +17,17 @@ import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.google.common.reflect.TypeToken; +import java.lang.reflect.Type; +import java.sql.ResultSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; @@ -30,18 +41,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; -import java.lang.reflect.Type; -import java.sql.ResultSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - /** * A class allow plugin load shops fast and simply. */ @@ -58,8 +57,7 @@ public class ShopLoader implements SubPasteItem { */ public ShopLoader(@NotNull QuickShop plugin) { this.plugin = plugin; - this.executorService = Executors.newWorkStealingPool(PackageUtil - .parsePackageProperly("parallelism") + this.executorService = Executors.newWorkStealingPool(PackageUtil.parsePackageProperly("parallelism") .asInteger(CommonUtil.multiProcessorThreadRecommended())); } @@ -83,19 +81,24 @@ public class ShopLoader implements SubPasteItem { plugin.logger().info("Loading shops from database..."); Timer dbFetchTimer = new Timer(true); List records = plugin.getDatabaseHelper().listShops(deleteCorruptShops); - plugin.logger().info("Used {}ms to fetch {} shops from database.", dbFetchTimer.stopAndGetTimePassed(), records.size()); + plugin.logger() + .info( + "Used {}ms to fetch {} shops from database.", + dbFetchTimer.stopAndGetTimePassed(), + records.size()); plugin.logger().info("Loading shops into memory..."); Timer shopTotalTimer = new Timer(true); AtomicInteger successCounter = new AtomicInteger(0); AtomicInteger chunkNotLoaded = new AtomicInteger(0); List shopsLoadInNextTick = new CopyOnWriteArrayList<>(); for (ShopRecord record : records) { - loadShopFromShopRecord(worldName, record, deleteCorruptShops, - shopsLoadInNextTick, successCounter, chunkNotLoaded) + loadShopFromShopRecord( + worldName, record, deleteCorruptShops, shopsLoadInNextTick, successCounter, chunkNotLoaded) .exceptionally(e -> { plugin.logger().warn("Failed to load shop {}", record, e); return null; - }).join(); + }) + .join(); } Util.mainThreadRun(() -> shopsLoadInNextTick.forEach(shop -> { try { @@ -104,35 +107,57 @@ public class ShopLoader implements SubPasteItem { plugin.logger().error("Failed to load shop {}.", shop.getShopId(), e); } })); - plugin.logger().info("Used {}ms to load {} shops into memory ({} shops will be loaded after chunks/world loaded).", shopTotalTimer.stopAndGetTimePassed(), successCounter.get(), chunkNotLoaded.get()); + plugin.logger() + .info( + "Used {}ms to load {} shops into memory ({} shops will be loaded after chunks/world loaded).", + shopTotalTimer.stopAndGetTimePassed(), + successCounter.get(), + chunkNotLoaded.get()); } - private CompletableFuture loadShopFromShopRecord(String worldName, ShopRecord shopRecord, boolean deleteCorruptShops, List shopsLoadInNextTick, AtomicInteger successCounter, AtomicInteger chunkNotLoaded) { - return CompletableFuture.supplyAsync(() -> { - InfoRecord infoRecord = shopRecord.getInfoRecord(); - DataRecord dataRecord = shopRecord.getDataRecord(); - Timer singleShopLoadingTimer = new Timer(true); - ShopLoadResult result = loadSingleShop(infoRecord, dataRecord, worldName, shopsLoadInNextTick); - switch (result) { - case LOADED -> successCounter.incrementAndGet(); - case LOAD_AFTER_CHUNK_LOADED -> chunkNotLoaded.incrementAndGet(); - case WORLD_NOT_MATCH_SKIPPED -> { - // Do nothing - } - case FAILED -> { - if (deleteCorruptShops) { - plugin.getDatabaseHelper().removeShopMap(infoRecord.getWorld(), infoRecord.getX(), infoRecord.getY(), infoRecord.getZ()); - plugin.logger().warn("Shop {} is corrupted, removed from database.", infoRecord.getShopId()); + private CompletableFuture loadShopFromShopRecord( + String worldName, + ShopRecord shopRecord, + boolean deleteCorruptShops, + List shopsLoadInNextTick, + AtomicInteger successCounter, + AtomicInteger chunkNotLoaded) { + return CompletableFuture.supplyAsync( + () -> { + InfoRecord infoRecord = shopRecord.getInfoRecord(); + DataRecord dataRecord = shopRecord.getDataRecord(); + Timer singleShopLoadingTimer = new Timer(true); + ShopLoadResult result = loadSingleShop(infoRecord, dataRecord, worldName, shopsLoadInNextTick); + switch (result) { + case LOADED -> successCounter.incrementAndGet(); + case LOAD_AFTER_CHUNK_LOADED -> chunkNotLoaded.incrementAndGet(); + case WORLD_NOT_MATCH_SKIPPED -> { + // Do nothing + } + case FAILED -> { + if (deleteCorruptShops) { + plugin.getDatabaseHelper() + .removeShopMap( + infoRecord.getWorld(), + infoRecord.getX(), + infoRecord.getY(), + infoRecord.getZ()); + plugin.logger() + .warn("Shop {} is corrupted, removed from database.", infoRecord.getShopId()); + } + } } - } - } - Log.timing("Shop loading completed: " + result.name(), singleShopLoadingTimer); - return null; - }, this.executorService); + Log.timing("Shop loading completed: " + result.name(), singleShopLoadingTimer); + return null; + }, + this.executorService); } - - private ShopLoadResult loadSingleShop(InfoRecord infoRecord, DataRecord dataRecord, @Nullable String worldName, @NotNull List shopsLoadInNextTick) { + private ShopLoadResult loadSingleShop( + InfoRecord infoRecord, + DataRecord dataRecord, + @Nullable String worldName, + @NotNull List shopsLoadInNextTick) { // World check if (worldName != null) { if (!worldName.equals(infoRecord.getWorld())) { @@ -160,7 +185,8 @@ public class ShopLoader implements SubPasteItem { DataRawDatabaseInfo rawInfo = new DataRawDatabaseInfo(dataRecord); Location location = new Location(Bukkit.getWorld(infoRecord.getWorld()), x, y, z); try { - shop = new ContainerShop(plugin, + shop = new ContainerShop( + plugin, infoRecord.getShopId(), location, rawInfo.getPrice(), @@ -196,7 +222,7 @@ public class ShopLoader implements SubPasteItem { plugin.getShopManager().registerShop(shop, false); // persist=false to load to memory (it already persisted) if (Util.isLoaded(location)) { // Load to World - //plugin.getShopManager().loadShop(shop); // Patch the shops won't load around the spawn + // plugin.getShopManager().loadShop(shop); // Patch the shops won't load around the spawn shopsLoadInNextTick.add(shop); } else { return ShopLoadResult.LOAD_AFTER_CHUNK_LOADED; @@ -298,7 +324,6 @@ public class ShopLoader implements SubPasteItem { private Benefit benefits; - DataRawDatabaseInfo(@NotNull DataRecord dataRecord) { this.owner = dataRecord.getOwner(); this.price = dataRecord.getPrice(); @@ -306,7 +331,7 @@ public class ShopLoader implements SubPasteItem { this.unlimited = dataRecord.isUnlimited(); String extraStr = dataRecord.getExtra(); this.name = dataRecord.getName(); - //handle old shops + // handle old shops this.currency = dataRecord.getCurrency(); this.hologram = dataRecord.isHologram(); this.taxAccount = null; @@ -318,8 +343,7 @@ public class ShopLoader implements SubPasteItem { this.benefits = SimpleBenefit.deserialize(dataRecord.getBenefit()); String permissionJson = dataRecord.getPermissions(); if (!StringUtils.isEmpty(permissionJson) && CommonUtil.isJson(permissionJson)) { - Type typeToken = new TypeToken>() { - }.getType(); + Type typeToken = new TypeToken>() {}.getType(); this.permissions = new HashMap<>(JsonUtil.getGson().fromJson(permissionJson, typeToken)); } else { this.permissions = new HashMap<>(); @@ -332,7 +356,9 @@ public class ShopLoader implements SubPasteItem { try { return Util.deserialize(itemConfig); } catch (InvalidConfigurationException e) { - QuickShop.getInstance().logger().warn("Failed load shop data, because target config can't deserialize the ItemStack", e); + QuickShop.getInstance() + .logger() + .warn("Failed load shop data, because target config can't deserialize the ItemStack", e); Log.debug("Failed to load data to the ItemStack: " + itemConfig); return null; } @@ -349,7 +375,6 @@ public class ShopLoader implements SubPasteItem { return yamlConfiguration; } - @Override public String toString() { return JsonUtil.getGson().toJson(this); @@ -393,5 +418,4 @@ public class ShopLoader implements SubPasteItem { } } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopPurger.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopPurger.java index d415ab3b7..a1a51f344 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopPurger.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopPurger.java @@ -8,14 +8,12 @@ import com.ghostchu.quickshop.database.SimpleDatabaseHelperV2; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.performance.BatchBukkitExecutor; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; - import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; - +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; public class ShopPurger { private final QuickShop plugin; @@ -52,7 +50,10 @@ public class ShopPurger { boolean skipOp = plugin.getConfig().getBoolean("purge.skip-op"); for (Shop shop : plugin.getShopManager().getAllShops()) { try { - OfflinePlayer player = shop.getOwner().getUniqueIdIfRealPlayer().map(Bukkit::getOfflinePlayer).orElse(null); + OfflinePlayer player = shop.getOwner() + .getUniqueIdIfRealPlayer() + .map(Bukkit::getOfflinePlayer) + .orElse(null); if (player == null) { return; } @@ -71,7 +72,9 @@ public class ShopPurger { continue; } boolean markDeletion = player.isBanned() && deleteBanned; - long noOfDaysBetween = ChronoUnit.DAYS.between(CommonUtil.getDateTimeFromTimestamp(lastPlayed), CommonUtil.getDateTimeFromTimestamp(System.currentTimeMillis())); + long noOfDaysBetween = ChronoUnit.DAYS.between( + CommonUtil.getDateTimeFromTimestamp(lastPlayed), + CommonUtil.getDateTimeFromTimestamp(System.currentTimeMillis())); if (noOfDaysBetween > days) { markDeletion = true; } @@ -86,12 +89,17 @@ public class ShopPurger { BatchBukkitExecutor purgeExecutor = new BatchBukkitExecutor<>(); purgeExecutor.addTasks(pendingRemovalShops); - purgeExecutor.startHandle(plugin.getJavaPlugin(), (shop) -> plugin.getShopManager().deleteShop(shop)) + purgeExecutor + .startHandle(plugin.getJavaPlugin(), (shop) -> plugin.getShopManager() + .deleteShop(shop)) .whenComplete((a, b) -> { - long usedTime = purgeExecutor.getStartTime().until(Instant.now(), java.time.temporal.ChronoUnit.MILLIS); - plugin.logger().info("[Shop Purger] Total shop {} has been purged, used {}ms", - pendingRemovalShops.size(), - usedTime); + long usedTime = + purgeExecutor.getStartTime().until(Instant.now(), java.time.temporal.ChronoUnit.MILLIS); + plugin.logger() + .info( + "[Shop Purger] Total shop {} has been purged, used {}ms", + pendingRemovalShops.size(), + usedTime); }); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopSignStorage.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopSignStorage.java index 957e50b1a..c686ae2d5 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopSignStorage.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/ShopSignStorage.java @@ -1,10 +1,9 @@ package com.ghostchu.quickshop.shop; +import java.util.Objects; import lombok.Builder; import lombok.Data; -import java.util.Objects; - /** * TODO This class used for storage the shop sign */ diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInfo.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInfo.java index aee79d9f7..bf1b174cb 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInfo.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInfo.java @@ -87,7 +87,6 @@ public class SimpleInfo implements Info { return this.item; } - /** * @return Location loc, Get shop's location, */ @@ -119,5 +118,4 @@ public class SimpleInfo implements Info { public boolean isBypassed() { return bypass; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInventoryTransaction.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInventoryTransaction.java index 40b15b62a..a54d3023d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInventoryTransaction.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleInventoryTransaction.java @@ -10,16 +10,15 @@ import com.ghostchu.quickshop.shop.operation.RemoveItemOperation; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.performance.PerfMonitor; -import lombok.Builder; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; +import lombok.Builder; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SimpleInventoryTransaction implements InventoryTransaction { private final Deque processingStack = new LinkedList<>(); @@ -31,7 +30,8 @@ public class SimpleInventoryTransaction implements InventoryTransaction { private String lastError; @Builder - public SimpleInventoryTransaction(@Nullable InventoryWrapper from, @Nullable InventoryWrapper to, @NotNull ItemStack item, int amount) { + public SimpleInventoryTransaction( + @Nullable InventoryWrapper from, @Nullable InventoryWrapper to, @NotNull ItemStack item, int amount) { if (from == null && to == null) { throw new IllegalArgumentException("Both from and to are null"); } @@ -60,18 +60,14 @@ public class SimpleInventoryTransaction implements InventoryTransaction { * * @param transaction Transaction */ - default void onFailed(@NotNull SimpleInventoryTransaction transaction) { - } + default void onFailed(@NotNull SimpleInventoryTransaction transaction) {} /** * Calling while Transaction commit successfully * * @param transaction Transaction */ - default void onSuccess(@NotNull SimpleInventoryTransaction transaction) { - } - - + default void onSuccess(@NotNull SimpleInventoryTransaction transaction) {} } /** @@ -84,8 +80,7 @@ public class SimpleInventoryTransaction implements InventoryTransaction { try (PerfMonitor ignored = new PerfMonitor("Inventory Transaction - Commit")) { return this.commit(new SimpleTransactionCallback() { @Override - public void onSuccess(@NotNull SimpleInventoryTransaction inventoryTransaction) { - } + public void onSuccess(@NotNull SimpleInventoryTransaction inventoryTransaction) {} }); } } @@ -98,7 +93,8 @@ public class SimpleInventoryTransaction implements InventoryTransaction { */ @Override public boolean commit(@NotNull TransactionCallback callback) { - Log.transaction("Transaction begin: Regular Commit --> " + from + " => " + to + "; Amount: " + amount + " Item: " + Util.serialize(item)); + Log.transaction("Transaction begin: Regular Commit --> " + from + " => " + to + "; Amount: " + amount + + " Item: " + Util.serialize(item)); if (!callback.onCommit(this)) { this.lastError = "Plugin cancelled this transaction."; return false; @@ -117,7 +113,6 @@ public class SimpleInventoryTransaction implements InventoryTransaction { return true; } - @Override public void setFrom(@Nullable InventoryWrapper from) { this.from = from; @@ -180,7 +175,8 @@ public class SimpleInventoryTransaction implements InventoryTransaction { */ @Override public boolean failSafeCommit() { - Log.transaction("Transaction begin: FailSafe Commit --> " + from + " => " + to + "; Amount: " + amount + " Item: " + Util.serialize(item)); + Log.transaction("Transaction begin: FailSafe Commit --> " + from + " => " + to + "; Amount: " + amount + + " Item: " + Util.serialize(item)); boolean result = commit(); if (!result) { Log.transaction(Level.WARNING, "Fail-safe commit failed, starting rollback: " + lastError); @@ -226,9 +222,17 @@ public class SimpleInventoryTransaction implements InventoryTransaction { } catch (Exception exception) { if (continueWhenFailed) { operations.add(operation); - plugin.logger().warn("Failed to rollback transaction: Operation: {}; Transaction: {}; Skipping...", operation, this); + plugin.logger() + .warn( + "Failed to rollback transaction: Operation: {}; Transaction: {}; Skipping...", + operation, + this); } else { - plugin.logger().warn("Failed to rollback transaction: Operation: {}; Transaction: {}", operation, this); + plugin.logger() + .warn( + "Failed to rollback transaction: Operation: {}; Transaction: {}", + operation, + this); break; } } @@ -247,6 +251,4 @@ public class SimpleInventoryTransaction implements InventoryTransaction { return false; } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimplePriceLimiter.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimplePriceLimiter.java index af46c7491..048ac7e49 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimplePriceLimiter.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimplePriceLimiter.java @@ -11,6 +11,15 @@ import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.quickshop.util.paste.util.HTMLTable; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.nio.file.Files; +import java.util.*; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.bukkit.command.CommandSender; @@ -22,16 +31,6 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.nio.file.Files; -import java.util.*; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteItem { private final QuickShop plugin; private final Map rules = new LinkedHashMap<>(); @@ -139,7 +138,11 @@ public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteIte Pattern pattern = Pattern.compile(currencyStr1); currency.add(pattern); } catch (PatternSyntaxException e) { - plugin.logger().warn("Failed to read rule {}'s a Currency option, invalid pattern {}! Skipping...", ruleName, currencyStr1); + plugin.logger() + .warn( + "Failed to read rule {}'s a Currency option, invalid pattern {}! Skipping...", + ruleName, + currencyStr1); } } return new RuleSet(items, bypassPermission, currency, min, max); @@ -159,7 +162,8 @@ public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteIte */ @Override @NotNull - public PriceLimiterCheckResult check(@NotNull CommandSender sender, @NotNull ItemStack itemStack, @Nullable String currency, double price) { + public PriceLimiterCheckResult check( + @NotNull CommandSender sender, @NotNull ItemStack itemStack, @Nullable String currency, double price) { if (Double.isInfinite(price) || Double.isNaN(price)) { return new SimplePriceLimiterCheckResult(PriceLimiterStatus.NOT_VALID, undefinedMin, undefinedMax); } @@ -168,7 +172,8 @@ public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteIte BigDecimal.valueOf(price).setScale(0, RoundingMode.UNNECESSARY); } catch (ArithmeticException exception) { Log.debug(exception.getMessage()); - return new SimplePriceLimiterCheckResult(PriceLimiterStatus.NOT_A_WHOLE_NUMBER, undefinedMin, undefinedMax); + return new SimplePriceLimiterCheckResult( + PriceLimiterStatus.NOT_A_WHOLE_NUMBER, undefinedMin, undefinedMax); } } for (RuleSet rule : rules.values()) { @@ -214,7 +219,12 @@ public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteIte if (StringUtils.isEmpty(currencies)) { currencies = "*"; } - rules.insert(entry.getKey(), rule.getBypassPermission(), rule.getItems().size(), currencies, rule.getMin() + " - " + rule.getMax()); + rules.insert( + entry.getKey(), + rule.getBypassPermission(), + rule.getItems().size(), + currencies, + rule.getMin() + " - " + rule.getMax()); } joiner.add(rules.render()); return joiner.toString(); @@ -233,7 +243,12 @@ public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteIte private final double min; private final double max; - public RuleSet(List> items, String bypassPermission, List currency, double min, double max) { + public RuleSet( + List> items, + String bypassPermission, + List currency, + double min, + double max) { this.items = items; this.bypassPermission = bypassPermission; this.currency = currency; @@ -270,7 +285,8 @@ public class SimplePriceLimiter implements Reloadable, PriceLimiter, SubPasteIte return false; } if (currency != null) { - if (this.currency.stream().noneMatch(pattern -> pattern.matcher(currency).matches())) { + if (this.currency.stream() + .noneMatch(pattern -> pattern.matcher(currency).matches())) { return false; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopExtra.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopExtra.java index 64a703dc0..a4c3719b6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopExtra.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopExtra.java @@ -1,10 +1,9 @@ package com.ghostchu.quickshop.shop; +import java.util.Map; import lombok.Data; import org.jetbrains.annotations.NotNull; -import java.util.Map; - /** * Storage the extra data that QuickShop needs or from 3rd-addon */ diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopItemBlackList.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopItemBlackList.java index e3e83954e..f85ab995f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopItemBlackList.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopItemBlackList.java @@ -6,15 +6,14 @@ import com.ghostchu.quickshop.util.ItemExpression; import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; -import org.bukkit.ChatColor; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; public class SimpleShopItemBlackList implements Reloadable, ShopItemBlackList, SubPasteItem { private final QuickShop plugin; @@ -87,7 +86,6 @@ public class SimpleShopItemBlackList implements Reloadable, ShopItemBlackList, S return false; } - @Override public ReloadResult reloadModule() throws Exception { init(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopManager.java index 1b1c42296..f8dabd7df 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopManager.java @@ -36,6 +36,14 @@ import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.papermc.lib.PaperLib; +import java.lang.reflect.InvocationTargetException; +import java.text.DecimalFormat; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; @@ -64,15 +72,6 @@ import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.text.DecimalFormat; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Function; - /** * Manage a lot of shops. */ @@ -84,20 +83,22 @@ public class SimpleShopManager implements ShopManager, Reloadable { // the performance impact on busy server private final InteractiveManager interactiveManager; private final QuickShop plugin; - private final Cache shopRuntimeUUIDCaching = - CacheBuilder.newBuilder() - .expireAfterAccess(10, TimeUnit.MINUTES) - .maximumSize(50) - .weakValues() - .initialCapacity(50) - .build(); + private final Cache shopRuntimeUUIDCaching = CacheBuilder.newBuilder() + .expireAfterAccess(10, TimeUnit.MINUTES) + .maximumSize(50) + .weakValues() + .initialCapacity(50) + .build(); private ShopCache shopCache; private final EconomyFormatter formatter; + @Getter @Nullable private QUser cacheTaxAccount; + @Getter private QUser cacheUnlimitedShopAccount; + private SimplePriceLimiter priceLimiter; private boolean useOldCanBuildAlgorithm; private boolean autoSign; @@ -155,9 +156,13 @@ public class SimpleShopManager implements ShopManager, Reloadable { this.tradeAllKeyword = plugin.getConfig().getString("shop.word-for-trade-all-items", "all"); this.disableCreativePurchase = plugin.getConfig().getBoolean("shop.disable-creative-mode-trading"); this.sendStockMessageToStaff = plugin.getConfig().getBoolean("shop.sending-stock-message-to-staffs"); - this.useShopableChecks = PackageUtil.parsePackageProperly("shoppableChecks").asBoolean(false); + this.useShopableChecks = + PackageUtil.parsePackageProperly("shoppableChecks").asBoolean(false); this.useShopCache = plugin.getConfig().getBoolean("shop.use-cache", true); - Map<@NotNull ShopCacheNamespacedKey, @NotNull Pair<@NotNull Function, @Nullable Cache>> map = new HashMap<>(); + Map< + @NotNull ShopCacheNamespacedKey, + @NotNull Pair<@NotNull Function, @Nullable Cache>> + map = new HashMap<>(); // SINGLE map.put(ShopCacheNamespacedKey.SINGLE, new ImmutablePair<>(this::getShop, null)); map.put(ShopCacheNamespacedKey.INCLUDE_ATTACHED, new ImmutablePair<>(this::getShopIncludeAttached, null)); @@ -177,7 +182,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { @NotNull Shop shop, int amount) { QUser buyerQUser = QUserImpl.createFullFilled(buyer); - if (!plugin.perm().hasPermission(buyer, "quickshop.other.use") && !shop.playerAuthorize(buyer.getUniqueId(), BuiltInShopPermission.PURCHASE)) { + if (!plugin.perm().hasPermission(buyer, "quickshop.other.use") + && !shop.playerAuthorize(buyer.getUniqueId(), BuiltInShopPermission.PURCHASE)) { plugin.text().of("no-permission").send(); return; } @@ -189,16 +195,21 @@ public class SimpleShopManager implements ShopManager, Reloadable { space = 10000; } if (space < amount) { - plugin.text().of(buyer, "shop-has-no-space", Component.text(space), Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(buyer, "shop-has-no-space", Component.text(space), Util.getItemStackName(shop.getItem())) + .send(); return; } int count = Util.countItems(buyerInventory, shop); // Not enough items if (amount > count) { - plugin.text().of(buyer, - "you-dont-have-that-many-items", - Component.text(count), - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of( + buyer, + "you-dont-have-that-many-items", + Component.text(count), + Util.getItemStackName(shop.getItem())) + .send(); return; } if (amount < 1) { @@ -239,23 +250,33 @@ public class SimpleShopManager implements ShopManager, Reloadable { builder.taxModifier(0.0d); } if (!shop.isUnlimited() - || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") - && shop.isUnlimited())) { + || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") && shop.isUnlimited())) { transaction = builder.from(shop.getOwner()).build(); } else { transaction = builder.from(null).build(); } if (!transaction.checkBalance()) { - plugin.text().of(buyer, "the-owner-cant-afford-to-buy-from-you", - format(total, shop.getLocation().getWorld(), shop.getCurrency()), - format(eco.getBalance(shop.getOwner(), shop.getLocation().getWorld(), - shop.getCurrency()), shop.getLocation().getWorld(), shop.getCurrency())).send(); + plugin.text() + .of( + buyer, + "the-owner-cant-afford-to-buy-from-you", + format(total, shop.getLocation().getWorld(), shop.getCurrency()), + format( + eco.getBalance( + shop.getOwner(), shop.getLocation().getWorld(), shop.getCurrency()), + shop.getLocation().getWorld(), + shop.getCurrency())) + .send(); return; } if (!transaction.failSafeCommit()) { - plugin.text().of(buyer, "economy-transaction-failed", transaction.getLastError()).send(); + plugin.text() + .of(buyer, "economy-transaction-failed", transaction.getLastError()) + .send(); plugin.logger().error("EconomyTransaction Failed, last error: {}", transaction.getLastError()); - plugin.logger().error("Tips: If you see any economy plugin name appears above, please don't ask QuickShop support. Contact with developer of economy plugin. QuickShop didn't process the transaction, we only receive the transaction result from your economy plugin."); + plugin.logger() + .error( + "Tips: If you see any economy plugin name appears above, please don't ask QuickShop support. Contact with developer of economy plugin. QuickShop didn't process the transaction, we only receive the transaction result from your economy plugin."); return; } @@ -264,7 +285,9 @@ public class SimpleShopManager implements ShopManager, Reloadable { } catch (Exception shopError) { plugin.logger().warn("Failed to processing purchase, rolling back...", shopError); transaction.rollback(true); - plugin.text().of(buyer, "shop-transaction-failed", shopError.getMessage()).send(); + plugin.text() + .of(buyer, "shop-transaction-failed", shopError.getMessage()) + .send(); return; } sendSellSuccess(buyerQUser, shop, amount, total, transaction.getTax()); @@ -275,24 +298,33 @@ public class SimpleShopManager implements ShopManager, Reloadable { private void notifySold(@NotNull QUser buyerQUser, @NotNull Shop shop, int amount, int space) { Util.asyncThreadRun(() -> { - String langCode = plugin.text().findRelativeLanguages(buyerQUser, true).getLocale(); + String langCode = + plugin.text().findRelativeLanguages(buyerQUser, true).getLocale(); List sendList = new ArrayList<>(); - Component notify = plugin.text().of("player-sold-to-your-store", buyerQUser.getDisplay(), + Component notify = plugin.text() + .of( + "player-sold-to-your-store", + buyerQUser.getDisplay(), amount, - Util.getItemStackName(shop.getItem())).forLocale(langCode) + Util.getItemStackName(shop.getItem())) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); sendList.add(notify); if (space == amount) { Component spaceWarn; if (shop.getShopName() == null) { - spaceWarn = plugin.text().of("shop-out-of-space", + spaceWarn = plugin.text() + .of( + "shop-out-of-space", shop.getLocation().getBlockX(), shop.getLocation().getBlockY(), - shop.getLocation().getBlockZ()).forLocale(langCode) + shop.getLocation().getBlockZ()) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); } else { - spaceWarn = plugin.text().of("shop-out-of-space-name", shop.getShopName(), - Util.getItemStackName(shop.getItem())).forLocale(langCode) + spaceWarn = plugin.text() + .of("shop-out-of-space-name", shop.getShopName(), Util.getItemStackName(shop.getItem())) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); } sendList.add(spaceWarn); @@ -311,7 +343,10 @@ public class SimpleShopManager implements ShopManager, Reloadable { public boolean shopIsNotValid(@Nullable QUser qUser, @NotNull Info info, @NotNull Shop shop) { if (plugin.getEconomy() == null) { - MsgUtil.sendDirectMessage(qUser, Component.text("Error: Economy system not loaded, type /quickshop main command to get details.").color(NamedTextColor.RED)); + MsgUtil.sendDirectMessage( + qUser, + Component.text("Error: Economy system not loaded, type /quickshop main command to get details.") + .color(NamedTextColor.RED)); return true; } if (!Util.canBeShop(info.getLocation().getBlock())) { @@ -330,7 +365,10 @@ public class SimpleShopManager implements ShopManager, Reloadable { QUser createQUser = QUserImpl.createFullFilled(p); Util.ensureThread(false); if (plugin.getEconomy() == null) { - MsgUtil.sendDirectMessage(p, Component.text("Error: Economy system not loaded, type /quickshop main command to get details.").color(NamedTextColor.RED)); + MsgUtil.sendDirectMessage( + p, + Component.text("Error: Economy system not loaded, type /quickshop main command to get details.") + .color(NamedTextColor.RED)); return; } @@ -346,7 +384,9 @@ public class SimpleShopManager implements ShopManager, Reloadable { String[] processedDouble = strFormat.split("\\."); if (processedDouble.length > 1) { if (processedDouble[1].length() > maximumDigitsLimit && maximumDigitsLimit != -1) { - plugin.text().of(p, "digits-reach-the-limit", Component.text(maximumDigitsLimit)).send(); + plugin.text() + .of(p, "digits-reach-the-limit", Component.text(maximumDigitsLimit)) + .send(); return; } } @@ -393,7 +433,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { Util.ensureThread(false); QUser sellerQUser = QUserImpl.createFullFilled(seller); - if (!plugin.perm().hasPermission(seller, "quickshop.other.use") && !shop.playerAuthorize(seller.getUniqueId(), BuiltInShopPermission.PURCHASE)) { + if (!plugin.perm().hasPermission(seller, "quickshop.other.use") + && !shop.playerAuthorize(seller.getUniqueId(), BuiltInShopPermission.PURCHASE)) { plugin.text().of("no-permission").send(); return; } @@ -405,13 +446,16 @@ public class SimpleShopManager implements ShopManager, Reloadable { stock = 10000; } if (stock < amount) { - plugin.text().of(seller, "shop-stock-too-low", Component.text(stock), - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of(seller, "shop-stock-too-low", Component.text(stock), Util.getItemStackName(shop.getItem())) + .send(); return; } int playerSpace = Util.countSpace(sellerInventory, shop); if (playerSpace < amount) { - plugin.text().of(seller, "inventory-space-full", amount, playerSpace).send(); + plugin.text() + .of(seller, "inventory-space-full", amount, playerSpace) + .send(); return; } if (amount < 1) { @@ -459,23 +503,29 @@ public class SimpleShopManager implements ShopManager, Reloadable { builder.taxModifier(0.0d); } if (!shop.isUnlimited() - || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") - && shop.isUnlimited())) { + || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") && shop.isUnlimited())) { transaction = builder.to(shop.getOwner()).build(); } else { transaction = builder.to(null).build(); } if (!transaction.checkBalance()) { - plugin.text().of(seller, "you-cant-afford-to-buy", - format(total, shop.getLocation().getWorld(), shop.getCurrency()), - format(eco.getBalance(seller, shop.getLocation().getWorld(), - shop.getCurrency()), shop.getLocation().getWorld(), - shop.getCurrency())).send(); + plugin.text() + .of( + seller, + "you-cant-afford-to-buy", + format(total, shop.getLocation().getWorld(), shop.getCurrency()), + format( + eco.getBalance(seller, shop.getLocation().getWorld(), shop.getCurrency()), + shop.getLocation().getWorld(), + shop.getCurrency())) + .send(); return; } if (!transaction.failSafeCommit()) { - plugin.text().of(seller, "economy-transaction-failed", transaction.getLastError()).send(); + plugin.text() + .of(seller, "economy-transaction-failed", transaction.getLastError()) + .send(); plugin.logger().error("EconomyTransaction Failed, last error: {}", transaction.getLastError()); return; } @@ -485,11 +535,14 @@ public class SimpleShopManager implements ShopManager, Reloadable { } catch (Exception shopError) { plugin.logger().warn("Failed to processing purchase, rolling back...", shopError); transaction.rollback(true); - plugin.text().of(seller, "shop-transaction-failed", shopError.getMessage()).send(); + plugin.text() + .of(seller, "shop-transaction-failed", shopError.getMessage()) + .send(); return; } sendPurchaseSuccess(sellerQUser, shop, amount, total, transaction.getTax()); - new ShopSuccessPurchaseEvent(shop, sellerQUser, sellerInventory, amount, total, transaction.getTax()).callEvent(); + new ShopSuccessPurchaseEvent(shop, sellerQUser, sellerInventory, amount, total, transaction.getTax()) + .callEvent(); notifyBought(sellerQUser, shop, amount, stock, transaction.getTax(), total); } @@ -501,9 +554,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { */ private void addShopToLookupTable(@NotNull Shop shop) { String world = shop.getLocation().getWorld().getName(); - Map> inWorld = - this.getShops() - .computeIfAbsent(world, k -> new MapMaker().initialCapacity(3).makeMap()); + Map> inWorld = this.getShops() + .computeIfAbsent(world, k -> new MapMaker().initialCapacity(3).makeMap()); // There's no world storage yet. We need to create that map. // Put it in the data universe // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT @@ -512,8 +564,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); // Get the chunk set from the world info ShopChunk shopChunk = new SimpleShopChunk(world, x, z); - Map inChunk = - inWorld.computeIfAbsent(shopChunk, k -> new MapMaker().initialCapacity(1).makeMap()); + Map inChunk = inWorld.computeIfAbsent( + shopChunk, k -> new MapMaker().initialCapacity(1).makeMap()); // That chunk data hasn't been created yet - Create it! // Put it in the world // Put the shop in its location in the chunk list. @@ -535,10 +587,10 @@ public class SimpleShopManager implements ShopManager, Reloadable { plugin.logger().info("Unloading loaded shops..."); getLoadedShops().forEach(this::unloadShop); plugin.logger().info("Saving shops, please allow up to 30 seconds for flush changes into database..."); - CompletableFuture saveTask = CompletableFuture.allOf( - plugin.getShopManager().getAllShops().stream().filter(Shop::isDirty) - .map(Shop::update) - .toArray(CompletableFuture[]::new)); + CompletableFuture saveTask = CompletableFuture.allOf(plugin.getShopManager().getAllShops().stream() + .filter(Shop::isDirty) + .map(Shop::update) + .toArray(CompletableFuture[]::new)); try { if (PackageUtil.parsePackageProperly("unlimitedWait").asBoolean()) { saveTask.get(); @@ -564,7 +616,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { * @throws IllegalStateException If the shop owner offline */ @Override - public void createShop(@NotNull Shop shop, @Nullable Block signBlock, boolean bypassProtectionCheck) throws IllegalStateException { + public void createShop(@NotNull Shop shop, @Nullable Block signBlock, boolean bypassProtectionCheck) + throws IllegalStateException { Util.ensureThread(false); Player p = shop.getOwner().getBukkitPlayer().orElse(null); @@ -574,7 +627,10 @@ public class SimpleShopManager implements ShopManager, Reloadable { } if (plugin.getEconomy() == null) { - MsgUtil.sendDirectMessage(p, Component.text("Error: Economy system not loaded, type /quickshop main command to get details.").color(NamedTextColor.RED)); + MsgUtil.sendDirectMessage( + p, + Component.text("Error: Economy system not loaded, type /quickshop main command to get details.") + .color(NamedTextColor.RED)); return; } @@ -591,13 +647,17 @@ public class SimpleShopManager implements ShopManager, Reloadable { // Check if item has been blacklisted if (plugin.getShopItemBlackList().isBlacklisted(shop.getItem()) && !plugin.perm() - .hasPermission(p, "quickshop.bypass." + shop.getItem().getType().name().toLowerCase(Locale.ROOT))) { + .hasPermission( + p, + "quickshop.bypass." + + shop.getItem().getType().name().toLowerCase(Locale.ROOT))) { plugin.text().of(p, "blacklisted-item").send(); return; } // Check if server/player allowed to create stacking shop if (plugin.isAllowStack() && !plugin.perm().hasPermission(p, "quickshop.create.stacks")) { - Log.debug("Player " + p.getName() + " no permission to create stacks shop, forcing creating single item shop"); + Log.debug("Player " + p.getName() + + " no permission to create stacks shop, forcing creating single item shop"); shop.getItem().setAmount(1); } @@ -608,9 +668,13 @@ public class SimpleShopManager implements ShopManager, Reloadable { if (!bypassProtectionCheck) { Result result = plugin.getPermissionChecker().canBuild(p, shop.getLocation()); if (!result.isSuccess()) { - plugin.text().of(p, "3rd-plugin-build-check-failed", result.getMessage()).send(); + plugin.text() + .of(p, "3rd-plugin-build-check-failed", result.getMessage()) + .send(); if (plugin.perm().hasPermission(p, "quickshop.alert")) { - plugin.text().of(p, "3rd-plugin-build-check-failed-admin", result.getMessage(), result.getListener()).send(); + plugin.text() + .of(p, "3rd-plugin-build-check-failed-admin", result.getMessage(), result.getListener()) + .send(); } Log.debug("Failed to create shop because protection check failed, found:" + result.getMessage()); return; @@ -639,9 +703,7 @@ public class SimpleShopManager implements ShopManager, Reloadable { } } else { Material signType = signBlock.getType(); - if (signType != Material.WATER - && !signType.isAir() - && !allowNoSpaceForSign) { + if (signType != Material.WATER && !signType.isAir() && !allowNoSpaceForSign) { plugin.text().of(p, "failed-to-put-sign").send(); return; } @@ -649,25 +711,48 @@ public class SimpleShopManager implements ShopManager, Reloadable { } // Price limit checking - PriceLimiterCheckResult priceCheckResult = this.priceLimiter.check(p, shop.getItem(), plugin.getCurrency(), shop.getPrice()); + PriceLimiterCheckResult priceCheckResult = + this.priceLimiter.check(p, shop.getItem(), plugin.getCurrency(), shop.getPrice()); switch (priceCheckResult.getStatus()) { - case REACHED_PRICE_MIN_LIMIT -> plugin.text().of(p, "price-too-cheap", - Component.text((useDecFormat) ? MsgUtil.decimalFormat(priceCheckResult.getMax()) - : Double.toString(priceCheckResult.getMin()))).send(); - case REACHED_PRICE_MAX_LIMIT -> plugin.text().of(p, "price-too-high", - Component.text((useDecFormat) ? MsgUtil.decimalFormat(priceCheckResult.getMax()) - : Double.toString(priceCheckResult.getMin()))).send(); - case PRICE_RESTRICTED -> plugin.text().of(p, "restricted-prices", - Util.getItemStackName(shop.getItem()), - Component.text(priceCheckResult.getMin()), - Component.text(priceCheckResult.getMax())).send(); - case NOT_VALID -> plugin.text().of(p, "not-a-number", shop.getPrice()).send(); - case NOT_A_WHOLE_NUMBER -> plugin.text().of(p, "not-a-integer", shop.getPrice()).send(); + case REACHED_PRICE_MIN_LIMIT -> plugin.text() + .of( + p, + "price-too-cheap", + Component.text( + (useDecFormat) + ? MsgUtil.decimalFormat(priceCheckResult.getMax()) + : Double.toString(priceCheckResult.getMin()))) + .send(); + case REACHED_PRICE_MAX_LIMIT -> plugin.text() + .of( + p, + "price-too-high", + Component.text( + (useDecFormat) + ? MsgUtil.decimalFormat(priceCheckResult.getMax()) + : Double.toString(priceCheckResult.getMin()))) + .send(); + case PRICE_RESTRICTED -> plugin.text() + .of( + p, + "restricted-prices", + Util.getItemStackName(shop.getItem()), + Component.text(priceCheckResult.getMin()), + Component.text(priceCheckResult.getMax())) + .send(); + case NOT_VALID -> plugin.text() + .of(p, "not-a-number", shop.getPrice()) + .send(); + case NOT_A_WHOLE_NUMBER -> plugin.text() + .of(p, "not-a-integer", shop.getPrice()) + .send(); case PASS -> { // Calling ShopCreateEvent ShopCreateEvent shopCreateEvent = new ShopCreateEvent(shop, shop.getOwner()); if (Util.fireCancellableEvent(shopCreateEvent)) { - plugin.text().of(p, "plugin-cancelled", shopCreateEvent.getCancelReason()).send(); + plugin.text() + .of(p, "plugin-cancelled", shopCreateEvent.getCancelReason()) + .send(); return; } // Handle create cost @@ -679,27 +764,34 @@ public class SimpleShopManager implements ShopManager, Reloadable { createCost = 0; } if (createCost > 0) { - SimpleEconomyTransaction economyTransaction = - SimpleEconomyTransaction.builder() - .taxAccount(cacheTaxAccount) - .taxModifier(0.0) - .core(plugin.getEconomy()) - .from(p.getUniqueId()) - .to(null) - .amount(createCost) - .currency(plugin.getCurrency()) - .world(shop.getLocation().getWorld()) - .build(); + SimpleEconomyTransaction economyTransaction = SimpleEconomyTransaction.builder() + .taxAccount(cacheTaxAccount) + .taxModifier(0.0) + .core(plugin.getEconomy()) + .from(p.getUniqueId()) + .to(null) + .amount(createCost) + .currency(plugin.getCurrency()) + .world(shop.getLocation().getWorld()) + .build(); if (!economyTransaction.checkBalance()) { - plugin.text().of(p, "you-cant-afford-a-new-shop", - format(createCost, shop.getLocation().getWorld(), - shop.getCurrency())).send(); + plugin.text() + .of( + p, + "you-cant-afford-a-new-shop", + format(createCost, shop.getLocation().getWorld(), shop.getCurrency())) + .send(); return; } if (!economyTransaction.failSafeCommit()) { - plugin.text().of(p, "economy-transaction-failed", economyTransaction.getLastError()).send(); - plugin.logger().error("EconomyTransaction Failed, last error:{} ", economyTransaction.getLastError()); - plugin.logger().error("Tips: If you see any economy plugin name appears above, please don't ask QuickShop support. Contact with developer of economy plugin. QuickShop didn't process the transaction, we only receive the transaction result from your economy plugin."); + plugin.text() + .of(p, "economy-transaction-failed", economyTransaction.getLastError()) + .send(); + plugin.logger() + .error("EconomyTransaction Failed, last error:{} ", economyTransaction.getLastError()); + plugin.logger() + .error( + "Tips: If you see any economy plugin name appears above, please don't ask QuickShop support. Contact with developer of economy plugin. QuickShop didn't process the transaction, we only receive the transaction result from your economy plugin."); return; } } @@ -712,7 +804,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { // Shop info sign check if (signBlock != null && autoSign) { if (signBlock.getType().isAir() || signBlock.getType() == Material.WATER) { - BlockState signState = this.processWaterLoggedSign(shop.getLocation().getBlock(), signBlock); + BlockState signState = + this.processWaterLoggedSign(shop.getLocation().getBlock(), signBlock); if (signState instanceof Sign puttedSign) { try { shop.claimShopSign(puttedSign); @@ -773,7 +866,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { public @NotNull List getAllShops() { try (PerfMonitor ignored = new PerfMonitor("Getting all shops")) { final List shopsCollected = new ArrayList<>(); - for (final Map> shopMapData : getShops().values()) { + for (final Map> shopMapData : + getShops().values()) { for (final Map shopData : shopMapData.values()) { shopsCollected.addAll(shopData.values()); } @@ -898,8 +992,7 @@ public class SimpleShopManager implements ShopManager, Reloadable { @Override @Nullable - public Shop getShopFromRuntimeRandomUniqueId( - @NotNull UUID runtimeRandomUniqueId, boolean includeInvalid) { + public Shop getShopFromRuntimeRandomUniqueId(@NotNull UUID runtimeRandomUniqueId, boolean includeInvalid) { Shop shop = shopRuntimeUUIDCaching.getIfPresent(runtimeRandomUniqueId); if (shop == null) { for (Shop shopWithoutCache : this.getLoadedShops()) { @@ -1026,7 +1119,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { final List worldShops = new ArrayList<>(); for (final Shop shop : getAllShops()) { Location location = shop.getLocation(); - if (location.isWorldLoaded() && StringUtils.equals(worldName, location.getWorld().getName())) { + if (location.isWorldLoaded() + && StringUtils.equals(worldName, location.getWorld().getName())) { worldShops.add(shop); } } @@ -1043,10 +1137,12 @@ public class SimpleShopManager implements ShopManager, Reloadable { } if (shop.isUnlimited() && plugin.perm().hasPermission(p, "quickshop.tax.bypassunlimited")) { tax = 0; - Log.debug("Disable the Tax for player " + p + " cause they have permission quickshop.tax.bypassunlimited and shop is unlimited."); + Log.debug("Disable the Tax for player " + p + + " cause they have permission quickshop.tax.bypassunlimited and shop is unlimited."); } if (tax >= 1.0) { - plugin.logger().warn("Disable tax due to is invalid, it should be in >=0.0 and <1.0 (current value is {})", tax); + plugin.logger() + .warn("Disable tax due to is invalid, it should be in >=0.0 and <1.0 (current value is {})", tax); tax = 0; } if (tax < 0) { @@ -1056,7 +1152,6 @@ public class SimpleShopManager implements ShopManager, Reloadable { tax = 0; // Is owner, so we won't will take them tax } - ShopTaxEvent taxEvent = new ShopTaxEvent(shop, tax, p); taxEvent.callEvent(); return taxEvent.getTax(); @@ -1117,9 +1212,13 @@ public class SimpleShopManager implements ShopManager, Reloadable { } int additional = 0; try { - additional = (int) Class.forName("dev.dan.quickshoplimit.QuickShopLimit").getMethod("getAdditionalCount", Player.class).invoke(additional, p.getBukkitPlayer().get()); - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | - InvocationTargetException e){ + additional = (int) Class.forName("dev.dan.quickshoplimit.QuickShopLimit") + .getMethod("getAdditionalCount", Player.class) + .invoke(additional, p.getBukkitPlayer().get()); + } catch (ClassNotFoundException + | NoSuchMethodException + | IllegalAccessException + | InvocationTargetException e) { e.printStackTrace(); } int max = plugin.getRankLimiter().getShopLimit(p) + additional; @@ -1143,7 +1242,6 @@ public class SimpleShopManager implements ShopManager, Reloadable { this.loadedShops.remove(shop); } - /** * Change the owner to unlimited shop owner. * It defined in configuration. @@ -1159,12 +1257,16 @@ public class SimpleShopManager implements ShopManager, Reloadable { // save to database addShopToLookupTable(shop); if (!persist) return CompletableFuture.completedFuture(null); - return plugin.getDatabaseHelper().createData(shop).thenCompose(plugin.getDatabaseHelper()::createShop) + return plugin.getDatabaseHelper() + .createData(shop) + .thenCompose(plugin.getDatabaseHelper()::createShop) .thenAccept(id -> { Log.debug("DEBUG: Setting shop id"); shop.setShopId(id); Log.debug("DEBUG: Creating shop map"); - plugin.getDatabaseHelper().createShopMap(id, shop.getLocation()).join(); + plugin.getDatabaseHelper() + .createShopMap(id, shop.getLocation()) + .join(); Log.debug("DEBUG: Creating shop successfully"); shop.setDirty(); new ShopCreateSuccessEvent(shop, shop.getOwner()).callEvent(); @@ -1180,7 +1282,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { removeShopFromLookupTable(shop); if (!persist) return CompletableFuture.completedFuture(null); Location loc = shop.getLocation(); - return plugin.getDatabaseHelper().removeShopMap(loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()) + return plugin.getDatabaseHelper() + .removeShopMap(loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()) .thenCombine(plugin.getDatabaseHelper().removeShop(shop.getShopId()), (a, b) -> null) .exceptionally(throwable -> { plugin.logger().warn("Failed to remove shop from database", throwable); @@ -1208,26 +1311,26 @@ public class SimpleShopManager implements ShopManager, Reloadable { if (plugin.getConfig().getBoolean("shop.refund")) { double cost = plugin.getConfig().getDouble("shop.cost"); SimpleEconomyTransaction transaction; - if (plugin.getConfig().getBoolean("shop.refund-from-tax-account", false) && shop.getTaxAccountActual() != null) { - cost = Math.min(cost, plugin.getEconomy().getBalance(shop.getTaxAccountActual(), world, plugin.getCurrency())); - transaction = - SimpleEconomyTransaction.builder() - .amount(cost) - .core(plugin.getEconomy()) - .currency(plugin.getCurrency()) - .world(world) - .from(shop.getTaxAccountActual()) - .to(shop.getOwner()) - .build(); + if (plugin.getConfig().getBoolean("shop.refund-from-tax-account", false) + && shop.getTaxAccountActual() != null) { + cost = Math.min( + cost, plugin.getEconomy().getBalance(shop.getTaxAccountActual(), world, plugin.getCurrency())); + transaction = SimpleEconomyTransaction.builder() + .amount(cost) + .core(plugin.getEconomy()) + .currency(plugin.getCurrency()) + .world(world) + .from(shop.getTaxAccountActual()) + .to(shop.getOwner()) + .build(); } else { - transaction = - SimpleEconomyTransaction.builder() - .amount(cost) - .core(plugin.getEconomy()) - .currency(plugin.getCurrency()) - .world(world) - .to(shop.getOwner()) - .build(); + transaction = SimpleEconomyTransaction.builder() + .amount(cost) + .core(plugin.getEconomy()) + .currency(plugin.getCurrency()) + .world(world) + .to(shop.getOwner()) + .build(); } if (!transaction.failSafeCommit()) { plugin.logger().warn("Shop deletion refund failed. Reason: {}", transaction.getLastError()); @@ -1267,21 +1370,31 @@ public class SimpleShopManager implements ShopManager, Reloadable { * @param amount Trading item amounts. */ @Override - public void sendPurchaseSuccess(@NotNull QUser purchaser, @NotNull Shop shop, int amount, double total, double tax) { + public void sendPurchaseSuccess( + @NotNull QUser purchaser, @NotNull Shop shop, int amount, double total, double tax) { ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(purchaser); chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(plugin.text().of(purchaser, "menu.successful-purchase").forLocale()); + chatSheetPrinter.printLine( + plugin.text().of(purchaser, "menu.successful-purchase").forLocale()); if (showTax) { - chatSheetPrinter.printLine(plugin.text().of(purchaser, "menu.item-name-and-price-tax", - Component.text(amount * shop.getItem().getAmount()), - Util.getItemStackName(shop.getItem()), - format(total, shop), - tax).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of( + purchaser, + "menu.item-name-and-price-tax", + Component.text(amount * shop.getItem().getAmount()), + Util.getItemStackName(shop.getItem()), + format(total, shop), + tax) + .forLocale()); } else { - chatSheetPrinter.printLine(plugin.text().of(purchaser, "menu.item-name-and-price", - Component.text(amount * shop.getItem().getAmount()), - Util.getItemStackName(shop.getItem()), - format(total, shop)).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of( + purchaser, + "menu.item-name-and-price", + Component.text(amount * shop.getItem().getAmount()), + Util.getItemStackName(shop.getItem()), + format(total, shop)) + .forLocale()); } MsgUtil.printEnchantment(shop, chatSheetPrinter); chatSheetPrinter.printFooter(); @@ -1298,20 +1411,25 @@ public class SimpleShopManager implements ShopManager, Reloadable { public void sendSellSuccess(@NotNull QUser seller, @NotNull Shop shop, int amount, double total, double tax) { ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(seller); chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(plugin.text().of(seller, "menu.successfully-sold").forLocale()); chatSheetPrinter.printLine( - plugin.text().of(seller, + plugin.text().of(seller, "menu.successfully-sold").forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of( + seller, "menu.item-name-and-price", amount, Util.getItemStackName(shop.getItem()), - format(total, shop)).forLocale()); + format(total, shop)) + .forLocale()); if (showTax) { if (tax != 0) { if (!seller.equals(shop.getOwner())) { - chatSheetPrinter.printLine( - plugin.text().of(seller, "menu.sell-tax", format(tax, shop)).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of(seller, "menu.sell-tax", format(tax, shop)) + .forLocale()); } else { - chatSheetPrinter.printLine(plugin.text().of(seller, "menu.sell-tax-self").forLocale()); + chatSheetPrinter.printLine( + plugin.text().of(seller, "menu.sell-tax-self").forLocale()); } } } @@ -1341,63 +1459,98 @@ public class SimpleShopManager implements ShopManager, Reloadable { ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(p); chatSheetPrinter.printHeader(); chatSheetPrinter.printLine(plugin.text().of(p, "menu.shop-information").forLocale()); - chatSheetPrinter.printLine(plugin.text().of(p, "menu.owner", shop.ownerName(locale)).forLocale()); + chatSheetPrinter.printLine( + plugin.text().of(p, "menu.owner", shop.ownerName(locale)).forLocale()); // Enabled if (shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.PREVIEW_SHOP) || plugin.perm().hasPermission(p, "quickshop.other.preview")) { ItemStack previewItemStack = shop.getItem().clone(); - ItemPreviewComponentPrePopulateEvent previewComponentPrePopulateEvent = new ItemPreviewComponentPrePopulateEvent(previewItemStack, p); + ItemPreviewComponentPrePopulateEvent previewComponentPrePopulateEvent = + new ItemPreviewComponentPrePopulateEvent(previewItemStack, p); previewComponentPrePopulateEvent.callEvent(); previewItemStack = previewComponentPrePopulateEvent.getItemStack(); - Component previewComponent = plugin.text().of(p, "menu.preview", Component.text(previewItemStack.getAmount())).forLocale() + Component previewComponent = plugin.text() + .of(p, "menu.preview", Component.text(previewItemStack.getAmount())) + .forLocale() .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(previewItemStack)) - .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, MsgUtil.fillArgs("/quickshop silentpreview {0}", shop.getRuntimeRandomUniqueId().toString()))); - ItemPreviewComponentPopulateEvent itemPreviewComponentPopulateEvent = new ItemPreviewComponentPopulateEvent(previewComponent, p); + .clickEvent(ClickEvent.clickEvent( + ClickEvent.Action.RUN_COMMAND, + MsgUtil.fillArgs( + "/quickshop silentpreview {0}", + shop.getRuntimeRandomUniqueId().toString()))); + ItemPreviewComponentPopulateEvent itemPreviewComponentPopulateEvent = + new ItemPreviewComponentPopulateEvent(previewComponent, p); itemPreviewComponentPopulateEvent.callEvent(); previewComponent = itemPreviewComponentPopulateEvent.getComponent(); - chatSheetPrinter.printLine(plugin.text().of(p, "menu.item", Util.getItemStackName(shop.getItem())).forLocale() + chatSheetPrinter.printLine(plugin.text() + .of(p, "menu.item", Util.getItemStackName(shop.getItem())) + .forLocale() .append(Component.text(" ")) - .append(previewComponent) - ); + .append(previewComponent)); } else { ItemStack previewItemStack = shop.getItem().clone(); - ItemPreviewComponentPrePopulateEvent previewComponentPrePopulateEvent = new ItemPreviewComponentPrePopulateEvent(previewItemStack, p); + ItemPreviewComponentPrePopulateEvent previewComponentPrePopulateEvent = + new ItemPreviewComponentPrePopulateEvent(previewItemStack, p); previewComponentPrePopulateEvent.callEvent(); - chatSheetPrinter.printLine(plugin.text().of(p, "menu.item", Util.getItemStackName(previewComponentPrePopulateEvent.getItemStack())).forLocale() - .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(previewComponentPrePopulateEvent.getItemStack())) - ); + chatSheetPrinter.printLine(plugin.text() + .of(p, "menu.item", Util.getItemStackName(previewComponentPrePopulateEvent.getItemStack())) + .forLocale() + .hoverEvent(plugin.getPlatform() + .getItemStackHoverEvent(previewComponentPrePopulateEvent.getItemStack()))); } if (Util.isTool(items.getType())) { - chatSheetPrinter.printLine( - plugin.text().of(p, "menu.damage-percent-remaining", Component.text(Util.getToolPercentage(items))).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of(p, "menu.damage-percent-remaining", Component.text(Util.getToolPercentage(items))) + .forLocale()); } if (shop.isSelling()) { if (shop.getRemainingStock() == -1) { - chatSheetPrinter.printLine( - plugin.text().of(p, "menu.stock", plugin.text().of(p, "signs.unlimited").forLocale()).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of( + p, + "menu.stock", + plugin.text().of(p, "signs.unlimited").forLocale()) + .forLocale()); } else { - chatSheetPrinter.printLine( - plugin.text().of(p, "menu.stock", Component.text(shop.getRemainingStock())).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of(p, "menu.stock", Component.text(shop.getRemainingStock())) + .forLocale()); } } else { if (shop.getRemainingSpace() == -1) { - chatSheetPrinter.printLine( - plugin.text().of(p, "menu.space", plugin.text().of(p, "signs.unlimited").forLocale()).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of( + p, + "menu.space", + plugin.text().of(p, "signs.unlimited").forLocale()) + .forLocale()); } else { - chatSheetPrinter.printLine( - plugin.text().of(p, "menu.space", Component.text(shop.getRemainingSpace())).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of(p, "menu.space", Component.text(shop.getRemainingSpace())) + .forLocale()); } } if (shop.getItem().getAmount() == 1) { - chatSheetPrinter.printLine(plugin.text().of(p, "menu.price-per", Util.getItemStackName(shop.getItem()), format(shop.getPrice(), shop)).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of(p, "menu.price-per", Util.getItemStackName(shop.getItem()), format(shop.getPrice(), shop)) + .forLocale()); } else { - chatSheetPrinter.printLine(plugin.text().of(p, "menu.price-per-stack", Util.getItemStackName(shop.getItem()), format(shop.getPrice(), shop), shop.getItem().getAmount()).forLocale()); + chatSheetPrinter.printLine(plugin.text() + .of( + p, + "menu.price-per-stack", + Util.getItemStackName(shop.getItem()), + format(shop.getPrice(), shop), + shop.getItem().getAmount()) + .forLocale()); } if (shop.isBuying()) { - chatSheetPrinter.printLine(plugin.text().of(p, "menu.this-shop-is-buying").forLocale()); + chatSheetPrinter.printLine( + plugin.text().of(p, "menu.this-shop-is-buying").forLocale()); } else { - chatSheetPrinter.printLine(plugin.text().of(p, "menu.this-shop-is-selling").forLocale()); + chatSheetPrinter.printLine( + plugin.text().of(p, "menu.this-shop-is-selling").forLocale()); } MsgUtil.printEnchantment(shop, chatSheetPrinter); if (items.getItemMeta() instanceof PotionMeta potionMeta) { @@ -1409,14 +1562,13 @@ public class SimpleShopManager implements ShopManager, Reloadable { translation = plugin.getPlatform().getTranslation(potionEffectType); } catch (Throwable th) { translation = MsgUtil.setHandleFailedHover(p, Component.text(potionEffectType.getName())); - plugin.logger().warn("Failed to handle translation for PotionEffect {}", potionEffectType.getKey(), th); + plugin.logger() + .warn("Failed to handle translation for PotionEffect {}", potionEffectType.getKey(), th); } chatSheetPrinter.printLine(plugin.text().of(p, "menu.effects").forLocale()); - //Because the bukkit API limit, we can't get the actual effect level - chatSheetPrinter.printLine(Component.empty() - .color(NamedTextColor.YELLOW) - .append(translation) - ); + // Because the bukkit API limit, we can't get the actual effect level + chatSheetPrinter.printLine( + Component.empty().color(NamedTextColor.YELLOW).append(translation)); } if (potionMeta.hasCustomEffects()) { for (PotionEffect potionEffect : potionMeta.getCustomEffects()) { @@ -1425,17 +1577,22 @@ public class SimpleShopManager implements ShopManager, Reloadable { try { translation = plugin.getPlatform().getTranslation(potionEffect.getType()); } catch (Throwable th) { - translation = MsgUtil.setHandleFailedHover(p, Component.text(potionEffect.getType().getName())); - plugin.logger().warn("Failed to handle translation for PotionEffect {}", potionEffect.getType().getKey(), th); + translation = MsgUtil.setHandleFailedHover( + p, Component.text(potionEffect.getType().getName())); + plugin.logger() + .warn( + "Failed to handle translation for PotionEffect {}", + potionEffect.getType().getKey(), + th); } chatSheetPrinter.printLine(Component.empty() .color(NamedTextColor.YELLOW) - .append(translation).append(Component.text(" " + (level <= 10 ? RomanNumber.toRoman(level) : level)))); + .append(translation) + .append(Component.text(" " + (level <= 10 ? RomanNumber.toRoman(level) : level)))); } } } chatSheetPrinter.printFooter(); - } @Override @@ -1443,26 +1600,33 @@ public class SimpleShopManager implements ShopManager, Reloadable { return this.interactiveManager; } - - private void notifyBought(@NotNull QUser seller, @NotNull Shop shop, int amount, int stock, double tax, double total) { + private void notifyBought( + @NotNull QUser seller, @NotNull Shop shop, int amount, int stock, double tax, double total) { Util.asyncThreadRun(() -> { - String langCode = plugin.text().findRelativeLanguages(shop.getOwner(), true).getLocale(); + String langCode = + plugin.text().findRelativeLanguages(shop.getOwner(), true).getLocale(); List sendList = new ArrayList<>(); Component notify; if (plugin.getConfig().getBoolean("show-tax")) { - notify = plugin.text().of("player-bought-from-your-store-tax", + notify = plugin.text() + .of( + "player-bought-from-your-store-tax", seller, amount * shop.getItem().getAmount(), Util.getItemStackName(shop.getItem()), this.formatter.format(total - tax, shop), - this.formatter.format(tax, shop)).forLocale(langCode) + this.formatter.format(tax, shop)) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); } else { - notify = plugin.text().of("player-bought-from-your-store", + notify = plugin.text() + .of( + "player-bought-from-your-store", seller, amount * shop.getItem().getAmount(), Util.getItemStackName(shop.getItem()), - this.formatter.format(total - tax, shop)).forLocale(langCode) + this.formatter.format(total - tax, shop)) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); } sendList.add(notify); @@ -1470,15 +1634,19 @@ public class SimpleShopManager implements ShopManager, Reloadable { if (stock == amount) { Component stockWarn; if (shop.getShopName() == null) { - stockWarn = plugin.text().of("shop-out-of-stock", + stockWarn = plugin.text() + .of( + "shop-out-of-stock", shop.getLocation().getBlockX(), shop.getLocation().getBlockY(), shop.getLocation().getBlockZ(), - Util.getItemStackName(shop.getItem())).forLocale(langCode) + Util.getItemStackName(shop.getItem())) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); } else { - stockWarn = plugin.text().of("shop-out-of-stock-name", shop.getShopName(), - Util.getItemStackName(shop.getItem())).forLocale(langCode) + stockWarn = plugin.text() + .of("shop-out-of-stock-name", shop.getShopName(), Util.getItemStackName(shop.getItem())) + .forLocale(langCode) .hoverEvent(plugin.getPlatform().getItemStackHoverEvent(shop.getItem())); } sendList.add(stockWarn); @@ -1510,23 +1678,21 @@ public class SimpleShopManager implements ShopManager, Reloadable { signBlockState.setBlockData(wallSignBlockData); } } else { - plugin.logger().warn( - "Sign material {} not a WallSign, make sure you using correct sign material.", signBlockState.getType().name()); + plugin.logger() + .warn( + "Sign material {} not a WallSign, make sure you using correct sign material.", + signBlockState.getType().name()); } signBlockState.update(true); return signBlockState; } - private int buyingShopAllCalc(@NotNull AbstractEconomy eco, @NotNull Shop shop, @NotNull Player p) { int amount; - int shopHaveSpaces = - Util.countSpace(shop.getInventory(), shop); + int shopHaveSpaces = Util.countSpace(shop.getInventory(), shop); int invHaveItems = Util.countItems(new BukkitInventoryWrapper(p.getInventory()), shop); // Check if shop owner has enough money - double ownerBalance = eco - .getBalance(shop.getOwner(), shop.getLocation().getWorld(), - shop.getCurrency()); + double ownerBalance = eco.getBalance(shop.getOwner(), shop.getLocation().getWorld(), shop.getCurrency()); int ownerCanAfford; if (shop.getPrice() != 0) { ownerCanAfford = (int) (ownerBalance / shop.getPrice()); @@ -1548,24 +1714,40 @@ public class SimpleShopManager implements ShopManager, Reloadable { if (amount < 1) { // typed 'all' but the auto set amount is 0 if (shopHaveSpaces == 0) { // when typed 'all' but the shop doesn't have any empty space - plugin.text().of(p, "shop-has-no-space", Component.text(shopHaveSpaces), - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of( + p, + "shop-has-no-space", + Component.text(shopHaveSpaces), + Util.getItemStackName(shop.getItem())) + .send(); return 0; } if (ownerCanAfford == 0 && (!shop.isUnlimited() || payUnlimitedShopOwner)) { // when typed 'all' but the shop owner doesn't have enough money to buy at least 1 // item (and shop isn't unlimited or pay-unlimited is true) - plugin.text().of(p, "the-owner-cant-afford-to-buy-from-you", - plugin.getShopManager().format(shop.getPrice(), shop.getLocation().getWorld(), - shop.getCurrency()), - plugin.getShopManager().format(ownerBalance, shop.getLocation().getWorld(), - shop.getCurrency())).send(); + plugin.text() + .of( + p, + "the-owner-cant-afford-to-buy-from-you", + plugin.getShopManager() + .format( + shop.getPrice(), + shop.getLocation().getWorld(), + shop.getCurrency()), + plugin.getShopManager() + .format(ownerBalance, shop.getLocation().getWorld(), shop.getCurrency())) + .send(); return 0; } // when typed 'all' but player doesn't have any items to sell - plugin.text().of(p, "you-dont-have-that-many-items", - Component.text(amount), - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of( + p, + "you-dont-have-that-many-items", + Component.text(amount), + Util.getItemStackName(shop.getItem())) + .send(); return 0; } return amount; @@ -1591,7 +1773,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { } } else { // optimize for performance - BlockState state = PaperLib.getBlockState(currentBlock, false).getState(); + BlockState state = + PaperLib.getBlockState(currentBlock, false).getState(); if (!(state instanceof InventoryHolder holder)) { return null; } @@ -1608,7 +1791,10 @@ public class SimpleShopManager implements ShopManager, Reloadable { private void actionTrade(@NotNull Player p, Info info, @NotNull String message) { Util.ensureThread(false); if (plugin.getEconomy() == null) { - MsgUtil.sendDirectMessage(p, Component.text("Error: Economy system not loaded, type /quickshop main command to get details.").color(NamedTextColor.RED)); + MsgUtil.sendDirectMessage( + p, + Component.text("Error: Economy system not loaded, type /quickshop main command to get details.") + .color(NamedTextColor.RED)); return; } AbstractEconomy eco = plugin.getEconomy(); @@ -1639,8 +1825,7 @@ public class SimpleShopManager implements ShopManager, Reloadable { // instead of output cancelled message (when typed neither integer or 'all'), just let // player know that there should be positive number or 'all' plugin.text().of(p, "not-a-integer", message).send(); - Log.debug( - "Receive the chat " + message + " and it format failed: " + message); + Log.debug("Receive the chat " + message + " and it format failed: " + message); return; } } @@ -1670,11 +1855,11 @@ public class SimpleShopManager implements ShopManager, Reloadable { @Override public CompletableFuture<@NotNull List> queryTaggedShops(@NotNull UUID tagger, @NotNull String tag) { Util.ensureThread(true); - return CompletableFuture.supplyAsync(() -> plugin.getDatabaseHelper().listShopsTaggedBy(tagger, tag) - .stream() - .map(this::getShop).toList() - , QuickExecutor.getDatabaseExecutor()); - + return CompletableFuture.supplyAsync( + () -> plugin.getDatabaseHelper().listShopsTaggedBy(tagger, tag).stream() + .map(this::getShop) + .toList(), + QuickExecutor.getDatabaseExecutor()); } @Override @@ -1690,7 +1875,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { } @Override - public CompletableFuture<@Nullable Integer> removeTag(@NotNull UUID tagger, @NotNull Shop shop, @NotNull String tag) { + public CompletableFuture<@Nullable Integer> removeTag( + @NotNull UUID tagger, @NotNull Shop shop, @NotNull String tag) { tag = tag.trim().toLowerCase(Locale.ROOT); tag = tag.replace(" ", "_"); return plugin.getDatabaseHelper().removeShopTag(tagger, shop.getShopId(), tag); @@ -1739,29 +1925,37 @@ public class SimpleShopManager implements ShopManager, Reloadable { } // typed 'all', check if player has enough money than price * amount double price = shop.getPrice(); - double balance = eco.getBalance(p.getUniqueId(), shop.getLocation().getWorld(), - shop.getCurrency()); + double balance = eco.getBalance(p.getUniqueId(), shop.getLocation().getWorld(), shop.getCurrency()); amount = Math.min(amount, (int) Math.floor(balance / price)); if (amount < 1) { // typed 'all' but the auto set amount is 0 // when typed 'all' but player can't buy any items if (!shop.isUnlimited() && shopHaveItems < 1) { // but also the shop's stock is 0 - plugin.text().of(p, "shop-stock-too-low", - Component.text(shop.getRemainingStock()), - Util.getItemStackName(shop.getItem())).send(); + plugin.text() + .of( + p, + "shop-stock-too-low", + Component.text(shop.getRemainingStock()), + Util.getItemStackName(shop.getItem())) + .send(); return 0; } else { // when if player's inventory is full if (invHaveSpaces <= 0) { - plugin.text().of(p, "not-enough-space", - Component.text(invHaveSpaces)).send(); + plugin.text() + .of(p, "not-enough-space", Component.text(invHaveSpaces)) + .send(); return 0; } - plugin.text().of(p, "you-cant-afford-to-buy", - plugin.getShopManager().format(price, shop.getLocation().getWorld(), - shop.getCurrency()), - plugin.getShopManager().format(balance, shop.getLocation().getWorld(), - shop.getCurrency())).send(); + plugin.text() + .of( + p, + "you-cant-afford-to-buy", + plugin.getShopManager() + .format(price, shop.getLocation().getWorld(), shop.getCurrency()), + plugin.getShopManager() + .format(balance, shop.getLocation().getWorld(), shop.getCurrency())) + .send(); } return 0; } @@ -1939,7 +2133,8 @@ public class SimpleShopManager implements ShopManager, Reloadable { if (tagName.isEmpty()) { throw new IllegalArgumentException("Tag name can't be empty"); } - List shops = singleCaching.computeIfAbsent(tag, (t) -> shopManager.queryTaggedShops(tagger, t).join()); + List shops = singleCaching.computeIfAbsent( + tag, (t) -> shopManager.queryTaggedShops(tagger, t).join()); return new ParseResult(behavior, shops); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopModerator.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopModerator.java index ca37de593..5f8fd508a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopModerator.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopModerator.java @@ -4,13 +4,12 @@ import com.ghostchu.quickshop.api.shop.ShopModerator; import com.ghostchu.quickshop.common.util.JsonUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.List; import java.util.UUID; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.jetbrains.annotations.NotNull; /** * Contains shop's moderators infomations, owner, staffs etc. @@ -169,5 +168,4 @@ public class SimpleShopModerator implements ShopModerator { SimpleShopModerator gsonWorkaround = (SimpleShopModerator) shopModerator; return gson.toJson(gsonWorkaround); // Use Gson serialize this class } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopPermissionManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopPermissionManager.java index da5edc74d..3e5cc209e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopPermissionManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/SimpleShopPermissionManager.java @@ -10,16 +10,15 @@ import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; import com.google.common.collect.ImmutableList; import com.google.common.collect.MapMaker; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; public class SimpleShopPermissionManager implements ShopPermissionManager, Reloadable { private final Map> permissionMapping = new MapMaker().makeMap(); @@ -109,7 +108,11 @@ public class SimpleShopPermissionManager implements ShopPermissionManager, Reloa YamlConfiguration yamlConfiguration = new YamlConfiguration(); yamlConfiguration.set("version", 1); for (BuiltInShopPermissionGroup group : BuiltInShopPermissionGroup.values()) { - yamlConfiguration.set(group.getNamespacedNode(), group.getPermissions().stream().map(BuiltInShopPermission::getNamespacedNode).toList()); + yamlConfiguration.set( + group.getNamespacedNode(), + group.getPermissions().stream() + .map(BuiltInShopPermission::getNamespacedNode) + .toList()); } try { //noinspection ResultOfMethodCallIgnored @@ -135,7 +138,11 @@ public class SimpleShopPermissionManager implements ShopPermissionManager, Reloa || !yamlConfiguration.isSet(namespace + ".blocked")) { plugin.logger().warn("Corrupted group configuration file, creating new one..."); try { - Files.move(file.toPath(), file.toPath().resolveSibling(file.getName() + ".corrupted." + UUID.randomUUID().toString().replace("-", ""))); + Files.move( + file.toPath(), + file.toPath() + .resolveSibling(file.getName() + ".corrupted." + + UUID.randomUUID().toString().replace("-", ""))); loadConfiguration(); } catch (IOException e) { plugin.logger().error("Failed to move corrupted group configuration file", e); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/BoxedShop.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/BoxedShop.java index 6b2a4355d..7c728a77f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/BoxedShop.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/BoxedShop.java @@ -1,9 +1,8 @@ package com.ghostchu.quickshop.shop.cache; import com.ghostchu.quickshop.api.shop.Shop; -import org.jetbrains.annotations.Nullable; - import java.lang.ref.WeakReference; +import org.jetbrains.annotations.Nullable; public class BoxedShop { @Nullable diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/SimpleShopCache.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/SimpleShopCache.java index 1fc07444a..945589635 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/SimpleShopCache.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/cache/SimpleShopCache.java @@ -10,29 +10,37 @@ import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; -import org.apache.commons.lang3.tuple.Pair; -import org.bukkit.Location; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Function; +import org.apache.commons.lang3.tuple.Pair; +import org.bukkit.Location; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SimpleShopCache implements SubPasteItem, ShopCache { private final QuickShop plugin; private final Map> CACHES = new HashMap<>(); private final Map> CACHE_VALUE_PROVIDER = new HashMap<>(); - public SimpleShopCache(@NotNull QuickShop plugin, @NotNull Map<@NotNull ShopCacheNamespacedKey, @NotNull Pair<@NotNull Function, @Nullable Cache>> initArgs) { + public SimpleShopCache( + @NotNull QuickShop plugin, + @NotNull + Map< + @NotNull ShopCacheNamespacedKey, + @NotNull Pair< + @NotNull Function, @Nullable Cache>> + initArgs) { this.plugin = plugin; this.plugin.getPasteManager().register(plugin.getJavaPlugin(), this); - for (Map.Entry, Cache>> entry : initArgs.entrySet()) { + for (Map.Entry, Cache>> entry : + initArgs.entrySet()) { ShopCacheNamespacedKey namespacedKey = entry.getKey(); if (CACHES.containsKey(namespacedKey) || CACHE_VALUE_PROVIDER.containsKey(namespacedKey)) { - throw new IllegalArgumentException("The namespaced key " + namespacedKey.name() + " already registered."); + throw new IllegalArgumentException( + "The namespaced key " + namespacedKey.name() + " already registered."); } Pair, Cache> pair = entry.getValue(); Function valueProvider = pair.getLeft(); @@ -41,7 +49,10 @@ public class SimpleShopCache implements SubPasteItem, ShopCache { } Cache cacheContainer = pair.getRight(); if (cacheContainer == null) { - cacheContainer = CacheBuilder.newBuilder().expireAfterAccess(3, TimeUnit.MINUTES).recordStats().build(); + cacheContainer = CacheBuilder.newBuilder() + .expireAfterAccess(3, TimeUnit.MINUTES) + .recordStats() + .build(); } CACHES.put(namespacedKey, cacheContainer); CACHE_VALUE_PROVIDER.put(namespacedKey, valueProvider); @@ -72,7 +83,9 @@ public class SimpleShopCache implements SubPasteItem, ShopCache { throw new IllegalArgumentException("Shop cache provider " + namespacedKey.name() + " not exists"); } try { - return targetCacheContainer.get(location, () -> new BoxedShop(provider.apply(location))).getShop(); + return targetCacheContainer + .get(location, () -> new BoxedShop(provider.apply(location))) + .getShop(); } catch (ExecutionException e) { plugin.logger().warn("Loading shops into cache failure, fallback to direct access", e); return provider.apply(location); @@ -92,7 +105,6 @@ public class SimpleShopCache implements SubPasteItem, ShopCache { } } - @Override public void invalidate(@Nullable ShopCacheNamespacedKey namespacedKey, @NotNull Location location) { if (namespacedKey == null) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanel.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanel.java index 17b70a192..843d5a59b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanel.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanel.java @@ -7,6 +7,8 @@ import com.ghostchu.quickshop.api.shop.ShopControlPanel; import com.ghostchu.quickshop.api.shop.ShopControlPanelPriority; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import com.ghostchu.quickshop.util.MsgUtil; +import java.util.ArrayList; +import java.util.List; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.HoverEvent; @@ -15,9 +17,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class SimpleShopControlPanel implements ShopControlPanel { /** * Generate components for the shop control panel. @@ -33,120 +32,161 @@ public class SimpleShopControlPanel implements ShopControlPanel { ProxiedLocale locale = plugin.text().findRelativeLanguages(sender.getLocale()); // Owner if (!plugin.perm().hasPermission(sender, "quickshop.setowner")) { - components.add(plugin.text().of(sender, "menu.owner", shop.ownerName(locale)).forLocale()); + components.add(plugin.text() + .of(sender, "menu.owner", shop.ownerName(locale)) + .forLocale()); } else { Component text; if (plugin.getConfig().getBoolean("shop.show-owner-uuid-in-controlpanel-if-op") && shop.isUnlimited()) { - text = plugin.text().of(sender, "controlpanel.setowner-uuid", shop.ownerName(locale), shop.getOwner().toString()).forLocale(); + text = plugin.text() + .of( + sender, + "controlpanel.setowner-uuid", + shop.ownerName(locale), + shop.getOwner().toString()) + .forLocale(); } else { - text = plugin.text().of(sender, "controlpanel.setowner", shop.ownerName(locale)).forLocale(); + text = plugin.text() + .of(sender, "controlpanel.setowner", shop.ownerName(locale)) + .forLocale(); } - components.add(text - .hoverEvent(HoverEvent.showText(plugin.text().of(sender, "controlpanel.setowner-hover").forLocale())) + components.add(text.hoverEvent(HoverEvent.showText(plugin.text() + .of(sender, "controlpanel.setowner-hover") + .forLocale())) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/quickshop setowner "))); } // Unlimited if (plugin.perm().hasPermission(sender, "quickshop.unlimited")) { - Component text = plugin.text().of(sender, "controlpanel.unlimited", MsgUtil.bool2String(shop.isUnlimited())).forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.unlimited-hover").forLocale(); - String clickCommand = MsgUtil.fillArgs("/quickshop silentunlimited {0}", shop.getRuntimeRandomUniqueId().toString()); - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + Component text = plugin.text() + .of(sender, "controlpanel.unlimited", MsgUtil.bool2String(shop.isUnlimited())) + .forLocale(); + Component hoverText = + plugin.text().of(sender, "controlpanel.unlimited-hover").forLocale(); + String clickCommand = MsgUtil.fillArgs( + "/quickshop silentunlimited {0}", + shop.getRuntimeRandomUniqueId().toString()); + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand))); } // Buying/Selling Mode if (plugin.perm().hasPermission(sender, "quickshop.create.buy") && plugin.perm().hasPermission(sender, "quickshop.create.sell") - && (shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_SHOPTYPE) || - plugin.perm().hasPermission(sender, "quickshop.create.admin"))) { + && (shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_SHOPTYPE) + || plugin.perm().hasPermission(sender, "quickshop.create.admin"))) { if (shop.isSelling()) { - Component text = plugin.text().of(sender, "controlpanel.mode-selling").forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.mode-selling-hover").forLocale(); - String clickCommand = MsgUtil.fillArgs("/quickshop silentbuy {0}", shop.getRuntimeRandomUniqueId().toString()); - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + Component text = + plugin.text().of(sender, "controlpanel.mode-selling").forLocale(); + Component hoverText = plugin.text() + .of(sender, "controlpanel.mode-selling-hover") + .forLocale(); + String clickCommand = MsgUtil.fillArgs( + "/quickshop silentbuy {0}", + shop.getRuntimeRandomUniqueId().toString()); + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand))); } else if (shop.isBuying()) { - Component text = plugin.text().of(sender, "controlpanel.mode-buying").forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.mode-buying-hover").forLocale(); - String clickCommand = MsgUtil.fillArgs("/quickshop silentsell {0}", shop.getRuntimeRandomUniqueId().toString()); - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + Component text = + plugin.text().of(sender, "controlpanel.mode-buying").forLocale(); + Component hoverText = plugin.text() + .of(sender, "controlpanel.mode-buying-hover") + .forLocale(); + String clickCommand = MsgUtil.fillArgs( + "/quickshop silentsell {0}", + shop.getRuntimeRandomUniqueId().toString()); + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand))); } } // Set Price if (plugin.perm().hasPermission(sender, "quickshop.other.price") - || (plugin.perm().hasPermission(sender, "quickshop.create.changeprice") && shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_PRICE))) { + || (plugin.perm().hasPermission(sender, "quickshop.create.changeprice") + && shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_PRICE))) { Component text = MsgUtil.fillArgs( plugin.text().of(sender, "controlpanel.price").forLocale(), - LegacyComponentSerializer.legacySection().deserialize( - (plugin.getConfig().getBoolean("use-decimal-format")) - ? MsgUtil.decimalFormat(shop.getPrice()) - : Double.toString(shop.getPrice())) - ); - Component hoverText = plugin.text().of(sender, "controlpanel.price-hover").forLocale(); + LegacyComponentSerializer.legacySection() + .deserialize( + (plugin.getConfig().getBoolean("use-decimal-format")) + ? MsgUtil.decimalFormat(shop.getPrice()) + : Double.toString(shop.getPrice()))); + Component hoverText = + plugin.text().of(sender, "controlpanel.price-hover").forLocale(); String clickCommand = "/quickshop price "; - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, clickCommand))); } - //Set amount per bulk + // Set amount per bulk if (plugin.isAllowStack()) { - if (plugin.perm().hasPermission(sender, "quickshop.other.amount") || - shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_STACK_AMOUNT) && - plugin.perm().hasPermission(sender, "quickshop.create.changeamount")) { - Component text = plugin.text().of(sender, "controlpanel.stack", shop.getItem().getAmount()).forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.stack-hover").forLocale(); + if (plugin.perm().hasPermission(sender, "quickshop.other.amount") + || shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.SET_STACK_AMOUNT) + && plugin.perm().hasPermission(sender, "quickshop.create.changeamount")) { + Component text = plugin.text() + .of(sender, "controlpanel.stack", shop.getItem().getAmount()) + .forLocale(); + Component hoverText = + plugin.text().of(sender, "controlpanel.stack-hover").forLocale(); String clickCommand = "/quickshop size "; - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, clickCommand))); } } if (!shop.isUnlimited()) { // Refill if (plugin.perm().hasPermission(sender, "quickshop.refill")) { - Component text = plugin.text().of(sender, "controlpanel.refill", shop.getPrice()).forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.refill-hover").forLocale(); + Component text = plugin.text() + .of(sender, "controlpanel.refill", shop.getPrice()) + .forLocale(); + Component hoverText = + plugin.text().of(sender, "controlpanel.refill-hover").forLocale(); String clickCommand = "/quickshop refill "; - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, clickCommand))); } // Empty if (plugin.perm().hasPermission(sender, "quickshop.empty")) { - Component text = plugin.text().of(sender, "controlpanel.empty", shop.getPrice()).forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.empty-hover").forLocale(); - String clickCommand = MsgUtil.fillArgs("/quickshop silentempty {0}", shop.getRuntimeRandomUniqueId().toString()); - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + Component text = plugin.text() + .of(sender, "controlpanel.empty", shop.getPrice()) + .forLocale(); + Component hoverText = + plugin.text().of(sender, "controlpanel.empty-hover").forLocale(); + String clickCommand = MsgUtil.fillArgs( + "/quickshop silentempty {0}", + shop.getRuntimeRandomUniqueId().toString()); + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand))); } } // ToggleDisplay if ((plugin.perm().hasPermission(sender, "quickshop.other.toggledisplay") - || shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.TOGGLE_DISPLAY)) + || shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.TOGGLE_DISPLAY)) && plugin.isDisplayEnabled()) { - Component text = plugin.text().of(sender, "controlpanel.toggledisplay", MsgUtil.bool2String(!shop.isDisableDisplay())).forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.toggledisplay-hover").forLocale(); - String clickCommand = MsgUtil.fillArgs("/quickshop silenttoggledisplay {0}", shop.getRuntimeRandomUniqueId().toString()); - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + Component text = plugin.text() + .of(sender, "controlpanel.toggledisplay", MsgUtil.bool2String(!shop.isDisableDisplay())) + .forLocale(); + Component hoverText = + plugin.text().of(sender, "controlpanel.toggledisplay-hover").forLocale(); + String clickCommand = MsgUtil.fillArgs( + "/quickshop silenttoggledisplay {0}", + shop.getRuntimeRandomUniqueId().toString()); + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand))); } // --------------------- FUNCTION BUTTON --------------------- // Remove - if (plugin.perm().hasPermission(sender, "quickshop.other.destroy") || shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.DELETE)) { - Component text = plugin.text().of(sender, "controlpanel.remove", shop.getPrice()).forLocale(); - Component hoverText = plugin.text().of(sender, "controlpanel.remove-hover").forLocale(); - String clickCommand = MsgUtil.fillArgs("/quickshop silentremove {0}", shop.getRuntimeRandomUniqueId().toString()); - components.add(text - .hoverEvent(HoverEvent.showText(hoverText)) + if (plugin.perm().hasPermission(sender, "quickshop.other.destroy") + || shop.playerAuthorize(sender.getUniqueId(), BuiltInShopPermission.DELETE)) { + Component text = plugin.text() + .of(sender, "controlpanel.remove", shop.getPrice()) + .forLocale(); + Component hoverText = + plugin.text().of(sender, "controlpanel.remove-hover").forLocale(); + String clickCommand = MsgUtil.fillArgs( + "/quickshop silentremove {0}", + shop.getRuntimeRandomUniqueId().toString()); + components.add(text.hoverEvent(HoverEvent.showText(hoverText)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand))); } return components; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanelManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanelManager.java index 0b6fe2813..c31c4a803 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanelManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/controlpanel/SimpleShopControlPanelManager.java @@ -6,17 +6,16 @@ import com.ghostchu.quickshop.api.shop.ShopControlPanel; import com.ghostchu.quickshop.api.shop.ShopControlPanelManager; import com.ghostchu.quickshop.util.ChatSheetPrinter; import com.ghostchu.quickshop.util.paste.item.SubPasteItem; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; public class SimpleShopControlPanelManager implements ShopControlPanelManager, SubPasteItem { private final QuickShop plugin; @@ -31,16 +30,24 @@ public class SimpleShopControlPanelManager implements ShopControlPanelManager, S public void openControlPanel(@NotNull Player player, @NotNull Shop shop) { ChatSheetPrinter chatSheetPrinter = new ChatSheetPrinter(player); chatSheetPrinter.printHeader(); - chatSheetPrinter.printLine(plugin.text().of(player, "controlpanel.infomation").forLocale()); + chatSheetPrinter.printLine( + plugin.text().of(player, "controlpanel.infomation").forLocale()); List total = new ArrayList<>(); for (ShopControlPanel entry : registry.keySet()) { try { total.addAll(entry.generate(player, shop)); } catch (Exception e) { try { - plugin.logger().warn("Failed to generate control panel for {}. Contact the developer of the plugin {}.", entry.getPlugin().getName(), entry.getClass().getName()); + plugin.logger() + .warn( + "Failed to generate control panel for {}. Contact the developer of the plugin {}.", + entry.getPlugin().getName(), + entry.getClass().getName()); } catch (Exception e2) { - plugin.logger().warn("Failed to generate control panel for {}. Contact the developer of that plugin", entry.getClass().getName()); + plugin.logger() + .warn( + "Failed to generate control panel for {}. Contact the developer of that plugin", + entry.getClass().getName()); } } } @@ -84,7 +91,6 @@ public class SimpleShopControlPanelManager implements ShopControlPanelManager, S } finally { LOCK.unlock(); } - } @Override diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/DisplayItemPersistentDataType.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/DisplayItemPersistentDataType.java index 7c2457551..5dfd3800a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/DisplayItemPersistentDataType.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/DisplayItemPersistentDataType.java @@ -8,8 +8,7 @@ import org.bukkit.persistence.PersistentDataAdapterContext; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; -public class DisplayItemPersistentDataType - implements PersistentDataType { +public class DisplayItemPersistentDataType implements PersistentDataType { static final DisplayItemPersistentDataType INSTANCE = new DisplayItemPersistentDataType(); @Override @@ -24,8 +23,7 @@ public class DisplayItemPersistentDataType @NotNull @Override - public String toPrimitive( - @NotNull ShopProtectionFlag complex, @NotNull PersistentDataAdapterContext context) { + public String toPrimitive(@NotNull ShopProtectionFlag complex, @NotNull PersistentDataAdapterContext context) { try { return JsonUtil.getGson().toJson(complex); } catch (Exception th) { @@ -36,8 +34,7 @@ public class DisplayItemPersistentDataType @NotNull @Override - public ShopProtectionFlag fromPrimitive( - @NotNull String primitive, @NotNull PersistentDataAdapterContext context) { + public ShopProtectionFlag fromPrimitive(@NotNull String primitive, @NotNull PersistentDataAdapterContext context) { try { return JsonUtil.getGson().fromJson(primitive, ShopProtectionFlag.class); } catch (Exception th) { @@ -45,5 +42,4 @@ public class DisplayItemPersistentDataType return new ShopProtectionFlag("", Util.serialize(new ItemStack(Material.STONE))); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentData.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentData.java index 40712fbdb..0019adbf8 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentData.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentData.java @@ -1,9 +1,8 @@ package com.ghostchu.quickshop.shop.datatype; import com.google.gson.annotations.Expose; -import lombok.Getter; - import java.util.UUID; +import lombok.Getter; @Getter public class HopperPersistentData { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentDataType.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentDataType.java index 8b19658d2..c51cecdb0 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentDataType.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/HopperPersistentDataType.java @@ -3,16 +3,16 @@ package com.ghostchu.quickshop.shop.datatype; import com.ghostchu.quickshop.util.MsgUtil; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.util.UUID; import org.bukkit.persistence.PersistentDataAdapterContext; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - public class HopperPersistentDataType implements PersistentDataType { public static final HopperPersistentDataType INSTANCE = new HopperPersistentDataType(); - private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + private static final Gson GSON = + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); @Override public @NotNull Class getPrimitiveType() { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/PreviewGuiPersistentDataType.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/PreviewGuiPersistentDataType.java index 1c4616d05..827c8a526 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/PreviewGuiPersistentDataType.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/PreviewGuiPersistentDataType.java @@ -1,13 +1,11 @@ package com.ghostchu.quickshop.shop.datatype; +import java.util.UUID; import org.bukkit.persistence.PersistentDataAdapterContext; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - -public class PreviewGuiPersistentDataType - implements PersistentDataType { +public class PreviewGuiPersistentDataType implements PersistentDataType { public static final PreviewGuiPersistentDataType INSTANCE = new PreviewGuiPersistentDataType(); @Override @@ -22,20 +20,17 @@ public class PreviewGuiPersistentDataType @NotNull @Override - public String toPrimitive( - @NotNull UUID complex, @NotNull PersistentDataAdapterContext context) { + public String toPrimitive(@NotNull UUID complex, @NotNull PersistentDataAdapterContext context) { return complex.toString(); } @NotNull @Override - public UUID fromPrimitive( - @NotNull String primitive, @NotNull PersistentDataAdapterContext context) { + public UUID fromPrimitive(@NotNull String primitive, @NotNull PersistentDataAdapterContext context) { try { return UUID.fromString(primitive); } catch (Exception exception) { return new UUID(0L, 0L); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentData.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentData.java index 1a625cf0c..688f979b6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentData.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentData.java @@ -3,17 +3,21 @@ package com.ghostchu.quickshop.shop.datatype; import com.google.gson.annotations.Expose; import lombok.Getter; -//TODO +// TODO @Getter public class ShopPersistentData { @Expose private final String world; + @Expose private final int x; + @Expose private final int y; + @Expose private final int z; + private final boolean setup; public ShopPersistentData(int x, int y, int z, String world, boolean setup) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentDataType.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentDataType.java index 09ffc39e8..dcb3ea3f1 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentDataType.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/datatype/ShopPersistentDataType.java @@ -10,7 +10,8 @@ import org.jetbrains.annotations.NotNull; public class ShopPersistentDataType implements PersistentDataType { static final ShopPersistentDataType INSTANCE = new ShopPersistentDataType(); - private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + private static final Gson GSON = + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); @Override public @NotNull Class getPrimitiveType() { @@ -35,8 +36,7 @@ public class ShopPersistentDataType implements PersistentDataType { +public class ShopSignPersistentDataType implements PersistentDataType { public static final ShopSignPersistentDataType INSTANCE = new ShopSignPersistentDataType(); @Override @@ -22,8 +21,7 @@ public class ShopSignPersistentDataType @NotNull @Override - public String toPrimitive( - @NotNull ShopSignStorage complex, @NotNull PersistentDataAdapterContext context) { + public String toPrimitive(@NotNull ShopSignStorage complex, @NotNull PersistentDataAdapterContext context) { return JsonUtil.getGson().toJson(complex); } @@ -32,5 +30,4 @@ public class ShopSignPersistentDataType @NotNull String primitive, @NotNull PersistentDataAdapterContext context) { return JsonUtil.getGson().fromJson(primitive, ShopSignStorage.class); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/AbstractDisplayItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/AbstractDisplayItem.java index 7191cf108..fba4f0a56 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/AbstractDisplayItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/AbstractDisplayItem.java @@ -32,8 +32,10 @@ public abstract class AbstractDisplayItem implements Reloadable { protected static final QuickShop PLUGIN = QuickShop.getInstance(); protected final ItemStack originalItemStack; protected final Shop shop; + @Nullable protected ItemStack guardedIstack; + private boolean pendingRemoval; private static boolean virtualDisplayDoesntWork = false; @@ -115,7 +117,7 @@ public abstract class AbstractDisplayItem implements Reloadable { protected void init() { if (PLUGIN.getConfig().getBoolean("shop.display-allow-stacks")) { - //Prevent stack over the normal size + // Prevent stack over the normal size originalItemStack.setAmount(Math.min(originalItemStack.getAmount(), originalItemStack.getMaxStackSize())); } else { this.originalItemStack.setAmount(1); @@ -182,7 +184,8 @@ public abstract class AbstractDisplayItem implements Reloadable { iMeta = Bukkit.getItemFactory().getItemMeta(itemStack.getType()); } if (iMeta == null) { - Log.debug("ItemStack " + itemStack + " cannot getting or creating ItemMeta, failed to create guarded ItemStack."); + Log.debug("ItemStack " + itemStack + + " cannot getting or creating ItemMeta, failed to create guarded ItemStack."); return itemStack; } if (!PLUGIN.getConfig().getBoolean("shop.display-item-use-name")) { @@ -203,8 +206,7 @@ public abstract class AbstractDisplayItem implements Reloadable { * @return ShopProtectionFlag obj */ @NotNull - public static ShopProtectionFlag createShopProtectionFlag( - @NotNull ItemStack itemStack, @NotNull Shop shop) { + public static ShopProtectionFlag createShopProtectionFlag(@NotNull ItemStack itemStack, @NotNull Shop shop) { return new ShopProtectionFlag(shop.getLocation().toString(), Util.serialize(itemStack)); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/RealDisplayItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/RealDisplayItem.java index 1209d1939..c0e36282a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/RealDisplayItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/RealDisplayItem.java @@ -9,6 +9,10 @@ import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import io.papermc.lib.PaperLib; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; import lombok.ToString; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -20,11 +24,6 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.UUID; - @ToString public class RealDisplayItem extends AbstractDisplayItem { @@ -85,14 +84,17 @@ public class RealDisplayItem extends AbstractDisplayItem { public void fixDisplayMovedOld() { Util.ensureThread(false); - for (Entity entity : Objects.requireNonNull(this.shop.getLocation().getWorld()) - .getEntities()) { + for (Entity entity : + Objects.requireNonNull(this.shop.getLocation().getWorld()).getEntities()) { if (!(entity instanceof Item eItem)) { continue; } if (eItem.getUniqueId().equals(Objects.requireNonNull(this.item).getUniqueId())) { Log.debug("Fixing moved Item displayItem " + eItem.getUniqueId() + " at " + eItem.getLocation()); - PaperLib.teleportAsync(entity, Objects.requireNonNull(getDisplayLocation()), PlayerTeleportEvent.TeleportCause.UNKNOWN); + PaperLib.teleportAsync( + entity, + Objects.requireNonNull(getDisplayLocation()), + PlayerTeleportEvent.TeleportCause.UNKNOWN); return; } } @@ -175,8 +177,7 @@ public class RealDisplayItem extends AbstractDisplayItem { public void safeGuard(@NotNull Entity entity) { Util.ensureThread(false); if (!(entity instanceof Item itemEntity)) { - Log.debug( - "Failed to safeGuard " + entity.getLocation() + ", cause target not a Item"); + Log.debug("Failed to safeGuard " + entity.getLocation() + ", cause target not a Item"); return; } // Set item protect in the armorstand's hand @@ -211,7 +212,8 @@ public class RealDisplayItem extends AbstractDisplayItem { return; } if (item != null && item.isValid()) { - Log.debug("Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!"); + Log.debug( + "Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!"); MsgUtil.debugStackTrace(Thread.currentThread().getStackTrace()); } if (!Util.isDisplayAllowBlock( @@ -220,14 +222,17 @@ public class RealDisplayItem extends AbstractDisplayItem { return; } - if (new ShopDisplayItemSpawnEvent(shop, originalItemStack, DisplayType.REALITEM).callCancellableEvent()) { - Log.debug("Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on"); + Log.debug( + "Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on"); return; } this.guardedIstack = AbstractDisplayItem.createGuardItemStack(this.originalItemStack, this.shop); try { - this.item = this.shop.getLocation().getWorld().dropItem(getDisplayLocation(), this.guardedIstack, this::safeGuard); + this.item = this.shop + .getLocation() + .getWorld() + .dropItem(getDisplayLocation(), this.guardedIstack, this::safeGuard); } catch (NoSuchMethodError noSuchMethodError) { try { this.item = this.shop.getLocation().getWorld().dropItem(getDisplayLocation(), this.guardedIstack); @@ -249,5 +254,4 @@ public class RealDisplayItem extends AbstractDisplayItem { Util.ensureThread(false); return shop.getLocation().clone().add(0.5, 1.2, 0.5); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItem.java index 01847f678..dbdabc8f6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItem.java @@ -12,18 +12,17 @@ import com.ghostchu.quickshop.shop.display.virtual.packetfactory.VirtualDisplayP import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.Reloadable; +import java.util.*; +import java.util.concurrent.ConcurrentSkipListSet; import org.bukkit.Bukkit; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.concurrent.ConcurrentSkipListSet; - public class VirtualDisplayItem extends AbstractDisplayItem implements Reloadable { private final int entityID; - //The List which store packet sender + // The List which store packet sender private final Set packetSenders = new ConcurrentSkipListSet<>(); private final VirtualDisplayPacketFactory virtualDisplayPacketFactory; private final VirtualDisplayItemManager manager; @@ -31,19 +30,21 @@ public class VirtualDisplayItem extends AbstractDisplayItem implements Reloadabl private final PacketContainer fakeItemMetaPacket; private final PacketContainer fakeItemVelocityPacket; private final PacketContainer fakeItemDestroyPacket; - //cache chunk x and z + // cache chunk x and z private ShopChunk chunkLocation; - //If packet initialized + // If packet initialized private boolean isSpawned = false; - //packets + // packets VirtualDisplayItem(VirtualDisplayItemManager manager, VirtualDisplayPacketFactory packetFactory, Shop shop) { super(shop); this.entityID = manager.generateEntityId(); this.manager = manager; this.virtualDisplayPacketFactory = packetFactory; - this.fakeItemSpawnPacket = virtualDisplayPacketFactory.createFakeItemSpawnPacket(entityID, getDisplayLocation()); - this.fakeItemMetaPacket = virtualDisplayPacketFactory.createFakeItemMetaPacket(entityID, getOriginalItemStack().clone()); + this.fakeItemSpawnPacket = + virtualDisplayPacketFactory.createFakeItemSpawnPacket(entityID, getDisplayLocation()); + this.fakeItemMetaPacket = virtualDisplayPacketFactory.createFakeItemMetaPacket( + entityID, getOriginalItemStack().clone()); this.fakeItemVelocityPacket = virtualDisplayPacketFactory.createFakeItemVelocityPacket(entityID); this.fakeItemDestroyPacket = virtualDisplayPacketFactory.createFakeItemDestroyPacket(entityID); load(); @@ -65,14 +66,10 @@ public class VirtualDisplayItem extends AbstractDisplayItem implements Reloadabl } @Override - public void fixDisplayMoved() { - - } + public void fixDisplayMoved() {} @Override - public void fixDisplayNeedRegen() { - - } + public void fixDisplayNeedRegen() {} @Override public @Nullable Entity getDisplay() { @@ -114,9 +111,7 @@ public class VirtualDisplayItem extends AbstractDisplayItem implements Reloadabl } @Override - public void safeGuard(@Nullable Entity entity) { - - } + public void safeGuard(@Nullable Entity entity) {} @Override public void spawn() { @@ -142,15 +137,14 @@ public class VirtualDisplayItem extends AbstractDisplayItem implements Reloadabl isSpawned = true; } - - //Due to the delay task in ChunkListener - //We must move load task to first spawn to prevent some bug and make the check lesser + // Due to the delay task in ChunkListener + // We must move load task to first spawn to prevent some bug and make the check lesser private void load() { Util.ensureThread(false); - //some time shop can be loaded when world isn't loaded + // some time shop can be loaded when world isn't loaded chunkLocation = SimpleShopChunk.fromLocation(shop.getLocation()); manager.put(chunkLocation, this); - //Let nearby player can saw fake item + // Let nearby player can saw fake item List onlinePlayers = new ArrayList<>(Bukkit.getOnlinePlayers()); onlinePlayers.removeIf(p -> !p.getWorld().equals(shop.getLocation().getWorld())); for (Player onlinePlayer : onlinePlayers) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItemManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItemManager.java index d76ce426b..e3b5c4a26 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItemManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/VirtualDisplayItemManager.java @@ -8,28 +8,32 @@ import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.ShopChunk; import com.ghostchu.quickshop.shop.display.virtual.packetfactory.*; import com.ghostchu.quickshop.util.logger.Log; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; public class VirtualDisplayItemManager { private final QuickShop plugin; private final AtomicInteger entityIdCounter; private final ProtocolManager protocolManager; + @Getter private final Map> chunksMapping = new ConcurrentHashMap<>(); + @Getter private VirtualDisplayPacketFactory packetFactory; + @Getter private PacketAdapter chunkSendingPacketAdapter; + @Getter private PacketAdapter chunkUnloadingPacketAdapter; + private boolean testPassed = true; public VirtualDisplayItemManager(QuickShop plugin) { @@ -39,7 +43,9 @@ public class VirtualDisplayItemManager { this.entityIdCounter = new AtomicInteger(Integer.MAX_VALUE); load(); } catch (NoClassDefFoundError noClassDefFoundError) { - plugin.logger().error("DisplayType already set to VIRTUAL_DISPLAY_ITEM, but ProtocolLib not installed on your server, please download ProtocolLib and install it from https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/ or change the display type to REAL_DISPLAY_ITEM (0) or disable display system."); + plugin.logger() + .error( + "DisplayType already set to VIRTUAL_DISPLAY_ITEM, but ProtocolLib not installed on your server, please download ProtocolLib and install it from https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/ or change the display type to REAL_DISPLAY_ITEM (0) or disable display system."); throw new IllegalStateException("ProtocolLib not installed on this server"); } } @@ -47,8 +53,11 @@ public class VirtualDisplayItemManager { public void load() { String stringClassLoader = protocolManager.getClass().getClassLoader().toString(); if (stringClassLoader.contains("pluginEnabled=true") && !stringClassLoader.contains("plugin=ProtocolLib")) { - plugin.logger().warn("Warning! ProtocolLib seems provided by another plugin, This seems to be a wrong packaging problem, " + - "QuickShop can't ensure the ProtocolLib is working correctly! Info: {}", stringClassLoader); + plugin.logger() + .warn( + "Warning! ProtocolLib seems provided by another plugin, This seems to be a wrong packaging problem, " + + "QuickShop can't ensure the ProtocolLib is working correctly! Info: {}", + stringClassLoader); } Log.debug("Loading VirtualDisplayItem chunks mapping manager..."); Log.debug("Load: PacketFactory..."); @@ -58,9 +67,8 @@ public class VirtualDisplayItemManager { case v1_19_R1 -> new v1_19_R1(plugin, this); case v1_19_R2, v1_19_R3, v1_20_R1 -> new v1_19_R2_TO_v1_20_R1(plugin, this); case v1_20_R2, v1_20_R3 -> new v1_20_R2(plugin, this); - default -> - throw new IllegalStateException("Unsupported Virtual Display Minecraft version: " + plugin.getGameVersion()); - }; + default -> throw new IllegalStateException( + "Unsupported Virtual Display Minecraft version: " + plugin.getGameVersion());}; this.chunkSendingPacketAdapter = packetFactory.getChunkSendPacketAdapter(); this.chunkUnloadingPacketAdapter = packetFactory.getChunkUnloadPacketAdapter(); Log.debug("Registering the packet listener..."); @@ -69,7 +77,7 @@ public class VirtualDisplayItemManager { } public void put(@NotNull ShopChunk key, @NotNull VirtualDisplayItem value) { - //Thread-safe was ensured by ONLY USE Map method to do something + // Thread-safe was ensured by ONLY USE Map method to do something List virtualDisplayItems = new ArrayList<>(Collections.singletonList(value)); chunksMapping.merge(key, virtualDisplayItems, (mapOldVal, mapNewVal) -> { mapOldVal.addAll(mapNewVal); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/VirtualDisplayPacketFactory.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/VirtualDisplayPacketFactory.java index 9799b4e68..12ab0c1a4 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/VirtualDisplayPacketFactory.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/VirtualDisplayPacketFactory.java @@ -23,7 +23,9 @@ public interface VirtualDisplayPacketFactory { @NotNull PacketContainer createFakeItemDestroyPacket(int entityID); - @NotNull PacketAdapter getChunkSendPacketAdapter(); + @NotNull + PacketAdapter getChunkSendPacketAdapter(); - @NotNull PacketAdapter getChunkUnloadPacketAdapter(); + @NotNull + PacketAdapter getChunkUnloadPacketAdapter(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_18.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_18.java index e72c50b91..1e10dfe25 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_18.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_18.java @@ -14,6 +14,9 @@ import com.ghostchu.quickshop.shop.SimpleShopChunk; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItem; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItemManager; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.Optional; +import java.util.UUID; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -24,10 +27,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.Optional; -import java.util.UUID; - public class v1_18 implements VirtualDisplayPacketFactory { private final QuickShop plugin; private final VirtualDisplayItemManager manager; @@ -40,7 +39,8 @@ public class v1_18 implements VirtualDisplayPacketFactory { @Override public @Nullable Throwable testFakeItem() { try { - createFakeItemSpawnPacket(0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); + createFakeItemSpawnPacket( + 0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); createFakeItemMetaPacket(0, new ItemStack(Material.values()[0])); createFakeItemVelocityPacket(0); createFakeItemDestroyPacket(0); @@ -52,57 +52,67 @@ public class v1_18 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemSpawnPacket(int entityID, @NotNull Location displayLocation) { - //First, create a new packet to spawn item + // First, create a new packet to spawn item PacketContainer fakeItemPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); - //and add data based on packet class in NMS (global scope variable) - //Reference: https://wiki.vg/Protocol#Spawn_Object - fakeItemPacket.getIntegers() - //Entity ID + // and add data based on packet class in NMS (global scope variable) + // Reference: https://wiki.vg/Protocol#Spawn_Object + fakeItemPacket + .getIntegers() + // Entity ID .write(0, entityID); - //int data to mark + // int data to mark fakeItemPacket.getEntityTypeModifier().write(0, EntityType.DROPPED_ITEM); - fakeItemPacket.getIntegers().write(1, 0) - //Velocity y + fakeItemPacket + .getIntegers() + .write(1, 0) + // Velocity y .write(2, 0) - //Velocity z + // Velocity z .write(3, 0) - //Pitch + // Pitch .write(4, 0) - //Yaw + // Yaw .write(5, 0); - //int data to mark + // int data to mark fakeItemPacket.getIntegers().write(6, 1); - //UUID + // UUID fakeItemPacket.getUUIDs().write(0, UUID.randomUUID()); - //Location - fakeItemPacket.getDoubles() - //X + // Location + fakeItemPacket + .getDoubles() + // X .write(0, displayLocation.getX()) - //Y + // Y .write(1, displayLocation.getY()) - //Z + // Z .write(2, displayLocation.getZ()); return fakeItemPacket; } @Override public @NotNull PacketContainer createFakeItemMetaPacket(int entityID, @NotNull ItemStack itemStack) { - //Next, create a new packet to update item data (default is empty) - PacketContainer fakeItemMetaPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - //Entity ID + // Next, create a new packet to update item data (default is empty) + PacketContainer fakeItemMetaPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + // Entity ID fakeItemMetaPacket.getIntegers().write(0, entityID); - //List Type are more complex - //Create a DataWatcher + // List Type are more complex + // Create a DataWatcher WrappedDataWatcher wpw = new WrappedDataWatcher(); - //https://wiki.vg/index.php?title=Entity_metadata#Entity + // https://wiki.vg/index.php?title=Entity_metadata#Entity if (plugin.getConfig().getBoolean("shop.display-item-use-name")) { String itemName = GsonComponentSerializer.gson().serialize(Util.getItemStackName(itemStack)); - wpw.setObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true), Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); - wpw.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), true); + wpw.setObject( + 2, + WrappedDataWatcher.Registry.getChatComponentSerializer(true), + Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); + wpw.setObject( + new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), + true); } - //1.17+ is 8 + // 1.17+ is 8 wpw.setObject(8, WrappedDataWatcher.Registry.getItemStackSerializer(false), itemStack); fakeItemMetaPacket.getWatchableCollectionModifier().write(0, wpw.getWatchableObjects()); return fakeItemMetaPacket; @@ -110,28 +120,31 @@ public class v1_18 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemVelocityPacket(int entityID) { - //And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) - PacketContainer fakeItemVelocityPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); - fakeItemVelocityPacket.getIntegers() - //Entity ID + // And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) + PacketContainer fakeItemVelocityPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); + fakeItemVelocityPacket + .getIntegers() + // Entity ID .write(0, entityID) - //Velocity x + // Velocity x .write(1, 0) - //Velocity y + // Velocity y .write(2, 0) - //Velocity z + // Velocity z .write(3, 0); return fakeItemVelocityPacket; } @Override public @NotNull PacketContainer createFakeItemDestroyPacket(int entityID) { - //Also make a DestroyPacket to remove it - PacketContainer fakeItemDestroyPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); + // Also make a DestroyPacket to remove it + PacketContainer fakeItemDestroyPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); // if (VERSION.ordinal() <= GameVersion.v1_19_R1.ordinal()) { MinecraftVersion minecraftVersion = manager.getProtocolManager().getMinecraftVersion(); - //On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list - //Entity to remove + // On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list + // Entity to remove try { fakeItemDestroyPacket.getIntLists().write(0, Collections.singletonList(entityID)); } catch (NoSuchMethodError e) { @@ -153,25 +166,28 @@ public class v1_18 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way - target.getPacketSenders().add(player.getUniqueId()); - target.sendDestroyItem(player); - target.sendFakeItem(player); - } - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way + target.getPacketSenders().add(player.getUniqueId()); + target.sendDestroyItem(player); + target.sendFakeItem(player); + } + } + return targetList; + }); } }; } @@ -188,22 +204,25 @@ public class v1_18 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - target.sendDestroyItem(player); - target.getPacketSenders().remove(player.getUniqueId()); - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + target.sendDestroyItem(player); + target.getPacketSenders().remove(player.getUniqueId()); + } + return targetList; + }); } }; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R1.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R1.java index afda11361..8773b2d3a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R1.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R1.java @@ -13,6 +13,9 @@ import com.ghostchu.quickshop.shop.SimpleShopChunk; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItem; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItemManager; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.Optional; +import java.util.UUID; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -23,10 +26,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.Optional; -import java.util.UUID; - public class v1_19_R1 implements VirtualDisplayPacketFactory { private final QuickShop plugin; private final VirtualDisplayItemManager manager; @@ -39,7 +38,8 @@ public class v1_19_R1 implements VirtualDisplayPacketFactory { @Override public @Nullable Throwable testFakeItem() { try { - createFakeItemSpawnPacket(0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); + createFakeItemSpawnPacket( + 0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); createFakeItemMetaPacket(0, new ItemStack(Material.values()[0])); createFakeItemVelocityPacket(0); createFakeItemDestroyPacket(0); @@ -51,74 +51,85 @@ public class v1_19_R1 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemSpawnPacket(int entityID, @NotNull Location displayLocation) { - //First, create a new packet to spawn item + // First, create a new packet to spawn item PacketContainer fakeItemPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); - //and add data based on packet class in NMS (global scope variable) - //Reference: https://wiki.vg/Protocol#Spawn_Object - fakeItemPacket.getIntegers() - //Entity ID + // and add data based on packet class in NMS (global scope variable) + // Reference: https://wiki.vg/Protocol#Spawn_Object + fakeItemPacket + .getIntegers() + // Entity ID .write(0, entityID); fakeItemPacket.getEntityTypeModifier().write(0, EntityType.DROPPED_ITEM); - //UUID + // UUID fakeItemPacket.getUUIDs().write(0, UUID.randomUUID()); - //Location - fakeItemPacket.getDoubles() - //X + // Location + fakeItemPacket + .getDoubles() + // X .write(0, displayLocation.getX()) - //Y + // Y .write(1, displayLocation.getY()) - //Z + // Z .write(2, displayLocation.getZ()); return fakeItemPacket; } @Override public @NotNull PacketContainer createFakeItemMetaPacket(int entityID, @NotNull ItemStack itemStack) { - //Next, create a new packet to update item data (default is empty) - PacketContainer fakeItemMetaPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - //Entity ID + // Next, create a new packet to update item data (default is empty) + PacketContainer fakeItemMetaPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + // Entity ID fakeItemMetaPacket.getIntegers().write(0, entityID); - //List Type are more complex - //Create a DataWatcher + // List Type are more complex + // Create a DataWatcher WrappedDataWatcher wpw = new WrappedDataWatcher(); - //https://wiki.vg/index.php?title=Entity_metadata#Entity + // https://wiki.vg/index.php?title=Entity_metadata#Entity if (plugin.getConfig().getBoolean("shop.display-item-use-name")) { String itemName = GsonComponentSerializer.gson().serialize(Util.getItemStackName(itemStack)); - wpw.setObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true), Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); - wpw.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), true); + wpw.setObject( + 2, + WrappedDataWatcher.Registry.getChatComponentSerializer(true), + Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); + wpw.setObject( + new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), + true); } - //Must in the certain slot:https://wiki.vg/Entity_metadata#Item - //1.17+ is 8 + // Must in the certain slot:https://wiki.vg/Entity_metadata#Item + // 1.17+ is 8 wpw.setObject(8, WrappedDataWatcher.Registry.getItemStackSerializer(false), itemStack); - //Add it + // Add it fakeItemMetaPacket.getWatchableCollectionModifier().write(0, wpw.getWatchableObjects()); return fakeItemMetaPacket; } @Override public @NotNull PacketContainer createFakeItemVelocityPacket(int entityID) { - //And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) - PacketContainer fakeItemVelocityPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); - fakeItemVelocityPacket.getIntegers() - //Entity ID + // And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) + PacketContainer fakeItemVelocityPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); + fakeItemVelocityPacket + .getIntegers() + // Entity ID .write(0, entityID) - //Velocity x + // Velocity x .write(1, 0) - //Velocity y + // Velocity y .write(2, 0) - //Velocity z + // Velocity z .write(3, 0); return fakeItemVelocityPacket; } @Override public @NotNull PacketContainer createFakeItemDestroyPacket(int entityID) { - //Also make a DestroyPacket to remove it - PacketContainer fakeItemDestroyPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); - //On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list - //Entity to remove + // Also make a DestroyPacket to remove it + PacketContainer fakeItemDestroyPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); + // On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list + // Entity to remove try { fakeItemDestroyPacket.getIntLists().write(0, Collections.singletonList(entityID)); } catch (NoSuchMethodError e) { @@ -140,25 +151,28 @@ public class v1_19_R1 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way - target.getPacketSenders().add(player.getUniqueId()); - target.sendDestroyItem(player); - target.sendFakeItem(player); - } - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way + target.getPacketSenders().add(player.getUniqueId()); + target.sendDestroyItem(player); + target.sendFakeItem(player); + } + } + return targetList; + }); } }; } @@ -175,22 +189,25 @@ public class v1_19_R1 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - target.sendDestroyItem(player); - target.getPacketSenders().remove(player.getUniqueId()); - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + target.sendDestroyItem(player); + target.getPacketSenders().remove(player.getUniqueId()); + } + return targetList; + }); } }; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R2_TO_v1_20_R1.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R2_TO_v1_20_R1.java index d59039735..2dd115792 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R2_TO_v1_20_R1.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_19_R2_TO_v1_20_R1.java @@ -16,6 +16,10 @@ import com.ghostchu.quickshop.shop.SimpleShopChunk; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItem; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItemManager; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.UUID; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -26,11 +30,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - public class v1_19_R2_TO_v1_20_R1 implements VirtualDisplayPacketFactory { private final QuickShop plugin; private final VirtualDisplayItemManager manager; @@ -43,7 +42,8 @@ public class v1_19_R2_TO_v1_20_R1 implements VirtualDisplayPacketFactory { @Override public @Nullable Throwable testFakeItem() { try { - createFakeItemSpawnPacket(0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); + createFakeItemSpawnPacket( + 0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); createFakeItemMetaPacket(0, new ItemStack(Material.values()[0])); createFakeItemVelocityPacket(0); createFakeItemDestroyPacket(0); @@ -55,61 +55,70 @@ public class v1_19_R2_TO_v1_20_R1 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemSpawnPacket(int entityID, @NotNull Location displayLocation) { - //First, create a new packet to spawn item + // First, create a new packet to spawn item PacketContainer fakeItemPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); - //and add data based on packet class in NMS (global scope variable) - //Reference: https://wiki.vg/Protocol#Spawn_Object - fakeItemPacket.getIntegers() - //Entity ID + // and add data based on packet class in NMS (global scope variable) + // Reference: https://wiki.vg/Protocol#Spawn_Object + fakeItemPacket + .getIntegers() + // Entity ID .write(0, entityID); - //Velocity x + // Velocity x fakeItemPacket.getEntityTypeModifier().write(0, EntityType.DROPPED_ITEM); - //UUID + // UUID fakeItemPacket.getUUIDs().write(0, UUID.randomUUID()); - //Location - fakeItemPacket.getDoubles() - //X + // Location + fakeItemPacket + .getDoubles() + // X .write(0, displayLocation.getX()) - //Y + // Y .write(1, displayLocation.getY()) - //Z + // Z .write(2, displayLocation.getZ()); return fakeItemPacket; } @Override public @NotNull PacketContainer createFakeItemMetaPacket(int entityID, @NotNull ItemStack itemStack) { - //Next, create a new packet to update item data (default is empty) - PacketContainer fakeItemMetaPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - //Entity ID + // Next, create a new packet to update item data (default is empty) + PacketContainer fakeItemMetaPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + // Entity ID fakeItemMetaPacket.getIntegers().write(0, entityID); - //List Type are more complex - //Create a DataWatcher + // List Type are more complex + // Create a DataWatcher WrappedDataWatcher wpw = new WrappedDataWatcher(); - //https://wiki.vg/index.php?title=Entity_metadata#Entity + // https://wiki.vg/index.php?title=Entity_metadata#Entity if (plugin.getConfig().getBoolean("shop.display-item-use-name")) { String itemName = GsonComponentSerializer.gson().serialize(Util.getItemStackName(itemStack)); - wpw.setObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true), Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); - wpw.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), true); + wpw.setObject( + 2, + WrappedDataWatcher.Registry.getChatComponentSerializer(true), + Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); + wpw.setObject( + new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), + true); } - //Must in the certain slot:https://wiki.vg/Entity_metadata#Item + // Must in the certain slot:https://wiki.vg/Entity_metadata#Item wpw.setObject(8, WrappedDataWatcher.Registry.getItemStackSerializer(false), itemStack); - //Add it - //For 1.19.2+, we need to use DataValue instead of WatchableObject - //Check for new version protocolLib + // Add it + // For 1.19.2+, we need to use DataValue instead of WatchableObject + // Check for new version protocolLib try { Class.forName("com.comphenix.protocol.wrappers.WrappedDataValue"); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to initialize packet, ProtocolLib update needed", e); } - //Convert List to List + // Convert List to List List wrappedWatchableObjects = wpw.getWatchableObjects(); List wrappedDataValues = new java.util.LinkedList<>(); for (WrappedWatchableObject wrappedWatchableObject : wrappedWatchableObjects) { WrappedDataWatcher.WrappedDataWatcherObject watchableObject = wrappedWatchableObject.getWatcherObject(); - wrappedDataValues.add(new WrappedDataValue(watchableObject.getIndex(), watchableObject.getSerializer(), wrappedWatchableObject.getRawValue())); + wrappedDataValues.add(new WrappedDataValue( + watchableObject.getIndex(), watchableObject.getSerializer(), wrappedWatchableObject.getRawValue())); } fakeItemMetaPacket.getDataValueCollectionModifier().write(0, wrappedDataValues); return fakeItemMetaPacket; @@ -117,27 +126,30 @@ public class v1_19_R2_TO_v1_20_R1 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemVelocityPacket(int entityID) { - //And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) - PacketContainer fakeItemVelocityPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); - fakeItemVelocityPacket.getIntegers() - //Entity ID + // And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) + PacketContainer fakeItemVelocityPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); + fakeItemVelocityPacket + .getIntegers() + // Entity ID .write(0, entityID) - //Velocity x + // Velocity x .write(1, 0) - //Velocity y + // Velocity y .write(2, 0) - //Velocity z + // Velocity z .write(3, 0); return fakeItemVelocityPacket; } @Override public @NotNull PacketContainer createFakeItemDestroyPacket(int entityID) { - //Also make a DestroyPacket to remove it - PacketContainer fakeItemDestroyPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); + // Also make a DestroyPacket to remove it + PacketContainer fakeItemDestroyPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); MinecraftVersion minecraftVersion = manager.getProtocolManager().getMinecraftVersion(); - //On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list - //Entity to remove + // On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list + // Entity to remove try { fakeItemDestroyPacket.getIntLists().write(0, Collections.singletonList(entityID)); } catch (NoSuchMethodError e) { @@ -159,25 +171,28 @@ public class v1_19_R2_TO_v1_20_R1 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way - target.getPacketSenders().add(player.getUniqueId()); - target.sendDestroyItem(player); - target.sendFakeItem(player); - } - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way + target.getPacketSenders().add(player.getUniqueId()); + target.sendDestroyItem(player); + target.sendFakeItem(player); + } + } + return targetList; + }); } }; } @@ -194,22 +209,25 @@ public class v1_19_R2_TO_v1_20_R1 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - target.sendDestroyItem(player); - target.getPacketSenders().remove(player.getUniqueId()); - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + target.sendDestroyItem(player); + target.getPacketSenders().remove(player.getUniqueId()); + } + return targetList; + }); } }; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_20_R2.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_20_R2.java index 52e3e8384..7eb46785c 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_20_R2.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/display/virtual/packetfactory/v1_20_R2.java @@ -13,6 +13,10 @@ import com.ghostchu.quickshop.shop.SimpleShopChunk; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItem; import com.ghostchu.quickshop.shop.display.virtual.VirtualDisplayItemManager; import com.ghostchu.quickshop.util.Util; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.UUID; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -23,11 +27,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - public class v1_20_R2 implements VirtualDisplayPacketFactory { private final QuickShop plugin; private final VirtualDisplayItemManager manager; @@ -40,7 +39,8 @@ public class v1_20_R2 implements VirtualDisplayPacketFactory { @Override public @Nullable Throwable testFakeItem() { try { - createFakeItemSpawnPacket(0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); + createFakeItemSpawnPacket( + 0, new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0)); createFakeItemMetaPacket(0, new ItemStack(Material.values()[0])); createFakeItemVelocityPacket(0); createFakeItemDestroyPacket(0); @@ -52,61 +52,70 @@ public class v1_20_R2 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemSpawnPacket(int entityID, @NotNull Location displayLocation) { - //First, create a new packet to spawn item + // First, create a new packet to spawn item PacketContainer fakeItemPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); - //and add data based on packet class in NMS (global scope variable) - //Reference: https://wiki.vg/Protocol#Spawn_Object - fakeItemPacket.getIntegers() - //Entity ID + // and add data based on packet class in NMS (global scope variable) + // Reference: https://wiki.vg/Protocol#Spawn_Object + fakeItemPacket + .getIntegers() + // Entity ID .write(0, entityID); - //Velocity x + // Velocity x fakeItemPacket.getEntityTypeModifier().write(0, EntityType.DROPPED_ITEM); - //UUID + // UUID fakeItemPacket.getUUIDs().write(0, UUID.randomUUID()); - //Location - fakeItemPacket.getDoubles() - //X + // Location + fakeItemPacket + .getDoubles() + // X .write(0, displayLocation.getX()) - //Y + // Y .write(1, displayLocation.getY()) - //Z + // Z .write(2, displayLocation.getZ()); return fakeItemPacket; } @Override public @NotNull PacketContainer createFakeItemMetaPacket(int entityID, @NotNull ItemStack itemStack) { - //Next, create a new packet to update item data (default is empty) - PacketContainer fakeItemMetaPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - //Entity ID + // Next, create a new packet to update item data (default is empty) + PacketContainer fakeItemMetaPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + // Entity ID fakeItemMetaPacket.getIntegers().write(0, entityID); - //List Type are more complex - //Create a DataWatcher + // List Type are more complex + // Create a DataWatcher WrappedDataWatcher wpw = new WrappedDataWatcher(); - //https://wiki.vg/index.php?title=Entity_metadata#Entity + // https://wiki.vg/index.php?title=Entity_metadata#Entity if (plugin.getConfig().getBoolean("shop.display-item-use-name")) { String itemName = GsonComponentSerializer.gson().serialize(Util.getItemStackName(itemStack)); - wpw.setObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true), Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); - wpw.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), true); + wpw.setObject( + 2, + WrappedDataWatcher.Registry.getChatComponentSerializer(true), + Optional.of(WrappedChatComponent.fromJson(itemName).getHandle())); + wpw.setObject( + new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), + true); } - //Must in the certain slot:https://wiki.vg/Entity_metadata#Item + // Must in the certain slot:https://wiki.vg/Entity_metadata#Item wpw.setObject(8, WrappedDataWatcher.Registry.getItemStackSerializer(false), itemStack); - //Add it - //For 1.19.2+, we need to use DataValue instead of WatchableObject - //Check for new version protocolLib + // Add it + // For 1.19.2+, we need to use DataValue instead of WatchableObject + // Check for new version protocolLib try { Class.forName("com.comphenix.protocol.wrappers.WrappedDataValue"); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to initialize packet, ProtocolLib update needed", e); } - //Convert List to List + // Convert List to List List wrappedWatchableObjects = wpw.getWatchableObjects(); List wrappedDataValues = new java.util.LinkedList<>(); for (WrappedWatchableObject wrappedWatchableObject : wrappedWatchableObjects) { WrappedDataWatcher.WrappedDataWatcherObject watchableObject = wrappedWatchableObject.getWatcherObject(); - wrappedDataValues.add(new WrappedDataValue(watchableObject.getIndex(), watchableObject.getSerializer(), wrappedWatchableObject.getRawValue())); + wrappedDataValues.add(new WrappedDataValue( + watchableObject.getIndex(), watchableObject.getSerializer(), wrappedWatchableObject.getRawValue())); } fakeItemMetaPacket.getDataValueCollectionModifier().write(0, wrappedDataValues); return fakeItemMetaPacket; @@ -114,27 +123,30 @@ public class v1_20_R2 implements VirtualDisplayPacketFactory { @Override public @NotNull PacketContainer createFakeItemVelocityPacket(int entityID) { - //And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) - PacketContainer fakeItemVelocityPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); - fakeItemVelocityPacket.getIntegers() - //Entity ID + // And, create a entity velocity packet to make it at a proper location (otherwise it will fly randomly) + PacketContainer fakeItemVelocityPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_VELOCITY); + fakeItemVelocityPacket + .getIntegers() + // Entity ID .write(0, entityID) - //Velocity x + // Velocity x .write(1, 0) - //Velocity y + // Velocity y .write(2, 0) - //Velocity z + // Velocity z .write(3, 0); return fakeItemVelocityPacket; } @Override public @NotNull PacketContainer createFakeItemDestroyPacket(int entityID) { - //Also make a DestroyPacket to remove it - PacketContainer fakeItemDestroyPacket = manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); + // Also make a DestroyPacket to remove it + PacketContainer fakeItemDestroyPacket = + manager.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); MinecraftVersion minecraftVersion = manager.getProtocolManager().getMinecraftVersion(); - //On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list - //Entity to remove + // On 1.17.1 (may be 1.17.1+? it's enough, Mojang, stop the changes), we need add the int list + // Entity to remove try { fakeItemDestroyPacket.getIntLists().write(0, Collections.singletonList(entityID)); } catch (NoSuchMethodError e) { @@ -156,25 +168,28 @@ public class v1_20_R2 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x int x = integerStructureModifier.read(0); - //chunk z + // chunk z int z = integerStructureModifier.read(1); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way - target.getPacketSenders().add(player.getUniqueId()); - target.sendDestroyItem(player); - target.sendFakeItem(player); - } - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + if (target.isApplicableForPlayer(player)) { // TODO: Refactor with better way + target.getPacketSenders().add(player.getUniqueId()); + target.sendDestroyItem(player); + target.sendFakeItem(player); + } + } + return targetList; + }); } }; } @@ -191,22 +206,25 @@ public class v1_20_R2 implements VirtualDisplayPacketFactory { if (player.getClass().getName().contains("TemporaryPlayer")) { return; } - StructureModifier intPairStructureModifier = event.getPacket().getChunkCoordIntPairs(); + StructureModifier intPairStructureModifier = + event.getPacket().getChunkCoordIntPairs(); ChunkCoordIntPair pair = intPairStructureModifier.read(0); - //chunk x + // chunk x int x = pair.getChunkX(); - //chunk z + // chunk z int z = pair.getChunkZ(); - manager.getChunksMapping().computeIfPresent(new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { - for (VirtualDisplayItem target : targetList) { - if (!target.isSpawned()) { - continue; - } - target.sendDestroyItem(player); - target.getPacketSenders().remove(player.getUniqueId()); - } - return targetList; - }); + manager.getChunksMapping() + .computeIfPresent( + new SimpleShopChunk(player.getWorld().getName(), x, z), (chunkLoc, targetList) -> { + for (VirtualDisplayItem target : targetList) { + if (!target.isSpawned()) { + continue; + } + target.sendDestroyItem(player); + target.getPacketSenders().remove(player.getUniqueId()); + } + return targetList; + }); } }; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapper.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapper.java index 6fb023768..5e0034bd2 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapper.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapper.java @@ -5,6 +5,7 @@ import com.ghostchu.quickshop.api.inventory.InventoryWrapper; import com.ghostchu.quickshop.api.inventory.InventoryWrapperIterator; import com.ghostchu.quickshop.api.inventory.InventoryWrapperManager; import com.ghostchu.quickshop.api.inventory.InventoryWrapperType; +import java.util.Map; import org.bukkit.Location; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; @@ -12,8 +13,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; - public class BukkitInventoryWrapper implements InventoryWrapper { private final Inventory inventory; private final InventoryWrapperManager manager; @@ -43,7 +42,6 @@ public class BukkitInventoryWrapper implements InventoryWrapper { } else { snapshot[i] = null; } - } return snapshot; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapperManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapperManager.java index ff5002cae..1d6740491 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapperManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/inventory/BukkitInventoryWrapperManager.java @@ -41,23 +41,28 @@ public class BukkitInventoryWrapperManager implements InventoryWrapperManager { if (world == null) { throw new IllegalArgumentException("Invalid symbol link: Invalid world name."); } - BlockState block = world.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ()).getState(); - if (PackageUtil.parsePackageProperly("forceLoadAnotherSideWhenInventoryLocate").asBoolean(false)) { + BlockState block = world.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ()) + .getState(); + if (PackageUtil.parsePackageProperly("forceLoadAnotherSideWhenInventoryLocate") + .asBoolean(false)) { BlockData blockData = block.getBlockData(); if (blockData instanceof Chest chest) { if (chest.getType() != Chest.Type.SINGLE) { // try load another side Block anotherBlock = Util.getSecondHalf(block.getBlock()); anotherBlock.getChunk().load(); - if (PackageUtil.parsePackageProperly("forceUpdateAnotherSideAfterForceLoadAnotherSide").asBoolean(false)) { + if (PackageUtil.parsePackageProperly("forceUpdateAnotherSideAfterForceLoadAnotherSide") + .asBoolean(false)) { block.update(); - block = world.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ()).getState(); + block = world.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ()) + .getState(); } } } } if (!(block instanceof InventoryHolder holder)) { - throw new IllegalArgumentException("Invalid symbol link: Target block not a InventoryHolder (map changed/resetted?)"); + throw new IllegalArgumentException( + "Invalid symbol link: Target block not a InventoryHolder (map changed/resetted?)"); } return new BukkitInventoryWrapper(holder.getInventory()); } @@ -73,23 +78,28 @@ public class BukkitInventoryWrapperManager implements InventoryWrapperManager { if (world == null) { throw new IllegalArgumentException("Invalid symbol link: Invalid world name."); } - BlockState block = world.getBlockAt(blockHolder.getX(), blockHolder.getY(), blockHolder.getZ()).getState(); - if (PackageUtil.parsePackageProperly("forceLoadAnotherSideWhenInventoryLocate").asBoolean(false)) { + BlockState block = world.getBlockAt(blockHolder.getX(), blockHolder.getY(), blockHolder.getZ()) + .getState(); + if (PackageUtil.parsePackageProperly("forceLoadAnotherSideWhenInventoryLocate") + .asBoolean(false)) { BlockData blockData = block.getBlockData(); if (blockData instanceof Chest chest) { if (chest.getType() != Chest.Type.SINGLE) { // try load another side Block anotherBlock = Util.getSecondHalf(block.getBlock()); anotherBlock.getChunk().load(); - if (PackageUtil.parsePackageProperly("forceUpdateAnotherSideAfterForceLoadAnotherSide").asBoolean(false)) { + if (PackageUtil.parsePackageProperly("forceUpdateAnotherSideAfterForceLoadAnotherSide") + .asBoolean(false)) { block.update(); - block = world.getBlockAt(blockHolder.getX(), blockHolder.getY(), blockHolder.getZ()).getState(); + block = world.getBlockAt(blockHolder.getX(), blockHolder.getY(), blockHolder.getZ()) + .getState(); } } } } if (!(block instanceof InventoryHolder holder)) { - throw new IllegalArgumentException("Invalid symbol link: Target block not a Container (map changed/resetted?)"); + throw new IllegalArgumentException( + "Invalid symbol link: Target block not a Container (map changed/resetted?)"); } return new BukkitInventoryWrapper(holder.getInventory()); } @@ -110,7 +120,8 @@ public class BukkitInventoryWrapperManager implements InventoryWrapperManager { @Deprecated public enum HolderType { - BLOCK("block"), UNKNOWN("unknown"); + BLOCK("block"), + UNKNOWN("unknown"); private final String typeString; HolderType(String typeString) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/AddItemOperation.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/AddItemOperation.java index 7513cc3b9..f4e7f97ca 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/AddItemOperation.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/AddItemOperation.java @@ -4,11 +4,10 @@ import com.ghostchu.quickshop.api.inventory.InventoryWrapper; import com.ghostchu.quickshop.api.operation.Operation; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Map; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Map; - /** * Operation to add items */ @@ -21,7 +20,6 @@ public class AddItemOperation implements Operation { private boolean rollback; private ItemStack[] snapshot; - /** * Constructor. * @@ -46,12 +44,14 @@ public class AddItemOperation implements Operation { while (remains > 0) { int stackSize = Math.min(remains, itemMaxStackSize); target.setAmount(stackSize); - Log.debug("Committing add item operation, remains: " + remains + ", stackSize: " + stackSize + ", target: " + target); + Log.debug("Committing add item operation, remains: " + remains + ", stackSize: " + stackSize + ", target: " + + target); Map notSaved = inv.addItem(target); if (notSaved.isEmpty()) { remains -= stackSize; } else { - remains -= stackSize - notSaved.entrySet().iterator().next().getValue().getAmount(); + remains -= stackSize + - notSaved.entrySet().iterator().next().getValue().getAmount(); } if (remains == lastRemains) { return false; @@ -76,5 +76,4 @@ public class AddItemOperation implements Operation { rollback = true; return inv.restoreSnapshot(this.snapshot); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/RemoveItemOperation.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/RemoveItemOperation.java index a40c23e5a..b390ffec3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/RemoveItemOperation.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/operation/RemoveItemOperation.java @@ -4,11 +4,10 @@ import com.ghostchu.quickshop.api.inventory.InventoryWrapper; import com.ghostchu.quickshop.api.operation.Operation; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Map; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Map; - /** * Operation to remove items */ @@ -33,7 +32,6 @@ public class RemoveItemOperation implements Operation { this.amount = amount; this.inv = inv; this.itemMaxStackSize = Util.getItemMaxStackSize(item.getType()); - } @Override @@ -45,12 +43,14 @@ public class RemoveItemOperation implements Operation { while (remains > 0) { int stackSize = Math.min(remains, itemMaxStackSize); item.setAmount(stackSize); - Log.debug("Committing remove item operation, remains: " + remains + ", stackSize: " + stackSize + ", target: " + item); + Log.debug("Committing remove item operation, remains: " + remains + ", stackSize: " + stackSize + + ", target: " + item); Map notFit = inv.removeItem(item.clone()); if (notFit.isEmpty()) { remains -= stackSize; } else { - remains -= stackSize - notFit.entrySet().iterator().next().getValue().getAmount(); + remains -= stackSize + - notFit.entrySet().iterator().next().getValue().getAmount(); } if (remains == lastRemains) { return false; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/package-info.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/package-info.java index fa8d8cbd2..9be225e8f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/package-info.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/package-info.java @@ -2,4 +2,4 @@ * The most important things obout QuickShop in there * APIs included */ -package com.ghostchu.quickshop.shop; \ No newline at end of file +package com.ghostchu.quickshop.shop; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/signhooker/SignHooker.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/signhooker/SignHooker.java index c98af9015..9a93b3b46 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/signhooker/SignHooker.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/signhooker/SignHooker.java @@ -11,6 +11,9 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Collection; +import java.util.List; +import java.util.Map; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -20,10 +23,6 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collection; -import java.util.List; -import java.util.Map; - public class SignHooker { private final QuickShop PLUGIN; private final ProtocolManager PROTOCOL_MANAGER = ProtocolLibrary.getProtocolManager(); @@ -35,36 +34,43 @@ public class SignHooker { } public void registerListener() { - chunkAdapter = new PacketAdapter(PLUGIN.getJavaPlugin(), ListenerPriority.HIGH, PacketType.Play.Server.MAP_CHUNK) { - @Override - public void onPacketSending(@NotNull PacketEvent event) { - //is really full chunk data - //In 1.17, this value was removed, so read safely - Boolean boxedIsFull = event.getPacket().getBooleans().readSafely(0); - boolean isFull = boxedIsFull == null || boxedIsFull; - if (!isFull) { - return; - } - Player player = event.getPlayer(); - if (player == null || !player.isOnline()) { - return; - } - if (player.getClass().getName().contains("TemporaryPlayer")) { - return; - } - StructureModifier integerStructureModifier = event.getPacket().getIntegers(); - //chunk x - int x = integerStructureModifier.read(0); - //chunk z - int z = integerStructureModifier.read(1); + chunkAdapter = + new PacketAdapter(PLUGIN.getJavaPlugin(), ListenerPriority.HIGH, PacketType.Play.Server.MAP_CHUNK) { + @Override + public void onPacketSending(@NotNull PacketEvent event) { + // is really full chunk data + // In 1.17, this value was removed, so read safely + Boolean boxedIsFull = event.getPacket().getBooleans().readSafely(0); + boolean isFull = boxedIsFull == null || boxedIsFull; + if (!isFull) { + return; + } + Player player = event.getPlayer(); + if (player == null || !player.isOnline()) { + return; + } + if (player.getClass().getName().contains("TemporaryPlayer")) { + return; + } + StructureModifier integerStructureModifier = + event.getPacket().getIntegers(); + // chunk x + int x = integerStructureModifier.read(0); + // chunk z + int z = integerStructureModifier.read(1); - Map shops = PLUGIN.getShopManager().getShops(player.getWorld().getName(), x, z); - if (shops == null) { - return; - } - Bukkit.getScheduler().runTaskLater(PLUGIN.getJavaPlugin(), () -> shops.forEach((loc, shop) -> updatePerPlayerShopSign(player, loc, shop)), 2); - } - }; + Map shops = PLUGIN.getShopManager() + .getShops(player.getWorld().getName(), x, z); + if (shops == null) { + return; + } + Bukkit.getScheduler() + .runTaskLater( + PLUGIN.getJavaPlugin(), + () -> shops.forEach((loc, shop) -> updatePerPlayerShopSign(player, loc, shop)), + 2); + } + }; PROTOCOL_MANAGER.addPacketListener(chunkAdapter); Log.debug("SignHooker chunk adapter registered."); @@ -78,10 +84,12 @@ public class SignHooker { if (!Util.isLoaded(location)) { return; } - Log.debug("Updating per-player packet sign: Player=" + player.getName() + ", Location=" + location + ", Shop=" + shop.getShopId()); + Log.debug("Updating per-player packet sign: Player=" + player.getName() + ", Location=" + location + ", Shop=" + + shop.getShopId()); List lines = shop.getSignText(PLUGIN.getTextManager().findRelativeLanguages(player)); for (Sign sign : shop.getSigns()) { - PLUGIN.getPlatform().sendSignTextChange(player, sign, PLUGIN.getConfig().getBoolean("shop.sign-glowing"), lines); + PLUGIN.getPlatform() + .sendSignTextChange(player, sign, PLUGIN.getConfig().getBoolean("shop.sign-glowing"), lines); } } @@ -99,7 +107,11 @@ public class SignHooker { if (world == null) { return; } - Collection nearbyPlayers = world.getNearbyEntities(shop.getLocation(), Bukkit.getViewDistance() * 16, shop.getLocation().getWorld().getMaxHeight(), Bukkit.getViewDistance() * 16); + Collection nearbyPlayers = world.getNearbyEntities( + shop.getLocation(), + Bukkit.getViewDistance() * 16, + shop.getLocation().getWorld().getMaxHeight(), + Bukkit.getViewDistance() * 16); for (Entity nearbyPlayer : nearbyPlayers) { if (nearbyPlayer instanceof Player player) { updatePerPlayerShopSign(player, location, shop); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ChatSheetPrinter.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ChatSheetPrinter.java index eb90abdfd..bd8a1c868 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ChatSheetPrinter.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ChatSheetPrinter.java @@ -8,7 +8,6 @@ import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; - @Getter @Setter /* @@ -30,10 +29,17 @@ public class ChatSheetPrinter { return; } - MsgUtil.sendDirectMessage(p, - QuickShop.getInstance().text().of(p, "tableformat.left_half_line").forLocale() + MsgUtil.sendDirectMessage( + p, + QuickShop.getInstance() + .text() + .of(p, "tableformat.left_half_line") + .forLocale() .append(text) - .append(QuickShop.getInstance().text().of(p, "tableformat.right_half_line").forLocale())); + .append(QuickShop.getInstance() + .text() + .of(p, "tableformat.right_half_line") + .forLocale())); } public void printFooter() { @@ -41,7 +47,8 @@ public class ChatSheetPrinter { } private void printFullLine() { - MsgUtil.sendDirectMessage(p, QuickShop.getInstance().text().of(p, "tableformat.full_line").forLocale()); + MsgUtil.sendDirectMessage( + p, QuickShop.getInstance().text().of(p, "tableformat.full_line").forLocale()); } public void printHeader() { @@ -52,7 +59,13 @@ public class ChatSheetPrinter { if (Util.isEmptyComponent(component)) { return; } - MsgUtil.sendDirectMessage(p, QuickShop.getInstance().text().of(p, "tableformat.left_begin").forLocale().append(component)); + MsgUtil.sendDirectMessage( + p, + QuickShop.getInstance() + .text() + .of(p, "tableformat.left_begin") + .forLocale() + .append(component)); } public CommandSender getSender() { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ExpiringSet.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ExpiringSet.java index 23ce9c933..c3014036e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ExpiringSet.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ExpiringSet.java @@ -2,7 +2,6 @@ package com.ghostchu.quickshop.util; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; - import java.util.concurrent.TimeUnit; public class ExpiringSet { @@ -10,9 +9,8 @@ public class ExpiringSet { private final long lifetime; public ExpiringSet(long lifetime, TimeUnit timeUnit) { - this.cache = CacheBuilder - .newBuilder() - .expireAfterWrite(lifetime, timeUnit).build(); + this.cache = + CacheBuilder.newBuilder().expireAfterWrite(lifetime, timeUnit).build(); this.lifetime = timeUnit.toMillis(lifetime); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/FastPlayerFinder.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/FastPlayerFinder.java index 7e5c0efa5..7c6745543 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/FastPlayerFinder.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/FastPlayerFinder.java @@ -17,6 +17,14 @@ import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; import com.google.common.reflect.TypeToken; import com.google.gson.annotations.SerializedName; +import java.io.File; +import java.io.FileReader; +import java.lang.ref.WeakReference; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.Consumer; +import java.util.function.Supplier; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import org.apache.commons.lang3.tuple.ImmutableTriple; @@ -27,22 +35,14 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.FileReader; -import java.lang.ref.WeakReference; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.*; -import java.util.function.Consumer; -import java.util.function.Supplier; - public class FastPlayerFinder implements PlayerFinder, SubPasteItem { private final Cache> nameCache = CacheBuilder.newBuilder() .expireAfterAccess(3, TimeUnit.DAYS) .maximumSize(5000) .recordStats() .build(); - private final Map, Map>> handling = new ConcurrentHashMap<>(); + private final Map, Map>> handling = + new ConcurrentHashMap<>(); private final QuickShop plugin; private final Timer cleanupTimer; private final PlayerFinderResolver resolver; @@ -52,13 +52,17 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { this.resolver = new PlayerFinderResolver(this, plugin); cleanupTimer = new Timer("Failure lookup clean timer"); plugin.getPasteManager().register(plugin.getJavaPlugin(), this); - cleanupTimer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - nameCache.asMap().entrySet().removeIf(entry -> entry.getValue().isEmpty()); - handling.entrySet().removeIf(entry -> entry.getKey().get() == null); - } - }, 0, 1000 * 60 * 60); + cleanupTimer.scheduleAtFixedRate( + new TimerTask() { + @Override + public void run() { + nameCache.asMap().entrySet().removeIf(entry -> entry.getValue() + .isEmpty()); + handling.entrySet().removeIf(entry -> entry.getKey().get() == null); + } + }, + 0, + 1000 * 60 * 60); } public void bakeCaches() { @@ -69,8 +73,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } Log.debug("Loading usercache.json at " + file.getAbsolutePath()); try (FileReader reader = new FileReader(file)) { - List userCacheBeans = JsonUtil.getGson().fromJson(reader, new TypeToken>() { - }.getType()); + List userCacheBeans = + JsonUtil.getGson().fromJson(reader, new TypeToken>() {}.getType()); List fullCacheBeans = userCacheBeans.stream() .filter(b -> b.getUuid() != null) .filter(b -> b.getName() != null) @@ -82,7 +86,6 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } } - public void cacheInBatch(List cacheBeans) { cacheBeans.forEach(b -> nameCache.put(b.getUuid(), Optional.of(b.getName()))); if (PackageUtil.parsePackageProperly("disableDatabaseCacheWrite").asBoolean(false)) { @@ -93,7 +96,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { DatabaseHelper databaseHelper = plugin.getDatabaseHelper(); if (databaseHelper != null) { Log.debug("Caching " + cacheBeans.size() + " usernames into database..."); - databaseHelper.updatePlayerProfileInBatch(batchUpdate) + databaseHelper + .updatePlayerProfileInBatch(batchUpdate) .thenAccept(i -> Log.debug("Username caches update successfully, total " + i + " records updated.")) .exceptionally((e) -> { Log.debug("Failed to bake caches: " + e.getMessage()); @@ -111,7 +115,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } @Override - public @Nullable String uuid2Name(@NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService) { + public @Nullable String uuid2Name( + @NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService) { return uuid2NameFuture(uuid, writeCache, executorService).join(); } @@ -121,7 +126,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } @Override - public @Nullable UUID name2Uuid(@NotNull String name, boolean writeCache, @NotNull ExecutorService executorService) { + public @Nullable UUID name2Uuid( + @NotNull String name, boolean writeCache, @NotNull ExecutorService executorService) { return name2UuidFuture(name, writeCache, executorService).join(); } @@ -132,7 +138,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { @NotNull private Map> getExecutorRef(@NotNull ExecutorService executorService) { - for (Map.Entry, Map>> entry : this.handling.entrySet()) { + for (Map.Entry, Map>> entry : + this.handling.entrySet()) { ExecutorService service = entry.getKey().get(); if (service == executorService) { return entry.getValue(); @@ -145,27 +152,29 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } @Override - public @NotNull CompletableFuture uuid2NameFuture(@NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService) { + public @NotNull CompletableFuture uuid2NameFuture( + @NotNull UUID uuid, boolean writeCache, @NotNull ExecutorService executorService) { Optional lookupName = nameCache.getIfPresent(uuid); if (lookupName != null && lookupName.isPresent()) { return CompletableFuture.completedFuture(lookupName.get()); } Map> handling = getExecutorRef(executorService); - @SuppressWarnings("unchecked") CompletableFuture inProgress = (CompletableFuture) handling.get(uuid); + @SuppressWarnings("unchecked") + CompletableFuture inProgress = (CompletableFuture) handling.get(uuid); if (inProgress != null) { - Log.debug("Reused " + inProgress + " for uuid2Name lookup: uuid=" + uuid + ", writeCache=" + writeCache + ", executorService=" + executorService); + Log.debug("Reused " + inProgress + " for uuid2Name lookup: uuid=" + uuid + ", writeCache=" + writeCache + + ", executorService=" + executorService); return inProgress; } - CompletableFuture future = - CompletableFuture.supplyAsync( - () -> resolver.uuid2Name(uuid, executorService, (name) -> { - handling.remove(uuid); - if (writeCache) { - cache(uuid, name); - } - }), - QuickExecutor.getPrimaryProfileIoExecutor()); + CompletableFuture future = CompletableFuture.supplyAsync( + () -> resolver.uuid2Name(uuid, executorService, (name) -> { + handling.remove(uuid); + if (writeCache) { + cache(uuid, name); + } + }), + QuickExecutor.getPrimaryProfileIoExecutor()); handling.put(uuid, future); return future; } @@ -176,27 +185,29 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } @Override - public @NotNull CompletableFuture name2UuidFuture(@NotNull String name, boolean writeCache, @NotNull ExecutorService executorService) { + public @NotNull CompletableFuture name2UuidFuture( + @NotNull String name, boolean writeCache, @NotNull ExecutorService executorService) { for (Map.Entry> entry : nameCache.asMap().entrySet()) { if (entry.getValue().isPresent() && entry.getValue().get().equals(name)) { return CompletableFuture.completedFuture(entry.getKey()); } } Map> handling = getExecutorRef(executorService); - @SuppressWarnings("unchecked") CompletableFuture inProgress = (CompletableFuture) handling.get(name); + @SuppressWarnings("unchecked") + CompletableFuture inProgress = (CompletableFuture) handling.get(name); if (inProgress != null) { - Log.debug("Reused " + inProgress + " for name2Uuid lookup: name=" + name + ", writeCache=" + writeCache + ", executorService=" + executorService); + Log.debug("Reused " + inProgress + " for name2Uuid lookup: name=" + name + ", writeCache=" + writeCache + + ", executorService=" + executorService); return inProgress; } - CompletableFuture future = - CompletableFuture.supplyAsync( - () -> resolver.name2Uuid(name, executorService, (uuid) -> { - handling.remove(name); - if (writeCache) { - cache(uuid, name); - } - }), - QuickExecutor.getPrimaryProfileIoExecutor()); + CompletableFuture future = CompletableFuture.supplyAsync( + () -> resolver.name2Uuid(name, executorService, (uuid) -> { + handling.remove(name); + if (writeCache) { + cache(uuid, name); + } + }), + QuickExecutor.getPrimaryProfileIoExecutor()); handling.put(name, future); return future; } @@ -216,7 +227,6 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } } - @Override public boolean isCached(@NotNull UUID uuid) { Optional value = this.nameCache.getIfPresent(uuid); @@ -253,11 +263,18 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } @Nullable - public String uuid2Name(@NotNull UUID uuid, @NotNull ExecutorService executorService, @NotNull Consumer endCallback) { + public String uuid2Name( + @NotNull UUID uuid, @NotNull ExecutorService executorService, @NotNull Consumer endCallback) { String name = null; try (PerfMonitor perf = new PerfMonitor("Username Lookup - " + uuid)) { - GrabConcurrentTask grabConcurrentTask = new GrabConcurrentTask<>(executorService, new DatabaseFindNameTask(plugin.getDatabaseHelper(), uuid), new BukkitFindNameTask(uuid), new EssentialsXFindNameTask(uuid), new PlayerDBFindNameTask(uuid)); - name = grabConcurrentTask.invokeAll("Username Lookup - " + uuid, 10, TimeUnit.SECONDS, Objects::nonNull); + GrabConcurrentTask grabConcurrentTask = new GrabConcurrentTask<>( + executorService, + new DatabaseFindNameTask(plugin.getDatabaseHelper(), uuid), + new BukkitFindNameTask(uuid), + new EssentialsXFindNameTask(uuid), + new PlayerDBFindNameTask(uuid)); + name = grabConcurrentTask.invokeAll( + "Username Lookup - " + uuid, 10, TimeUnit.SECONDS, Objects::nonNull); return name; } catch (InterruptedException e) { return null; @@ -267,12 +284,19 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } @NotNull - public UUID name2Uuid(@NotNull String name, @NotNull ExecutorService executorService, @NotNull Consumer endCallback) { + public UUID name2Uuid( + @NotNull String name, @NotNull ExecutorService executorService, @NotNull Consumer endCallback) { UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); try (PerfMonitor perf = new PerfMonitor("UniqueID Lookup - " + name)) { - GrabConcurrentTask grabConcurrentTask = new GrabConcurrentTask<>(executorService, new DatabaseFindUUIDTask(plugin.getDatabaseHelper(), name), new BukkitFindUUIDTask(name), new EssentialsXFindUUIDTask(name), new PlayerDBFindUUIDTask(name)); + GrabConcurrentTask grabConcurrentTask = new GrabConcurrentTask<>( + executorService, + new DatabaseFindUUIDTask(plugin.getDatabaseHelper(), name), + new BukkitFindUUIDTask(name), + new EssentialsXFindUUIDTask(name), + new PlayerDBFindUUIDTask(name)); // This cannot fail. - UUID lookupResult = grabConcurrentTask.invokeAll("UniqueID Lookup - " + name, 15, TimeUnit.SECONDS, Objects::nonNull); + UUID lookupResult = grabConcurrentTask.invokeAll( + "UniqueID Lookup - " + name, 15, TimeUnit.SECONDS, Objects::nonNull); if (lookupResult != null) { uuid = lookupResult; } @@ -316,7 +340,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { if (!PackageUtil.parsePackageProperly("playerDBFindUUIDTask").asBoolean(false)) { return null; } - HttpResponse response = Unirest.get("https://playerdb.co/api/player/minecraft/" + name).asString(); + HttpResponse response = Unirest.get("https://playerdb.co/api/player/minecraft/" + name) + .asString(); PlayerDBResponse playerDBResponse = JsonUtil.getGson().fromJson(response.getBody(), PlayerDBResponse.class); if (!playerDBResponse.getSuccess()) { return null; @@ -328,10 +353,13 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { @SerializedName("code") private String code; + @SerializedName("message") private String message; + @SerializedName("data") private DataDTO data; + @SerializedName("success") private Boolean success; @@ -382,14 +410,19 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { public static class PlayerDTO { @SerializedName("meta") private MetaDTO meta; + @SerializedName("username") private String username; + @SerializedName("id") private String id; + @SerializedName("raw_id") private String rawId; + @SerializedName("avatar") private String avatar; + @SerializedName("name_history") private List nameHistory; @@ -470,7 +503,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { if (!PackageUtil.parsePackageProperly("playerDBFindNameTask").asBoolean(false)) { return null; } - HttpResponse response = Unirest.get("https://playerdb.co/api/player/minecraft/" + uuid).asString(); + HttpResponse response = Unirest.get("https://playerdb.co/api/player/minecraft/" + uuid) + .asString(); PlayerDBResponse playerDBResponse = JsonUtil.getGson().fromJson(response.getBody(), PlayerDBResponse.class); if (!playerDBResponse.getSuccess()) { return null; @@ -482,10 +516,13 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { @SerializedName("code") private String code; + @SerializedName("message") private String message; + @SerializedName("data") private DataDTO data; + @SerializedName("success") private Boolean success; @@ -536,14 +573,19 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { public static class PlayerDTO { @SerializedName("meta") private MetaDTO meta; + @SerializedName("username") private String username; + @SerializedName("id") private String id; + @SerializedName("raw_id") private String rawId; + @SerializedName("avatar") private String avatar; + @SerializedName("name_history") private List nameHistory; @@ -631,7 +673,6 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } } - static class EssentialsXFindUUIDTask implements Supplier { public final String name; @@ -694,7 +735,6 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } } - static class DatabaseFindNameTask implements Supplier { private final DatabaseHelper db; private final UUID uuid; @@ -720,7 +760,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { Thread.currentThread().interrupt(); return null; } catch (ExecutionException e) { - Log.debug("Error: a exception created while query the database for username looking up: " + e.getMessage()); + Log.debug("Error: a exception created while query the database for username looking up: " + + e.getMessage()); return null; } catch (TimeoutException e) { Log.debug("Warning, timeout when query the database for username looking up, slow connection?"); @@ -745,7 +786,7 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { } if (this.db == null) { return null; - }/**/ + } /**/ try { UUID uuid = db.getPlayerUUID(name).get(30, TimeUnit.SECONDS); Log.debug("Lookup result: " + uuid); @@ -754,7 +795,8 @@ public class FastPlayerFinder implements PlayerFinder, SubPasteItem { Thread.currentThread().interrupt(); return null; } catch (ExecutionException e) { - Log.debug("Error: a exception created while query the database for unique id looking up: " + e.getMessage()); + Log.debug("Error: a exception created while query the database for unique id looking up: " + + e.getMessage()); return null; } catch (TimeoutException e) { Log.debug("Warning, timeout when query the database for unique id looking up, slow connection?"); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemExpression.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemExpression.java index 9ff3c5401..600ec6235 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemExpression.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemExpression.java @@ -1,6 +1,8 @@ package com.ghostchu.quickshop.util; import com.ghostchu.quickshop.QuickShop; +import java.util.Optional; +import java.util.function.Function; import org.apache.commons.lang3.StringUtils; import org.bukkit.Material; import org.bukkit.NamespacedKey; @@ -9,13 +11,11 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Optional; -import java.util.function.Function; - public class ItemExpression { public static final String ITEM_REFERENCE_MARKER = "@"; public static final String ENCHANTMENT_MARKER = "%"; private final QuickShop plugin; + @Nullable private final Function function; @@ -30,7 +30,6 @@ public class ItemExpression { } } - private @NotNull Function handleItemReference(@NotNull String item) { String reference = item.substring(1); ItemStack stack = plugin.getItemMarker().get(reference); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemMarker.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemMarker.java index 1d4600183..bfe42ae9d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemMarker.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ItemMarker.java @@ -6,12 +6,6 @@ import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.quickshop.util.paste.util.HTMLTable; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.Reloadable; -import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -20,13 +14,18 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.regex.Pattern; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class ItemMarker implements Reloadable, SubPasteItem { private static final String NAME_REG_EXP = "[a-zA-Z0-9_]*"; private final QuickShop plugin; private final Map stacks = new HashMap<>(); private final File file; - //private static final String NAME_REG_EXP = "\\w"; + // private static final String NAME_REG_EXP = "\\w"; private final Pattern namePattern = Pattern.compile(NAME_REG_EXP); private YamlConfiguration configuration; @@ -143,7 +142,10 @@ public class ItemMarker implements Reloadable, SubPasteItem { HTMLTable table = new HTMLTable(2); table.setTableTitle("Name", "Item"); for (Map.Entry entry : stacks.entrySet()) { - table.insert(entry.getKey(), PlainTextComponentSerializer.plainText().serialize(Util.getItemStackName(entry.getValue())) + " [" + entry.getValue().getType().getKey() + "]"); + table.insert( + entry.getKey(), + PlainTextComponentSerializer.plainText().serialize(Util.getItemStackName(entry.getValue())) + " [" + + entry.getValue().getType().getKey() + "]"); } return table.render(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MetricDataUtil.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MetricDataUtil.java index a3c7d5889..b813ef6b0 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MetricDataUtil.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MetricDataUtil.java @@ -6,15 +6,14 @@ import com.ghostchu.quickshop.api.database.bean.DataRecord; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.google.common.html.HtmlEscapers; +import java.text.DecimalFormat; +import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.text.DecimalFormat; -import java.util.UUID; - public class MetricDataUtil { private final QuickShop plugin; @@ -74,7 +73,12 @@ public class MetricDataUtil { if (shop != null) { Location location = shop.getLocation(); String template = "%s %s,%s,%s"; - nameBuilder.append(String.format(template, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); + nameBuilder.append(String.format( + template, + location.getWorld().getName(), + location.getBlockX(), + location.getBlockY(), + location.getBlockZ())); } else { nameBuilder.append("N/A"); } @@ -85,7 +89,12 @@ public class MetricDataUtil { @NotNull public String loc2String(@NotNull Location location) { String template = "%s %s,%s,%s"; - return String.format(template, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return String.format( + template, + location.getWorld().getName(), + location.getBlockX(), + location.getBlockY(), + location.getBlockZ()); } @NotNull diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MsgUtil.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MsgUtil.java index d7503653f..068f68a38 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MsgUtil.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/MsgUtil.java @@ -12,6 +12,10 @@ import com.ghostchu.quickshop.util.logging.container.PluginGlobalAlertLog; import com.google.common.collect.Iterables; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; +import java.text.DecimalFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.logging.Level; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.event.HoverEvent; @@ -31,12 +35,6 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.text.DecimalFormat; -import java.util.*; -import java.util.Map.Entry; -import java.util.logging.Level; - - public class MsgUtil { private static final QuickShop PLUGIN = QuickShop.getInstance(); private static DecimalFormat decimalFormat; @@ -65,10 +63,10 @@ public class MsgUtil { * Deletes any messages that are older than a week in the database, to save on space. */ public static void clean() { - PLUGIN.logger() - .info("Cleaning purchase messages from the database that are over a week old..."); + PLUGIN.logger().info("Cleaning purchase messages from the database that are over a week old..."); // 604800,000 msec = 1 week. - PLUGIN.getDatabaseHelper().cleanMessage(System.currentTimeMillis() - 604800000) + PLUGIN.getDatabaseHelper() + .cleanMessage(System.currentTimeMillis() - 604800000) .thenAccept(result -> Log.debug("Cleaned " + result + " messages from the database")) .exceptionally(error -> { Log.debug(Level.SEVERE, "Error cleaning purchase messages from the database:" + error.getMessage()); @@ -91,7 +89,7 @@ public class MsgUtil { public static String decimalFormat(double value) { if (decimalFormat == null) { - //lazy initialize + // lazy initialize try { String format = PLUGIN.getConfig().getString("dep.sendMessage(\"容器设置成功\");cimal-format"); decimalFormat = format == null ? new DecimalFormat() : new DecimalFormat(format); @@ -153,14 +151,19 @@ public class MsgUtil { return false; } UUID playerUniqueId = player.getUniqueId(); - PLUGIN.getDatabaseHelper().selectPlayerMessages(playerUniqueId) + PLUGIN.getDatabaseHelper() + .selectPlayerMessages(playerUniqueId) .thenAccept(msgs -> { for (String msg : msgs) { - PLUGIN.getPlatform().sendMessage(player, GsonComponentSerializer.gson().deserialize(msg)); + PLUGIN.getPlatform() + .sendMessage( + player, GsonComponentSerializer.gson().deserialize(msg)); } - PLUGIN.getDatabaseHelper().cleanMessageForPlayer(playerUniqueId) + PLUGIN.getDatabaseHelper() + .cleanMessageForPlayer(playerUniqueId) .exceptionally(error -> { - PLUGIN.logger().warn("Error on cleaning the purchase messages from the database", error); + PLUGIN.logger() + .warn("Error on cleaning the purchase messages from the database", error); return 0; }); }) @@ -216,11 +219,12 @@ public class MsgUtil { @NotNull @Deprecated(since = "4.2.0.0") public static Component getTranslateText(@NotNull ItemStack stack) { - //if (PLUGIN.getConfig().getBoolean("shop.force-use-item-original-name") || !stack.hasItemMeta() || !stack.getItemMeta().hasDisplayName()) { + // if (PLUGIN.getConfig().getBoolean("shop.force-use-item-original-name") || !stack.hasItemMeta() || + // !stack.getItemMeta().hasDisplayName()) { // return PLUGIN.getPlatform().getTranslation(stack.getType()); - //} else { + // } else { return Util.getItemStackName(stack); - //} + // } } @Deprecated @@ -236,28 +240,40 @@ public class MsgUtil { printEnchantment(chatSheetPrinter, enchantmentIntegerMap); } - private static void printEnchantment(@NotNull ChatSheetPrinter chatSheetPrinter, @NotNull Map enchs) { + private static void printEnchantment( + @NotNull ChatSheetPrinter chatSheetPrinter, @NotNull Map enchs) { if (enchs.isEmpty()) { return; } chatSheetPrinter.printCenterLine(PLUGIN.text().of("menu.enchants").forLocale()); for (Entry entries : enchs.entrySet()) { - //Use boxed object to avoid NPE + // Use boxed object to avoid NPE Integer level = entries.getValue(); Component component; try { - component = Component.empty().color(NamedTextColor.YELLOW).append(PLUGIN.getPlatform().getTranslation(entries.getKey())); + component = Component.empty() + .color(NamedTextColor.YELLOW) + .append(PLUGIN.getPlatform().getTranslation(entries.getKey())); } catch (Throwable error) { - component = MsgUtil.setHandleFailedHover(null, Component.text(entries.getKey().getKey().toString())); - QuickShop.getInstance().logger().warn("Failed to handle translation for Enchantment {}", entries.getKey().getKey(), error); + component = MsgUtil.setHandleFailedHover( + null, Component.text(entries.getKey().getKey().toString())); + QuickShop.getInstance() + .logger() + .warn( + "Failed to handle translation for Enchantment {}", + entries.getKey().getKey(), + error); } - chatSheetPrinter.printLine(component.append(Component.text(" " + RomanNumber.toRoman(level == null ? 1 : level)))); + chatSheetPrinter.printLine( + component.append(Component.text(" " + RomanNumber.toRoman(level == null ? 1 : level)))); } } @NotNull - private static HoverEvent getHandleFailedHoverEvent(@Nullable CommandSender sender, @Nullable HoverEvent oldHoverEvent) { - HoverEvent hoverEvent = HoverEvent.showText(PLUGIN.text().of(sender, "display-fallback").forLocale()); + private static HoverEvent getHandleFailedHoverEvent( + @Nullable CommandSender sender, @Nullable HoverEvent oldHoverEvent) { + HoverEvent hoverEvent = + HoverEvent.showText(PLUGIN.text().of(sender, "display-fallback").forLocale()); if (oldHoverEvent != null) { hoverEvent = hoverEvent.value(hoverEvent.value().appendNewline().append(hoverEvent.value())); } @@ -266,14 +282,13 @@ public class MsgUtil { @NotNull public static Component setHandleFailedHover(@Nullable CommandSender sender, @NotNull Component component) { - return Component.empty().append(component.hoverEvent( - getHandleFailedHoverEvent(sender, null)) - .decorate(TextDecoration.UNDERLINED) - .color(NamedTextColor.RED) - ); + return Component.empty() + .append(component + .hoverEvent(getHandleFailedHoverEvent(sender, null)) + .decorate(TextDecoration.UNDERLINED) + .color(NamedTextColor.RED)); } - /** * @param shop The shop purchased * @param uuid The uuid of the player to message @@ -310,9 +325,9 @@ public class MsgUtil { Log.debug(serialized); OfflinePlayer p = Bukkit.getOfflinePlayer(uuid); if (!p.isOnline()) { - PLUGIN.getDatabaseHelper().saveOfflineTransactionMessage(uuid, serialized, System.currentTimeMillis()) - .thenAccept(v -> { - }) + PLUGIN.getDatabaseHelper() + .saveOfflineTransactionMessage(uuid, serialized, System.currentTimeMillis()) + .thenAccept(v -> {}) .exceptionally(err -> { PLUGIN.logger().warn("Could not save transaction message to database", err); return null; @@ -326,7 +341,8 @@ public class MsgUtil { }); } } catch (Exception e) { - Log.debug("Could not send shop transaction message to player " + p.getName() + " via BungeeCord: " + e.getMessage()); + Log.debug("Could not send shop transaction message to player " + p.getName() + " via BungeeCord: " + + e.getMessage()); } } else { Player player = p.getPlayer(); @@ -336,8 +352,10 @@ public class MsgUtil { } } - public static void sendBungeeMessage(@NotNull String playerName, @NotNull Component message, @NotNull String locale) { - Component csmMessage = PLUGIN.text().of("bungee-cross-server-msg", message).forLocale(locale); + public static void sendBungeeMessage( + @NotNull String playerName, @NotNull Component message, @NotNull String locale) { + Component csmMessage = + PLUGIN.text().of("bungee-cross-server-msg", message).forLocale(locale); ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("MessageRaw"); out.writeUTF(playerName); @@ -367,7 +385,6 @@ public class MsgUtil { } PLUGIN.getShopManager().bakeShopRuntimeRandomUniqueIdCache(shop); PLUGIN.getShopControlPanelManager().openControlPanel((Player) sender, shop); - } public static void sendDirectMessage(@NotNull UUID sender, @Nullable Component... messages) { @@ -426,8 +443,7 @@ public class MsgUtil { public static void sendGlobalAlert(@Nullable String content) { if (content == null) { Log.debug("Content is null"); - Throwable throwable = - new Throwable("Known issue: Global Alert accepted null string, what the fuck"); + Throwable throwable = new Throwable("Known issue: Global Alert accepted null string, what the fuck"); PLUGIN.getSentryErrorReporter().sendError(throwable, "NullCheck"); return; } @@ -444,14 +460,14 @@ public class MsgUtil { public static void sendGlobalAlert(@Nullable Component content) { if (content == null) { Log.debug("Content is null"); - Throwable throwable = - new Throwable("Known issue: Global Alert accepted null string, what the fuck"); + Throwable throwable = new Throwable("Known issue: Global Alert accepted null string, what the fuck"); PLUGIN.getSentryErrorReporter().sendError(throwable, "NullCheck"); return; } sendMessageToOps(content); PLUGIN.logger().warn(LegacyComponentSerializer.legacySection().serialize(content)); - PLUGIN.logEvent(new PluginGlobalAlertLog(LegacyComponentSerializer.legacySection().serialize(content))); + PLUGIN.logEvent(new PluginGlobalAlertLog( + LegacyComponentSerializer.legacySection().serialize(content))); } /** @@ -462,7 +478,8 @@ public class MsgUtil { public static void sendMessageToOps(@NotNull String message) { for (Player player : Bukkit.getOnlinePlayers()) { if (QuickShop.getPermissionManager().hasPermission(player, "quickshop.alerts")) { - MsgUtil.sendDirectMessage(player, LegacyComponentSerializer.legacySection().deserialize(message)); + MsgUtil.sendDirectMessage( + player, LegacyComponentSerializer.legacySection().deserialize(message)); } } } @@ -487,7 +504,6 @@ public class MsgUtil { if (profile != null) { name = profile.getName(); uuid = profile.getUniqueId().toString(); - } if (name == null) { name = "Unknown"; @@ -497,13 +513,14 @@ public class MsgUtil { } if (PLUGIN == null) { - return Component.text(name).color(TextColor.color(NamedTextColor.AQUA)) + return Component.text(name) + .color(TextColor.color(NamedTextColor.AQUA)) .append(Component.text("(").color(TextColor.color(NamedTextColor.GOLD))) - .append(Component.text(uuid)).color(TextColor.color(NamedTextColor.YELLOW)) + .append(Component.text(uuid)) + .color(TextColor.color(NamedTextColor.YELLOW)) .append(Component.text(")").color(TextColor.color(NamedTextColor.GOLD))); } else { return PLUGIN.text().of(sender, "player-profile-format", name, uuid).forLocale(); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/PermissionChecker.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/PermissionChecker.java index f45c27f43..08600eaf2 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/PermissionChecker.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/PermissionChecker.java @@ -14,6 +14,10 @@ import com.ghostchu.quickshop.util.performance.PerfMonitor; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; @@ -26,11 +30,6 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.plugin.RegisteredListener; import org.jetbrains.annotations.NotNull; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - /** * A helper to resolve issue around other plugins with BlockBreakEvent * @@ -43,7 +42,6 @@ public class PermissionChecker implements Reloadable { private QuickEventManager eventManager; - public PermissionChecker(@NotNull QuickShop plugin) { this.plugin = plugin; plugin.getReloadManager().register(this); @@ -60,7 +58,8 @@ public class PermissionChecker implements Reloadable { this.eventManager = new QSEventManager(plugin); plugin.logger().info("Loaded {} rules for listener blacklist.", listenerBlacklist.size()); } - plugin.logger().info("EventManager selected: {}", this.eventManager.getClass().getSimpleName()); + plugin.logger() + .info("EventManager selected: {}", this.eventManager.getClass().getSimpleName()); } /** @@ -86,8 +85,11 @@ public class PermissionChecker implements Reloadable { public Result canBuild(@NotNull Player player, @NotNull Block block) { try (PerfMonitor ignored = new PerfMonitor("Build Permission Check", Duration.of(1, ChronoUnit.SECONDS))) { QUser qUser = QUserImpl.createFullFilled(player); - if (plugin.getConfig().getStringList("shop.protection-checking-blacklist").contains(block.getWorld().getName())) { - Log.debug("Skipping protection checking in world " + block.getWorld().getName() + " causing it in blacklist."); + if (plugin.getConfig() + .getStringList("shop.protection-checking-blacklist") + .contains(block.getWorld().getName())) { + Log.debug("Skipping protection checking in world " + + block.getWorld().getName() + " causing it in blacklist."); return Result.SUCCESS; } @@ -105,16 +107,18 @@ public class PermissionChecker implements Reloadable { @Override public void setCancelled(boolean cancel) { - //tracking cancel plugin + // tracking cancel plugin if (cancel && !isCancelled()) { if (qsCancelling.get()) { return; } Log.debug("An plugin blocked the protection checking event! See this stacktrace:"); for (StackTraceElement element : Thread.currentThread().getStackTrace()) { - Log.debug(element.getClassName() + "." + element.getMethodName() + "(" + element.getLineNumber() + ")"); + Log.debug(element.getClassName() + "." + element.getMethodName() + "(" + + element.getLineNumber() + ")"); } - isCanBuild.setMessage(Thread.currentThread().getStackTrace()[2].getClassName()); + isCanBuild.setMessage( + Thread.currentThread().getStackTrace()[2].getClassName()); out: for (StackTraceElement element : Thread.currentThread().getStackTrace()) { @@ -122,7 +126,8 @@ public class PermissionChecker implements Reloadable { if (listener.getListener().getClass().getName().equals(element.getClassName())) { isCanBuild.setResult(false); isCanBuild.setMessage(listener.getPlugin().getName()); - isCanBuild.setListener(listener.getListener().getClass().getName()); + isCanBuild.setListener( + listener.getListener().getClass().getName()); break out; } } @@ -132,28 +137,37 @@ public class PermissionChecker implements Reloadable { } }; // Call for event for protection check start - this.eventManager.callEvent(new ShopProtectionCheckEvent(block.getLocation(), qUser, ProtectionCheckStatus.BEGIN, beMainHand), null); + this.eventManager.callEvent( + new ShopProtectionCheckEvent(block.getLocation(), qUser, ProtectionCheckStatus.BEGIN, beMainHand), + null); beMainHand.setDropItems(false); beMainHand.setExpToDrop(0); - //register a listener to cancel test event - Bukkit.getPluginManager().registerEvents(new Listener() { - @EventHandler(priority = EventPriority.HIGHEST) - public void onTestEvent(BlockBreakEvent event) { - if (event.equals(beMainHand)) { - // Call for event for protection check end - eventManager.callEvent( - new ShopProtectionCheckEvent( - block.getLocation(), qUser, ProtectionCheckStatus.END, beMainHand), null); - if (!event.isCancelled()) { - //Ensure this test will no be logged by some plugin - beMainHand.setCancelled(true); - isCanBuild.setResult(true); - } - HandlerList.unregisterAll(this); - } - } - }, plugin.getJavaPlugin()); + // register a listener to cancel test event + Bukkit.getPluginManager() + .registerEvents( + new Listener() { + @EventHandler(priority = EventPriority.HIGHEST) + public void onTestEvent(BlockBreakEvent event) { + if (event.equals(beMainHand)) { + // Call for event for protection check end + eventManager.callEvent( + new ShopProtectionCheckEvent( + block.getLocation(), + qUser, + ProtectionCheckStatus.END, + beMainHand), + null); + if (!event.isCancelled()) { + // Ensure this test will no be logged by some plugin + beMainHand.setCancelled(true); + isCanBuild.setResult(true); + } + HandlerList.unregisterAll(this); + } + } + }, + plugin.getJavaPlugin()); this.eventManager.callEvent(beMainHand, (event) -> { if (plugin.getConfig().getBoolean("shop.cancel-protection-fake-event-before-reach-monitor-listeners")) { if (event instanceof BlockBreakEvent blockBreakEvent) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Profile.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Profile.java index 314a46ce3..55188aede 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Profile.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Profile.java @@ -1,10 +1,9 @@ package com.ghostchu.quickshop.util; +import java.util.UUID; import lombok.AllArgsConstructor; import lombok.Data; -import java.util.UUID; - @AllArgsConstructor @Data public class Profile { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ProgressMonitor.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ProgressMonitor.java index 60898dbca..c19c566a7 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ProgressMonitor.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ProgressMonitor.java @@ -1,13 +1,12 @@ package com.ghostchu.quickshop.util; -import org.apache.commons.lang3.tuple.Triple; -import org.jetbrains.annotations.NotNull; - import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; +import org.apache.commons.lang3.tuple.Triple; +import org.jetbrains.annotations.NotNull; public class ProgressMonitor implements Iterable { private final Collection elements; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ReflectFactory.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ReflectFactory.java index cd991549f..dc22d48dc 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ReflectFactory.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/ReflectFactory.java @@ -12,8 +12,7 @@ public class ReflectFactory { private static String nmsVersion; - private ReflectFactory() { - } + private ReflectFactory() {} @NotNull public static String getNMSVersion() { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Util.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Util.java index ca73de103..f39153570 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Util.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/Util.java @@ -12,6 +12,14 @@ import com.ghostchu.quickshop.common.util.RomanNumber; import com.ghostchu.quickshop.shop.display.AbstractDisplayItem; import com.ghostchu.quickshop.util.logger.Log; import io.papermc.lib.PaperLib; +import java.io.File; +import java.io.FileNotFoundException; +import java.lang.management.ManagementFactory; +import java.text.DecimalFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import net.kyori.adventure.text.Component; @@ -43,32 +51,24 @@ import org.jetbrains.annotations.Nullable; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; -import java.io.File; -import java.io.FileNotFoundException; -import java.lang.management.ManagementFactory; -import java.text.DecimalFormat; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; -import java.util.stream.Collectors; - public class Util { private static final EnumMap CUSTOM_STACKSIZE = new EnumMap<>(Material.class); private static final EnumSet SHOPABLES = EnumSet.noneOf(Material.class); - private static final List VERTICAL_FACING = List.of(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST); + private static final List VERTICAL_FACING = + List.of(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST); private static int BYPASSED_CUSTOM_STACKSIZE = -1; private static Yaml yaml = null; private static Boolean devMode = null; + @Setter private static QuickShop plugin; + @Getter @Nullable private static DyeColor dyeColor = null; - private Util() { - } + private Util() {} @Deprecated @ApiStatus.Internal @@ -91,7 +91,6 @@ public class Util { return SHOPABLES; } - /** * Execute the Runnable in async thread. * If it already on main-thread, will be move to async thread. @@ -244,7 +243,8 @@ public class Util { * @return Game StackSize or Custom */ public static int getItemMaxStackSize(@NotNull Material material) { - return CUSTOM_STACKSIZE.getOrDefault(material, BYPASSED_CUSTOM_STACKSIZE == -1 ? material.getMaxStackSize() : BYPASSED_CUSTOM_STACKSIZE); + return CUSTOM_STACKSIZE.getOrDefault( + material, BYPASSED_CUSTOM_STACKSIZE == -1 ? material.getMaxStackSize() : BYPASSED_CUSTOM_STACKSIZE); } /** @@ -302,7 +302,7 @@ public class Util { DumperOptions yamlOptions = new DumperOptions(); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlOptions.setIndent(2); - yaml = new Yaml(yamlOptions); //Caching it! + yaml = new Yaml(yamlOptions); // Caching it! } YamlConfiguration yamlConfiguration = new YamlConfiguration(); Map root = yaml.load(config); @@ -330,8 +330,13 @@ public class Util { config = yaml.dump(root); Log.debug("Updated, we will try load as hacked ItemStack: " + config); } else { - plugin.logger().warn("Cannot load ItemStack {} because it saved from higher Minecraft server version, the action will fail and you will receive a exception, PLEASE DON'T REPORT TO QUICKSHOP!", config); - plugin.logger().warn("You can try force load this ItemStack by our hacked ItemStack read util (shop.force-load-downgrade-items), but beware, the data may corrupt if you load on this lower Minecraft server version, Please backup your world and database before enable!"); + plugin.logger() + .warn( + "Cannot load ItemStack {} because it saved from higher Minecraft server version, the action will fail and you will receive a exception, PLEASE DON'T REPORT TO QUICKSHOP!", + config); + plugin.logger() + .warn( + "You can try force load this ItemStack by our hacked ItemStack read util (shop.force-load-downgrade-items), but beware, the data may corrupt if you load on this lower Minecraft server version, Please backup your world and database before enable!"); } } yamlConfiguration.loadFromString(config); @@ -367,7 +372,9 @@ public class Util { * @return Equals or not. */ private static boolean equalsBlockStateLocation(@NotNull Location b1, @NotNull Location b2) { - return (b1.getBlockX() == b2.getBlockX()) && (b1.getBlockY() == b2.getBlockY()) && (b1.getBlockZ() == b2.getBlockZ()); + return (b1.getBlockX() == b2.getBlockX()) + && (b1.getBlockY() == b2.getBlockY()) + && (b1.getBlockZ() == b2.getBlockZ()); } /** @@ -447,7 +454,8 @@ public class Util { try { result = plugin.getPlatform().getTranslation(itemStack); } catch (Throwable th) { - result = MsgUtil.setHandleFailedHover(null, Component.text(itemStack.getType().getKey().toString())); + result = MsgUtil.setHandleFailedHover( + null, Component.text(itemStack.getType().getKey().toString())); plugin.logger().warn("Failed to handle translation for ItemStack {}", Util.serialize(itemStack), th); } } @@ -458,28 +466,33 @@ public class Util { public static Component getItemCustomName(@NotNull ItemStack itemStack) { if (useEnchantmentForEnchantedBook() && itemStack.getType() == Material.ENCHANTED_BOOK) { ItemMeta meta = itemStack.getItemMeta(); - if (meta instanceof EnchantmentStorageMeta enchantmentStorageMeta && enchantmentStorageMeta.hasStoredEnchants()) { + if (meta instanceof EnchantmentStorageMeta enchantmentStorageMeta + && enchantmentStorageMeta.hasStoredEnchants()) { return getFirstEnchantmentName(enchantmentStorageMeta); } } -// if (plugin.getConfig().getBoolean("shop.use-effect-for-potion-item") && itemStack.getType().name().endsWith("POTION")) { -// ItemMeta meta = itemStack.getItemMeta(); -// if (meta instanceof PotionMeta potionMeta) { -// PotionData potionData = potionMeta.getBasePotionData(); -// PotionEffectType potionEffectType = potionData.getType().getEffectType(); -// if (potionEffectType != null) { -// //Because the bukkit API limit, we can't get the actual effect level -// return plugin.getPlatform().getTranslation(potionEffectType); -// } else if (potionMeta.hasCustomEffects()) { -// PotionEffect potionEffect = potionMeta.getCustomEffects().get(0); -// if (potionEffect != null) { -// int level = potionEffect.getAmplifier(); -// return plugin.getPlatform().getTranslation(potionEffect.getType()).append(LegacyComponentSerializer.legacySection().deserialize(" " + (level <= 10 ? RomanNumber.toRoman(potionEffect.getAmplifier()) : level))); -// } -// } -// } -// } - if (itemStack.hasItemMeta() && Objects.requireNonNull(itemStack.getItemMeta()).hasDisplayName() && !QuickShop.getInstance().getConfig().getBoolean("shop.force-use-item-original-name")) { + // if (plugin.getConfig().getBoolean("shop.use-effect-for-potion-item") && + // itemStack.getType().name().endsWith("POTION")) { + // ItemMeta meta = itemStack.getItemMeta(); + // if (meta instanceof PotionMeta potionMeta) { + // PotionData potionData = potionMeta.getBasePotionData(); + // PotionEffectType potionEffectType = potionData.getType().getEffectType(); + // if (potionEffectType != null) { + // //Because the bukkit API limit, we can't get the actual effect level + // return plugin.getPlatform().getTranslation(potionEffectType); + // } else if (potionMeta.hasCustomEffects()) { + // PotionEffect potionEffect = potionMeta.getCustomEffects().get(0); + // if (potionEffect != null) { + // int level = potionEffect.getAmplifier(); + // return + // plugin.getPlatform().getTranslation(potionEffect.getType()).append(LegacyComponentSerializer.legacySection().deserialize(" " + (level <= 10 ? RomanNumber.toRoman(potionEffect.getAmplifier()) : level))); + // } + // } + // } + // } + if (itemStack.hasItemMeta() + && Objects.requireNonNull(itemStack.getItemMeta()).hasDisplayName() + && !QuickShop.getInstance().getConfig().getBoolean("shop.force-use-item-original-name")) { return plugin.getPlatform().getDisplayName(itemStack.getItemMeta()); } return null; @@ -504,13 +517,19 @@ public class Util { if (!meta.hasStoredEnchants()) { throw new IllegalArgumentException("Item does not have an enchantment!"); } - Entry entry = meta.getStoredEnchants().entrySet().iterator().next(); + Entry entry = + meta.getStoredEnchants().entrySet().iterator().next(); Component name; try { name = plugin.getPlatform().getTranslation(entry.getKey()); } catch (Throwable throwable) { - name = MsgUtil.setHandleFailedHover(null, Component.text(entry.getKey().getKey().getKey())); - plugin.logger().warn("Failed to handle translation for Enchantment {}", entry.getKey().getKey(), throwable); + name = MsgUtil.setHandleFailedHover( + null, Component.text(entry.getKey().getKey().getKey())); + plugin.logger() + .warn( + "Failed to handle translation for Enchantment {}", + entry.getKey().getKey(), + throwable); } if (entry.getValue() == 1 && entry.getKey().getMaxLevel() == 1) { return name; @@ -534,9 +553,13 @@ public class Util { */ @NotNull public static List getPlayerList() { - List tabList = Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); + List tabList = + Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); if (plugin.getConfig().getBoolean("include-offlineplayer-list")) { - tabList.addAll(Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName).filter(Objects::nonNull).toList()); + tabList.addAll(Arrays.stream(Bukkit.getOfflinePlayers()) + .map(OfflinePlayer::getName) + .filter(Objects::nonNull) + .toList()); } return tabList; } @@ -584,7 +607,9 @@ public class Util { return null; } BlockFace towardsLeft = getRightSide(chest.getFacing()); - BlockFace actuallyBlockFace = chest.getType() == org.bukkit.block.data.type.Chest.Type.LEFT ? towardsLeft : towardsLeft.getOppositeFace(); + BlockFace actuallyBlockFace = chest.getType() == org.bukkit.block.data.type.Chest.Type.LEFT + ? towardsLeft + : towardsLeft.getOppositeFace(); return block.getRelative(actuallyBlockFace); } @@ -633,7 +658,8 @@ public class Util { */ @NotNull public static Material getSignMaterial() { - Material signMaterial = Material.matchMaterial(plugin.getConfig().getString("shop.sign-material", "OAK_WALL_SIGN")); + Material signMaterial = + Material.matchMaterial(plugin.getConfig().getString("shop.sign-material", "OAK_WALL_SIGN")); if (signMaterial != null) { return signMaterial; } @@ -754,7 +780,13 @@ public class Util { } iterator.remove(); Log.debug("Found shop display item in an inventory" + location + ", Removing..."); - MsgUtil.sendGlobalAlert(plugin.text().of("inventory-check-global-alert", location, inv.getHolder().getClass().getName(), Util.getItemStackName(itemStack)).forLocale(MsgUtil.getDefaultGameLanguageCode())); + MsgUtil.sendGlobalAlert(plugin.text() + .of( + "inventory-check-global-alert", + location, + inv.getHolder().getClass().getName(), + Util.getItemStackName(itemStack)) + .forLocale(MsgUtil.getDefaultGameLanguageCode())); } } } catch (Exception ignored) { @@ -786,7 +818,9 @@ public class Util { * @return DevEdition status */ public static boolean isDevEdition() { - return !"origin/release".equalsIgnoreCase(QuickShop.getInstance().getBuildInfo().getGitInfo().getBranch()); + return !"origin/release" + .equalsIgnoreCase( + QuickShop.getInstance().getBuildInfo().getGitInfo().getBranch()); } /** @@ -859,7 +893,7 @@ public class Util { * @param args the arg of method * @return boolean Available */ - public static boolean isMethodAvailable(@NotNull String className, String method, Class... args) {// nosemgrep + public static boolean isMethodAvailable(@NotNull String className, String method, Class... args) { // nosemgrep try { Class clazz = Class.forName(className); try { @@ -887,7 +921,8 @@ public class Util { } Shop shop = plugin.getShopManager().getShopIncludeAttached(bshop.getLocation()); if (shop == null) { - shop = plugin.getShopManager().getShopIncludeAttached(bshop.getLocation().clone().add(0, 1, 0)); + shop = plugin.getShopManager() + .getShopIncludeAttached(bshop.getLocation().clone().add(0, 1, 0)); } return shop != null && !shop.playerAuthorize(p.getUniqueId(), BuiltInShopPermission.ACCESS_INVENTORY); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/WarningSender.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/WarningSender.java index 9dae43640..98903fc87 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/WarningSender.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/WarningSender.java @@ -14,8 +14,10 @@ import org.jetbrains.annotations.NotNull; @ToString public class WarningSender { private final long cooldown; + @ToString.Exclude private final QuickShop plugin; + private long lastSend = 0; /** @@ -43,5 +45,4 @@ public class WarningSender { } return false; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigProvider.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigProvider.java index ddb671a52..7ca3559c0 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigProvider.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigProvider.java @@ -1,12 +1,9 @@ package com.ghostchu.quickshop.util.config; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.QuickShopInstanceHolder; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -16,8 +13,10 @@ import java.nio.file.Files; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; - -import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; public class ConfigProvider extends QuickShopInstanceHolder { private final File configFile; @@ -61,19 +60,29 @@ public class ConfigProvider extends QuickShopInstanceHolder { } } catch (IOException | InvalidConfigurationException exception) { if (!defaults) { - logger.log(Level.SEVERE, "Cannot reading the configuration " + configFile.getName() + ", doing backup configuration and use default", exception); + logger.log( + Level.SEVERE, + "Cannot reading the configuration " + configFile.getName() + + ", doing backup configuration and use default", + exception); try { - Files.copy(configFile.toPath(), plugin.getDataFolder().toPath().resolve(configFile.getName() + "-broken-" + UUID.randomUUID() + ".yml"), REPLACE_EXISTING); + Files.copy( + configFile.toPath(), + plugin.getDataFolder() + .toPath() + .resolve(configFile.getName() + "-broken-" + UUID.randomUUID() + ".yml"), + REPLACE_EXISTING); } catch (IOException fatalException) { - throw new IllegalStateException("Failed to backup configuration " + configFile.getName(), fatalException); + throw new IllegalStateException( + "Failed to backup configuration " + configFile.getName(), fatalException); } plugin.saveResource(configFile.getName(), true); reload(true); } else { - throw new IllegalStateException("Failed to load default configuration " + configFile.getName(), exception); + throw new IllegalStateException( + "Failed to load default configuration " + configFile.getName(), exception); } } - } public void save() { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigUpdateScript.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigUpdateScript.java index e11c6b91d..0a2a952e6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigUpdateScript.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigUpdateScript.java @@ -2,16 +2,16 @@ package com.ghostchu.quickshop.util.config; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.Util; +import java.io.File; +import java.util.List; import lombok.Getter; import org.bukkit.configuration.file.FileConfiguration; import org.jetbrains.annotations.NotNull; -import java.io.File; -import java.util.List; - @SuppressWarnings("unused") public class ConfigUpdateScript { private final QuickShop plugin; + @Getter private final FileConfiguration config; @@ -53,7 +53,6 @@ public class ConfigUpdateScript { getConfig().set("shop.cancel-protection-fake-event-before-reach-monitor-listeners", true); } - @UpdateScript(version = 1019) public void oldConfigCleanup() { getConfig().set("plugin.OpenInv", null); @@ -128,7 +127,6 @@ public class ConfigUpdateScript { getConfig().set("tax-free-for-unlimited-shop", false); } - @UpdateScript(version = 1007) public void refundFromTaxAccountOption() { getConfig().set("shop.refund-from-tax-account", false); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationFixer.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationFixer.java index a448c362d..b8ec1b448 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationFixer.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationFixer.java @@ -1,13 +1,12 @@ package com.ghostchu.quickshop.util.config; import com.ghostchu.quickshop.QuickShop; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; - import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Objects; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; /** * ConfigurationFixer is a utilities to help user automatically fix broken configuration. @@ -20,14 +19,17 @@ public class ConfigurationFixer { private final FileConfiguration externalConfig; private final FileConfiguration builtInConfig; - public ConfigurationFixer(QuickShop plugin, File externalConfigFile, FileConfiguration externalConfig, FileConfiguration builtInConfig) { + public ConfigurationFixer( + QuickShop plugin, + File externalConfigFile, + FileConfiguration externalConfig, + FileConfiguration builtInConfig) { this.plugin = plugin; this.externalConfigFile = externalConfigFile; this.externalConfig = externalConfig; this.builtInConfig = builtInConfig; } - public boolean fix() { // There read the default value as true but we should set default value as false in config.yml // So that we can check the configuration may broken or other else. @@ -38,7 +40,12 @@ public class ConfigurationFixer { plugin.logger().warn("Warning! QuickShop detected the configuration has been corrupted."); plugin.logger().warn("Backup - Creating backup for configuration..."); try { - Files.copy(externalConfigFile.toPath(), new File(externalConfigFile.getParent(), externalConfigFile.getName() + "." + System.currentTimeMillis()).toPath()); + Files.copy( + externalConfigFile.toPath(), + new File( + externalConfigFile.getParent(), + externalConfigFile.getName() + "." + System.currentTimeMillis()) + .toPath()); } catch (IOException ioException) { plugin.logger().warn("Failed to create file backup.", ioException); } @@ -46,12 +53,19 @@ public class ConfigurationFixer { for (String key : builtInConfig.getKeys(true)) { Object value = externalConfig.get(key); Object buildInValue = builtInConfig.get(key); - if (!(value instanceof ConfigurationSection) || !value.getClass().getTypeName().equals(Objects.requireNonNull(buildInValue).getClass().getTypeName())) { + if (!(value instanceof ConfigurationSection) + || !value.getClass() + .getTypeName() + .equals(Objects.requireNonNull(buildInValue) + .getClass() + .getTypeName())) { plugin.logger().warn("Fixing configuration use default value: {}", key); plugin.getConfig().set(key, buildInValue); } } - plugin.logger().info("QuickShop fixed the corrupted parts in configuration that we can found. We recommend you restart the server and make fix apply."); + plugin.logger() + .info( + "QuickShop fixed the corrupted parts in configuration that we can found. We recommend you restart the server and make fix apply."); externalConfig.set("config-damaged", false); try { externalConfig.save(externalConfigFile); @@ -61,4 +75,3 @@ public class ConfigurationFixer { return true; } } - diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationUpdater.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationUpdater.java index 5e16196f5..f0156f4ee 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationUpdater.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/ConfigurationUpdater.java @@ -3,12 +3,6 @@ package com.ghostchu.quickshop.util.config; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.logger.Log; -import lombok.Getter; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.NotNull; - import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; @@ -17,12 +11,19 @@ import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.*; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; public class ConfigurationUpdater { private static final String CONFIG_VERSION_KEY = "config-version"; private final QuickShop plugin; + @Getter private final ConfigurationSection configuration; + private int selectedVersion = -1; public ConfigurationUpdater(QuickShop plugin) { @@ -31,8 +32,16 @@ public class ConfigurationUpdater { } private void brokenConfigurationFix() { - try (InputStreamReader buildInConfigReader = new InputStreamReader(new BufferedInputStream(Objects.requireNonNull(plugin.getJavaPlugin().getResource("config.yml"))), StandardCharsets.UTF_8)) { - if (new ConfigurationFixer(plugin, new File(plugin.getDataFolder(), "config.yml"), plugin.getConfig(), YamlConfiguration.loadConfiguration(buildInConfigReader)).fix()) { + try (InputStreamReader buildInConfigReader = new InputStreamReader( + new BufferedInputStream( + Objects.requireNonNull(plugin.getJavaPlugin().getResource("config.yml"))), + StandardCharsets.UTF_8)) { + if (new ConfigurationFixer( + plugin, + new File(plugin.getDataFolder(), "config.yml"), + plugin.getConfig(), + YamlConfiguration.loadConfiguration(buildInConfigReader)) + .fix()) { plugin.getJavaPlugin().reloadConfig(); } } catch (Exception e) { @@ -51,7 +60,9 @@ public class ConfigurationUpdater { if (current >= updateScript.version()) { continue; } - plugin.logger().info("[ConfigUpdater] Updating configuration from " + current + " to " + updateScript.version()); + plugin.logger() + .info("[ConfigUpdater] Updating configuration from " + current + " to " + + updateScript.version()); String scriptName = updateScript.description(); if (StringUtils.isEmpty(scriptName)) { scriptName = method.getName(); @@ -61,29 +72,41 @@ public class ConfigurationUpdater { if (method.getParameterCount() == 0) { method.invoke(configUpdateScript); } else { - if (method.getParameterCount() == 1 && (method.getParameterTypes()[0] == int.class || method.getParameterTypes()[0] == Integer.class)) { + if (method.getParameterCount() == 1 + && (method.getParameterTypes()[0] == int.class + || method.getParameterTypes()[0] == Integer.class)) { method.invoke(configUpdateScript, current); } } } catch (Exception e) { - plugin.logger().warn("Failed to execute update script {} for version {}: {}, plugin may not working properly!", method.getName(), updateScript.version(), e.getMessage(), e); + plugin.logger() + .warn( + "Failed to execute update script {} for version {}: {}, plugin may not working properly!", + method.getName(), + updateScript.version(), + e.getMessage(), + e); } getConfiguration().set(CONFIG_VERSION_KEY, updateScript.version()); plugin.logger().info("[ConfigUpdater] Configuration updated to version " + updateScript.version()); } catch (Throwable throwable) { - plugin.logger().warn("Failed execute update script {} for updating to version {}, some configuration options may missing or outdated", method.getName(), method.getAnnotation(UpdateScript.class).version(), throwable); + plugin.logger() + .warn( + "Failed execute update script {} for updating to version {}, some configuration options may missing or outdated", + method.getName(), + method.getAnnotation(UpdateScript.class).version(), + throwable); } } plugin.logger().info("[ConfigUpdater] Saving configuration changes..."); plugin.getJavaPlugin().saveConfig(); plugin.getJavaPlugin().reloadConfig(); - //Delete old example configuration files + // Delete old example configuration files try { cleanupOldConfigs(); } catch (IOException e) { Log.debug("Failed to cleanup old configuration files: " + e.getMessage()); } - } private void writeServerUniqueId() { @@ -93,7 +116,6 @@ public class ConfigurationUpdater { } } - @NotNull public List getUpdateScripts(@NotNull Object configUpdateScript) { List methods = new ArrayList<>(); @@ -103,7 +125,8 @@ public class ConfigurationUpdater { } methods.add(declaredMethod); } - methods.sort(Comparator.comparingInt(o -> o.getAnnotation(UpdateScript.class).version())); + methods.sort( + Comparator.comparingInt(o -> o.getAnnotation(UpdateScript.class).version())); return methods; } @@ -113,7 +136,9 @@ public class ConfigurationUpdater { Files.deleteIfExists(new File(plugin.getDataFolder(), "example-configuration.yml").toPath()); try { if (new File(plugin.getDataFolder(), "messages.yml").exists()) { - Files.move(new File(plugin.getDataFolder(), "messages.yml").toPath(), new File(plugin.getDataFolder(), "messages.yml.outdated").toPath()); + Files.move( + new File(plugin.getDataFolder(), "messages.yml").toPath(), + new File(plugin.getDataFolder(), "messages.yml.outdated").toPath()); } } catch (Exception ignore) { } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/UpdateScript.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/UpdateScript.java index 954cc5c48..049cdf0c3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/UpdateScript.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/config/UpdateScript.java @@ -1,8 +1,7 @@ package com.ghostchu.quickshop.util.config; -import org.jetbrains.annotations.Nullable; - import java.lang.annotation.*; +import org.jetbrains.annotations.Nullable; /** * Mark a method as update script and will be executed by ConfigurationUpdater @@ -12,7 +11,8 @@ import java.lang.annotation.*; @Target(ElementType.METHOD) @Inherited public @interface UpdateScript { - @Nullable String description() default ""; + @Nullable + String description() default ""; int version(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/BuiltInEconomyFormatter.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/BuiltInEconomyFormatter.java index 0112d7707..b3c530555 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/BuiltInEconomyFormatter.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/BuiltInEconomyFormatter.java @@ -6,12 +6,11 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.Nullable; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; public class BuiltInEconomyFormatter implements Reloadable { private static final Map CURRENCY_SYMBOL_MAPPING = new HashMap<>(); @@ -41,12 +40,13 @@ public class BuiltInEconomyFormatter implements Reloadable { return new ReloadResult(ReloadStatus.SUCCESS, "Reload successfully.", null); } - public String getInternalFormat(double amount, @Nullable String currency) { if (StringUtils.isEmpty(currency)) { Log.debug("Format: Currency is null"); String formatted = useDecimalFormat ? MsgUtil.decimalFormat(amount) : Double.toString(amount); - return currencySymbolOnRight ? formatted + plugin.getConfig().getString("shop.alternate-currency-symbol", "$") : plugin.getConfig().getString("shop.alternate-currency-symbol", "$") + formatted; + return currencySymbolOnRight + ? formatted + plugin.getConfig().getString("shop.alternate-currency-symbol", "$") + : plugin.getConfig().getString("shop.alternate-currency-symbol", "$") + formatted; } else { Log.debug("Format: Currency is: [" + currency + "]"); String formatted = useDecimalFormat ? MsgUtil.decimalFormat(amount) : Double.toString(amount); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/EconomyFormatter.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/EconomyFormatter.java index 55b86e2e2..6ce76b89d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/EconomyFormatter.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/economyformatter/EconomyFormatter.java @@ -8,15 +8,14 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class EconomyFormatter implements Reloadable { private static final Map CURRENCY_SYMBOL_MAPPING = new HashMap<>(); private final QuickShop plugin; @@ -68,8 +67,7 @@ public class EconomyFormatter implements Reloadable { try { String formatted = plugin.getEconomy().format(n, world, currency); if (StringUtils.isEmpty(formatted)) { - Log.debug( - "Use alternate-currency-symbol to formatting, Cause economy plugin returned null"); + Log.debug("Use alternate-currency-symbol to formatting, Cause economy plugin returned null"); return getInternalFormat(n, currency); } else { return formatted; @@ -85,7 +83,9 @@ public class EconomyFormatter implements Reloadable { if (StringUtils.isEmpty(currency)) { Log.debug("Format: Currency is null"); String formatted = useDecimalFormat ? MsgUtil.decimalFormat(amount) : Double.toString(amount); - return currencySymbolOnRight ? formatted + plugin.getConfig().getString("shop.alternate-currency-symbol", "$") : plugin.getConfig().getString("shop.alternate-currency-symbol", "$") + formatted; + return currencySymbolOnRight + ? formatted + plugin.getConfig().getString("shop.alternate-currency-symbol", "$") + : plugin.getConfig().getString("shop.alternate-currency-symbol", "$") + formatted; } else { Log.debug("Format: Currency is: [" + currency + "]"); String formatted = useDecimalFormat ? MsgUtil.decimalFormat(amount) : Double.toString(amount); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/CheckResult.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/CheckResult.java index 2fd834a2f..821f37f72 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/CheckResult.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/CheckResult.java @@ -1,7 +1,11 @@ package com.ghostchu.quickshop.util.envcheck; public enum CheckResult { - SKIPPED("Skip"), PASSED("Pass"), WARNING("Warning"), STOP_WORKING("Error"), DISABLE_PLUGIN("Fatal"); + SKIPPED("Skip"), + PASSED("Pass"), + WARNING("Warning"), + STOP_WORKING("Error"), + DISABLE_PLUGIN("Fatal"); private final String display; CheckResult(String display) { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/EnvironmentChecker.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/EnvironmentChecker.java index 7e518b844..f0fa1de15 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/EnvironmentChecker.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/EnvironmentChecker.java @@ -11,11 +11,10 @@ import com.ghostchu.quickshop.util.ReflectFactory; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; import io.papermc.lib.PaperLib; -import org.bukkit.Bukkit; -import org.jetbrains.annotations.NotNull; - import java.lang.reflect.Method; import java.util.*; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; public final class EnvironmentChecker { private static final String CHECK_PASSED_RETURNS = "Check passed"; @@ -24,7 +23,7 @@ public final class EnvironmentChecker { public EnvironmentChecker(QuickShop plugin) { this.plugin = plugin; - this.registerTests(this.getClass()); //register self + this.registerTests(this.getClass()); // register self } /** @@ -60,10 +59,16 @@ public final class EnvironmentChecker { String nmsVersion = ReflectFactory.getNMSVersion(); GameVersion gameVersion = GameVersion.get(nmsVersion); if (!gameVersion.isCoreSupports()) { - return new ResultContainer(CheckResult.STOP_WORKING, "Your Minecraft version is no longer supported: " + plugin.getPlatform().getMinecraftVersion() + " (" + nmsVersion + ")"); + return new ResultContainer( + CheckResult.STOP_WORKING, + "Your Minecraft version is no longer supported: " + + plugin.getPlatform().getMinecraftVersion() + " (" + nmsVersion + ")"); } if (gameVersion == GameVersion.UNKNOWN) { - return new ResultContainer(CheckResult.WARNING, "QuickShop may not fully support version " + nmsVersion + "/" + plugin.getPlatform().getMinecraftVersion() + ", Some features may not work."); + return new ResultContainer( + CheckResult.WARNING, + "QuickShop may not fully support version " + nmsVersion + "/" + + plugin.getPlatform().getMinecraftVersion() + ", Some features may not work."); } return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); } @@ -71,7 +76,9 @@ public final class EnvironmentChecker { @EnvCheckEntry(name = "End of life Test", priority = Integer.MAX_VALUE, stage = EnvCheckEntry.Stage.ON_ENABLE) public ResultContainer eolTest() { if (plugin.getGameVersion().isEndOfLife()) { - return new ResultContainer(CheckResult.WARNING, "You're running a Minecraft server with end of life version, QuickShop may not work on this version in future, and you won't receive any in-game update notification anymore, upgrade your server version!"); + return new ResultContainer( + CheckResult.WARNING, + "You're running a Minecraft server with end of life version, QuickShop may not work on this version in future, and you won't receive any in-game update notification anymore, upgrade your server version!"); } return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); } @@ -81,13 +88,15 @@ public final class EnvironmentChecker { String nmsVersion = ReflectFactory.getNMSVersion(); GameVersion gameVersion = GameVersion.get(nmsVersion); if (gameVersion == GameVersion.UNKNOWN) { - return new ResultContainer(CheckResult.WARNING, "Your Minecraft server version not tested by developers, QuickShop may ran into issues on this version."); + return new ResultContainer( + CheckResult.WARNING, + "Your Minecraft server version not tested by developers, QuickShop may ran into issues on this version."); } return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); } public boolean isOutdatedJvm() { - String jvmVersion = System.getProperty("java.version"); //Use java version not jvm version. + String jvmVersion = System.getProperty("java.version"); // Use java version not jvm version. String[] splitVersion = jvmVersion.split("\\."); if (splitVersion.length < 1) { Log.debug("Failed to parse jvm version to check: " + jvmVersion); @@ -95,7 +104,7 @@ public final class EnvironmentChecker { } try { int majorVersion = Integer.parseInt(splitVersion[0]); - return majorVersion < 17; //Target JDK/JRE version + return majorVersion < 17; // Target JDK/JRE version } catch (NumberFormatException ignored) { Log.debug("Failed to parse jvm major version to check: " + splitVersion[0]); return false; @@ -125,15 +134,18 @@ public final class EnvironmentChecker { @EnvCheckEntry(name = "ModdedServer Database Driver Test", priority = 5) public ResultContainer moddedServerDatabaseDriverTest() { - boolean trigged = (isForgeBasedServer() || isFabricBasedServer()) && !plugin.getConfig().getBoolean("database.mysql", false); + boolean trigged = (isForgeBasedServer() || isFabricBasedServer()) + && !plugin.getConfig().getBoolean("database.mysql", false); if (trigged && Bukkit.getPluginManager().getPlugin("Mohist") == null) { - return new ResultContainer(CheckResult.STOP_WORKING, "You can't use H2 database driver on Forge/Fabric hybird server (it's buggy and will destroy your data on Arclight). Use a MySQL server instead. If you're running Mohist or other no-bug software, add -Dcom.ghostchu.quickshop.util.envcheck.EnvironmentChecker.skip.MODDEDSERVER_DATABASE_DRIVER_TEST=true to startup flag to skip this check."); + return new ResultContainer( + CheckResult.STOP_WORKING, + "You can't use H2 database driver on Forge/Fabric hybird server (it's buggy and will destroy your data on Arclight). Use a MySQL server instead. If you're running Mohist or other no-bug software, add -Dcom.ghostchu.quickshop.util.envcheck.EnvironmentChecker.skip.MODDEDSERVER_DATABASE_DRIVER_TEST=true to startup flag to skip this check."); } return new ResultContainer(CheckResult.PASSED, "OK"); } public boolean isForgeBasedServer() { - //Forge server detect - Arclight + // Forge server detect - Arclight if (CommonUtil.isClassAvailable("net.minecraftforge.server.ServerMain")) { return true; } @@ -147,14 +159,16 @@ public final class EnvironmentChecker { } public boolean isFabricBasedServer() { - //Nobody really make it right!? - return CommonUtil.isClassAvailable("net.fabricmc.loader.launch.knot.KnotClient"); //OMG + // Nobody really make it right!? + return CommonUtil.isClassAvailable("net.fabricmc.loader.launch.knot.KnotClient"); // OMG } @EnvCheckEntry(name = "Old QuickShop Test", priority = 3) public ResultContainer oldQuickShopTest() { if (CommonUtil.isClassAvailable("com.ghostchu.quickshop.Util.NMS")) { - return new ResultContainer(CheckResult.STOP_WORKING, "FATAL: Old QuickShop build is installed! You must remove old QuickShop jar from the plugins folder!"); + return new ResultContainer( + CheckResult.STOP_WORKING, + "FATAL: Old QuickShop build is installed! You must remove old QuickShop jar from the plugins folder!"); } return new ResultContainer(CheckResult.PASSED, "No old QuickShop jar installled on this server"); } @@ -162,15 +176,22 @@ public final class EnvironmentChecker { @EnvCheckEntry(name = "Permission Manager Test", priority = 10, stage = EnvCheckEntry.Stage.ON_ENABLE) public ResultContainer permManagerConflictTest() { if (Bukkit.getPluginManager().isPluginEnabled("GroupManager")) { - return new ResultContainer(CheckResult.WARNING, "WARNING: Unsupported plugin management plugin [GroupManager] installed, the permissions may not working."); + return new ResultContainer( + CheckResult.WARNING, + "WARNING: Unsupported plugin management plugin [GroupManager] installed, the permissions may not working."); } return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); } @EnvCheckEntry(name = "PacketListenerAPI Conflict Test", priority = 10) public ResultContainer plapiConflictTest() { - if (plugin.isDisplayEnabled() && AbstractDisplayItem.getNowUsing() == DisplayType.VIRTUALITEM && Bukkit.getPluginManager().isPluginEnabled("ProtocolLib") && Bukkit.getPluginManager().isPluginEnabled("PacketListenerAPI")) { - return new ResultContainer(CheckResult.WARNING, "Virtual DisplayItem may stop working on your server. We are already aware that [PacketListenerAPI] and [ProtocolLib] are conflicting. (QuickShops requirement to send fake items). If your display is not showing, please uninstall [PacketListenerAPI]."); + if (plugin.isDisplayEnabled() + && AbstractDisplayItem.getNowUsing() == DisplayType.VIRTUALITEM + && Bukkit.getPluginManager().isPluginEnabled("ProtocolLib") + && Bukkit.getPluginManager().isPluginEnabled("PacketListenerAPI")) { + return new ResultContainer( + CheckResult.WARNING, + "Virtual DisplayItem may stop working on your server. We are already aware that [PacketListenerAPI] and [ProtocolLib] are conflicting. (QuickShops requirement to send fake items). If your display is not showing, please uninstall [PacketListenerAPI]."); } return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); } @@ -178,37 +199,39 @@ public final class EnvironmentChecker { @EnvCheckEntry(name = "Reremake Test", priority = 11, stage = EnvCheckEntry.Stage.ON_ENABLE) public ResultContainer rereMakeTest() { if (Bukkit.getPluginManager().isPluginEnabled("QuickShop")) { - return new ResultContainer(CheckResult.WARNING, "WARNING: Multiple QuickShop installed, uninstall one of them."); + return new ResultContainer( + CheckResult.WARNING, "WARNING: Multiple QuickShop installed, uninstall one of them."); } return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); } -// @EnvCheckEntry(name = "Legal Compliance Check", priority = 12, stage = EnvCheckEntry.Stage.ON_ENABLE) -// public ResultContainer neteaseRegionTest() { -// HttpResponse resp = Unirest.get("https://cloudflare.com/cdn-cgi/trace") -// .connectTimeout(1000 * 10) -// .socketTimeout(1000 * 10) -// .asString(); -// if (!resp.isSuccess()) { -// return new ResultContainer(CheckResult.PASSED, "Failed to check NetEase region."); -// } -// String cloudflareResponse = resp.getBody(); -// String[] exploded = cloudflareResponse.split("\n"); -// for (String s : exploded) { -// if (s.startsWith("loc=")) { -// String[] kv = s.split("="); -// if (kv.length != 2) { -// continue; -// } -// String key = kv[0]; -// String value = kv[1]; -// if (key.equalsIgnoreCase("loc") && value.equalsIgnoreCase("CN")) { -// return new ResultContainer(CheckResult.DISABLE_PLUGIN, "自 Hikari-4.1.0.3 开始,由于潜在的法律法规风险,我们暂时停止向处于中国大陆的服务器提供服务,有关更多信息,请参考:https://ghost-chu.github.io/QuickShop-Hikari-Documents/docs/about/netease"); -// } -// } -// } -// return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); -// } + // @EnvCheckEntry(name = "Legal Compliance Check", priority = 12, stage = EnvCheckEntry.Stage.ON_ENABLE) + // public ResultContainer neteaseRegionTest() { + // HttpResponse resp = Unirest.get("https://cloudflare.com/cdn-cgi/trace") + // .connectTimeout(1000 * 10) + // .socketTimeout(1000 * 10) + // .asString(); + // if (!resp.isSuccess()) { + // return new ResultContainer(CheckResult.PASSED, "Failed to check NetEase region."); + // } + // String cloudflareResponse = resp.getBody(); + // String[] exploded = cloudflareResponse.split("\n"); + // for (String s : exploded) { + // if (s.startsWith("loc=")) { + // String[] kv = s.split("="); + // if (kv.length != 2) { + // continue; + // } + // String key = kv[0]; + // String value = kv[1]; + // if (key.equalsIgnoreCase("loc") && value.equalsIgnoreCase("CN")) { + // return new ResultContainer(CheckResult.DISABLE_PLUGIN, "自 Hikari-4.1.0.3 + // 开始,由于潜在的法律法规风险,我们暂时停止向处于中国大陆的服务器提供服务,有关更多信息,请参考:https://ghost-chu.github.io/QuickShop-Hikari-Documents/docs/about/netease"); + // } + // } + // } + // return new ResultContainer(CheckResult.PASSED, CHECK_PASSED_RETURNS); + // } public ResultReport run(EnvCheckEntry.Stage stage) { sortTests(); @@ -226,12 +249,16 @@ public final class EnvironmentChecker { try { EnvCheckEntry envCheckEntry = declaredMethod.getAnnotation(EnvCheckEntry.class); if (Arrays.stream(envCheckEntry.stage()).noneMatch(entry -> entry == stage)) { - Log.debug("Skip test: " + envCheckEntry.name() + ": Except stage: " + Arrays.toString(envCheckEntry.stage()) + " Current stage: " + stage); + Log.debug("Skip test: " + envCheckEntry.name() + ": Except stage: " + + Arrays.toString(envCheckEntry.stage()) + " Current stage: " + stage); continue; } - if (!PackageUtil.parsePackageProperly("skip." + envCheckEntry.name().toUpperCase(Locale.ROOT).replace(" ", "_")).asBoolean()) { + if (!PackageUtil.parsePackageProperly("skip." + + envCheckEntry.name().toUpperCase(Locale.ROOT).replace(" ", "_")) + .asBoolean()) { executeResult = (ResultContainer) declaredMethod.invoke(this); - if (executeResult.getResult().ordinal() > result.ordinal()) { //set bad result if its worse than the latest one. + if (executeResult.getResult().ordinal() + > result.ordinal()) { // set bad result if its worse than the latest one. result = executeResult.getResult(); } } else { @@ -260,22 +287,33 @@ public final class EnvironmentChecker { plugin.logger().warn("[STOP] {}: {}", envCheckEntry.name(), executeResult.getResultMessage()); Log.debug("[Stop-Freeze] " + envCheckEntry.name() + ": " + executeResult.getResultMessage()); } - //It's okay, QuickShop should continue executing checks to collect more data. - //And show user all errors at once. + // It's okay, QuickShop should continue executing checks to collect more data. + // And show user all errors at once. case DISABLE_PLUGIN -> { plugin.logger().warn("[FATAL] {}: {}", envCheckEntry.name(), executeResult.getResultMessage()); Log.debug("[Fatal-Disable] " + envCheckEntry.name() + ": " + executeResult.getResultMessage()); - skipAllTest = true; //We need to disable the plugin NOW! Some HUGE exception is happening here, hurry up! + skipAllTest = + true; // We need to disable the plugin NOW! Some HUGE exception is happening here, hurry + // up! } - default -> - plugin.logger().warn("[UNDEFINED] {}: {}", envCheckEntry.name(), executeResult.getResultMessage()); + default -> plugin.logger() + .warn("[UNDEFINED] {}: {}", envCheckEntry.name(), executeResult.getResultMessage()); } - results.put(envCheckEntry, Objects.requireNonNullElseGet(executeResult, () -> new ResultContainer(CheckResult.SKIPPED, "Startup flag mark this check should be skipped."))); - if (result.ordinal() > gResult.ordinal()) { //set bad result if its worse than the latest one. + results.put( + envCheckEntry, + Objects.requireNonNullElseGet( + executeResult, + () -> new ResultContainer( + CheckResult.SKIPPED, "Startup flag mark this check should be skipped."))); + if (result.ordinal() > gResult.ordinal()) { // set bad result if its worse than the latest one. gResult = result; } } catch (Exception e) { - plugin.logger().warn("Failed to execute EnvCheckEntry [{}]: Exception thrown out without getting caught. Something went wrong!", declaredMethod.getName(), e); + plugin.logger() + .warn( + "Failed to execute EnvCheckEntry [{}]: Exception thrown out without getting caught. Something went wrong!", + declaredMethod.getName(), + e); plugin.logger().warn("[FAIL] {}", declaredMethod.getName()); } } @@ -293,7 +331,8 @@ public final class EnvironmentChecker { @EnvCheckEntry(name = "Spigot Based Server Test", priority = 2) public ResultContainer spigotBasedServer() { ResultContainer success = new ResultContainer(CheckResult.PASSED, "Server"); - ResultContainer failed = new ResultContainer(CheckResult.STOP_WORKING, "Server must be Spigot based, Don't use CraftBukkit!"); + ResultContainer failed = + new ResultContainer(CheckResult.STOP_WORKING, "Server must be Spigot based, Don't use CraftBukkit!"); if (!PaperLib.isSpigot()) { return failed; } @@ -312,11 +351,15 @@ public final class EnvironmentChecker { } if (!gameVersion.isVirtualDisplaySupports()) { AbstractDisplayItem.setVirtualDisplayDoesntWork(true); - return new ResultContainer(CheckResult.WARNING, "Your server version are not supports Virtual DisplayItem, resetting to RealDisplayItem..."); + return new ResultContainer( + CheckResult.WARNING, + "Your server version are not supports Virtual DisplayItem, resetting to RealDisplayItem..."); } if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { AbstractDisplayItem.setVirtualDisplayDoesntWork(true); - return new ResultContainer(CheckResult.WARNING, "Plugin [ProtocolLib] not installed on your server, Virtual DisplayItem will not work, resetting to RealDisplayItem.."); + return new ResultContainer( + CheckResult.WARNING, + "Plugin [ProtocolLib] not installed on your server, Virtual DisplayItem will not work, resetting to RealDisplayItem.."); } return new ResultContainer(CheckResult.PASSED, "Passed checks"); @@ -326,14 +369,18 @@ public final class EnvironmentChecker { public ResultContainer virtualDisplayWorkingTest() { if (plugin.getVirtualDisplayItemManager() == null) { AbstractDisplayItem.setVirtualDisplayDoesntWork(true); - return new ResultContainer(CheckResult.WARNING, "VirtualDisplayItemManager is null, this shouldn't happen, contact with QuickShop-Hikari developer."); + return new ResultContainer( + CheckResult.WARNING, + "VirtualDisplayItemManager is null, this shouldn't happen, contact with QuickShop-Hikari developer."); } - Throwable testResult = plugin.getVirtualDisplayItemManager().getPacketFactory().testFakeItem(); + Throwable testResult = + plugin.getVirtualDisplayItemManager().getPacketFactory().testFakeItem(); if (testResult != null) { plugin.getVirtualDisplayItemManager().setTestPassed(false); AbstractDisplayItem.setVirtualDisplayDoesntWork(true); plugin.logger().warn("Failed to load the VirtualDisplayItem, self-test failure", testResult); - return new ResultContainer(CheckResult.WARNING, "VirtualDisplayItem test failed, resetting to RealDisplayItem..."); + return new ResultContainer( + CheckResult.WARNING, "VirtualDisplayItem test failed, resetting to RealDisplayItem..."); } return new ResultContainer(CheckResult.PASSED, "Passed checks"); } @@ -345,10 +392,14 @@ public final class EnvironmentChecker { } catch (ClassNotFoundException e) { return new ResultContainer(CheckResult.SKIPPED, "ProtocolLib not detected."); } - String stringClassLoader = ProtocolLibrary.getProtocolManager().getClass().getClassLoader().toString(); + String stringClassLoader = + ProtocolLibrary.getProtocolManager().getClass().getClassLoader().toString(); if (stringClassLoader.contains("pluginEnabled=true") && !stringClassLoader.contains("plugin=ProtocolLib")) { - plugin.logger().warn("Warning! ProtocolLib seems provided by another plugin, This seems to be a wrong packaging problem, " + - "QuickShop can't ensure the ProtocolLib is working correctly! Info: {}", stringClassLoader); + plugin.logger() + .warn( + "Warning! ProtocolLib seems provided by another plugin, This seems to be a wrong packaging problem, " + + "QuickShop can't ensure the ProtocolLib is working correctly! Info: {}", + stringClassLoader); return new ResultContainer(CheckResult.WARNING, "Incorrect locate: " + stringClassLoader); } return new ResultContainer(CheckResult.PASSED, stringClassLoader); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultContainer.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultContainer.java index 8a7578b48..f0f708fed 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultContainer.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultContainer.java @@ -24,4 +24,3 @@ public class ResultContainer { return resultMessage; } } - diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultReport.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultReport.java index 2754735c7..00b731546 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultReport.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/envcheck/ResultReport.java @@ -1,8 +1,7 @@ package com.ghostchu.quickshop.util.envcheck; -import lombok.Data; - import java.util.Map; +import lombok.Data; @Data public class ResultReport { diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/DatabaseStatusHolder.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/DatabaseStatusHolder.java index e1a320e56..c3057f3bc 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/DatabaseStatusHolder.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/DatabaseStatusHolder.java @@ -10,19 +10,16 @@ public class DatabaseStatusHolder { private IsolatedScanResult shopIds; private long reportGeneratedAt; - public DatabaseStatusHolder(Status status, IsolatedScanResult dataIds, IsolatedScanResult shopIds, long reportGeneratedAt) { + public DatabaseStatusHolder( + Status status, IsolatedScanResult dataIds, IsolatedScanResult shopIds, long reportGeneratedAt) { this.status = status; this.dataIds = dataIds; this.shopIds = shopIds; this.reportGeneratedAt = reportGeneratedAt; } - public enum Status { GOOD, MAINTENANCE_REQUIRED, } } - - - diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/QuickShopPreviewGUIHolder.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/QuickShopPreviewGUIHolder.java index 161fae8b4..3e9081436 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/QuickShopPreviewGUIHolder.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/QuickShopPreviewGUIHolder.java @@ -9,6 +9,4 @@ public class QuickShopPreviewGUIHolder implements InventoryHolder { public @NotNull Inventory getInventory() { return null; } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/Result.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/Result.java index e08163611..415788fa8 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/Result.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/holder/Result.java @@ -16,12 +16,10 @@ public class Result { } @Override - public void setMessage(String message) { - } + public void setMessage(String message) {} @Override - public void setResult(boolean result) { - } + public void setResult(boolean result) {} @Override public String getListener() { @@ -33,18 +31,19 @@ public class Result { return true; } }; + @Setter private boolean result = false; + @Setter @Getter private String message; + @Getter @Setter private String listener; - - public Result() { - } + public Result() {} public Result(String message) { result = false; diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logger/Log.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logger/Log.java index df5c7eab2..6a8133525 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logger/Log.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logger/Log.java @@ -5,6 +5,12 @@ import com.ghostchu.quickshop.common.util.QuickExecutor; import com.ghostchu.quickshop.common.util.Timer; import com.ghostchu.quickshop.util.Util; import com.google.common.collect.EvictingQueue; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.logging.Level; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -13,13 +19,6 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Level; - public class Log { private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock(); private static final int BUFFER_SIZE = 500 * Type.values().length; @@ -51,7 +50,6 @@ public class Log { } finally { LOCK.writeLock().unlock(); } - } private static void debugStdOutputs(Record recordEntry) { @@ -91,7 +89,6 @@ public class Log { debug(level, message, Caller.create()); } - public static void privacy(@NotNull String message) { privacy(Level.INFO, message, Caller.create()); } @@ -117,7 +114,6 @@ public class Log { privacy(level, message, Caller.create()); } - public static void performance(@NotNull Level level, @NotNull String message, @NotNull Caller caller) { LOCK.writeLock().lock(); try { @@ -143,7 +139,9 @@ public class Log { public static List fetchLogs(@NotNull Type type) { LOCK.readLock().lock(); try { - return LOGGER_BUFFER.stream().filter(recordEntry -> recordEntry.getType() == type).toList(); + return LOGGER_BUFFER.stream() + .filter(recordEntry -> recordEntry.getType() == type) + .toList(); } finally { LOCK.readLock().unlock(); } @@ -170,7 +168,9 @@ public class Log { public static List fetchLogsLevel(@NotNull Type type, @NotNull Level level) { LOCK.readLock().lock(); try { - return LOGGER_BUFFER.stream().filter(recordEntry -> recordEntry.getType() == type && recordEntry.getLevel() == level).toList(); + return LOGGER_BUFFER.stream() + .filter(recordEntry -> recordEntry.getType() == type && recordEntry.getLevel() == level) + .toList(); } finally { LOCK.readLock().unlock(); } @@ -195,7 +195,6 @@ public class Log { } finally { LOCK.writeLock().unlock(); } - } public static void permission(@NotNull Level level, @NotNull String message) { @@ -207,21 +206,23 @@ public class Log { } @ApiStatus.Internal - public static void timing(@NotNull Level level, @NotNull String operation, @NotNull Timer timer, @Nullable Caller caller) { + public static void timing( + @NotNull Level level, @NotNull String operation, @NotNull Timer timer, @Nullable Caller caller) { LOCK.writeLock().lock(); try { Record recordEntry; if (DISABLE_LOCATION_RECORDING) { - recordEntry = new Record(level, Type.TIMING, operation + " (cost " + timer.getPassedTime() + " ms)", null); + recordEntry = + new Record(level, Type.TIMING, operation + " (cost " + timer.getPassedTime() + " ms)", null); } else { - recordEntry = new Record(level, Type.TIMING, operation + " (cost " + timer.getPassedTime() + " ms)", caller); + recordEntry = + new Record(level, Type.TIMING, operation + " (cost " + timer.getPassedTime() + " ms)", caller); } LOGGER_BUFFER.offer(recordEntry); debugStdOutputs(recordEntry); } finally { LOCK.writeLock().unlock(); } - } public static void transaction(@NotNull String message) { @@ -263,12 +264,16 @@ public class Log { @EqualsAndHashCode public static class Record { private final long timestamp = System.currentTimeMillis(); + @NotNull private final Level level; + @NotNull private final Type type; + @NotNull private final String message; + @Nullable private final Caller caller; @@ -280,28 +285,35 @@ public class Log { } public CompletableFuture generate() { - return CompletableFuture.supplyAsync(() -> { - StringBuilder sb = new StringBuilder(); - Log.Caller caller; - if (this.caller == null) { - caller = new Caller("", "", "", -1); - } else { - caller = this.caller; - } - String simpleClassName = caller.getClassName().substring(caller.getClassName().lastIndexOf('.') + 1); - sb.append("["); - sb.append(caller.getThreadName()); - sb.append("/"); - sb.append(this.getLevel().getName()); - sb.append("]"); - sb.append(" "); - sb.append("("); - sb.append(simpleClassName).append("#").append(caller.getMethodName()).append(":").append(caller.getLineNumber()); - sb.append(")"); - sb.append(" "); - sb.append(this.getMessage()); - return sb.toString(); - }, QuickExecutor.getCommonExecutor()); + return CompletableFuture.supplyAsync( + () -> { + StringBuilder sb = new StringBuilder(); + Log.Caller caller; + if (this.caller == null) { + caller = new Caller("", "", "", -1); + } else { + caller = this.caller; + } + String simpleClassName = caller.getClassName() + .substring(caller.getClassName().lastIndexOf('.') + 1); + sb.append("["); + sb.append(caller.getThreadName()); + sb.append("/"); + sb.append(this.getLevel().getName()); + sb.append("]"); + sb.append(" "); + sb.append("("); + sb.append(simpleClassName) + .append("#") + .append(caller.getMethodName()) + .append(":") + .append(caller.getLineNumber()); + sb.append(")"); + sb.append(" "); + sb.append(this.getMessage()); + return sb.toString(); + }, + QuickExecutor.getCommonExecutor()); } @Override @@ -311,16 +323,20 @@ public class Log { } @Data - public final static class Caller { + public static final class Caller { @NotNull private final String threadName; + @NotNull private final String className; + @NotNull private final String methodName; + private final int lineNumber; - public Caller(@NotNull String threadName, @NotNull String className, @NotNull String methodName, int lineNumber) { + public Caller( + @NotNull String threadName, @NotNull String className, @NotNull String methodName, int lineNumber) { this.threadName = threadName; this.className = className; this.methodName = methodName; @@ -349,16 +365,16 @@ public class Log { return new Caller("", "", "", -1); } } - return STACK_WALKER.walk(stream -> stream.skip(steps).findFirst() - .map(frame -> { - String threadName = Thread.currentThread().getName(); - String className = frame.getClassName(); - String methodName = frame.getMethodName(); - int codeLine = frame.getLineNumber(); - return new Caller(threadName, className, methodName, codeLine); - }) - .orElseGet(() -> new Caller("", "", "", -1))); + return STACK_WALKER.walk(stream -> stream.skip(steps) + .findFirst() + .map(frame -> { + String threadName = Thread.currentThread().getName(); + String className = frame.getClassName(); + String methodName = frame.getMethodName(); + int codeLine = frame.getLineNumber(); + return new Caller(threadName, className, methodName, codeLine); + }) + .orElseGet(() -> new Caller("", "", "", -1))); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/EconomyTransactionLog.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/EconomyTransactionLog.java index 21bea2a05..50854dfb6 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/EconomyTransactionLog.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/EconomyTransactionLog.java @@ -15,7 +15,15 @@ public class EconomyTransactionLog { private double amount; private String lastError; - public EconomyTransactionLog(boolean success, QUser from, QUser to, String currency, double tax, QUser taxAccount, double amount, String lastError) { + public EconomyTransactionLog( + boolean success, + QUser from, + QUser to, + String currency, + double tax, + QUser taxAccount, + double amount, + String lastError) { this.success = success; this.from = from.serialize(); this.to = to.serialize(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/ShopPurchaseLog.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/ShopPurchaseLog.java index 4eaeb19bf..f10ea2bc1 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/ShopPurchaseLog.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/logging/container/ShopPurchaseLog.java @@ -17,7 +17,15 @@ public class ShopPurchaseLog { private double balance; private double tax; - public ShopPurchaseLog(ShopInfoStorage shop, ShopType type, QUser trader, String itemName, String itemStack, int amount, double balance, double tax) { + public ShopPurchaseLog( + ShopInfoStorage shop, + ShopType type, + QUser trader, + String itemName, + String itemStack, + int amount, + double balance, + double tax) { this.shop = shop; this.type = type; this.trader = trader.serialize(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/matcher/item/QuickShopItemMatcherImpl.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/matcher/item/QuickShopItemMatcherImpl.java index 16e1b0ecd..efb16f6eb 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/matcher/item/QuickShopItemMatcherImpl.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/matcher/item/QuickShopItemMatcherImpl.java @@ -7,6 +7,7 @@ import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; +import java.util.*; import org.bukkit.OfflinePlayer; import org.bukkit.attribute.Attribute; import org.bukkit.block.ShulkerBox; @@ -19,8 +20,6 @@ import org.bukkit.potion.PotionData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { private final QuickShop plugin; @@ -28,7 +27,6 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { private int workType; - public QuickShopItemMatcherImpl(@NotNull QuickShop plugin) { this.plugin = plugin; plugin.getReloadManager().register(this); @@ -86,10 +84,12 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { if (requireStack.length != givenStack.length) { return false; } - //For performance, we just check really equals in each index,check isn't contain or match will cost n^n time in most + // For performance, we just check really equals in each index,check isn't contain or match will cost n^n time in + // most for (int i = 0; i < requireStack.length; i++) { - if ((requireStack[i] != null) && (givenStack[i] != null) && - (requireStack[i].getAmount() != givenStack[i].getAmount())) { + if ((requireStack[i] != null) + && (givenStack[i] != null) + && (requireStack[i].getAmount() != givenStack[i].getAmount())) { Log.debug("Fail: Amount mismatch!"); return false; } @@ -118,19 +118,19 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { } if (requireStack == null || givenStack == null) { - Log.debug( - "Match failed: A stack is null: " - + "requireStack[" - + requireStack - + "] givenStack[" - + givenStack - + "]"); + Log.debug("Match failed: A stack is null: " + + "requireStack[" + + requireStack + + "] givenStack[" + + givenStack + + "]"); return false; // One of them is null (Can't be both, see above) } String shopIdOrigin = plugin.getPlatform().getItemShopId(requireStack); if (shopIdOrigin != null) { - Log.debug("ShopId compare -> Origin: " + shopIdOrigin + " Given: " + plugin.getPlatform().getItemShopId(givenStack)); + Log.debug("ShopId compare -> Origin: " + shopIdOrigin + " Given: " + + plugin.getPlatform().getItemShopId(givenStack)); String shopIdTester = plugin.getPlatform().getItemShopId(givenStack); if (shopIdOrigin.equals(shopIdTester)) { return true; @@ -182,7 +182,8 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { private final List matcherList = new ArrayList<>(); - public ItemMetaMatcher(@NotNull ConfigurationSection itemMatcherConfig, @NotNull QuickShopItemMatcherImpl itemMatcher) { + public ItemMetaMatcher( + @NotNull ConfigurationSection itemMatcherConfig, @NotNull QuickShopItemMatcherImpl itemMatcher) { QuickShop plugin = QuickShop.getInstance(); addIfEnable(itemMatcherConfig, "damage", (meta1, meta2) -> { if (meta1 instanceof Damageable != meta2 instanceof Damageable) { @@ -190,15 +191,15 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { } if (meta1 instanceof Damageable damage1) { Damageable damage2 = (Damageable) meta2; - //Given item damaged but matching item doesn't, allow it + // Given item damaged but matching item doesn't, allow it if (damage1.hasDamage() && !damage2.hasDamage()) { return true; } - //Given item NOT damaged but matching item damaged, denied it + // Given item NOT damaged but matching item damaged, denied it if (!damage1.hasDamage() && damage2.hasDamage()) { return false; } - //last condition: Check them damages, if givenDamage >= requireDamage, allow it. + // last condition: Check them damages, if givenDamage >= requireDamage, allow it. return damage2.getDamage() <= damage1.getDamage(); } return true; @@ -211,22 +212,33 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { Repairable repairable2 = (Repairable) meta2; boolean hasRepairCost1 = repairable1.hasRepairCost(); boolean hasRepairCost2 = repairable2.hasRepairCost(); - //Given item have repair cost but matching item doesn't, allow it + // Given item have repair cost but matching item doesn't, allow it if (hasRepairCost1 && !hasRepairCost2) { return true; } - //Given item DOESN'T have repair cost but matching item have, denied it + // Given item DOESN'T have repair cost but matching item have, denied it if (!hasRepairCost1 && hasRepairCost2) { return false; } - //last condition: both having repair cost, so allow items lesser than or equals given item Repair Cost + // last condition: both having repair cost, so allow items lesser than or equals given item Repair + // Cost return repairable2.getRepairCost() <= repairable1.getRepairCost(); } return true; }); - addIfEnable(itemMatcherConfig, "displayname", ((meta1, meta2) -> Objects.equals(plugin.getPlatform().getDisplayName(meta1), plugin.getPlatform().getDisplayName(meta2)))); + addIfEnable( + itemMatcherConfig, + "displayname", + ((meta1, meta2) -> Objects.equals( + plugin.getPlatform().getDisplayName(meta1), + plugin.getPlatform().getDisplayName(meta2)))); // We didn't touch the loresMatches because many plugin use this check item. - addIfEnable(itemMatcherConfig, "lores", ((meta1, meta2) -> Objects.equals(plugin.getPlatform().getLore(meta1), plugin.getPlatform().getLore(meta2)))); + addIfEnable( + itemMatcherConfig, + "lores", + ((meta1, meta2) -> Objects.equals( + plugin.getPlatform().getLore(meta1), + plugin.getPlatform().getLore(meta2)))); addIfEnable(itemMatcherConfig, "enchs", ((meta1, meta2) -> { if (meta1.hasEnchants() != meta2.hasEnchants()) { return false; @@ -262,7 +274,10 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { if (potion1.hasCustomEffects() != potion2.hasCustomEffects()) { return false; } - if (potion1.hasCustomEffects() && !Arrays.deepEquals(potion1.getCustomEffects().toArray(), potion2.getCustomEffects().toArray())) { + if (potion1.hasCustomEffects() + && !Arrays.deepEquals( + potion1.getCustomEffects().toArray(), + potion2.getCustomEffects().toArray())) { return false; } PotionData data1 = potion1.getBasePotionData(); @@ -285,19 +300,27 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { return false; } if (meta1.hasAttributeModifiers() && meta2.hasAttributeModifiers()) { - Set set1 = Objects.requireNonNull(meta1.getAttributeModifiers()).keySet(); - Set set2 = Objects.requireNonNull(meta2.getAttributeModifiers()).keySet(); + Set set1 = Objects.requireNonNull(meta1.getAttributeModifiers()) + .keySet(); + Set set2 = Objects.requireNonNull(meta2.getAttributeModifiers()) + .keySet(); for (Attribute att : set1) { if (!set2.contains(att)) { return false; - } else if (!meta1.getAttributeModifiers().get(att).equals(meta2.getAttributeModifiers().get(att))) { + } else if (!meta1.getAttributeModifiers() + .get(att) + .equals(meta2.getAttributeModifiers().get(att))) { return false; } } } return true; }); - addIfEnable(itemMatcherConfig, "itemflags", ((meta1, meta2) -> Arrays.deepEquals(meta1.getItemFlags().toArray(), meta2.getItemFlags().toArray()))); + addIfEnable( + itemMatcherConfig, + "itemflags", + ((meta1, meta2) -> Arrays.deepEquals( + meta1.getItemFlags().toArray(), meta2.getItemFlags().toArray()))); addIfEnable(itemMatcherConfig, "books", ((meta1, meta2) -> { if (meta1 instanceof BookMeta != meta2 instanceof BookMeta) { return false; @@ -347,8 +370,8 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { return false; } if (meta1 instanceof SkullMeta skullMeta1) { - //getOwningPlayer will let server query playerProfile in server thread - //Causing huge lag, so using String instead + // getOwningPlayer will let server query playerProfile in server thread + // Causing huge lag, so using String instead OfflinePlayer player1 = skullMeta1.getOwningPlayer(); OfflinePlayer player2 = skullMeta1.getOwningPlayer(); return Objects.equals(player1, player2); @@ -360,8 +383,8 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { return false; } if (meta1 instanceof BundleMeta bundleMeta1) { - //getOwningPlayer will let server query playerProfile in server thread - //Causing huge lag, so using String instead + // getOwningPlayer will let server query playerProfile in server thread + // Causing huge lag, so using String instead BundleMeta bundleMeta2 = (BundleMeta) meta2; if (bundleMeta1.hasItems() != bundleMeta2.hasItems()) { return false; @@ -381,19 +404,25 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { if (mapMeta1.hasMapView() != mapMeta2.hasMapView()) { return false; } - if (mapMeta1.hasMapView() && mapMeta2.hasMapView() && !Objects.equals(mapMeta1.getMapView(), mapMeta2.getMapView())) { + if (mapMeta1.hasMapView() + && mapMeta2.hasMapView() + && !Objects.equals(mapMeta1.getMapView(), mapMeta2.getMapView())) { return false; } if (mapMeta1.hasColor() != mapMeta2.hasColor()) { return false; } - if (mapMeta1.hasColor() && mapMeta2.hasColor() && !Objects.equals(mapMeta1.getColor(), mapMeta2.getColor())) { + if (mapMeta1.hasColor() + && mapMeta2.hasColor() + && !Objects.equals(mapMeta1.getColor(), mapMeta2.getColor())) { return false; } if (mapMeta1.hasLocationName() != mapMeta2.hasLocationName()) { return false; } - return !mapMeta1.hasLocationName() || !mapMeta2.hasLocationName() || Objects.equals(mapMeta1.getLocationName(), mapMeta2.getLocationName()); + return !mapMeta1.hasLocationName() + || !mapMeta2.hasLocationName() + || Objects.equals(mapMeta1.getLocationName(), mapMeta2.getLocationName()); } return true; }); @@ -433,22 +462,27 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { } return !fishBucketMeta1.hasVariant() || (fishBucketMeta1.getPattern() == fishBucketMeta2.getPattern() - && fishBucketMeta1.getBodyColor().equals(fishBucketMeta2.getBodyColor()) - && fishBucketMeta1.getPatternColor().equals(fishBucketMeta2.getPatternColor())); + && fishBucketMeta1.getBodyColor().equals(fishBucketMeta2.getBodyColor()) + && fishBucketMeta1.getPatternColor().equals(fishBucketMeta2.getPatternColor())); } return true; }); addIfEnable(itemMatcherConfig, "shulkerBox", ((meta1, meta2) -> { - //https://www.spigotmc.org/threads/getting-the-inventory-of-a-shulker-box-itemstack.212369 + // https://www.spigotmc.org/threads/getting-the-inventory-of-a-shulker-box-itemstack.212369 if ((meta1 instanceof BlockStateMeta) != (meta2 instanceof BlockStateMeta)) { return false; } if (meta1 instanceof BlockStateMeta blockStateMeta1) { - if ((blockStateMeta1.getBlockState() instanceof ShulkerBox) != ((BlockStateMeta) meta2).getBlockState() instanceof ShulkerBox) { + if ((blockStateMeta1.getBlockState() instanceof ShulkerBox) + != ((BlockStateMeta) meta2).getBlockState() instanceof ShulkerBox) { return false; } if (((BlockStateMeta) meta1).getBlockState() instanceof ShulkerBox shulkerBox1) { - return itemMatcher.matches(shulkerBox1.getInventory().getContents(), ((ShulkerBox) ((BlockStateMeta) meta2).getBlockState()).getInventory().getContents()); + return itemMatcher.matches( + shulkerBox1.getInventory().getContents(), + ((ShulkerBox) ((BlockStateMeta) meta2).getBlockState()) + .getInventory() + .getContents()); } } return true; @@ -472,7 +506,8 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { return false; } if (stewMeta1.hasCustomEffects()) { - return CommonUtil.listDisorderMatches(stewMeta1.getCustomEffects(), stewMeta2.getCustomEffects()); + return CommonUtil.listDisorderMatches( + stewMeta1.getCustomEffects(), stewMeta2.getCustomEffects()); } } return true; @@ -491,7 +526,7 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { } ItemMeta meta1 = requireStack.getItemMeta(); ItemMeta meta2 = givenStack.getItemMeta(); - //If givenStack don't have meta, try to generate one + // If givenStack don't have meta, try to generate one if (meta1 != null && meta2 != null) { for (Matcher matcher : matcherList) { boolean result = matcher.match(meta1, meta2); @@ -518,7 +553,5 @@ public class QuickShopItemMatcherImpl implements ItemMatcher, Reloadable { */ boolean match(ItemMeta meta1, ItemMeta meta2); } - - } -} \ No newline at end of file +} diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/MetricManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/MetricManager.java index 54307c5b4..ecdf69d2b 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/MetricManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/MetricManager.java @@ -3,13 +3,12 @@ package com.ghostchu.quickshop.util.metric; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.metric.collect.BuiltInCollects; +import java.lang.reflect.Method; +import java.util.Locale; import org.bstats.bukkit.Metrics; import org.bstats.charts.CustomChart; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.Method; -import java.util.Locale; - public class MetricManager { private final QuickShop plugin; private final Metrics metrics; @@ -24,7 +23,13 @@ public class MetricManager { if (chart == null) { return; // ignore } - plugin.getPrivacyController().privacyReview(dataType, moduleName.replace(" ", "_").replace("-", "_").toUpperCase(Locale.ROOT), reason, () -> this.metrics.addCustomChart(chart), () -> Log.debug("Blocked chart register: failed privacy reviewing.")); + plugin.getPrivacyController() + .privacyReview( + dataType, + moduleName.replace(" ", "_").replace("-", "_").toUpperCase(Locale.ROOT), + reason, + () -> this.metrics.addCustomChart(chart), + () -> Log.debug("Blocked chart register: failed privacy reviewing.")); } public void initCollects() { @@ -44,7 +49,10 @@ public class MetricManager { try { Object result = method.invoke(object, (Object[]) null); if (result != null) { - registerChart(collectEntry.dataType(), collectEntry.moduleName(), collectEntry.description(), + registerChart( + collectEntry.dataType(), + collectEntry.moduleName(), + collectEntry.description(), (CustomChart) result); Log.debug("Registered metrics collector: " + collectEntry.moduleName()); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/collect/BuiltInCollects.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/collect/BuiltInCollects.java index 3b52fdafd..ded4ad5b3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/collect/BuiltInCollects.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/metric/collect/BuiltInCollects.java @@ -5,32 +5,36 @@ import com.ghostchu.quickshop.shop.display.AbstractDisplayItem; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.metric.MetricCollectEntry; import com.ghostchu.quickshop.util.metric.MetricDataType; -import org.bstats.charts.*; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.HashMap; import java.util.Map; import java.util.StringJoiner; +import org.bstats.charts.*; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; -public class BuiltInCollects {//Statistic +public class BuiltInCollects { // Statistic private final QuickShop plugin; public BuiltInCollects(QuickShop plugin) { this.plugin = plugin; } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Research - Addons or Compacts Discovered", description = "QuickShop collects the QuickShop's addons/compacts (including 3rd-party) list that installed on your server to discover new addons/compacts so we can contact authors when we have major API changes, or use for improve exists official addons/compacts who have most of users using.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Research - Addons or Compacts Discovered", + description = + "QuickShop collects the QuickShop's addons/compacts (including 3rd-party) list that installed on your server to discover new addons/compacts so we can contact authors when we have major API changes, or use for improve exists official addons/compacts who have most of users using.") public CustomChart researchAddonsCompacts() { return new AdvancedPie("research_addons_or_compacts_discovered", () -> { String myName = plugin.getJavaPlugin().getDescription().getName(); Map data = new HashMap<>(); for (Plugin discoverPlugin : Bukkit.getPluginManager().getPlugins()) { PluginDescriptionFile descriptionFile = discoverPlugin.getDescription(); - if (descriptionFile.getDepend().contains(myName) || descriptionFile.getSoftDepend().contains(myName)) { + if (descriptionFile.getDepend().contains(myName) + || descriptionFile.getSoftDepend().contains(myName)) { data.put(descriptionFile.getName(), 1); } } @@ -41,21 +45,34 @@ public class BuiltInCollects {//Statistic }); } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Research - Item Stacking Shop", description = "We collect this for determine if we should push Item Stacking Shop to a feature that default enabled.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Research - Item Stacking Shop", + description = + "We collect this for determine if we should push Item Stacking Shop to a feature that default enabled.") public CustomChart researchItemStackingShop() { return new SimplePie("research_item_stacking_shop", () -> String.valueOf(plugin.isAllowStack())); } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Research - Protection Listener Blacklist", description = "We collect this for determine if we should add common listener blacklist entry to default configuration.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Research - Protection Listener Blacklist", + description = + "We collect this for determine if we should add common listener blacklist entry to default configuration.") public CustomChart researchProtectionListenerBlacklist() { return new AdvancedPie("research_protection_checker_blacklist", () -> { Map data = new HashMap<>(); - plugin.getConfig().getStringList("shop.protection-checking-listener-blacklist").forEach(s -> data.put(s, 1)); + plugin.getConfig() + .getStringList("shop.protection-checking-listener-blacklist") + .forEach(s -> data.put(s, 1)); return data; }); } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Research - Command Alias", description = "We collect this for determine if we should add/remove alias to default configuration.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Research - Command Alias", + description = "We collect this for determine if we should add/remove alias to default configuration.") public CustomChart researchCommandAlias() { return new AdvancedPie("research_command_alias", () -> { Map data = new HashMap<>(); @@ -64,59 +81,93 @@ public class BuiltInCollects {//Statistic }); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Database Types", description = "We collect this so we can know the percent of different database types users.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Database Types", + description = "We collect this so we can know the percent of different database types users.") public CustomChart statisticDatabaseTypes() { - return new SimplePie("statistic_database_types", () -> plugin.getDatabaseDriverType().name()); + return new SimplePie( + "statistic_database_types", () -> plugin.getDatabaseDriverType().name()); } - - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Database Product", description = "We collect this so we can know the database vendor that users using, and provide dedicated driver if possible.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Database Product", + description = + "We collect this so we can know the database vendor that users using, and provide dedicated driver if possible.") public CustomChart statisticDatabaseProject() { return new SimplePie("statistic_database_product", () -> { try (Connection connection = plugin.getSqlManager().getConnection()) { DatabaseMetaData metaData = connection.getMetaData(); return metaData.getDatabaseProductName(); } catch (Throwable throwable) { - Log.debug("Populate statistic database version failed: " + throwable.getClass().getName() + ": " + throwable.getMessage()); + Log.debug("Populate statistic database version failed: " + + throwable.getClass().getName() + ": " + throwable.getMessage()); return "Error"; } }); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Database Version", description = "We collect this so we can know the database versions that users using, and provide/update dedicated driver or drop the support for too old database versions.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Database Version", + description = + "We collect this so we can know the database versions that users using, and provide/update dedicated driver or drop the support for too old database versions.") public CustomChart statisticDatabaseVersion() { return new SimplePie("statistic_database_version", () -> { try (Connection connection = plugin.getSqlManager().getConnection()) { DatabaseMetaData metaData = connection.getMetaData(); return metaData.getDatabaseProductName() + "@" + metaData.getDatabaseProductVersion(); } catch (Throwable throwable) { - Log.debug("Populate statistic database version failed: " + throwable.getClass().getName() + ": " + throwable.getMessage()); + Log.debug("Populate statistic database version failed: " + + throwable.getClass().getName() + ": " + throwable.getMessage()); return "Error"; } }); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Economy Types", description = "We collect this so we can know the percent of different economy types users.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Economy Types", + description = "We collect this so we can know the percent of different economy types users.") public CustomChart statisticEconomyTypes() { - return new SimplePie("statistic_economy_types", () -> plugin.getEconomy().getName()); + return new SimplePie( + "statistic_economy_types", () -> plugin.getEconomy().getName()); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - ItemMatcher", description = "We collect this so we can know the item matcher that users using, and improve it.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - ItemMatcher", + description = "We collect this so we can know the item matcher that users using, and improve it.") public CustomChart statisticItemMatcher() { - return new SimplePie("statistic_item_matcher", () -> plugin.getItemMatcher().getName()); + return new SimplePie( + "statistic_item_matcher", () -> plugin.getItemMatcher().getName()); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - DisplayImpl", description = "We collect this so we can know the which one item display impl most using, and improve it.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - DisplayImpl", + description = "We collect this so we can know the which one item display impl most using, and improve it.") public CustomChart statisticDisplayImpl() { - return new SimplePie("statistic_displayimpl", () -> AbstractDisplayItem.getNowUsing().name()); + return new SimplePie( + "statistic_displayimpl", () -> AbstractDisplayItem.getNowUsing().name()); } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Statistic - All shops hosting across all servers", description = "How many shops we can power across all servers? This research will used for performance tweak for components like shop managing/looking up/caching size etc.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Statistic - All shops hosting across all servers", + description = + "How many shops we can power across all servers? This research will used for performance tweak for components like shop managing/looking up/caching size etc.") public CustomChart statisticAllShops() { - return new SingleLineChart("statistic_all_shops_hosting_across_all_servers", () -> plugin.getShopManager().getAllShops().size()); + return new SingleLineChart( + "statistic_all_shops_hosting_across_all_servers", + () -> plugin.getShopManager().getAllShops().size()); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Background Debug Logger", description = "We collect this so we can know the which one item display impl most using, and improve it.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Background Debug Logger", + description = "We collect this so we can know the which one item display impl most using, and improve it.") public CustomChart statisticBackgroundDebugLogger() { return new SimplePie("statistic_background_debug_logger", () -> { if (plugin.getConfig().getBoolean("debug.disable-debuglogger")) { @@ -127,7 +178,11 @@ public class BuiltInCollects {//Statistic }); } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Research - ProtocolLib Version", description = "We collect this so we can know the which one ProtocolLib is popular. ProtocolLib sometimes releases destructive updates, so we collect this metric to know the distribution of ProtocolLib versions among users and remove unused ProtocolLib workaround code to improve code maintainability and program performance.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Research - ProtocolLib Version", + description = + "We collect this so we can know the which one ProtocolLib is popular. ProtocolLib sometimes releases destructive updates, so we collect this metric to know the distribution of ProtocolLib versions among users and remove unused ProtocolLib workaround code to improve code maintainability and program performance.") public CustomChart researchProtocolLibVersion() { return new SimplePie("research_protocollib_version", () -> { Plugin protocolLib = Bukkit.getPluginManager().getPlugin("ProtocolLib"); @@ -138,7 +193,11 @@ public class BuiltInCollects {//Statistic }); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Server Software Build Version", description = "Spigot and Paper always release updates during their version support cycles. Counting the server-side software versions used by users lets us know which builds are popular. And it allows us to be more aggressive with newly added APIs, This can improve code maintainability, stability and program performance.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Server Software Build Version", + description = + "Spigot and Paper always release updates during their version support cycles. Counting the server-side software versions used by users lets us know which builds are popular. And it allows us to be more aggressive with newly added APIs, This can improve code maintainability, stability and program performance.") public CustomChart statisticServerSoftwareBuildVersion() { return new DrilldownPie("statistic_server_software_build_version", () -> { Map> map = new HashMap<>(); @@ -149,12 +208,22 @@ public class BuiltInCollects {//Statistic }); } - @MetricCollectEntry(dataType = MetricDataType.STATISTIC, moduleName = "Statistic - Publisher", description = "We count the name of the publisher (in BuildInfo) so that we know if someone else is recompiling our plugin without changing the fork name. if you are a QuickShop-Hikari fork developer, please change the return value of your getFork() to something else in order to separate it from the stats. This value is usually fixed to Ghost-chu@Hikari.") + @MetricCollectEntry( + dataType = MetricDataType.STATISTIC, + moduleName = "Statistic - Publisher", + description = + "We count the name of the publisher (in BuildInfo) so that we know if someone else is recompiling our plugin without changing the fork name. if you are a QuickShop-Hikari fork developer, please change the return value of your getFork() to something else in order to separate it from the stats. This value is usually fixed to Ghost-chu@Hikari.") public CustomChart statisticPublisher() { - return new SimplePie("statistic_publisher", () -> plugin.getBuildInfo().getGitInfo().getCommitUsername() + "@" + plugin.getFork()); + return new SimplePie( + "statistic_publisher", + () -> plugin.getBuildInfo().getGitInfo().getCommitUsername() + "@" + plugin.getFork()); } - @MetricCollectEntry(dataType = MetricDataType.RESEARCH, moduleName = "Research - Geyser", description = "We've released the Suspension Closure expansion for Geyser, but we're ultimately undecided about a Geyser-specific update. The data collected from this study allows us to analyze the QuickShop-Hikari user base to check if Geyser or Floodgate is installed, and with the percentage of users who have the statistics, we will decide whether to add support for Geyser GUIs and the like. We also welcome your feedback on our Discord server.") + @MetricCollectEntry( + dataType = MetricDataType.RESEARCH, + moduleName = "Research - Geyser", + description = + "We've released the Suspension Closure expansion for Geyser, but we're ultimately undecided about a Geyser-specific update. The data collected from this study allows us to analyze the QuickShop-Hikari user base to check if Geyser or Floodgate is installed, and with the percentage of users who have the statistics, we will decide whether to add support for Geyser GUIs and the like. We also welcome your feedback on our Discord server.") public CustomChart researchGeyser() { return new SimplePie("research_geyser", () -> { StringJoiner joiner = new StringJoiner("+"); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/mojangapi/MojangAPI.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/mojangapi/MojangAPI.java index be2e9df0a..d2babd0a3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/mojangapi/MojangAPI.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/mojangapi/MojangAPI.java @@ -7,16 +7,15 @@ import com.google.common.cache.CacheBuilder; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import lombok.Data; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - public class MojangAPI { private final MojangApiMirror mirror; @@ -24,7 +23,6 @@ public class MojangAPI { this.mirror = mirror; } - @NotNull public AssetsAPI getAssetsAPI(@NotNull String serverVersion) { return new AssetsAPI(mirror, serverVersion); @@ -44,7 +42,6 @@ public class MojangAPI { return new ResourcesAPI(mirror); } - @Data public static class AssetsFileData { private String content; @@ -60,9 +57,8 @@ public class MojangAPI { @Data public static class ResourcesAPI { - protected final Cache requestCachePool = CacheBuilder.newBuilder() - .expireAfterWrite(7, TimeUnit.DAYS) - .build(); + protected final Cache requestCachePool = + CacheBuilder.newBuilder().expireAfterWrite(7, TimeUnit.DAYS).build(); private final MojangApiMirror apiMirror; public ResourcesAPI(MojangApiMirror mirror) { @@ -79,7 +75,6 @@ public class MojangAPI { } } - public static class AssetsAPI { private final MetaAPI metaAPI; @@ -120,15 +115,12 @@ public class MojangAPI { public boolean isAvailable() { return this.metaAPI.get().isPresent(); } - - } @Data public static class GameInfoAPI { - protected final Cache requestCachePool = CacheBuilder.newBuilder() - .expireAfterWrite(7, TimeUnit.DAYS) - .build(); + protected final Cache requestCachePool = + CacheBuilder.newBuilder().expireAfterWrite(7, TimeUnit.DAYS).build(); private final String json; private final Gson gson = JsonUtil.getGson(); @@ -145,6 +137,7 @@ public class MojangAPI { static class DataBean { @Nullable private AssetIndexBean assetIndex; + @Nullable private String assets; @@ -159,15 +152,14 @@ public class MojangAPI { */ @Nullable private String id; + @Nullable private String sha1; + @Nullable private String url; } - } - - } public static class MetaAPI { @@ -203,9 +195,11 @@ public class MojangAPI { for (JsonElement gameVersionData : availableVersions.getAsJsonArray()) { if (gameVersionData.isJsonObject()) { JsonElement gameId = gameVersionData.getAsJsonObject().get("id"); - JsonElement gameIndexUrl = gameVersionData.getAsJsonObject().get("url"); + JsonElement gameIndexUrl = + gameVersionData.getAsJsonObject().get("url"); if (Objects.equals(gameId.getAsString(), version)) { - HttpResponse response1 = Unirest.get(gameIndexUrl.getAsString()).asString(); + HttpResponse response1 = + Unirest.get(gameIndexUrl.getAsString()).asString(); if (!response1.isSuccess()) { return Optional.empty(); } @@ -219,6 +213,4 @@ public class MojangAPI { } } } - - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/GuavaCacheRender.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/GuavaCacheRender.java index 0a41ea8fe..0e016030c 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/GuavaCacheRender.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/GuavaCacheRender.java @@ -2,9 +2,8 @@ package com.ghostchu.quickshop.util.paste; import com.ghostchu.quickshop.util.paste.util.HTMLTable; import com.google.common.cache.CacheStats; -import org.jetbrains.annotations.NotNull; - import java.text.NumberFormat; +import org.jetbrains.annotations.NotNull; public class GuavaCacheRender { @NotNull @@ -33,5 +32,4 @@ public class GuavaCacheRender { private static String toPercentage(double n) { return String.format("%.000f", n * 100) + "%"; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/HelpChatPastebinPaster.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/HelpChatPastebinPaster.java index f15a79fbd..4b0aa0c12 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/HelpChatPastebinPaster.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/HelpChatPastebinPaster.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is a part of project QuickShop, the name is HelpChatPastebinPaster.java // * Copyright (C) Ghost_chu and contributors // * @@ -17,24 +17,24 @@ // * // */ // -//package com.ghostchu.quickshop.util.paste; +// package com.ghostchu.quickshop.util.paste; // -//import com.ghostchu.quickshop.common.util.JsonUtil; -//import kong.unirest.HttpResponse; -//import kong.unirest.Unirest; -//import lombok.AllArgsConstructor; -//import lombok.Data; -//import lombok.NoArgsConstructor; -//import org.jetbrains.annotations.NotNull; +// import com.ghostchu.quickshop.common.util.JsonUtil; +// import kong.unirest.HttpResponse; +// import kong.unirest.Unirest; +// import lombok.AllArgsConstructor; +// import lombok.Data; +// import lombok.NoArgsConstructor; +// import org.jetbrains.annotations.NotNull; // -//import java.io.IOException; +// import java.io.IOException; // -///** +/// ** // * Paste the paste through https://paste.helpch.at/ // * // * @author Ghost_chu // */ -//public class HelpChatPastebinPaster implements PasteInterface { +// public class HelpChatPastebinPaster implements PasteInterface { // @Override // @NotNull // public String pasteTheText(@NotNull String text) throws IOException { @@ -76,5 +76,5 @@ // private final String _paster = "QuickShop"; // private String data; // } -//} +// } // diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/LuckoPastebinPaster.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/LuckoPastebinPaster.java index eafa204c4..472399121 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/LuckoPastebinPaster.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/LuckoPastebinPaster.java @@ -1,14 +1,13 @@ package com.ghostchu.quickshop.util.paste; import com.ghostchu.quickshop.common.util.JsonUtil; +import java.io.IOException; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import lombok.Data; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; -import java.io.IOException; - /** * Paste the paste through https://bytebin.lucko.me/post * Website Author: Lucko (https://github.com/lucko) @@ -19,9 +18,8 @@ public class LuckoPastebinPaster implements PasteInterface { @Override @NotNull public String pasteTheText(@NotNull String text) throws IOException { - HttpResponse response = Unirest.post("https://bytebin.lucko.me/post") - .body(text) - .asString(); + HttpResponse response = + Unirest.post("https://bytebin.lucko.me/post").body(text).asString(); if (response.isSuccess()) { String json = response.getBody(); Response req = JsonUtil.getGson().fromJson(json, Response.class); @@ -29,7 +27,6 @@ public class LuckoPastebinPaster implements PasteInterface { } else { throw new IOException(response.getStatus() + " " + response.getStatusText() + ": " + response.getBody()); } - } @Override @@ -62,4 +59,3 @@ public class LuckoPastebinPaster implements PasteInterface { } } } - diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/Paste.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/Paste.java index df56ed819..b117abbde 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/Paste.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/Paste.java @@ -5,8 +5,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class Paste { - private Paste() { - } + private Paste() {} @Nullable public static String paste(@NotNull String content) { @@ -18,19 +17,19 @@ public class Paste { } catch (Exception ex) { Log.debug(ex.getMessage()); } -// try { -// paster = new HelpChatPastebinPaster(); -// return paster.pasteTheTextJson(content); -// } catch (Exception ex) { -// Log.debug(ex.getMessage()); -// } -// try { -// // Ubuntu Pastebin -// paster = new UbuntuPaster(); -// return paster.pasteTheTextDirect(content); -// } catch (Exception ex) { -// Util.debugLog(ex.getMessage()); -// } + // try { + // paster = new HelpChatPastebinPaster(); + // return paster.pasteTheTextJson(content); + // } catch (Exception ex) { + // Log.debug(ex.getMessage()); + // } + // try { + // // Ubuntu Pastebin + // paster = new UbuntuPaster(); + // return paster.pasteTheTextDirect(content); + // } catch (Exception ex) { + // Util.debugLog(ex.getMessage()); + // } return null; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteGenerator.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteGenerator.java index 3248979a2..87e38c9bb 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteGenerator.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteGenerator.java @@ -3,19 +3,19 @@ package com.ghostchu.quickshop.util.paste; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.paste.item.*; +import java.text.SimpleDateFormat; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import lombok.Getter; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.text.SimpleDateFormat; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - public class PasteGenerator { - private static final String DOCUMENT_HEADER = """ + private static final String DOCUMENT_HEADER = + """ @@ -28,7 +28,8 @@ public class PasteGenerator {
"""; - private static final String DOCUMENT_FOOTER = """ + private static final String DOCUMENT_FOOTER = + """


@@ -44,7 +45,8 @@ public class PasteGenerator { """; - private static final String INLINE_STYLE = """ + private static final String INLINE_STYLE = + """ /* Sakura.css v1.3.0 * ================ * Minimal css theme. @@ -54,7 +56,7 @@ public class PasteGenerator { html { font-size: 62.5%; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif; } - + body { font-size: 1.8rem; line-height: 1.618; @@ -63,15 +65,15 @@ public class PasteGenerator { color: #4a4a4a; background-color: #f9f9f9; padding: 13px; } - + @media (max-width: 684px) { body { font-size: 1.53rem; } } - + @media (max-width: 382px) { body { font-size: 1.35rem; } } - + h1, h2, h3, h4, h5, h6 { line-height: 1.1; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif; @@ -86,50 +88,50 @@ public class PasteGenerator { -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } - + h1 { font-size: 2.35em; } - + h2 { font-size: 2.00em; } - + h3 { font-size: 1.75em; } - + h4 { font-size: 1.5em; } - + h5 { font-size: 1.25em; } - + h6 { font-size: 1em; } - + p { margin-top: 0px; margin-bottom: 2.5rem; } - + small, sub, sup { font-size: 75%; } - + hr { border-color: #2c8898; } - + a { text-decoration: none; color: #2c8898; } a:hover { color: #982c61; border-bottom: 2px solid #4a4a4a; } - + ul { padding-left: 1.4em; margin-top: 0px; margin-bottom: 2.5rem; } - + li { margin-bottom: 0.4em; } - + blockquote { margin-left: 0px; margin-right: 0px; @@ -140,16 +142,16 @@ public class PasteGenerator { border-left: 5px solid #2c8898; margin-bottom: 2.5rem; background-color: #f1f1f1; } - + blockquote p { margin-bottom: 0; } - + img { height: auto; max-width: 100%; margin-top: 0px; margin-bottom: 2.5rem; } - + /* Pre and Code */ pre { background-color: #f1f1f1; @@ -158,18 +160,18 @@ public class PasteGenerator { overflow-x: auto; margin-top: 0px; margin-bottom: 2.5rem; } - + code { font-size: 0.9em; padding: 0 0.5em; background-color: #f1f1f1; white-space: pre-wrap; } - + pre > code { padding: 0; background-color: transparent; white-space: pre; } - + /* Tables */ table { text-align: justify; @@ -177,22 +179,22 @@ public class PasteGenerator { border-collapse: collapse; word-wrap:break-word; word-break:break-all;} - + td, th { padding: 0.5em; border-bottom: 1px solid #f1f1f1; word-wrap:break-word; word-break:break-all;} - + /* Buttons, forms and input */ input, textarea { border: 1px solid #4a4a4a; } input:focus, textarea:focus { border: 1px solid #2c8898; } - + textarea { width: 100%; } - + .button, button, input[type="submit"], input[type="reset"], input[type="button"] { display: inline-block; padding: 5px 10px; @@ -213,7 +215,7 @@ public class PasteGenerator { border-color: #982c61; color: #f9f9f9; outline: 0; } - + textarea, select, input[type] { color: #4a4a4a; padding: 6px 10px; @@ -227,17 +229,19 @@ public class PasteGenerator { textarea:focus, select:focus, input[type]:focus { border: 1px solid #2c8898; outline: 0; } - + input[type="checkbox"]:focus { outline: 1px dotted #2c8898; } - + label, legend, fieldset { display: block; margin-bottom: .5rem; font-weight: 600; } """; + @Getter private final List pasteItems = new LinkedList<>(); + private final long timestamp = System.currentTimeMillis(); private final CommandSender sender; @@ -280,9 +284,18 @@ public class PasteGenerator { try { builder.append(pasteItem.toHTML()).append("\n"); } catch (Throwable e) { - QuickShop.getInstance().logger().warn("Cannot render the paste item {}, skipping...", pasteItem.getClass().getName(), e); - builder.append("

# ").append(pasteItem.getClass().getName()).append("

") - .append("
").append("Failed to render this paste item:
").append(e.getMessage()); + QuickShop.getInstance() + .logger() + .warn( + "Cannot render the paste item {}, skipping...", + pasteItem.getClass().getName(), + e); + builder.append("

# ") + .append(pasteItem.getClass().getName()) + .append("

") + .append("
") + .append("Failed to render this paste item:
") + .append(e.getMessage()); } } builder.append(bakeFooter()); @@ -299,14 +312,21 @@ public class PasteGenerator { @NotNull private String bakeFooter() { return DOCUMENT_FOOTER - .replace("{product}", "QuickShop-" + QuickShop.getInstance().getFork() + " v" + QuickShop.getInstance().getVersion()) + .replace( + "{product}", + "QuickShop-" + QuickShop.getInstance().getFork() + " v" + + QuickShop.getInstance().getVersion()) .replace("{time}", formatTime(timestamp)) .replace("{pastecreator}", sender == null ? "Automatic" : sender.getName()); } @NotNull private String formatTime(long time) { - String timeUnit = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeUnit = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); SimpleDateFormat format; try { format = new SimpleDateFormat(timeUnit); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteInterface.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteInterface.java index dde590ef7..76b19fef9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteInterface.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteInterface.java @@ -20,5 +20,4 @@ public interface PasteInterface { * @throws Exception IOException if paste failed */ String pasteTheTextJson(@NotNull String text) throws Exception; - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteManager.java index b5f5d23c1..e120ee608 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PasteManager.java @@ -1,17 +1,17 @@ package com.ghostchu.quickshop.util.paste; import com.ghostchu.quickshop.util.paste.item.SubPasteItem; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - import java.lang.ref.WeakReference; import java.util.*; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; public class PasteManager { private final Map>> registry = new LinkedHashMap<>(); public void register(@NotNull Plugin plugin, @NotNull List collectors) { - List> collectorsWeakCopy = collectors.stream().map(WeakReference::new).toList(); + List> collectorsWeakCopy = + collectors.stream().map(WeakReference::new).toList(); List> registered = registry.getOrDefault(plugin, new ArrayList<>()); registered.addAll(collectorsWeakCopy); registry.put(plugin, registered); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PastebinPaster.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PastebinPaster.java index 02c480ff6..3c8661c78 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PastebinPaster.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/PastebinPaster.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is a part of project QuickShop, the name is PastebinPaster.java // * Copyright (C) Ghost_chu and contributors // * @@ -17,15 +17,15 @@ // * // */ // -//package com.ghostchu.quickshop.util.paste; +// package com.ghostchu.quickshop.util.paste; // -//import kong.unirest.HttpResponse; -//import kong.unirest.Unirest; -//import org.jetbrains.annotations.NotNull; +// import kong.unirest.HttpResponse; +// import kong.unirest.Unirest; +// import org.jetbrains.annotations.NotNull; // -//import java.io.IOException; +// import java.io.IOException; // -//public class PastebinPaster implements PasteInterface { +// public class PastebinPaster implements PasteInterface { // private final static String DEVELOPER_KEY = "kYoezdaN6Gg9c2VnY78NcpylWRwdzQdk"; // // @Override @@ -48,4 +48,4 @@ // public String pasteTheTextDirect(@NotNull String text) throws Exception { // return null; // } -//} +// } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/UbuntuPaster.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/UbuntuPaster.java index 81341e755..781544f2a 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/UbuntuPaster.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/UbuntuPaster.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is a part of project QuickShop, the name is UbuntuPaster.java // * Copyright (C) Ghost_chu and contributors // * @@ -17,21 +17,21 @@ // * // */ // -//package com.ghostchu.quickshop.util.paste; +// package com.ghostchu.quickshop.util.paste; // -//import org.jetbrains.annotations.NotNull; -//import com.ghostchu.quickshop.util.Util; +// import org.jetbrains.annotations.NotNull; +// import com.ghostchu.quickshop.util.Util; // -//import java.io.BufferedReader; -//import java.io.IOException; -//import java.io.InputStreamReader; -//import java.io.PrintWriter; -//import java.net.URL; -//import java.net.URLConnection; -//import java.net.URLEncoder; -//import java.nio.charset.StandardCharsets; +// import java.io.BufferedReader; +// import java.io.IOException; +// import java.io.InputStreamReader; +// import java.io.PrintWriter; +// import java.net.URL; +// import java.net.URLConnection; +// import java.net.URLEncoder; +// import java.nio.charset.StandardCharsets; // -//public class UbuntuPaster implements PasteInterface { +// public class UbuntuPaster implements PasteInterface { // /** // * Paste a text to paste.ubuntu.com // * @@ -48,7 +48,8 @@ // conn.setRequestProperty("connection", "Keep-Alive"); // conn.setRequestProperty( // "user-agent", -// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"); +// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 +// Safari/537.36"); // conn.setDoOutput(true); // conn.setDoInput(true); // conn.setConnectTimeout(50000); @@ -74,4 +75,4 @@ // return link; // } // -//} +// } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CachePerformanceItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CachePerformanceItem.java index f56ec3713..c45447608 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CachePerformanceItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CachePerformanceItem.java @@ -4,22 +4,20 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.FastPlayerFinder; import com.ghostchu.quickshop.util.paste.GuavaCacheRender; import com.google.common.cache.CacheStats; -import org.jetbrains.annotations.NotNull; - import java.text.NumberFormat; +import org.jetbrains.annotations.NotNull; public class CachePerformanceItem implements SubPasteItem { private final QuickShop plugin = QuickShop.getInstance(); @Override public @NotNull String genBody() { - return "
Player Lookup Cache
" + - buildPlayerLookupCache(); + return "
Player Lookup Cache
" + buildPlayerLookupCache(); } - private String buildPlayerLookupCache() { - CacheStats stats = ((FastPlayerFinder) plugin.getPlayerFinder()).getNameCache().stats(); + CacheStats stats = + ((FastPlayerFinder) plugin.getPlayerFinder()).getNameCache().stats(); return renderTable(stats); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ChatProcessorInfoItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ChatProcessorInfoItem.java index 6b7c5b14c..9de009173 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ChatProcessorInfoItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ChatProcessorInfoItem.java @@ -18,8 +18,7 @@ public class ChatProcessorInfoItem implements SubPasteItem { private static final String IMPL = "Adventure"; private static final String FORMATTER = "MiniMessage"; - public ChatProcessorInfoItem() { - } + public ChatProcessorInfoItem() {} @Override public @NotNull String genBody() { @@ -38,13 +37,21 @@ public class ChatProcessorInfoItem implements SubPasteItem { table.insert("Formatter", FORMATTER); table.insert("Adventure API", CommonUtil.getClassPathRelative(Adventure.class)); table.insert("Adventure Bukkit Platform", CommonUtil.getClassPathRelative(BukkitAudiences.class)); - table.insert("Adventure Text Serializer (Legacy)", CommonUtil.getClassPathRelative(LegacyComponentSerializer.class)); - table.insert("Adventure Text Serializer (Gson)", CommonUtil.getClassPathRelative(GsonComponentSerializer.class)); - table.insert("Adventure Text Serializer (Json)", CommonUtil.getClassPathRelative(JSONComponentSerializer.class)); - table.insert("Adventure Text Serializer (BungeeChat)", CommonUtil.getClassPathRelative(BungeeComponentSerializer.class)); + table.insert( + "Adventure Text Serializer (Legacy)", CommonUtil.getClassPathRelative(LegacyComponentSerializer.class)); + table.insert( + "Adventure Text Serializer (Gson)", CommonUtil.getClassPathRelative(GsonComponentSerializer.class)); + table.insert( + "Adventure Text Serializer (Json)", CommonUtil.getClassPathRelative(JSONComponentSerializer.class)); + table.insert( + "Adventure Text Serializer (BungeeChat)", + CommonUtil.getClassPathRelative(BungeeComponentSerializer.class)); table.insert("Adventure Text Serializer (ViaVersion Facet)", CommonUtil.getClassPathRelative(ViaFacet.class)); - table.insert("Adventure Text Serializer (ANSI)", CommonUtil.getClassPathRelative(ANSIComponentSerializer.class)); - table.insert("Adventure Text Serializer (Plain)", CommonUtil.getClassPathRelative(PlainTextComponentSerializer.class)); + table.insert( + "Adventure Text Serializer (ANSI)", CommonUtil.getClassPathRelative(ANSIComponentSerializer.class)); + table.insert( + "Adventure Text Serializer (Plain)", + CommonUtil.getClassPathRelative(PlainTextComponentSerializer.class)); table.insert("Adventure MiniMessage", CommonUtil.getClassPathRelative(MiniMessage.class)); return table.render(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ConfigCollectorItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ConfigCollectorItem.java index c55ee2f2f..ba95c3b2d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ConfigCollectorItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ConfigCollectorItem.java @@ -2,19 +2,17 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.*; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class ConfigCollectorItem implements SubPasteItem { private final List file = new ArrayList<>(); - public ConfigCollectorItem() { file.add(new File(QuickShop.getInstance().getDataFolder(), "config.yml")); file.add(new File(QuickShop.getInstance().getDataFolder(), "group.yml")); @@ -27,7 +25,10 @@ public class ConfigCollectorItem implements SubPasteItem { // 1.19 and up paper configuration File newConfigFolder = new File("config"); if (newConfigFolder.exists() && newConfigFolder.isDirectory()) { - File[] filesInsideConfig = newConfigFolder.listFiles((dir, name) -> name.endsWith(".yml") || name.endsWith(".yaml") || name.endsWith(".json") || name.endsWith(".toml")); + File[] filesInsideConfig = newConfigFolder.listFiles((dir, name) -> name.endsWith(".yml") + || name.endsWith(".yaml") + || name.endsWith(".json") + || name.endsWith(".toml")); if (filesInsideConfig != null) { Collections.addAll(file, filesInsideConfig); } @@ -66,14 +67,15 @@ public class ConfigCollectorItem implements SubPasteItem { if (!file.exists()) { return null; } - return "
" + file.getName() + "
" + - "
"; + return "
" + file.getName() + "
" + "
"; } private String censor(@NotNull String string) { - String seedList = """ + String seedList = + """ patch_red_mushroom fossil_diamonds seagrass_slightly_less_short @@ -315,13 +317,15 @@ public class ConfigCollectorItem implements SubPasteItem { mineshaft """; String[] paperSeedTypes = seedList.trim().split("\n"); - List seedType = Arrays.stream(paperSeedTypes).sorted((o1, o2) -> { - int i = Integer.compare(o2.length(), o1.length()); - if (i == 0) { - return o2.compareTo(o1); - } - return i; - }).toList(); + List seedType = Arrays.stream(paperSeedTypes) + .sorted((o1, o2) -> { + int i = Integer.compare(o2.length(), o1.length()); + if (i == 0) { + return o2.compareTo(o1); + } + return i; + }) + .toList(); string = string.replaceAll("secret:.*", "secret: ******") .replaceAll("user:.*", "user: ******") .replaceAll("username:.*", "username: ******") @@ -342,8 +346,6 @@ public class ConfigCollectorItem implements SubPasteItem { string = string.replaceAll(paperSeedType + ":.*", "seed-protected: ******"); } return string; - - } @NotNull diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CronLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CronLogsItem.java index fdf228742..9e56de634 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CronLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/CronLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class CronLogsItem implements SubPasteItem { private SimpleDateFormat format; public CronLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,13 +40,13 @@ public class CronLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.CRON). - stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + List debugLogs = Log.fetchLogs(Log.Type.CRON).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) .toList(); List tail = CommonUtil.tail(debugLogs, 1000); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DatabaseInfoItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DatabaseInfoItem.java index 320b84d99..a06a8db8c 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DatabaseInfoItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DatabaseInfoItem.java @@ -3,14 +3,13 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.PackageUtil; import com.ghostchu.quickshop.util.paste.util.HTMLTable; -import org.jetbrains.annotations.NotNull; - import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.List; +import org.jetbrains.annotations.NotNull; public class DatabaseInfoItem implements SubPasteItem { private static final String VERBOSE_PREFIX = "[verbose] "; @@ -53,8 +52,7 @@ public class DatabaseInfoItem implements SubPasteItem { Float.class, Double.class, Byte.class, - Character.class - ); + Character.class); for (Method method : meta.getClass().getDeclaredMethods()) { if (method.canAccess(meta)) { if (allowedClasses.contains(method.getReturnType())) { @@ -66,12 +64,11 @@ public class DatabaseInfoItem implements SubPasteItem { table.insert(VERBOSE_PREFIX + method.getName(), "null"); } } catch (Exception exception) { - //ignore + // ignore table.insert(VERBOSE_PREFIX + method.getName(), exception.getMessage()); } } } } - } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DebugLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DebugLogsItem.java index 42b00a16b..0ce46f197 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DebugLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DebugLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class DebugLogsItem implements SubPasteItem { private SimpleDateFormat format; public DebugLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,11 +40,13 @@ public class DebugLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.DEBUG).stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry).toList(); + List debugLogs = Log.fetchLogs(Log.Type.DEBUG).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + .toList(); List tail = CommonUtil.tail(debugLogs, 1000); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DisplaySystemItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DisplaySystemItem.java index 5b067435d..b97e5550c 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DisplaySystemItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/DisplaySystemItem.java @@ -26,5 +26,4 @@ public class DisplaySystemItem implements SubPasteItem { public @NotNull String getTitle() { return "Display Item Manager"; } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/HeaderItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/HeaderItem.java index 24e5621f6..1547842bf 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/HeaderItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/HeaderItem.java @@ -1,14 +1,14 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.QuickShop; +import java.util.Map; import lombok.Data; import org.jetbrains.annotations.NotNull; -import java.util.Map; - @Data public class HeaderItem implements PasteItem { - private static final String TEMPLATE = """ + private static final String TEMPLATE = + """

{title}

@@ -32,8 +32,8 @@ public class HeaderItem implements PasteItem { @Override public @NotNull String toHTML() { - return TEMPLATE - .replace("{title}", "QuickShop-" + QuickShop.getInstance().getFork() + " // Paste") + return TEMPLATE.replace( + "{title}", "QuickShop-" + QuickShop.getInstance().getFork() + " // Paste") .replace("{content}", buildContent()); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/MiscUtilItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/MiscUtilItem.java index 8ff0a2b0f..709d19779 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/MiscUtilItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/MiscUtilItem.java @@ -3,11 +3,10 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.paste.util.HTMLTable; -import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; - import java.util.Map; import java.util.StringJoiner; +import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; public class MiscUtilItem implements SubPasteItem { @SuppressWarnings("deprecation") @@ -35,7 +34,8 @@ public class MiscUtilItem implements SubPasteItem { HTMLTable customStackSize = new HTMLTable(2); customStackSize.setTableTitle("Bukkit Material", "Minecraft NamespacedKey", "Override StackSize"); for (Map.Entry entry : Util.getCustomStacksize().entrySet()) { - customStackSize.insert(entry.getKey().name(), entry.getKey().getKey().toString(), entry.getValue()); + customStackSize.insert( + entry.getKey().name(), entry.getKey().getKey().toString(), entry.getValue()); } joiner.add(customStackSize.render()); return joiner.toString(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PerformanceLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PerformanceLogsItem.java index f2b5083fd..79978ddaa 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PerformanceLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PerformanceLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class PerformanceLogsItem implements SubPasteItem { private SimpleDateFormat format; public PerformanceLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,11 +40,13 @@ public class PerformanceLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.PERFORMANCE).stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry).toList(); + List debugLogs = Log.fetchLogs(Log.Type.PERFORMANCE).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + .toList(); List tail = CommonUtil.tail(debugLogs, 1000); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PermissionLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PermissionLogsItem.java index b242f5ce4..75abdbb28 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PermissionLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PermissionLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class PermissionLogsItem implements SubPasteItem { private SimpleDateFormat format; public PermissionLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,11 +40,13 @@ public class PermissionLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.PERMISSION).stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry).toList(); + List debugLogs = Log.fetchLogs(Log.Type.PERMISSION).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + .toList(); List tail = CommonUtil.tail(debugLogs, 300); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PluginsInfoItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PluginsInfoItem.java index 045fb1a9e..2ebff9353 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PluginsInfoItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PluginsInfoItem.java @@ -3,12 +3,11 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.paste.util.HTMLTable; +import java.util.Objects; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.Objects; - public class PluginsInfoItem implements SubPasteItem { @Override public @NotNull String genBody() { @@ -25,7 +24,8 @@ public class PluginsInfoItem implements SubPasteItem { HTMLTable table = new HTMLTable(6); table.setTableTitle("Name", "Status", "Version", "API Version", "Addon", "Main-Class"); for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - table.insert(plugin.getName(), + table.insert( + plugin.getName(), CommonUtil.boolean2Status(plugin.isEnabled()), plugin.getDescription().getVersion(), Objects.requireNonNullElse(plugin.getDescription().getAPIVersion(), "N/A"), @@ -37,6 +37,7 @@ public class PluginsInfoItem implements SubPasteItem { private boolean isAddon(Plugin plugin) { String plugName = QuickShop.getInstance().getJavaPlugin().getName(); - return plugin.getDescription().getDepend().contains(plugName) || plugin.getDescription().getSoftDepend().contains(plugName); + return plugin.getDescription().getDepend().contains(plugName) + || plugin.getDescription().getSoftDepend().contains(plugName); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PrivacyLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PrivacyLogsItem.java index 6e71c945b..e016d6f75 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PrivacyLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/PrivacyLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class PrivacyLogsItem implements SubPasteItem { private SimpleDateFormat format; public PrivacyLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,11 +40,13 @@ public class PrivacyLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.PRIVACY).stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry).toList(); + List debugLogs = Log.fetchLogs(Log.Type.PRIVACY).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + .toList(); List tail = CommonUtil.tail(debugLogs, 1000); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ReplaceableModulesItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ReplaceableModulesItem.java index d3d70e2ed..5ea2c5f77 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ReplaceableModulesItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ReplaceableModulesItem.java @@ -14,17 +14,20 @@ public class ReplaceableModulesItem implements SubPasteItem { public ReplaceableModulesItem() { QuickShop plugin = QuickShop.getInstance(); - itemMatcher = plugin.getItemMatcher().getName() + "@" + plugin.getItemMatcher().getPlugin().getName(); + itemMatcher = plugin.getItemMatcher().getName() + "@" + + plugin.getItemMatcher().getPlugin().getName(); if (plugin.getEconomy() == null) { economyCore = "undefined@unknown"; } else { - economyCore = plugin.getEconomy().getName() + "@" + plugin.getEconomy().getPlugin().getName(); + economyCore = plugin.getEconomy().getName() + "@" + + plugin.getEconomy().getPlugin().getName(); } DisplayProvider provider = ServiceInjector.getInjectedService(DisplayProvider.class, null); if (provider == null) { displayItem = AbstractDisplayItem.getNowUsing().name() + "@QuickShop-Hikari"; } else { - displayItem = provider.getClass().getSimpleName() + "@" + provider.getProvider().getName(); + displayItem = provider.getClass().getSimpleName() + "@" + + provider.getProvider().getName(); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ShopsInfoItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ShopsInfoItem.java index a087b0300..9e5fbe4ab 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ShopsInfoItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/ShopsInfoItem.java @@ -2,12 +2,11 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.shop.Shop; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.jetbrains.annotations.NotNull; public class ShopsInfoItem implements SubPasteItem { private final String totalShops; @@ -19,7 +18,8 @@ public class ShopsInfoItem implements SubPasteItem { plugin.getShopManager().getAllShops().stream() .filter(shop -> shop.getLocation().getWorld() != null) .forEach(shop -> { - List worldShops = shopsMapping.get(shop.getLocation().getWorld().getName()); + List worldShops = + shopsMapping.get(shop.getLocation().getWorld().getName()); if (worldShops == null) { worldShops = new ArrayList<>(); } @@ -45,7 +45,12 @@ public class ShopsInfoItem implements SubPasteItem { htmlBuilder.append("

Total Shops: ").append(totalShops).append("

"); htmlBuilder.append("
Shops in world
"); htmlBuilder.append("
    "); - shopsMapping.keySet().forEach(worldName -> htmlBuilder.append("
  • ").append(worldName).append(": ").append(shopsMapping.get(worldName).size()).append("
  • ")); + shopsMapping.keySet().forEach(worldName -> htmlBuilder + .append("
  • ") + .append(worldName) + .append(": ") + .append(shopsMapping.get(worldName).size()) + .append("
  • ")); htmlBuilder.append("
"); return htmlBuilder.toString(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/SystemInfoItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/SystemInfoItem.java index 21c3bb68c..cb223ea99 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/SystemInfoItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/SystemInfoItem.java @@ -3,12 +3,11 @@ package com.ghostchu.quickshop.util.paste.item; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.PackageUtil; import com.ghostchu.quickshop.util.paste.util.HTMLTable; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.stream.Collectors; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class SystemInfoItem implements SubPasteItem { private final String os; @@ -30,7 +29,8 @@ public class SystemInfoItem implements SubPasteItem { this.javaImplName = runtimeMxBean.getVmName(); this.inputArgs = CommonUtil.list2String(runtimeMxBean.getInputArguments()); this.systemProperties = runtimeMxBean.getSystemProperties().keySet().stream() - .map(key -> StringEscapeUtils.escapeHtml4(key + "=" + runtimeMxBean.getSystemProperties().get(key))) + .map(key -> StringEscapeUtils.escapeHtml4( + key + "=" + runtimeMxBean.getSystemProperties().get(key))) .collect(Collectors.joining("
")); } @@ -54,7 +54,8 @@ public class SystemInfoItem implements SubPasteItem { table.insert("Java Version", javaVersion); table.insert("JVM Name", javaImplName); table.insert("Input Arguments", inputArgs); - String propertiesContent = """ + String propertiesContent = + """
System Properties (Click to open/close) {properties} diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TimingsLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TimingsLogsItem.java index e25dd026c..166112c9e 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TimingsLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TimingsLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class TimingsLogsItem implements SubPasteItem { private SimpleDateFormat format; public TimingsLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,11 +40,13 @@ public class TimingsLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.TIMING).stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry).toList(); + List debugLogs = Log.fetchLogs(Log.Type.TIMING).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + .toList(); List tail = CommonUtil.tail(debugLogs, 1000); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TransactionLogsItem.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TransactionLogsItem.java index d00e70acb..b2ff8557f 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TransactionLogsItem.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/item/TransactionLogsItem.java @@ -4,19 +4,22 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.common.util.CommonUtil; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.logger.Log; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import org.apache.commons.text.StringEscapeUtils; -import org.jetbrains.annotations.NotNull; - import java.text.SimpleDateFormat; import java.util.List; import java.util.StringJoiner; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.text.StringEscapeUtils; +import org.jetbrains.annotations.NotNull; public class TransactionLogsItem implements SubPasteItem { private SimpleDateFormat format; public TransactionLogsItem() { - String timeFormat = LegacyComponentSerializer.legacySection().serialize(QuickShop.getInstance().text().of("timeunit.std-time-format").forLocale(MsgUtil.getDefaultGameLanguageCode())); + String timeFormat = LegacyComponentSerializer.legacySection() + .serialize(QuickShop.getInstance() + .text() + .of("timeunit.std-time-format") + .forLocale(MsgUtil.getDefaultGameLanguageCode())); try { format = new SimpleDateFormat(timeFormat); } catch (IllegalArgumentException e) { @@ -37,11 +40,13 @@ public class TransactionLogsItem implements SubPasteItem { @NotNull private String buildContent() { StringJoiner builder = new StringJoiner("\n"); - List debugLogs = Log.fetchLogs(Log.Type.TRANSACTION).stream().map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry).toList(); + List debugLogs = Log.fetchLogs(Log.Type.TRANSACTION).stream() + .map(recordEntry -> "[" + format.format(recordEntry.getTimestamp()) + "] " + recordEntry) + .toList(); List tail = CommonUtil.tail(debugLogs, 1000); tail.forEach(builder::add); - return "
"; + return "
"; } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/util/HTMLTable.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/util/HTMLTable.java index ef94da937..f850cab7d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/util/HTMLTable.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/paste/util/HTMLTable.java @@ -1,15 +1,15 @@ package com.ghostchu.quickshop.util.paste.util; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class HTMLTable { - private static final String TEMPLATE = """ + private static final String TEMPLATE = + """ {col} {thead} @@ -75,8 +75,7 @@ public class HTMLTable { public String render() { String thead = renderHead(); String tbody = renderBody(); - return TEMPLATE - .replace("{col}", renderColAttributes()) + return TEMPLATE.replace("{col}", renderColAttributes()) .replace("{thead}", thead) .replace("{tbody}", tbody); } @@ -96,7 +95,8 @@ public class HTMLTable { {th} - """.replace("{th}", tdBuilder.toString()); + """ + .replace("{th}", tdBuilder.toString()); } private String renderBody() { @@ -112,7 +112,7 @@ public class HTMLTable { } private String renderColAttributes() { -// String base ="\n"; + // String base ="\n"; String base = "\n"; return base.replace("{length}", String.valueOf(100 / columns)).repeat(columns); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/BatchBukkitExecutor.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/BatchBukkitExecutor.java index 16dcb76ce..56929471d 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/BatchBukkitExecutor.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/BatchBukkitExecutor.java @@ -1,9 +1,5 @@ package com.ghostchu.quickshop.util.performance; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitRunnable; -import org.jetbrains.annotations.NotNull; - import java.time.Instant; import java.util.Arrays; import java.util.Collection; @@ -11,6 +7,9 @@ import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; public class BatchBukkitExecutor { private final Queue tasks = new LinkedList<>(); @@ -18,8 +17,7 @@ public class BatchBukkitExecutor { private boolean started = false; private Instant startTime = Instant.MIN; - public BatchBukkitExecutor() { - } + public BatchBukkitExecutor() {} public BatchBukkitExecutor(int maxTickMsUsage) { this.maxTickMsUsage = maxTickMsUsage; @@ -68,7 +66,8 @@ public class BatchBukkitExecutor { public final int maxTickMsUsage; private final CompletableFuture callback; - public BatchBukkitTask(Queue tasks, Consumer consumer, int maxTickMsUsage, CompletableFuture callback) { + public BatchBukkitTask( + Queue tasks, Consumer consumer, int maxTickMsUsage, CompletableFuture callback) { this.tasks = tasks; this.consumer = consumer; this.maxTickMsUsage = maxTickMsUsage; @@ -95,5 +94,4 @@ public class BatchBukkitExecutor { callback.complete(null); } } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/PerfMonitor.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/PerfMonitor.java index 93bec3cda..a7bd42b22 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/PerfMonitor.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/performance/PerfMonitor.java @@ -1,20 +1,21 @@ package com.ghostchu.quickshop.util.performance; import com.ghostchu.quickshop.util.logger.Log; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.time.Duration; import java.time.Instant; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PerfMonitor implements AutoCloseable { private final String name; private final Instant startTime; + @Nullable private final Duration exceptedDuration; + private final Log.Caller caller; + @Nullable private String context; @@ -51,7 +52,6 @@ public class PerfMonitor implements AutoCloseable { this.context = context; } - @Override public void close() { Duration passedDuration = getTimePassed(); @@ -64,7 +64,10 @@ public class PerfMonitor implements AutoCloseable { messageBuilder.append("has finished in ").append(passed).append("."); Level level = Level.INFO; if (isReachedLimit()) { - messageBuilder.append(" OVER LIMIT! The excepted time cost should less than ").append(exceptedDuration.toMillis()).append("ms."); + messageBuilder + .append(" OVER LIMIT! The excepted time cost should less than ") + .append(exceptedDuration.toMillis()) + .append("ms."); level = Level.WARNING; } Log.performance(level, messageBuilder.toString(), caller); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/privacy/PrivacyController.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/privacy/PrivacyController.java index 115169910..7833e56bc 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/privacy/PrivacyController.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/privacy/PrivacyController.java @@ -3,9 +3,8 @@ package com.ghostchu.quickshop.util.privacy; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.metric.MetricDataType; -import org.bukkit.configuration.ConfigurationSection; - import java.util.UUID; +import org.bukkit.configuration.ConfigurationSection; public class PrivacyController { private final QuickShop plugin; @@ -32,7 +31,8 @@ public class PrivacyController { } ConfigurationSection moduleSection = section.getConfigurationSection("module"); if (moduleSection == null) { - Log.privacy("[CHECK] Transaction " + transaction + " was approved: `module` section not found but " + dataType.name() + " type was explicitly enabled."); + Log.privacy("[CHECK] Transaction " + transaction + " was approved: `module` section not found but " + + dataType.name() + " type was explicitly enabled."); return true; } boolean r = moduleSection.getBoolean(moduleName, true); @@ -44,9 +44,12 @@ public class PrivacyController { return r; } - public void privacyReview(MetricDataType dataType, String moduleName, String reason, Runnable accepted, Runnable declined) { + public void privacyReview( + MetricDataType dataType, String moduleName, String reason, Runnable accepted, Runnable declined) { UUID privacyTransaction = UUID.randomUUID(); - Log.privacy("[REVIEW] The module [" + moduleName + "] requesting to processing your data off your local machine for usage [" + dataType.name() + "], the reason is: " + reason + ". Transaction Id: " + privacyTransaction); + Log.privacy("[REVIEW] The module [" + moduleName + + "] requesting to processing your data off your local machine for usage [" + dataType.name() + + "], the reason is: " + reason + ". Transaction Id: " + privacyTransaction); if (!isAllowed(dataType, moduleName, privacyTransaction)) { Log.privacy("[REVIEW] Declined transaction " + privacyTransaction); declined.run(); diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/reporter/error/RollbarErrorReporter.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/reporter/error/RollbarErrorReporter.java index a6d040892..fec8677fc 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/reporter/error/RollbarErrorReporter.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/reporter/error/RollbarErrorReporter.java @@ -10,12 +10,6 @@ import com.google.common.collect.Lists; import com.rollbar.notifier.Rollbar; import com.rollbar.notifier.config.Config; import com.rollbar.notifier.config.ConfigBuilder; -import lombok.Getter; -import org.bukkit.Bukkit; -import org.bukkit.plugin.InvalidPluginException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.IOException; import java.net.ProtocolException; import java.sql.SQLException; @@ -23,28 +17,33 @@ import java.util.*; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.plugin.InvalidPluginException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class RollbarErrorReporter { private static final String QUICKSHOP_ROOT_PACKAGE_NAME = "com.ghostchu.quickshop"; private final Rollbar rollbar; private final List reported = new ArrayList<>(5); - private final List> ignoredException = Lists.newArrayList(IOException.class - , OutOfMemoryError.class - , ProtocolException.class - , InvalidPluginException.class - , UnsupportedClassVersionError.class - , LinkageError.class - , SQLException.class - ); + private final List> ignoredException = Lists.newArrayList( + IOException.class, + OutOfMemoryError.class, + ProtocolException.class, + InvalidPluginException.class, + UnsupportedClassVersionError.class, + LinkageError.class, + SQLException.class); private final QuickShop plugin; private final QuickShopExceptionFilter quickShopExceptionFilter; private final GlobalExceptionFilter serverExceptionFilter; private boolean disable; private boolean tempDisable; + @Getter private volatile boolean enabled; - public RollbarErrorReporter(@NotNull QuickShop plugin) { this.plugin = plugin; Config config = ConfigBuilder.withAccessToken("feae3ac28ad84326b17c1c61e00bd981") @@ -55,10 +54,14 @@ public class RollbarErrorReporter { .build(); this.rollbar = Rollbar.init(config); - quickShopExceptionFilter = new QuickShopExceptionFilter(plugin.getJavaPlugin().getLogger().getFilter()); - plugin.getJavaPlugin().getLogger().setFilter(quickShopExceptionFilter); // Redirect log request passthrough our error catcher. + quickShopExceptionFilter = + new QuickShopExceptionFilter(plugin.getJavaPlugin().getLogger().getFilter()); + plugin.getJavaPlugin() + .getLogger() + .setFilter(quickShopExceptionFilter); // Redirect log request passthrough our error catcher. - serverExceptionFilter = new GlobalExceptionFilter(plugin.getJavaPlugin().getLogger().getFilter()); + serverExceptionFilter = + new GlobalExceptionFilter(plugin.getJavaPlugin().getLogger().getFilter()); Bukkit.getLogger().setFilter(serverExceptionFilter); Log.debug("Rollbar error reporter success loaded."); @@ -96,41 +99,54 @@ public class RollbarErrorReporter { } } @NotNull Throwable finalThrowable = throwable; - plugin.getPrivacyController().privacyReview(MetricDataType.DIAGNOSTIC, "RollbarErrorReporter", "QuickShop detected a error, we will report it to Rollbar Error Tracker so QuickShop's developers will receive the notification so we can fix it.", - () -> { - try { - this.rollbar.error(finalThrowable, this.makeMapping(), throwable.getMessage()); - plugin - .logger() - .warn( - "A exception was thrown, QuickShop already caught this exception and reported it. This error will only shown once before next restart."); - plugin.logger().warn("====QuickShop Error Report BEGIN==="); - plugin.logger().warn("Description: {}", finalThrowable.getMessage()); - plugin.logger().warn("Server ID: {}", plugin.getServerUniqueID()); - plugin.logger().warn("Exception : "); - ignoreThrows(); - finalThrowable.printStackTrace(); - resetIgnores(); - plugin.logger().warn("====QuickShop Error Report E N D==="); - plugin - .logger() - .warn( - "If this error affects any function, you can join our Discord server to report it and track the feedback: https://discord.gg/Bu3dVtmsD3"); - Log.debug(finalThrowable.getMessage()); - Arrays.stream(finalThrowable.getStackTrace()).forEach(a -> Log.debug(a.getClassName() + "." + a.getMethodName() + ":" + a.getLineNumber())); - if (Util.isDevMode()) { - finalThrowable.printStackTrace(); - } - } catch (Exception ex) { - ignoreThrow(); - plugin.logger().warn("An error occurred during error handling, hard break it to prevent StackOverFlowError", throwable); - plugin.logger().warn("An error occurred during error handling, hard break it to prevent StackOverFlowError", ex); - } - }, () -> { - ignoreThrow(); - plugin.logger().warn("An error occurred during running, because your privacy setting, the error not reported to server.", throwable); - }); - + plugin.getPrivacyController() + .privacyReview( + MetricDataType.DIAGNOSTIC, + "RollbarErrorReporter", + "QuickShop detected a error, we will report it to Rollbar Error Tracker so QuickShop's developers will receive the notification so we can fix it.", + () -> { + try { + this.rollbar.error(finalThrowable, this.makeMapping(), throwable.getMessage()); + plugin.logger() + .warn( + "A exception was thrown, QuickShop already caught this exception and reported it. This error will only shown once before next restart."); + plugin.logger().warn("====QuickShop Error Report BEGIN==="); + plugin.logger().warn("Description: {}", finalThrowable.getMessage()); + plugin.logger().warn("Server ID: {}", plugin.getServerUniqueID()); + plugin.logger().warn("Exception : "); + ignoreThrows(); + finalThrowable.printStackTrace(); + resetIgnores(); + plugin.logger().warn("====QuickShop Error Report E N D==="); + plugin.logger() + .warn( + "If this error affects any function, you can join our Discord server to report it and track the feedback: https://discord.gg/Bu3dVtmsD3"); + Log.debug(finalThrowable.getMessage()); + Arrays.stream(finalThrowable.getStackTrace()) + .forEach(a -> Log.debug( + a.getClassName() + "." + a.getMethodName() + ":" + a.getLineNumber())); + if (Util.isDevMode()) { + finalThrowable.printStackTrace(); + } + } catch (Exception ex) { + ignoreThrow(); + plugin.logger() + .warn( + "An error occurred during error handling, hard break it to prevent StackOverFlowError", + throwable); + plugin.logger() + .warn( + "An error occurred during error handling, hard break it to prevent StackOverFlowError", + ex); + } + }, + () -> { + ignoreThrow(); + plugin.logger() + .warn( + "An error occurred during running, because your privacy setting, the error not reported to server.", + throwable); + }); } /** @@ -163,7 +179,8 @@ public class RollbarErrorReporter { return PossiblyLevel.IMPOSSIBLE; } - if (stackTraceElements[0].getClassName().contains(QUICKSHOP_ROOT_PACKAGE_NAME) && stackTraceElements[1].getClassName().contains(QUICKSHOP_ROOT_PACKAGE_NAME)) { + if (stackTraceElements[0].getClassName().contains(QUICKSHOP_ROOT_PACKAGE_NAME) + && stackTraceElements[1].getClassName().contains(QUICKSHOP_ROOT_PACKAGE_NAME)) { return PossiblyLevel.CONFIRM; } @@ -248,7 +265,8 @@ public class RollbarErrorReporter { Log.debug("Cannot to check reportable: " + exception.getMessage()); return false; } - if (!GameVersion.get(plugin.getPlatform().getMinecraftVersion()).isCoreSupports()) { // Ignore errors if user install quickshop on unsupported + if (!GameVersion.get(plugin.getPlatform().getMinecraftVersion()) + .isCoreSupports()) { // Ignore errors if user install quickshop on unsupported // version. return false; } @@ -272,12 +290,11 @@ public class RollbarErrorReporter { resetIgnores(); return false; } - String text = - stackTraceElement.getClassName() - + "#" - + stackTraceElement.getMethodName() - + "#" - + stackTraceElement.getLineNumber(); + String text = stackTraceElement.getClassName() + + "#" + + stackTraceElement.getMethodName() + + "#" + + stackTraceElement.getLineNumber(); if (!reported.contains(text)) { reported.add(text); return true; @@ -349,7 +366,9 @@ public class RollbarErrorReporter { return true; } if (possiblyLevel == PossiblyLevel.MAYBE) { - plugin.logger().warn("This seems not a QuickShop error. If you have any question, you should ask QuickShop developer."); + plugin.logger() + .warn( + "This seems not a QuickShop error. If you have any question, you should ask QuickShop developer."); return true; } return false; @@ -359,7 +378,6 @@ public class RollbarErrorReporter { private boolean defaultValue(LogRecord rec) { return preFilter == null || preFilter.isLoggable(rec); } - } class QuickShopExceptionFilter implements Filter { @@ -399,7 +417,9 @@ public class RollbarErrorReporter { return true; } if (possiblyLevel == PossiblyLevel.MAYBE) { - plugin.logger().warn("This seems not a QuickShop error. If you have any question, you may can ask QuickShop developer but don't except any solution."); + plugin.logger() + .warn( + "This seems not a QuickShop error. If you have any question, you may can ask QuickShop developer but don't except any solution."); return true; } return false; @@ -409,6 +429,5 @@ public class RollbarErrorReporter { private boolean defaultValue(LogRecord rec) { return preFilter == null || preFilter.isLoggable(rec); } - } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/updater/NexusManager.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/updater/NexusManager.java index 8308412c8..a7725b5a5 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/updater/NexusManager.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/util/updater/NexusManager.java @@ -4,6 +4,9 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.logger.Log; import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.quickshop.util.paste.util.HTMLTable; +import java.io.StringReader; +import java.util.Optional; +import java.util.logging.Level; import kong.unirest.HttpResponse; import kong.unirest.Unirest; import kong.unirest.UnirestException; @@ -18,12 +21,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.xml.sax.SAXException; -import java.io.StringReader; -import java.util.Optional; -import java.util.logging.Level; - public class NexusManager implements SubPasteItem { - private static final String NEXUS_ROOT_METADATA_URL = "https://repo.codemc.io/repository/maven-releases/com/ghostchu/quickshop-hikari/maven-metadata.xml"; + private static final String NEXUS_ROOT_METADATA_URL = + "https://repo.codemc.io/repository/maven-releases/com/ghostchu/quickshop-hikari/maven-metadata.xml"; private final QuickShop plugin; private NexusMetadata cachedMetadata; @@ -75,9 +75,11 @@ public class NexusManager implements SubPasteItem { if (!resp.isSuccess()) { Optional exceptionOptional = resp.getParsingError(); if (exceptionOptional.isPresent()) { - Log.debug("Failed to fetch metadata from Nexus: " + exceptionOptional.get().getMessage()); + Log.debug("Failed to fetch metadata from Nexus: " + + exceptionOptional.get().getMessage()); } else { - Log.debug("Failed to fetch metadata from CodeMC.io nexus:" + resp.getStatus() + "-" + resp.getStatusText()); + Log.debug("Failed to fetch metadata from CodeMC.io nexus:" + resp.getStatus() + "-" + + resp.getStatusText()); } return null; } @@ -98,7 +100,8 @@ public class NexusManager implements SubPasteItem { } HTMLTable table = new HTMLTable(3); table.setTableTitle("Last Update", "Latest Version", "Release Version"); - table.insert(cachedMetadata.getLastUpdate(), cachedMetadata.getLatestVersion(), cachedMetadata.getReleaseVersion()); + table.insert( + cachedMetadata.getLastUpdate(), cachedMetadata.getLatestVersion(), cachedMetadata.getReleaseVersion()); return table.render(); } @@ -120,7 +123,8 @@ public class NexusManager implements SubPasteItem { } @NotNull - public static NexusMetadata parse(@NotNull String xml) throws DocumentException, IllegalStateException, SAXException { + public static NexusMetadata parse(@NotNull String xml) + throws DocumentException, IllegalStateException, SAXException { SAXReader reader = new SAXReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); Document document = reader.read(new StringReader(xml)); @@ -144,7 +148,8 @@ public class NexusManager implements SubPasteItem { if (lastUpdate == null) { throw new IllegalStateException("No lastUpdated element found"); } - NexusMetadata metadata = new NexusMetadata(Long.parseLong(lastUpdate.getText()), latest.getText(), release.getText()); + NexusMetadata metadata = + new NexusMetadata(Long.parseLong(lastUpdate.getText()), latest.getText(), release.getText()); Log.debug("Parsed NexusMetadata: " + metadata); return metadata; } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/CalendarWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/CalendarWatcher.java index 2b6fbb293..5f1acbbd2 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/CalendarWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/CalendarWatcher.java @@ -4,15 +4,14 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.event.CalendarEvent; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.logger.Log; +import java.io.File; +import java.io.IOException; +import java.util.Calendar; import lombok.Getter; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; -import java.io.File; -import java.io.IOException; -import java.util.Calendar; - /** * CalendarWatcher check-call calendar events related stuffs * @@ -21,8 +20,10 @@ import java.util.Calendar; public class CalendarWatcher extends BukkitRunnable { @Getter private final File calendarFile = new File(Util.getCacheFolder(), "calendar.cache"); + @Getter private final YamlConfiguration configuration; + private final QuickShop plugin; private BukkitTask task; @@ -32,7 +33,11 @@ public class CalendarWatcher extends BukkitRunnable { try { calendarFile.createNewFile(); } catch (IOException ioException) { - plugin.logger().warn("Cannot create calendar cache file at {}, scheduled tasks may cannot or execute wrongly!", calendarFile.getAbsolutePath(), ioException); + plugin.logger() + .warn( + "Cannot create calendar cache file at {}, scheduled tasks may cannot or execute wrongly!", + calendarFile.getAbsolutePath(), + ioException); } } configuration = YamlConfiguration.loadConfiguration(calendarFile); @@ -86,7 +91,6 @@ public class CalendarWatcher extends BukkitRunnable { type = CalendarEvent.CalendarTriggerType.YEAR; } - configuration.set("second", secondNow); configuration.set("minute", minuteNow); configuration.set("hour", hourNow); @@ -94,9 +98,8 @@ public class CalendarWatcher extends BukkitRunnable { configuration.set("week", weekNow); configuration.set("month", monthNow); configuration.set("year", yearNow); - //We can use ordinal() to check we need update or not - //If we need update every minute, use type.ordinal() >= MINUTE - + // We can use ordinal() to check we need update or not + // If we need update every minute, use type.ordinal() >= MINUTE if (type.ordinal() >= CalendarEvent.CalendarTriggerType.HOUR.ordinal()) { save(); @@ -109,7 +112,11 @@ public class CalendarWatcher extends BukkitRunnable { try { configuration.save(calendarFile); } catch (IOException ioException) { - plugin.logger().warn("Cannot save calendar cache file at {}, scheduled tasks may cannot or execute wrongly!", calendarFile.getAbsolutePath(), ioException); + plugin.logger() + .warn( + "Cannot save calendar cache file at {}, scheduled tasks may cannot or execute wrongly!", + calendarFile.getAbsolutePath(), + ioException); } } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/DisplayAutoDespawnWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/DisplayAutoDespawnWatcher.java index 1e180d50e..777a6bf94 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/DisplayAutoDespawnWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/DisplayAutoDespawnWatcher.java @@ -8,6 +8,7 @@ import com.ghostchu.quickshop.util.paste.item.SubPasteItem; import com.ghostchu.simplereloadlib.ReloadResult; import com.ghostchu.simplereloadlib.ReloadStatus; import com.ghostchu.simplereloadlib.Reloadable; +import java.util.StringJoiner; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; @@ -15,8 +16,6 @@ import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull; -import java.util.StringJoiner; - public class DisplayAutoDespawnWatcher extends BukkitRunnable implements Reloadable, SubPasteItem { private final QuickShop plugin; private int range; @@ -46,12 +45,12 @@ public class DisplayAutoDespawnWatcher extends BukkitRunnable implements Reloada @Override public void run() { for (Shop shop : plugin.getShopManager().getLoadedShops()) { - //Shop may be deleted or unloaded when iterating + // Shop may be deleted or unloaded when iterating if (!shop.isLoaded()) { continue; } Location location = shop.getLocation(); - World world = shop.getLocation().getWorld(); //Cache this, because it will took some time. + World world = shop.getLocation().getWorld(); // Cache this, because it will took some time. AbstractDisplayItem displayItem = ((ContainerShop) shop).getDisplayItem(); if (displayItem != null) { // Check the range has player? @@ -83,7 +82,8 @@ public class DisplayAutoDespawnWatcher extends BukkitRunnable implements Reloada @Override public @NotNull String genBody() { StringJoiner joiner = new StringJoiner("
"); - joiner.add("Warning: DisplayAutoDespawnWatcher has been enabled, this may cause lag. This feature is not recommended"); + joiner.add( + "Warning: DisplayAutoDespawnWatcher has been enabled, this may cause lag. This feature is not recommended"); joiner.add("

Range: " + range + "

"); return joiner.toString(); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/LogWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/LogWatcher.java index eb3a2f050..df3846725 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/LogWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/LogWatcher.java @@ -1,11 +1,6 @@ package com.ghostchu.quickshop.watcher; import com.ghostchu.quickshop.QuickShop; -import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; -import org.apache.commons.compress.compressors.gzip.GzipParameters; -import org.bukkit.scheduler.BukkitRunnable; -import org.jetbrains.annotations.NotNull; - import java.io.*; import java.nio.file.Files; import java.nio.file.Path; @@ -16,10 +11,16 @@ import java.time.format.DateTimeFormatter; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; +import org.apache.commons.compress.compressors.gzip.GzipParameters; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; public class LogWatcher extends BukkitRunnable implements AutoCloseable { - private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneId.systemDefault()); - private static final DateTimeFormatter LOG_FILE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()); + private static final DateTimeFormatter DATETIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneId.systemDefault()); + private static final DateTimeFormatter LOG_FILE_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()); private final Queue logs = new ConcurrentLinkedQueue<>(); private PrintWriter printWriter = null; @@ -36,17 +37,19 @@ public class LogWatcher extends BukkitRunnable implements AutoCloseable { if ((log.length() / 1024f / 1024f) > plugin.getConfig().getDouble("logging.file-size")) { Path logPath = plugin.getDataFolder().toPath().resolve("logs"); Files.createDirectories(logPath); - //Find a available name + // Find a available name Path targetPath; int i = 1; do { - targetPath = logPath.resolve(ZonedDateTime.now().format(LOG_FILE_FORMATTER) + "-" + i + ".log.gz"); + targetPath = + logPath.resolve(ZonedDateTime.now().format(LOG_FILE_FORMATTER) + "-" + i + ".log.gz"); i++; } while (Files.exists(targetPath)); Files.createFile(targetPath); GzipParameters gzipParameters = new GzipParameters(); gzipParameters.setFilename(log.getName()); - try (GzipCompressorOutputStream archiveOutputStream = new GzipCompressorOutputStream(new BufferedOutputStream(new FileOutputStream(targetPath.toFile())), gzipParameters)) { + try (GzipCompressorOutputStream archiveOutputStream = new GzipCompressorOutputStream( + new BufferedOutputStream(new FileOutputStream(targetPath.toFile())), gzipParameters)) { Files.copy(log.toPath(), archiveOutputStream); archiveOutputStream.finish(); if (log.delete()) { @@ -60,10 +63,10 @@ public class LogWatcher extends BukkitRunnable implements AutoCloseable { } FileWriter logFileWriter; if (deleteFailed) { - //If could not delete, just override it + // If could not delete, just override it logFileWriter = new FileWriter(log, false); } else { - //Otherwise append + // Otherwise append logFileWriter = new FileWriter(log, true); } printWriter = new PrintWriter(logFileWriter); @@ -89,7 +92,7 @@ public class LogWatcher extends BukkitRunnable implements AutoCloseable { @Override public void run() { if (printWriter == null) { - //Waiting for init + // Waiting for init return; } Iterator iterator = logs.iterator(); @@ -100,5 +103,4 @@ public class LogWatcher extends BukkitRunnable implements AutoCloseable { } printWriter.flush(); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/OngoingFeeWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/OngoingFeeWatcher.java index 4a0fac42a..2ee0be4a9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/OngoingFeeWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/OngoingFeeWatcher.java @@ -10,14 +10,13 @@ import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; import com.ghostchu.quickshop.util.WarningSender; import com.ghostchu.quickshop.util.logger.Log; +import java.util.Objects; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull; -import java.util.Objects; - /** * Check the shops after server booted up, make sure shop can correct self-deleted when container * lost. @@ -47,13 +46,16 @@ public class OngoingFeeWatcher extends BukkitRunnable { QUser shopOwner = shop.getOwner(); Location location = shop.getLocation(); if (!location.isWorldLoaded()) { - //ignore unloaded world + // ignore unloaded world continue; } double cost = gobalCost; World world = location.getWorld(); - //We must check balance manually to avoid shop missing hell when tax account broken - if (allowLoan || plugin.getEconomy().getBalance(shopOwner, Objects.requireNonNull(world), plugin.getCurrency()) >= cost) { + // We must check balance manually to avoid shop missing hell when tax account broken + if (allowLoan + || plugin.getEconomy() + .getBalance(shopOwner, Objects.requireNonNull(world), plugin.getCurrency()) + >= cost) { QUser taxAccount = null; if (shop.getTaxAccount() != null) { taxAccount = shop.getTaxAccount(); @@ -81,11 +83,13 @@ public class OngoingFeeWatcher extends BukkitRunnable { .world(world) .amount(finalCost) .to(finalTaxAccount) - .from(shopOwner).build(); + .from(shopOwner) + .build(); boolean success = transaction.failSafeCommit(); if (!success) { - warningSender.sendWarn("Unable to deposit ongoing fee to tax account, the last error is " + transaction.getLastError()); + warningSender.sendWarn("Unable to deposit ongoing fee to tax account, the last error is " + + transaction.getLastError()); } }); } else { @@ -102,14 +106,23 @@ public class OngoingFeeWatcher extends BukkitRunnable { */ public void removeShop(@NotNull Shop shop) { Util.mainThreadRun(() -> plugin.getShopManager().deleteShop(shop)); - MsgUtil.send(shop, shop.getOwner(), plugin.text().of("shop-removed-cause-ongoing-fee", LegacyComponentSerializer.legacySection().deserialize("World:" - + Objects.requireNonNull(shop.getLocation().getWorld()).getName() - + " X:" - + shop.getLocation().getBlockX() - + " Y:" - + shop.getLocation().getBlockY() - + " Z:" - + shop.getLocation().getBlockZ())).forLocale()); + MsgUtil.send( + shop, + shop.getOwner(), + plugin.text() + .of( + "shop-removed-cause-ongoing-fee", + LegacyComponentSerializer.legacySection() + .deserialize("World:" + + Objects.requireNonNull(shop.getLocation() + .getWorld()) + .getName() + + " X:" + + shop.getLocation().getBlockX() + + " Y:" + + shop.getLocation().getBlockY() + + " Z:" + + shop.getLocation().getBlockZ())) + .forLocale()); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopContainerWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopContainerWatcher.java index 04b0980f9..bcbec45f3 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopContainerWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopContainerWatcher.java @@ -1,18 +1,18 @@ -//package com.ghostchu.quickshop.watcher; +// package com.ghostchu.quickshop.watcher; // -//import com.ghostchu.quickshop.api.shop.Shop; -//import com.ghostchu.quickshop.shop.ContainerShop; -//import org.bukkit.scheduler.BukkitRunnable; -//import org.jetbrains.annotations.NotNull; +// import com.ghostchu.quickshop.api.shop.Shop; +// import com.ghostchu.quickshop.shop.ContainerShop; +// import org.bukkit.scheduler.BukkitRunnable; +// import org.jetbrains.annotations.NotNull; // -//import java.util.LinkedList; -//import java.util.Queue; +// import java.util.LinkedList; +// import java.util.Queue; // -///** +/// ** // * Check the shops after server booted up, make sure shop can correct self-deleted when container // * lost. // */ -//public class ShopContainerWatcher extends BukkitRunnable { +// public class ShopContainerWatcher extends BukkitRunnable { // private final Queue checkQueue = new LinkedList<>(); // // @Override @@ -35,4 +35,4 @@ // checkQueue.add(shop); // } // -//} +// } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopDataSaveWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopDataSaveWatcher.java index c52719ae5..b72a525e7 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopDataSaveWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/ShopDataSaveWatcher.java @@ -4,9 +4,8 @@ import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.common.util.QuickExecutor; import com.ghostchu.quickshop.util.logger.Log; -import org.bukkit.scheduler.BukkitRunnable; - import java.util.concurrent.CompletableFuture; +import org.bukkit.scheduler.BukkitRunnable; public class ShopDataSaveWatcher extends BukkitRunnable { private final QuickShop plugin; @@ -22,17 +21,21 @@ public class ShopDataSaveWatcher extends BukkitRunnable { Log.debug("Another save task still running!"); return; } - CompletableFuture[] shopsToSaveFuture = plugin.getShopManager().getAllShops().stream().filter(Shop::isDirty) + CompletableFuture[] shopsToSaveFuture = plugin.getShopManager().getAllShops().stream() + .filter(Shop::isDirty) .map(Shop::update) .toArray(CompletableFuture[]::new); saveTask = CompletableFuture.allOf(shopsToSaveFuture) - .thenAcceptAsync((v) -> { - if (shopsToSaveFuture.length != 0) { - Log.debug("Saved " + shopsToSaveFuture.length + " shops in background."); - } - }, QuickExecutor.getShopSaveExecutor()) + .thenAcceptAsync( + (v) -> { + if (shopsToSaveFuture.length != 0) { + Log.debug("Saved " + shopsToSaveFuture.length + " shops in background."); + } + }, + QuickExecutor.getShopSaveExecutor()) .exceptionally(e -> { - plugin.logger().warn("Error while saving shops, all failed shops will attempt save again in next time", e); + plugin.logger() + .warn("Error while saving shops, all failed shops will attempt save again in next time", e); return null; }); } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/SignUpdateWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/SignUpdateWatcher.java index 31ea47d4e..caf5dcab9 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/SignUpdateWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/SignUpdateWatcher.java @@ -2,12 +2,11 @@ package com.ghostchu.quickshop.watcher; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.shop.Shop; -import org.bukkit.scheduler.BukkitRunnable; -import org.jetbrains.annotations.NotNull; - import java.time.Instant; import java.util.LinkedList; import java.util.Queue; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; public class SignUpdateWatcher extends BukkitRunnable { private final Queue signUpdateQueue = new LinkedList<>(); @@ -29,5 +28,4 @@ public class SignUpdateWatcher extends BukkitRunnable { } signUpdateQueue.add(shop); } - } diff --git a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/UpdateWatcher.java b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/UpdateWatcher.java index 71a1ee5fd..6f87fd748 100644 --- a/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/UpdateWatcher.java +++ b/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/watcher/UpdateWatcher.java @@ -3,6 +3,8 @@ package com.ghostchu.quickshop.watcher; import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.util.MsgUtil; import com.ghostchu.quickshop.util.Util; +import java.util.List; +import java.util.Random; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; @@ -16,34 +18,57 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.scheduler.BukkitTask; -import java.util.List; -import java.util.Random; - public class UpdateWatcher implements Listener { private final Random random = new Random(); private final QuickShop plugin = QuickShop.getInstance(); private BukkitTask cronTask = null; public void init() { - cronTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin.getJavaPlugin(), () -> { - if (!plugin.getNexusManager().isLatest()) { - plugin.logger().info("A new version of QuickShop has been released! [{}]", plugin.getNexusManager().getLatestVersion()); - plugin.logger().info("Update here: https://modrinth.com/plugin/quickshop-hikari"); - for (Player player : Bukkit.getOnlinePlayers()) { - if (plugin.perm().hasPermission(player, "quickshop.alerts")) { - MsgUtil.sendDirectMessage(player, ChatColor.GREEN + "---------------------------------------------------"); - MsgUtil.sendDirectMessage(player, ChatColor.GREEN + LegacyComponentSerializer.legacySection().serialize(pickRandomMessage(player))); -// MsgUtil.sendDirectMessage(player, ChatColor.GREEN + "Type command " + ChatColor.YELLOW + "/quickshop update" + ChatColor.GREEN + " or click the link below to update QuickShop :)"); - MsgUtil.sendDirectMessage(player, Component.text("https://modrinth.com/plugin/quickshop-hikari").color(NamedTextColor.AQUA).clickEvent(ClickEvent.openUrl("https://modrinth.com/plugin/quickshop-hikari"))); - MsgUtil.sendDirectMessage(player, ChatColor.GREEN + "---------------------------------------------------"); - } - } - } - }, 1, 20L * 60L * 60L); + cronTask = Bukkit.getScheduler() + .runTaskTimerAsynchronously( + plugin.getJavaPlugin(), + () -> { + if (!plugin.getNexusManager().isLatest()) { + plugin.logger() + .info( + "A new version of QuickShop has been released! [{}]", + plugin.getNexusManager().getLatestVersion()); + plugin.logger().info("Update here: https://modrinth.com/plugin/quickshop-hikari"); + for (Player player : Bukkit.getOnlinePlayers()) { + if (plugin.perm().hasPermission(player, "quickshop.alerts")) { + MsgUtil.sendDirectMessage( + player, + ChatColor.GREEN + + "---------------------------------------------------"); + MsgUtil.sendDirectMessage( + player, + ChatColor.GREEN + + LegacyComponentSerializer.legacySection() + .serialize(pickRandomMessage(player))); + // MsgUtil.sendDirectMessage(player, ChatColor.GREEN + + // "Type command " + ChatColor.YELLOW + "/quickshop update" + ChatColor.GREEN + + // " or click the link below to update QuickShop :)"); + MsgUtil.sendDirectMessage( + player, + Component.text("https://modrinth.com/plugin/quickshop-hikari") + .color(NamedTextColor.AQUA) + .clickEvent(ClickEvent.openUrl( + "https://modrinth.com/plugin/quickshop-hikari"))); + MsgUtil.sendDirectMessage( + player, + ChatColor.GREEN + + "---------------------------------------------------"); + } + } + } + }, + 1, + 20L * 60L * 60L); } private Component pickRandomMessage(CommandSender sender) { - List messages = plugin.text().ofList(sender, "updatenotify.list").forLocale(); + List messages = + plugin.text().ofList(sender, "updatenotify.list").forLocale(); int notifyNum = -1; if (messages.size() > 1) { notifyNum = random.nextInt(messages.size()); @@ -54,19 +79,28 @@ public class UpdateWatcher implements Listener { } else { notify = Component.text("New update {0} now available! Please update!"); } - return MsgUtil.fillArgs(notify, Component.text(plugin.getNexusManager().getLatestVersion()), Component.text(plugin.getVersion())); + return MsgUtil.fillArgs( + notify, + Component.text(plugin.getNexusManager().getLatestVersion()), + Component.text(plugin.getVersion())); } @EventHandler public void playerJoin(PlayerJoinEvent e) { Util.asyncThreadRun(() -> { - if (!plugin.perm().hasPermission(e.getPlayer(), "quickshop.alerts") || plugin.getNexusManager().isLatest()) { + if (!plugin.perm().hasPermission(e.getPlayer(), "quickshop.alerts") + || plugin.getNexusManager().isLatest()) { return; } - MsgUtil.sendDirectMessage(e.getPlayer(), ChatColor.GREEN + "---------------------------------------------------"); - MsgUtil.sendDirectMessage(e.getPlayer(), ChatColor.GREEN + LegacyComponentSerializer.legacySection().serialize(pickRandomMessage(e.getPlayer()))); + MsgUtil.sendDirectMessage( + e.getPlayer(), ChatColor.GREEN + "---------------------------------------------------"); + MsgUtil.sendDirectMessage( + e.getPlayer(), + ChatColor.GREEN + + LegacyComponentSerializer.legacySection().serialize(pickRandomMessage(e.getPlayer()))); MsgUtil.sendDirectMessage(e.getPlayer(), ChatColor.AQUA + " https://modrinth.com/plugin/quickshop-hikari"); - MsgUtil.sendDirectMessage(e.getPlayer(), ChatColor.GREEN + "---------------------------------------------------"); + MsgUtil.sendDirectMessage( + e.getPlayer(), ChatColor.GREEN + "---------------------------------------------------"); }); } diff --git a/quickshop-common/.gitignore b/quickshop-common/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/quickshop-common/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/quickshop-common/pom.xml b/quickshop-common/pom.xml deleted file mode 100644 index 278305db8..000000000 --- a/quickshop-common/pom.xml +++ /dev/null @@ -1,178 +0,0 @@ - - - - quickshop-hikari - com.ghostchu - 5.2.0.7 - - 4.0.0 - - quickshop-common - - - 17 - 17 - - - - - org.apache.commons - commons-lang3 - 3.14.0 - compile - - - org.slf4j - slf4j-jdk14 - 2.0.9 - compile - - - com.google.code.gson - gson - 2.10.1 - compile - - - com.ghostchu - simplereloadlib - compile - 1.1.2 - - - cc.carm.lib - easysql-hikaricp - compile - 0.4.7 - - - org.apache.commons - commons-text - compile - 1.11.0 - - - org.apache.commons - commons-compress - compile - 1.25.0 - - - net.kyori - adventure-api - compile - 4.14.0 - - - net.kyori - adventure-key - compile - 4.14.0 - - - net.kyori - adventure-nbt - compile - 4.14.0 - - - net.kyori - adventure-platform-api - compile - 4.3.1 - - - net.kyori - adventure-platform-bukkit - compile - 4.3.1 - - - net.kyori - adventure-platform-facet - compile - 4.3.1 - - - net.kyori - adventure-platform-viaversion - compile - 4.3.1 - - - net.kyori - adventure-serializer-configurate4 - compile - 4.14.0 - - - net.kyori - adventure-text-logger-slf4j - compile - 4.14.0 - - - net.kyori - adventure-text-minimessage - compile - 4.14.0 - - - net.kyori - adventure-text-serializer-ansi - compile - 4.14.0 - - - net.kyori - adventure-text-serializer-bungeecord - compile - 4.3.1 - - - net.kyori - adventure-text-serializer-gson-legacy-impl - compile - 4.14.0 - - - net.kyori - adventure-text-serializer-json - compile - 4.14.0 - - - net.kyori - adventure-text-serializer-json-legacy-impl - compile - 4.14.0 - - - net.kyori - adventure-text-serializer-legacy - compile - 4.14.0 - - - net.kyori - adventure-text-serializer-plain - compile - 4.14.0 - - - net.kyori - examination-api - compile - 1.3.0 - - - net.kyori - examination-string - compile - 1.3.0 - - - - \ No newline at end of file diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CalculateUtil.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CalculateUtil.java index bf4909fca..4949a5792 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CalculateUtil.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CalculateUtil.java @@ -12,8 +12,7 @@ public final class CalculateUtil { private static final MathContext MATH_CONTEXT = MathContext.DECIMAL32; - private CalculateUtil() { - } + private CalculateUtil() {} public static double add(double number1, double number2) { return (BigDecimal.valueOf(number1).add(BigDecimal.valueOf(number2), MATH_CONTEXT)).doubleValue(); @@ -30,6 +29,4 @@ public final class CalculateUtil { public static double subtract(double number1, double number2) { return (BigDecimal.valueOf(number1).subtract(BigDecimal.valueOf(number2), MATH_CONTEXT)).doubleValue(); } - - } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CommonUtil.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CommonUtil.java index f393242d4..1a695615d 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CommonUtil.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/CommonUtil.java @@ -3,12 +3,6 @@ package com.ghostchu.quickshop.common.util; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.*; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -19,10 +13,14 @@ import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.time.DateFormatUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class CommonUtil { - private CommonUtil() { - } + private CommonUtil() {} /** * Convert strArray to String. E.g "Foo, Bar" @@ -119,7 +117,8 @@ public class CommonUtil { */ @NotNull public static String getClassPathRelative(@NotNull Class clazz) { - String jarPath = clazz.getProtectionDomain().getCodeSource().getLocation().getFile(); + String jarPath = + clazz.getProtectionDomain().getCodeSource().getLocation().getFile(); jarPath = URLDecoder.decode(jarPath, StandardCharsets.UTF_8); File file = new File(jarPath); return getRelativePath(new File("."), file); @@ -189,11 +188,11 @@ public class CommonUtil { // http://www.java2s.com/Tutorials/Java/Data_Type_How_to/Date_Convert/Convert_long_type_timestamp_to_LocalDate_and_LocalDateTime.htm public static @NotNull LocalDateTime getDateTimeFromTimestamp(long timestamp) { if (timestamp == 0) { - return LocalDateTime.ofInstant(Instant.ofEpochMilli(0), TimeZone - .getDefault().toZoneId()); + return LocalDateTime.ofInstant( + Instant.ofEpochMilli(0), TimeZone.getDefault().toZoneId()); } - return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone - .getDefault().toZoneId()); + return LocalDateTime.ofInstant( + Instant.ofEpochMilli(timestamp), TimeZone.getDefault().toZoneId()); } /** @@ -278,7 +277,6 @@ public class CommonUtil { } } - public static UUID fromTrimmedUUID(@NotNull String trimmedUUID) { StringBuilder builder = new StringBuilder(trimmedUUID.trim()); /* Backwards adding to avoid index adjustments */ @@ -302,7 +300,6 @@ public class CommonUtil { return processors; } - public static boolean isJson(String str) { if (str == null || str.isBlank()) { return false; @@ -388,7 +385,8 @@ public class CommonUtil { StringBuilder sb = new StringBuilder(); for (int i = 0; i < nameParts.length; i++) { if (!nameParts[i].isEmpty()) { - sb.append(Character.toUpperCase(nameParts[i].charAt(0))).append(nameParts[i].substring(1).toLowerCase()); + sb.append(Character.toUpperCase(nameParts[i].charAt(0))) + .append(nameParts[i].substring(1).toLowerCase()); } if (i + 1 != nameParts.length) { sb.append(" "); @@ -470,7 +468,8 @@ public class CommonUtil { */ @NotNull public static String getClassPath(@NotNull Class clazz) { - String jarPath = clazz.getProtectionDomain().getCodeSource().getLocation().getFile(); + String jarPath = + clazz.getProtectionDomain().getCodeSource().getLocation().getFile(); jarPath = URLDecoder.decode(jarPath, StandardCharsets.UTF_8); return jarPath; } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/GrabConcurrentTask.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/GrabConcurrentTask.java index 7269db8c7..42cafe890 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/GrabConcurrentTask.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/GrabConcurrentTask.java @@ -1,8 +1,5 @@ package com.ghostchu.quickshop.common.util; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -12,6 +9,8 @@ import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.function.Supplier; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class GrabConcurrentTask { private final LinkedBlockingDeque> deque = new LinkedBlockingDeque<>(); @@ -29,7 +28,8 @@ public class GrabConcurrentTask { } @Nullable - public T invokeAll(String executeName, long timeout, @NotNull TimeUnit unit, @Nullable Predicate condition) throws InterruptedException { + public T invokeAll(String executeName, long timeout, @NotNull TimeUnit unit, @Nullable Predicate condition) + throws InterruptedException { // Submit all tasks into executor for (Supplier supplier : suppliers) { service.submit(new GrabConcurrentExecutor<>(executeName, deque, supplier)); @@ -63,7 +63,10 @@ public class GrabConcurrentTask { private final Supplier supplier; private final String executeName; - public GrabConcurrentExecutor(@NotNull String executeName, @NotNull LinkedBlockingDeque> targetDeque, @NotNull Supplier supplier) { + public GrabConcurrentExecutor( + @NotNull String executeName, + @NotNull LinkedBlockingDeque> targetDeque, + @NotNull Supplier supplier) { this.executeName = executeName; this.targetDeque = targetDeque; this.supplier = supplier; @@ -83,11 +86,10 @@ public class GrabConcurrentTask { @Override public String toString() { - return "GrabConcurrentExecutor{" + - "targetDeque=" + targetDeque + - ", supplier=" + supplier + - ", executeName='" + executeName + '\'' + - '}'; + return "GrabConcurrentExecutor{" + "targetDeque=" + + targetDeque + ", supplier=" + + supplier + ", executeName='" + + executeName + '\'' + '}'; } } } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/JsonUtil.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/JsonUtil.java index 6c67ec5ec..39d18e937 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/JsonUtil.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/JsonUtil.java @@ -1,11 +1,9 @@ package com.ghostchu.quickshop.common.util; import com.google.gson.*; -import org.jetbrains.annotations.NotNull; - import java.io.Reader; import java.util.Objects; - +import org.jetbrains.annotations.NotNull; /** * Utilities to prevent create Gson object in other place and reuse gson object in runtime @@ -94,9 +92,7 @@ public final class JsonUtil { prettyPrinting().toJson(object, writer); } - public @interface Hidden { - - } + public @interface Hidden {} public static class HiddenAnnotationExclusionStrategy implements ExclusionStrategy { @Override @@ -109,5 +105,4 @@ public final class JsonUtil { return clazz.getDeclaredAnnotation(Hidden.class) != null; } } - } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickExecutor.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickExecutor.java index efba04e21..8c6f5551e 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickExecutor.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickExecutor.java @@ -4,17 +4,20 @@ import java.util.concurrent.*; public class QuickExecutor { - private static final ExecutorService DATABASE_EXECUTOR = new ThreadPoolExecutor(2, 16, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); + private static final ExecutorService DATABASE_EXECUTOR = + new ThreadPoolExecutor(2, 16, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); - private static final ExecutorService SHOP_SAVE_EXECUTOR = new ThreadPoolExecutor(0, 16, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); + private static final ExecutorService SHOP_SAVE_EXECUTOR = + new ThreadPoolExecutor(0, 16, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); private static final ExecutorService COMMON_EXECUTOR = Executors.newCachedThreadPool(); private static final BlockingQueue PRIMARY_PROFILE_IO_QUEUE = new LinkedBlockingDeque<>(); - private static ExecutorService PRIMARY_PROFILE_IO_EXECUTOR = new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, PRIMARY_PROFILE_IO_QUEUE); + private static ExecutorService PRIMARY_PROFILE_IO_EXECUTOR = + new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, PRIMARY_PROFILE_IO_QUEUE); private static final BlockingQueue SECONDARY_PROFILE_IO_QUEUE = new LinkedBlockingDeque<>(); - private static ExecutorService SECONDARY_PROFILE_IO_EXECUTOR = new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, SECONDARY_PROFILE_IO_QUEUE); + private static ExecutorService SECONDARY_PROFILE_IO_EXECUTOR = + new ThreadPoolExecutor(2, 32, 60L, TimeUnit.SECONDS, SECONDARY_PROFILE_IO_QUEUE); - private QuickExecutor() { - } + private QuickExecutor() {} public static ExecutorService getCommonExecutor() { return COMMON_EXECUTOR; @@ -48,7 +51,6 @@ public class QuickExecutor { return SECONDARY_PROFILE_IO_QUEUE; } - public static void setSecondaryProfileIoExecutor(ExecutorService secondaryProfileIoExecutor) { SECONDARY_PROFILE_IO_EXECUTOR = secondaryProfileIoExecutor; } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickSLF4JLogger.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickSLF4JLogger.java index a98fe3a25..1715c2077 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickSLF4JLogger.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/QuickSLF4JLogger.java @@ -1,11 +1,10 @@ package com.ghostchu.quickshop.common.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.jul.JDK14LoggerAdapter; - import java.lang.reflect.Constructor; import java.util.logging.Level; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.jul.JDK14LoggerAdapter; public class QuickSLF4JLogger { diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/RomanNumber.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/RomanNumber.java index ab708b084..ee32e6a4b 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/RomanNumber.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/RomanNumber.java @@ -25,8 +25,7 @@ public class RomanNumber { MAP.put(1, "I"); } - private RomanNumber() { - } + private RomanNumber() {} public static String toRoman(Integer number) { return toRoman(number == null ? 1 : number); @@ -42,5 +41,4 @@ public class RomanNumber { } return MAP.get(l) + toRoman(number - l); } - } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/Timer.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/Timer.java index 9c6f4379b..903745de4 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/Timer.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/Timer.java @@ -3,7 +3,6 @@ package com.ghostchu.quickshop.common.util; import lombok.EqualsAndHashCode; import lombok.ToString; - /** * Simple Timer for QuickShop to calc time passed (timestamp based) * @@ -13,15 +12,16 @@ import lombok.ToString; @ToString public class Timer { private long startTime; + @EqualsAndHashCode.Exclude private long passedTime; + private boolean isPaused = false; /** * Create a empty timer, use setTimer to start */ - public Timer() { - } + public Timer() {} /** * Create a empty timer, auto start if autoStart is true @@ -103,5 +103,4 @@ public class Timer { startTime = 0; return time; } - } diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/UrlEncoderDecoder.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/UrlEncoderDecoder.java index 5880c75ae..aa0e92cec 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/UrlEncoderDecoder.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/UrlEncoderDecoder.java @@ -11,8 +11,11 @@ import java.util.BitSet; */ @SuppressWarnings("all") public class UrlEncoderDecoder { - private static final BitSet safeCharacters; //http://www.java2s.com/Code/Java/Network-Protocol/ProvidesamethodtoencodeanystringintoaURLsafeform.htm - private static final char[] hexadecimal = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + private static final BitSet + safeCharacters; // http://www.java2s.com/Code/Java/Network-Protocol/ProvidesamethodtoencodeanystringintoaURLsafeform.htm + private static final char[] hexadecimal = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; static { safeCharacters = new BitSet(256); @@ -70,7 +73,6 @@ public class UrlEncoderDecoder { return decodePath.toString(StandardCharsets.UTF_8); } - /** * Encode a path as required by the URL specification ( * RFC 1738). This differs from java.net.URLEncoder.encode() which encodes according @@ -125,7 +127,6 @@ public class UrlEncoderDecoder { return rewrittenPath.toString(); } - public static String encodeToLegalPath(String path) { int maxBytesPerChar = 10; StringBuilder rewrittenPath = new StringBuilder(path.length()); @@ -140,7 +141,7 @@ public class UrlEncoderDecoder { for (int i = 0; i < path.length(); i++) { int c = path.charAt(i); - if (safeCharacters.get(c) || (char) c == '%') { //其實只加了這一小行,讓已經被encode的值不要再被encode了 + if (safeCharacters.get(c) || (char) c == '%') { // 其實只加了這一小行,讓已經被encode的值不要再被encode了 rewrittenPath.append((char) c); } else { try { diff --git a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/jacky/ResultSetToJson.java b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/jacky/ResultSetToJson.java index 8909328d6..9fe7220f7 100644 --- a/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/jacky/ResultSetToJson.java +++ b/quickshop-common/src/main/java/com/ghostchu/quickshop/common/util/jacky/ResultSetToJson.java @@ -2,18 +2,16 @@ package com.ghostchu.quickshop.common.util.jacky; import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import org.jetbrains.annotations.NotNull; - import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; +import org.jetbrains.annotations.NotNull; /** * @author jackypan1989 (...) */ public class ResultSetToJson { - private ResultSetToJson() { - } + private ResultSetToJson() {} @NotNull public static JsonArray resultSetToJsonArray(@NotNull ResultSet rs) { @@ -60,5 +58,4 @@ public class ResultSetToJson { } return jo; } - } diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 000000000..b254b4359 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,38 @@ +rootProject.name = "Quickshop-OG" + +// Run the bootstrap at configuration time. +val process = ProcessBuilder("sh", "bootstrap.sh").directory(rootDir).start() + +val exitValue = process.waitFor() + +if (exitValue != 0) { + throw GradleException("bootstrap.sh failed with exit code $exitValue") +} + +include( + "libs:Utilities-OG", + "quickshop-common", + "quickshop-api", + + "platform:quickshop-platform-interface", + "platform:quickshop-platform-spigot-abstract", + "platform:quickshop-platform-spigot-v1_19_R1", + "platform:quickshop-platform-spigot-v1_19_R2", + "platform:quickshop-platform-spigot-v1_19_R3", + "platform:quickshop-platform-paper", + + "quickshop-bukkit", + + "compatibility:common", + "compatibility:clearlag", + "compatibility:nocheatplus", + "compatibility:worldguard", + "compatibility:worldedit", + "compatibility:openinv", + + "addon:discount", + "addon:list", + "addon:shopitemonly", + "addon:bluemap", +) +