diff --git a/.default.docker.env b/.default.docker.env new file mode 100644 index 00000000..01ee4f28 --- /dev/null +++ b/.default.docker.env @@ -0,0 +1,5 @@ +# Set default Sonarqube environment variables used by docker-compose +# You can override these envvars by creating a '.override.docker.env' file +# For available envvars list, see https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/configure-and-operate-a-server/environment-variables/ + +SONAR_LOG_LEVEL_WEB=INFO diff --git a/.gitattributes b/.gitattributes index 12b960c4..62749323 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,7 +1,12 @@ # Ensure all SH files are checked out with LF line endings (regardless of the # OS they were checked out on). *.sh text eol=lf +mvnw text eol=lf # Ensure BAT files will always be checked out with CRLFs (regardless of the # OS they were checked out on). -*.bat text eol=crlf \ No newline at end of file +*.bat text eol=crlf + +# Ensure BAT files will always be checked out with CRLFs (regardless of the +# OS they were checked out on). +*.cmd text eol=crlf diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..cde26d47 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "maven" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" + ignore: + # Ignore all versions : cf pom.xml comments + - dependency-name: "com.mycila:license-maven-plugin" + - dependency-name: "org.springframework.data:spring-data-commons" + - dependency-name: "org.springframework:spring-context" + - dependency-name: "org.sonarsource.api.plugin:sonar-plugin-api" diff --git a/.github/workflows/_BACKUP_manual_release.yml b/.github/workflows/_BACKUP_manual_release.yml deleted file mode 100644 index 90818a55..00000000 --- a/.github/workflows/_BACKUP_manual_release.yml +++ /dev/null @@ -1,91 +0,0 @@ -name: Manual Release -on: - workflow_dispatch: - inputs: - confirmeRelease: - description: 'Confirm manual release creation (by typing "true") ? ----- WARNING : check version (in pom.xml files) and release notes (in CHANGELOG.md file) before confirm' - default: 'false' -jobs: - checks: - name: Requirements - if: github.event.inputs.confirmeRelease == 'true' - runs-on: ubuntu-latest - steps: - - name: Check user permissions - uses: 74th/workflow-permission-action@1.0.0 - with: - users: dedece35,glalloue,jhertout,jules-delecour-dav,olegoaer,zippy1978 - build: - name: Build And Release - needs: checks - runs-on: ubuntu-latest - permissions: write-all - outputs: - last_tag: ${{ steps.export_last_tag.outputs.last_tag }} - upload_url: ${{ steps.export_upload_url.outputs.upload_url }} - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Change commiter - run: | - git config user.name 'github-actions[bot]' - git config user.email '' - - name: Maven release - run: mvn release:prepare -B -ff -DtagNameFormat=@{project.version} - - name: Maven release clean - run: mvn release:clean - - name: Get last TAG - run: echo "LAST_TAG=$(git tag --sort=-version:refname | head -n 1)" >> $GITHUB_ENV - - name: Extract release notes - id: extract-release-notes - uses: ffurrer2/extract-release-notes@v1 - - name: Checkout tag "${{ env.LAST_TAG }}" - uses: actions/checkout@v3 - with: - ref: ${{ env.LAST_TAG }} - - name: Build project - run: mvn -e -B clean package -DskipTests - - name: Create release - id: create_release - uses: actions/create-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{ env.LAST_TAG }} - release_name: Release ${{ env.LAST_TAG }} - draft: false - prerelease: false - body: ${{ steps.extract-release-notes.outputs.release_notes }} - - name: Export plugin Jar files - id: export_jar_files - uses: actions/upload-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Export LAST_TAG - id: export_last_tag - run: echo "last_tag=${{ env.LAST_TAG }}" >> $GITHUB_OUTPUT - - name: Export UPLOAD_URL - id: export_upload_url - run: echo "upload_url=${{ steps.create_release.outputs.upload_url }}" >> $GITHUB_OUTPUT - upload-java: - name: Upload Java Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - Java Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-java-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_name: ecocode-java-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_content_type: application/zip diff --git a/.github/workflows/build-jdk17.yml b/.github/workflows/build-jdk17.yml new file mode 100644 index 00000000..ac698016 --- /dev/null +++ b/.github/workflows/build-jdk17.yml @@ -0,0 +1,34 @@ +name: Build and Tests for JDK 17 + +on: + push: + branches: + - main + paths-ignore: + - "*.md" + tags: + - "[0-9]+.[0-9]+.[0-9]+" + pull_request: + types: [opened, synchronize, reopened] + +jobs: + build: + name: Build + runs-on: ubuntu-latest + permissions: + pull-requests: read # allows SonarCloud to decorate PRs with analysis results + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + - name: Set up JDK 17 + uses: actions/setup-java@v5 + with: + distribution: "temurin" + java-version: 17 + cache: maven + + - name: Verify + run: ./mvnw -e -B verify -Dtest-it.sonarqube.version=24.12.0.100206 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 60db5ba0..63d9e84b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,16 +1,15 @@ -name: Build and Tests +name: Build, Tests and check SonarQube on: push: branches: - main paths-ignore: - - '*.md' - - '.github/**/*.yml' + - "*.md" tags: - - '[0-9]+.[0-9]+.[0-9]+' + - "[0-9]+.[0-9]+.[0-9]+" pull_request: - types: [ opened, synchronize, reopened ] + types: [opened, synchronize, reopened] jobs: build: @@ -20,41 +19,40 @@ jobs: pull-requests: read # allows SonarCloud to decorate PRs with analysis results steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Set up JDK 11 - uses: actions/setup-java@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v5 with: - distribution: 'temurin' - java-version: 11 + distribution: "temurin" + java-version: 21 + cache: maven - - name: Cache Maven packages - uses: actions/cache@v3 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - - name: Verify - run: mvn -e -B verify - - - name: Set up JDK 17 - uses: actions/setup-java@v3 - with: - distribution: 'temurin' - java-version: 17 + - name: Configure Maven for Sonar + run: | + mkdir -p ~/.m2 + echo "org.sonarsource.scanner.maven" > ~/.m2/settings.xml - name: Cache SonarQube packages - uses: actions/cache@v3 + uses: actions/cache@v5 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar + - name: Verify + run: ./mvnw -e -B verify + - name: SonarQube Scan + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -e -B org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=green-code-initiative_ecoCode-java + run: | + if [ -z "$SONAR_TOKEN" ]; then + echo "⚠️ SONAR_TOKEN is not set (Dependabot PR or external fork). Skipping SonarQube scan." + else + ./mvnw -e -B sonar:sonar -Dsonar.projectKey=green-code-initiative_creedengo-java -Dsonar.organization=green-code-initiative + fi diff --git a/.github/workflows/build_container.yml b/.github/workflows/build_container.yml index eda94a3e..d5bb22c4 100644 --- a/.github/workflows/build_container.yml +++ b/.github/workflows/build_container.yml @@ -2,24 +2,24 @@ # template source: https://github.com/bretfisher/docker-build-workflow/blob/main/templates/call-docker-build.yaml name: Docker Build -on: - push: - branches: - - main - tags: - - '*' - # pull_request: - # branches: - # - main +#on: +# push: +# branches: +# - main +# tags: +# - '*' +# # pull_request: +# # branches: +# # - main env: # github.repository as / -# IMAGE_NAME: sonarqube-ecocode +# IMAGE_NAME: sonarqube-creedengo # IMAGES: | -# ghcr.io/${{ github.repository_owner }}/sonarqube-ecocode - IMAGE_NAME: sonarqube-ecocode-java +# ghcr.io/${{ github.repository_owner }}/sonarqube-creedengo + IMAGE_NAME: sonarqube-creedengo-java IMAGES: | - ghcr.io/${{ github.repository_owner }}/sonarqube-ecocode-java + ghcr.io/${{ github.repository_owner }}/sonarqube-creedengo-java jobs: Build: @@ -34,26 +34,26 @@ jobs: steps: - name: Login to GitHub Container Registry - uses: docker/login-action@v2 + uses: docker/login-action@v4 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: Set up QEMU - uses: docker/setup-qemu-action@v2 + uses: docker/setup-qemu-action@v4 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v4 - name: Docker metadata id: meta - uses: docker/metadata-action@v4 + uses: docker/metadata-action@v6 with: github-token: ${{ secrets.GITHUB_TOKEN }} images: ${{ env.IMAGES }} @@ -70,7 +70,7 @@ jobs: - name: Publish image id: push - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v7 with: push: true tags: ${{ steps.meta.outputs.tags }} diff --git a/.github/workflows/stale_tag.yml b/.github/workflows/stale_tag.yml index 4c7a9ff9..75db955f 100644 --- a/.github/workflows/stale_tag.yml +++ b/.github/workflows/stale_tag.yml @@ -7,8 +7,11 @@ on: jobs: stale: runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write steps: - - uses: actions/stale@v8.0.0 + - uses: actions/stale@v10 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-issue-stale: -1 # We don't want to address issues diff --git a/.github/workflows/tag_release.yml b/.github/workflows/tag_release.yml index b405ace1..572af966 100644 --- a/.github/workflows/tag_release.yml +++ b/.github/workflows/tag_release.yml @@ -1,74 +1,90 @@ name: Tag Release on: - push: - tags: - - '[0-9]+.[0-9]+.[0-9]+' + #push: + # tags: + # - '[0-9]+.[0-9]+.[0-9]+' + workflow_dispatch: + inputs: + tag: + description: 'Release tag to deploy (e.g. 2.3.0). Leave empty to use the latest available tag.' + required: false + type: string jobs: checks: name: Requirements runs-on: ubuntu-latest + permissions: + contents: read steps: - name: Check user permissions - uses: 74th/workflow-permission-action@1.0.0 + uses: 74th/workflow-permission-action@61b695d54d72c612459668d29fca41281a0f49d4 # v1.0.0 with: - users: dedece35,glalloue,jhertout,jules-delecour-dav,olegoaer,zippy1978,utarwyn + users: dedece35,glalloue,jhertout,olegoaer,zippy1978,utarwyn build: name: Build And Release runs-on: ubuntu-latest needs: checks - outputs: - upload_url: ${{ steps.create_release.outputs.upload_url }} + permissions: + contents: write steps: - - name: Checkout tag "${{ github.ref_name }}" - uses: actions/checkout@v3 + - name: Checkout repository + uses: actions/checkout@v6 with: - ref: ${{ github.ref_name }} + fetch-depth: 0 + + - name: Resolve release tag + id: resolve_tag + env: + INPUT_TAG: ${{ inputs.tag }} + run: | + if [ -n "$INPUT_TAG" ]; then + RELEASE_TAG="$INPUT_TAG" + else + RELEASE_TAG=$(git tag --sort=-version:refname | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1) + fi + if [ -z "$RELEASE_TAG" ]; then + echo "No tag found. Please specify one as input." + exit 1 + fi + echo "Tag used: $RELEASE_TAG" + echo "release_tag=$RELEASE_TAG" >> $GITHUB_ENV + + - name: Checkout tag "${{ env.release_tag }}" + uses: actions/checkout@v6 + with: + ref: ${{ env.release_tag }} + - name: Extract release notes id: extract-release-notes - uses: ffurrer2/extract-release-notes@v1 + uses: ffurrer2/extract-release-notes@273da39a24fb7db106a35526c8162815faffd31d # v3.1.0 + - name: Build project - run: mvn -e -B clean package -DskipTests - - name: Create release - id: create_release - uses: actions/create-release@v1 env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # the plugin maven-release-plugin uses the environment variable VERSIONING_GIT_REF to determine the version to use when building the project. + # By setting this variable to refs/tags/${{ env.release_tag }}, we are telling the plugin to use the specified tag as the project version. + VERSIONING_GIT_REF: refs/tags/${{ env.release_tag }} + run: mvn -e -B clean package -DskipTests -Drevision=${{ env.release_tag }} + + - name: Resolve JAR filename + id: resolve_jar + run: | + JAR_FILE=$(ls target/creedengo-java-plugin-*.jar | grep -v original | head -n 1) + if [ -z "$JAR_FILE" ]; then + echo "No JAR found in target/" + exit 1 + fi + echo "JAR found: $JAR_FILE" + echo "jar_path=$JAR_FILE" >> $GITHUB_ENV + + - name: Create release and upload asset + uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0 with: - tag_name: ${{ github.ref_name }} - release_name: Release ${{ github.ref_name }} + tag_name: ${{ env.release_tag }} + name: Release ${{ env.release_tag }} + body: ${{ steps.extract-release-notes.outputs.release_notes }} + generate_release_notes: true draft: false prerelease: false - body: ${{ steps.extract-release-notes.outputs.release_notes }} - - name: Export plugin Jar files - id: export_jar_files - uses: actions/upload-artifact@v3 - with: - name: ecocode-plugins - path: target - - name: Export UPLOAD_URL - id: export_upload_url - run: echo "upload_url=${{ steps.create_release.outputs.upload_url }}" >> $GITHUB_OUTPUT - - upload: - name: Upload Java Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: target - - name: Upload Release Asset - Java Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: target/ecocode-java-plugin-${{ github.ref_name }}.jar - asset_name: ecocode-java-plugin-${{ github.ref_name }}.jar - asset_content_type: application/zip + files: ${{ env.jar_path }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 67cc592c..3633a5cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,10 @@ # Ignore all files and folders starting with ".", except a few exceptions .* +!.mvn/ !.gitignore !.gitattributes !.github/ +!.default.docker.env # Ignore generated files target diff --git a/.mvn/extensions.xml b/.mvn/extensions.xml new file mode 100644 index 00000000..094fe108 --- /dev/null +++ b/.mvn/extensions.xml @@ -0,0 +1,7 @@ + + + me.qoomon + maven-git-versioning-extension + 9.11.0 + + diff --git a/.mvn/maven-git-versioning-extension.xml b/.mvn/maven-git-versioning-extension.xml new file mode 100644 index 00000000..071e3ab1 --- /dev/null +++ b/.mvn/maven-git-versioning-extension.xml @@ -0,0 +1,18 @@ + + + + .+ + ${ref}-SNAPSHOT + + + + \d+\.\d+\.\d+.*)$]]> + ${ref.version} + + + + + + ${commit} + + diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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/CHANGELOG.md b/CHANGELOG.md index b859fc04..107e0292 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,23 +9,117 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#12](https://github.com/green-code-initiative/ecoCode-java/issues/12) Add support for SonarQube 10.4 "DownloadOnlyWhenRequired" feature +### Changed + +- compatibility updates for SonarQube up to 26.7.0 +- update default CI JDK from 17 to 21 +- upgrade internal librairies versions +- add CI check for JDK17 and JDK21 +- [#198](https://github.com/green-code-initiative/creedengo-java/pull/198) GCI82 : fix rule to handle record types and adjust test cases +- [#199](https://github.com/green-code-initiative/creedengo-java/pull/199) GCI82 : fix rule to handle Lombok generated setters (`@Setter`, `@Data`, `@Setter(AccessLevel.NONE)`), including fully qualified annotations used without any `lombok` import +- [#200](https://github.com/green-code-initiative/creedengo-java/pull/200) GCI82 : fix rule to accept instanceof pattern +- [#201](https://github.com/green-code-initiative/creedengo-java/pull/201) GCI82 : fix rule on abstract methods + +### Deleted + +## [2.2.0] - 2026-06-16 ### Changed +- [#119](https://github.com/green-code-initiative/creedengo-java/issues/119) GCI94 - reduce false positives: rule no longer flags `orElse()` when argument is a constant, literal, static field or null; detection extended to Optional variables (semantic type check) and to computed arguments nested inside concatenation, ternary or object instantiation +- [#69](https://github.com/green-code-initiative/creedengo-java/issues/69) correction of NullPointer in GCI79 rule + technical refactoring of GCI79 +- update integration tests system to use the new component "creedengo-integration-test" +- compatibility updates for SonarQube up to 26.6.0 +- upgrade internal libraries versions - non retro-compatibility upgrades +- refacto to have all the test files in the same place (for UT and IT), to avoid maintaining 2 test directories +- refacto all test files to add sub-directories for each rule, to be more clear and to be able to add more tests for each rule in the future +- fix integration test system run + fix TI GCI82 +- upgrade delivery process to be dynamic + +## [2.1.2] - 2026-01-11 + +### Changed + +- [#103](https://github.com/green-code-initiative/creedengo-java/pull/103) GCI69 Java : calls to hasMoreElements() and nextElement() methods from java.util.Enumeration interface aren't flagged anymore when called in a for loop +- [#110](https://github.com/green-code-initiative/creedengo-java/pull/110) GCI82 - remove false positives with reassignment using this and with passing a variable to a function it can be reassigned in +- compatibility updates for SonarQube 25.12.0 +- upgrade libraries versions +- correction of technical problem with Integration tests (because of Maven format in technical answer to "sonar-orchestrator-junit5" library) +- upgrade JDK from 11 to 17 +- [#4](https://github.com/green-code-initiative/creedengo-java/issues/4) Improvement: "++i" statement is not so bad + +## [2.1.1] - 2025-03-13 + +### Changed + +- compatibility updates for SonarQube 25.1.0, 25.2.0 and 25.3.0 compatibility +- upgrade creedengo-rules-specifications lib to 2.2.2 + +## [2.1.0] - 2025-01-07 + +### Added + +- [#88](https://github.com/green-code-initiative/creedengo-java/pull/88) Add new Java rule GCI94 - Use orElseGet instead of orElse +- [#89](https://github.com/green-code-initiative/creedengo-java/pull/89) Add new Java rule GCI82 - Make non reassigned variables constants + +### Changed + +- upgrade some libraries versions +- improve Integration Tests system to be more flexible (add new IT for each rule) +- [#21](https://github.com/green-code-initiative/creedengo-java/issues/21) Improvement: some method calls are legitimate in a for loop expression +- check compatibility with SonarQube 10.7.0 and 24.12.0 +- upgrade actions/upload-artifact and actions/download-artifact from v3 to v4) + +## [2.0.0] - 2024-12-18 + +### Added + +- [#59](https://github.com/green-code-initiative/creedengo-java/pull/59) Add builtin profile `ecoCode way` to aggregate all implemented ecoCode rules by this plugin +- [#53](https://github.com/green-code-initiative/creedengo-java/issues/53) Improve integration tests +- Rename rules ECXXX to the new Green Code Initiative naming convention GCIXXX +- migration from ecocode to creedengo - all over the code + +### Changed + +- [#49](https://github.com/green-code-initiative/creedengo-java/pull/49) Add test to ensure all Rules are registered +- [#336](https://github.com/green-code-initiative/creedengo-rules-specifications/issues/336) [Adds Maven Wrapper](https://github.com/green-code-initiative/creedengo-java/pull/67) + +## [1.6.2] - 2024-07-21 + +### Changed + +- [#60](https://github.com/green-code-initiative/creedengo-java/issues/60) Check + update for SonarQube 10.6.0 compatibility +- refactoring docker system +- upgrade ecocode-rules-specifications to 1.6.2 + +## [1.6.1] - 2024-05-15 + +### Changed + +- [#15](https://github.com/green-code-initiative/creedengo-java/issues/15) correction NullPointer in EC2 rule +- check Sonarqube 10.5.1 compatibility + update docker files and README.md + +## [1.6.0] - 2024-02-02 + +### Added + +- [#12](https://github.com/green-code-initiative/creedengo-java/issues/12) Add support for SonarQube 10.4 "DownloadOnlyWhenRequired" feature + ### Deleted +- [#6](https://github.com/green-code-initiative/creedengo-java/pull/6) Delete deprecated java rules EC4, EC53, EC63 and EC75 + ## [1.5.2] - 2024-01-23 ### Changed -- [#9](https://github.com/green-code-initiative/ecoCode-java/issues/9) EC2 rule : correction no block statement use case +- [#9](https://github.com/green-code-initiative/creedengo-java/issues/9) EC2 rule : correction no block statement use case ## [1.5.1] - 2024-01-23 ### Changed -- [#7](https://github.com/green-code-initiative/ecoCode-java/issues/7) EC2 rule : correction NullPointer with interface +- [#7](https://github.com/green-code-initiative/creedengo-java/issues/7) EC2 rule : correction NullPointer with interface ## [1.5.0] - 2024-01-06 @@ -38,7 +132,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Update ecocode-rules-specifications to 1.4.6 -[unreleased](https://github.com/green-code-initiative/ecoCode-java/compare/1.5.2...HEAD) -[1.5.2](https://github.com/green-code-initiative/ecoCode-java/compare/1.5.1...1.5.2) -[1.5.1](https://github.com/green-code-initiative/ecoCode-java/compare/1.5.0...1.5.1) -[1.5.0](https://github.com/green-code-initiative/ecoCode-java/releases/tag/1.5.0) +[unreleased](https://github.com/green-code-initiative/creedengo-java/compare/2.2.0...HEAD) +[2.2.0](https://github.com/green-code-initiative/creedengo-java/compare/2.1.2...2.2.0) +[2.1.2](https://github.com/green-code-initiative/creedengo-java/compare/2.1.1...2.1.2) +[2.1.1](https://github.com/green-code-initiative/creedengo-java/compare/2.1.0...2.1.1) +[2.1.0](https://github.com/green-code-initiative/creedengo-java/compare/2.0.0...2.1.0) +[2.0.0](https://github.com/green-code-initiative/creedengo-java/compare/1.6.2...2.0.0) +[1.6.2](https://github.com/green-code-initiative/creedengo-java/compare/1.6.1...1.6.2) +[1.6.1](https://github.com/green-code-initiative/creedengo-java/compare/1.6.0...1.6.1) +[1.6.0](https://github.com/green-code-initiative/creedengo-java/compare/1.5.2...1.6.0) +[1.5.2](https://github.com/green-code-initiative/creedengo-java/compare/1.5.1...1.5.2) +[1.5.1](https://github.com/green-code-initiative/creedengo-java/compare/1.5.0...1.5.1) +[1.5.0](https://github.com/green-code-initiative/creedengo-java/releases/tag/1.5.0) diff --git a/CODE_STYLE.md b/CODE_STYLE.md index 86b0ab3f..c46ab38c 100644 --- a/CODE_STYLE.md +++ b/CODE_STYLE.md @@ -1 +1 @@ -Please read common [CODE_STYLE.md](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/CODE_STYLE.md) in `ecoCode-common` repository. +Please read common [CODE_STYLE.md](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/CODE_STYLE.md) in `creedengo-common` repository. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77e81dc6..aeeae916 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1 +1 @@ -Please read common [CONTRIBUTING.md](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/CONTRIBUTING.md) in `ecoCode-common` repository. +Please read common [CONTRIBUTING.md](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/CONTRIBUTING.md) in `creedengo-common` repository. diff --git a/Dockerfile b/Dockerfile index 2b336220..00a72653 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,48 @@ -FROM maven:3-openjdk-11-slim AS builder +ARG MAVEN_BUILDER=3-openjdk-17-slim -COPY . /usr/src/ecocode +#ARG SONARQUBE_VERSION=9.9.0-community +#ARG SONARQUBE_VERSION=24.12.0.100206-community +#ARG SONARQUBE_VERSION=25.1.0.102122-community +#ARG SONARQUBE_VERSION=25.2.0.102705-community +#ARG SONARQUBE_VERSION=25.3.0.104237-community +#ARG SONARQUBE_VERSION=25.9.0.112764-community +ARG SONARQUBE_VERSION=25.11.0.114957-community +#ARG SONARQUBE_VERSION=25.12.0.117093-community +#ARG SONARQUBE_VERSION=26.1.0.118079-community + +FROM maven:${MAVEN_BUILDER} AS builder + +COPY . /usr/src/creedengo + +WORKDIR /usr/src/creedengo +COPY src src/ +COPY pom.xml tool_build.sh ./ -WORKDIR /usr/src/ecocode RUN ./tool_build.sh -FROM sonarqube:10.3.0-community -COPY --from=builder /usr/src/ecocode/target/ecocode-*.jar /opt/sonarqube/extensions/plugins/ +FROM sonarqube:${SONARQUBE_VERSION} + +COPY --from=builder /usr/src/creedengo/target/creedengo-*.jar /opt/sonarqube/extensions/plugins/ + +# Install the ca-certificate package +USER root +# RUN apt-get update && apt-get install -y ca-certificates +# Copy SSL certificates to the container +COPY downloads-sonarsource.crt /usr/local/share/ca-certificates/ +# Update SSL certificates in system inside the container +# RUN update-ca-certificates + +## Update SSL certificates in the JDK inside the container +RUN $JAVA_HOME/bin/keytool -import -trustcacerts -file /usr/local/share/ca-certificates/downloads-sonarsource.crt -alias downloads-sonarsource -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt + +## Process manuel +# GENERATION CERTIFICAT +# openssl s_client -showcerts -connect downloads.sonarsource.com:443 /dev/null | openssl x509 > downloads-sonarsource.crt +# COPIE CERTIFICAT SUR CONTENEUR +# dk cp downloads-sonarsource.crt sonar_creedengo_java:/tmp/. +# AJOUT CERTIFICAT DANS LE KEYSTORE (en root) +# dk exec -u root -it sonar_creedengo_java /bin/bash +# $JAVA_HOME/bin/keytool -import -trustcacerts -file /tmp/downloads-sonarsource.crt -alias downloads-sonarsource -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt +# RELANCE CONTENEUR pour relancer le service sonarqube + +USER sonarqube \ No newline at end of file diff --git a/IA_description.md b/IA_description.md new file mode 100644 index 00000000..cb25c3b7 --- /dev/null +++ b/IA_description.md @@ -0,0 +1,88 @@ +This file contains the technical description of the project + +Global description +--- +This project is a SonarQube plugin project and it is named "creedengo-java". +This plugin is for Java project analysis. +When this plugin is installed inside SonarQube, it adds some new rules for Java language analysis. +The new rules can be added to an existing Java quality profile or to a new Java quality profile. +A Sonarqube quality profile must be associated to only one programming language. +A quality profile can be the default quality profile for one language (here Java language), thus +all future Java project analysis will be done by default with this quality profile. +If a quality profile is not the default, a specific project (already analysed) can be associated with this +quality profile. + +Technical description +--- +Important elements of the plugin : +- the plugin contains a list of rule implementations +- each rule has a unique rule id +- each rule is implemented by one class +- there are several tests for each implementation rule class with several ressource files containing compliant code or / and non compliant code + +The implementation code is in src/main/java. + +Sonarqube analysis are based on the navigation inside the code to detect bad practices and to raise an issue when detected. +The code navigation is done through the AST principle. + +Implementation Structure +--- +- rule implementations : inside the package org.greencodeinitiative.creedengo.java.checks +- each implementation class has the same code template : + - "Rule" annotation : to give the rule id + - the rule id is previously defined in another maven component named "creedengo-rules-specifications" + - to enable a rule, the rule id must be added in the resources file named "creedengo_way_profile.json" + - extends a SonarQube API class "IssuableSubscriptionVisitor" + - "initialize" method (forom super-class) to declare for which AST node type, the analysis will deeply analyse the code. + - each "registerSyntaxNodeConsumer" method call implies that the node will be deeply analyzed. + - For each, a new private method is given to implement the deeply analysis and raise an issue if needed. +- to have a plugin working with activated rules, the Sonarqube plugin development guidelines is followed + - "JavaPlugin" : enable 2 following extensions + - "JavaRuleRepository" : extension containing the definition of the plugin and the list of implemented rule classes + - "JavaCreedengoWayProfile" : extension containing the definition a the quality profile (and rules activated inside) created with the plugin installation + +Unit Tests Implementation Structure +--- +Inside the "test/java" directory, there are unit tests for each class of the plugin. +The package "org.greencodeinitiative.creedengo.java.checks" contains one unit test class for each rule implementation class + +Each unit test class checking rule implementation class has the same template of code : +- at least one test method using the "CheckVerifier" class to check and simulate a SonarQube analysis + - usage of "CheckVerifier.verify" to check if there is some issues raised or not + - usage of "CheckVerifier.verifyNoIssues" to check there is no issues raised +- each call to "CheckVerifier" needs a test resource file : this one is the resource code file for the simulated analysis + +each test resource file is in the "src/test/files" directory (or sub-directories). +each test resource file contains compliuant code or / and non compliant code. +If there is non compliant code on which Sonarqube analysis should raise an issue, the line with the issue has a comment at the end of the line with the following template : +"// Noncompliant {{ERROR_MESSAGE_TO_DISPLAY}}" + - the "ERROR_MESSAGE_TO_DISPLAY" in the previous template is replaced by the real error message. + - this comment gives the information to "CheckVerifier", the simulation tool, that an error is expected at this line + +Integration Tests Implementation Structure +--- +Inside the "it/java" directory, there are integration tests for each class of the plugin. +The package "org.greencodeinitiative.creedengo.java.integration.tests" contains one unit test class with one method for each rule. + +The integration test class extends the common class "GCIRulesBase" to use the system to initialize integration test. + +Integration test system process exists to check in a local and real environment that all implemented rules do the raises expected issues. + +The "src/it/test-projects" directory contains a real project to analyse. + +Here is the process +- build the plugin project +- download and launch a specific sonarqube version in local machine +- install the built plugin inside sonarqube +- create a specific default quality profile with all rules of the plugin installed +- launch the analysis of the test-project +- send analysis result to local sonarqube +- check the result of the analysis in front of expected results describe inside each test method + +Each test method describe different elements to check inside the result analysis : +- the relative path of each resource test file inside de test-project +- the complete rule id containing 2 parts : the plugin id ("creedengo-java") and the rule id (ex : "GCI2") +- the rule error message +- the lines where errors shoudl be raised : there are 2 arrays with the same size representing the start line and the end line of each issue raised + +Each test method ends with a call of a common method with all these parameters input. diff --git a/IA_rule.md b/IA_rule.md new file mode 100644 index 00000000..22710167 --- /dev/null +++ b/IA_rule.md @@ -0,0 +1,33 @@ +Rule Implementation Plan +--- + +# Rule Implementation Methodology + +Use the TDD (Test-Driven Development) methodology to implement a rule in an efficient and structured way. + +# Rule Implementation Process + +## STEP 1: Define unit test resources + technical shell of the rule +- Define test resources for the rule to be implemented with all possible cases: + - Compliant code + - Non-compliant code + - Code with elements that should not be analyzed +- Location of test resource files: + - Files for unit tests: in "src/test/files" or subdirectories + - Files for integration tests: in "src/it/test-projects" or subdirectories +- Create the rule implementation class in the package "org.greencodeinitiative.creedengo.java.checks" + - Add the "Rule" annotation with the correct rule id (the rule is previously defined in another maven component named "creedengo-rules-specifications") + - Extend the "IssuableSubscriptionVisitor" class + - Override the "nodesToVisit", "visitNode" and (optionally) "leaveNode" methods, which will be used respectively to declare the AST node types to analyze in depth and to implement the analysis logic, but leave their bodies empty for now +- Create the rule unit test class in the package "org.greencodeinitiative.creedengo.java.checks" +- Verify that unit tests fail with non-compliant test resources + +## STEP 2: Implement the rule + unit test validation +- Implement the rule in the implementation class created in step 1 +- Implement the "nodesToVisit" method to declare the AST node types to analyze in depth and implement the "visitNode" and, if needed, "leaveNode" methods to perform the analysis on those nodes +- Implement private methods to analyze in depth the declared AST nodes and raise issues if needed +- Verify that unit tests pass with both compliant and non-compliant test resources, and call them from "visitNode"/"leaveNode" + +## STEP 3: Implement integration tests +- Add a test method in the integration class "GCIRulesIT" for the implemented rule using the same pattern as other existing test methods +- Verify that integration tests pass with both compliant and non-compliant test resources diff --git a/INSTALL.md b/INSTALL.md index ee50d0ae..82cd69dc 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,8 +1,8 @@ Common installation notes / requirements ======================================== -Please read common [INSTALL.md](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md) -in `ecoCode-common` repository. Please follow the specific guides below for additional information on installing the +Please read common [INSTALL.md](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/INSTALL.md) +in `creedengo-common` repository. Please follow the specific guides below for additional information on installing the desired plugins. Special points for Standard plugins @@ -14,7 +14,7 @@ Project structure Here is a preview of project tree : ```txt -ecoCode-java # Root directory +creedengo-java # Root directory | +--src # source directory | diff --git a/README.md b/README.md index 0a0d9226..11ebf2bd 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -EcoCode-java +creedengo-java =========== -_ecoCode_ is a collective project aiming to reduce environmental footprint of software at the code level. The goal of +_creedengo_ is a collective project aiming to reduce environmental footprint of software at the code level. The goal of the project is to provide a list of static code analyzers to highlight code structures that may have a negative ecological impact: energy and resources over-consumption, "fatware", shortening terminals' lifespan, etc. -_ecoCode_ is based on evolving catalogs -of [good practices](https://github.com/green-code-initiative/ecoCode/blob/main/docs/rules), for various technologies. +_creedengo_ is based on evolving catalogs +of [good practices](https://github.com/green-code-initiative/creedengo-rules-specifications/blob/main/docs/rules), for various technologies. This SonarQube plugin then implements these catalogs as rules for scanning your Java projects. @@ -14,71 +14,69 @@ SonarQube plugin then implements these catalogs as rules for scanning your Java > refer to the contribution section. [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) -[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/CODE_OF_CONDUCT.md) +[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/CODE_OF_CONDUCT.md) 🌿 SonarQube Plugins ------------------- -This plugin is part of the ecoCode project.\ +This plugin is part of the creedengo project.\ You can find a list of all our other plugins in -the [ecoCode repository](https://github.com/green-code-initiative/ecoCode#-sonarqube-plugins) +the [creedengo repository](https://github.com/green-code-initiative/creedengo-rules-specifications#-sonarqube-plugins) 🚀 Getting Started ------------------ -You can give a try with a one command docker : +You can give a try with a one command: ```sh -docker run -ti --rm \ - -p 9000:9000 \ - --name sonarqube-ecocode-java ghcr.io/green-code-initiative/sonarqube-ecocode-java:latest +./mvnw verify -Pkeep-running ``` -or (with logs and data locally stored) : +... then you can use Java test project repository to test the environment : see [Java test project in `./src/it/test-projects/creedengo-java-plugin-test-project`](./src/it/test-projects/creedengo-java-plugin-test-project) -```sh -docker run -ti --rm \ - -v sq_ecocode_logs:/opt/sonarqube/logs \ - -v sq_ecocode_data:/opt/sonarqube/data \ - -p 9000:9000 \ - --name sonarqube-ecocode-java ghcr.io/green-code-initiative/sonarqube-ecocode-java:latest -``` +NB: To install other `creedengo` plugins, you can : -... and configure local SonarQube (security config and quality profile : see [configuration](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#configuration-sonarqube) for more details). +- add JAVA System properties `Dtest-it.additional-plugins` with a comma separated list of plugin IDs (`groupId:artifactId:version`), or plugins JAR (`file://....`) to install. -To install other `ecocode` plugins, you can also : + For example : -- download each plugin separatly and copy the plugin (jar file) to `$SONAR_INSTALL_DIR/extensions/plugins` and restart SonarQube. -- install different ecocode plugins with Marketplace (inside admin panel of SonarQube) + ```sh + ./mvnw verify -Pkeep-running -Dtest-it.additional-plugins=org.sonarsource.javascript:sonar-plugin:10.1.0.21143 + ``` +- install different creedengo plugins with Marketplace (inside admin panel of SonarQube) -Then you can use Java test project repository to test the environment : see README.md of [Java test project](https://github.com/green-code-initiative/ecoCode-java-test-project) +You can also directly use a [all-in-one docker-compose](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/INSTALL.md#start-sonarqube-if-first-time) -Finally, you can directly use a [all-in-one docker-compose](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#start-sonarqube-if-first-time) +... and configure local SonarQube (security config and quality profile : see [configuration](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/INSTALL.md#configuration-sonarqube) for more details). 🛒 Distribution ------------------ -Ready to use binaries are available [from GitHub](https://github.com/green-code-initiative/ecoCode-java/releases). +Ready to use binaries are available [from GitHub](https://github.com/green-code-initiative/creedengo-java/releases). 🧩 Compatibility ----------------- -| Plugin version | SonarQube version | Java version | -|----------------|-------------------|--------------| -| 1.5.+ | 9.4.+ LTS to 10.3 | 11 / 17 | +| Plugin version | SonarQube version | Java version | +|----------------|--------------------|--------------| +| 1.6.+ | 9.4.+ to 10.6.+ | 11 / 17 | +| 1.7.+ | 9.9.+ to 10.6.+ | 17 | +| 2.0.+ / 2.1.+ | 9.9.+ to 25.12.+ | 17 | +| 2.2.+ | 24.12.+ to 25.12.+ | 17 | +| 2.2.+ | 25.2.+ to 26.7.+ | 21 | > Compatibility table of versions lower than 1.4.+ are available from the -> main [ecoCode repository](https://github.com/green-code-initiative/ecoCode#-plugins-version-compatibility). +> main [creedengo repository](https://github.com/green-code-initiative/creedengo-rules-specifications#-plugins-version-compatibility). 🤝 Contribution --------------- -check [ecoCode repository](https://github.com/green-code-initiative/ecoCode#-contribution) +check [creedengo repository](https://github.com/green-code-initiative/creedengo-rules-specifications#-contribution) 🤓 Main contributors -------------------- -check [ecoCode repository](https://github.com/green-code-initiative/ecoCode#-main-contributors) +check [creedengo repository](https://github.com/green-code-initiative/creedengo-rules-specifications#-main-contributors) Links ----- diff --git a/RULES.md b/RULES.md index 13bf375f..d48fa61d 100644 --- a/RULES.md +++ b/RULES.md @@ -1 +1 @@ -Please read [RULES.md](https://github.com/green-code-initiative/ecoCode/blob/main/RULES.md) in `ecoCode` repository. +Please read [RULES.md](https://github.com/green-code-initiative/creedengo-rules-specifications/blob/main/RULES.md) in `creedengo-rules-specifications` repository. diff --git a/_TODOs_DDC.md b/_TODOs_DDC.md index d318d99e..85e767d8 100644 --- a/_TODOs_DDC.md +++ b/_TODOs_DDC.md @@ -7,4 +7,5 @@ - check usefulness - upgrade versions - enable github `dependabot` to create automatically PR with version upgrades of dependencides (when all dependencies will be ok) -- ménage dans les branches de dev (local et remote) \ No newline at end of file +- ménage dans les branches de dev (local et remote) +- docker-compose : ":9000" (génération port aléatoire pour l'IHM + repérage pour IHM) au lieu de "9000:9000" si erreur lors du démarrage "Error response from daemon: Ports are not available: exposing port TCP 0.0.0.0:9000 -> 0.0.0.0:0: listen tcp 0.0.0.0:9000: bind: address already in use" \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 682d39e0..98a460d4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,30 +1,34 @@ -version: "3.3" +name: sonarqube_creedengo_java + services: sonar: - image: sonarqube:10.3.0-community - container_name: sonar_ecocode_java + build: . + container_name: sonar_creedengo_java ports: - - "9000:9000" + - ":9000" networks: - sonarnet depends_on: - - db + db: + condition: service_healthy environment: SONAR_JDBC_USERNAME: sonar SONAR_JDBC_PASSWORD: sonar SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonarqube SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' + env_file: + - path: ./.default.docker.env + required: true + - path: ./.override.docker.env + required: false volumes: - - type: bind - source: ./target/ecocode-java-plugin-1.5.3-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.5.3-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" db: image: postgres:12 - container_name: postgresql_ecocode_java + container_name: postgresql_creedengo_java networks: - sonarnet volumes: @@ -34,6 +38,11 @@ services: POSTGRES_PASSWORD: sonar POSTGRES_DB: sonarqube PGDATA: pg_data:/var/lib/postgresql/data/pgdata + healthcheck: + test: [ "CMD-SHELL", "pg_isready -U sonar -d sonarqube" ] + interval: 5s + timeout: 5s + retries: 5 networks: sonarnet: diff --git a/downloads-sonarsource.crt b/downloads-sonarsource.crt new file mode 100644 index 00000000..01e7ff70 --- /dev/null +++ b/downloads-sonarsource.crt @@ -0,0 +1,26 @@ +-----BEGIN CERTIFICATE----- +MIIEZzCCA0+gAwIBAgIQb93rHKoediFVBatlARo+izANBgkqhkiG9w0BAQsFADCB +hzELMAkGA1UEBhMCRlIxFjAUBgNVBAgTDUlsZS1kZS1mcmFuY2UxDjAMBgNVBAcT +BVBhcmlzMRIwEAYDVQQKEwlDYXBnZW1pbmkxFDASBgNVBAsTC0dyb3VwIEluZnJh +MSYwJAYDVQQDEx16dG56aWEtaW50ZXJuZXQuY2FwZ2VtaW5pLmNvbTAeFw0yNTAz +MjAxOTUyNDVaFw0yNTA0MDMyMDUyNDVaMFExITAfBgNVBAMTGGJpbmFyaWVzLnNv +bmFyc291cmNlLmNvbTEVMBMGA1UECgwMWnNjYWxlciBJbmMuMRUwEwYDVQQLDAxa +c2NhbGVyIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDPn2/p +TD/pccqvIL7ek6xkyRJz+GV2a5BhZLHBzErFyUE+UyT3h4jxkwHTnSDcFHPynyud +MxpBdPxpbAAmzp+kqs/kOjMiSoRdgjv4U/Lerypiox+wYns/zvN/9tUuHPSdbRu7 +5BZZw7GotNwN0i8eQy0MZsoy+T5dCFEy2xwKVUqJtg0seiHFrr6jp7RVfLwdAmkE +Zg1+vPYLB2iDzii3Me1ym71ewcG/Ow+QavNUjOprwJpxLOwfeeX9SYt0KcpW0FXV +PriGAGLLcko1X8JS1AwlKCNdS6QesX2uGxATHFK1tncj974n+ogHaVdjRP5wGNyx +p9SnpWN3jFM8l7YpAgMBAAGjggECMIH/MD4GA1UdEQQ3MDWCGGJpbmFyaWVzLnNv +bmFyc291cmNlLmNvbYIZZG93bmxvYWRzLnNvbmFyc291cmNlLmNvbTAOBgNVHQ8B +Af8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADBKBgNV +HR8EQzBBMD+gPaA7hjlodHRwOi8vZ2F0ZXdheS56c2NhbGVyLm5ldC96c2NhbGVy +LXpzY3JsLTgxMjQyNTk5LTkxMC5jcmwwHQYDVR0OBBYEFHaP8PqoHXC3EtPdtrNB +G5mJm2JYMB8GA1UdIwQYMBaAFLD7L1k58j8FcvBXLU2Z4ZbZvg8IMA0GCSqGSIb3 +DQEBCwUAA4IBAQBGHb5Xw5VKtAoJbWY/irUgsXmgtNRioJreF5vX97/lbngJpk1C +VtMPI0OrF8UHtgZkJuf/aK5NwOshqVHNxQ56Y+qF5ctd379mkvvnGuNVs2t8NpgW +pOOoRqLH+f4SF2/5bzZkwlMjfxs6h2AJuW3iNNgns7mG8pQ3/chK99+tqwLZ4E+J +uRVmeCcFHgy2BdvspB7QZE9J8cWjMrkk7q5JH2PTj1ksst5XhdjoS3lI8sbRBlbV +hkctVQHpKr3ksnHycoboqNHbcAimYtYjsvDi/JV9rIOLnGelttfZtrDB0nCL0p/u +Ir+1+11jcCSCkqo+cj+kkZshTmduOrU+soBN +-----END CERTIFICATE----- diff --git a/mvnw b/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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 new file mode 100644 index 00000000..249bdf38 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : 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/pom.xml b/pom.xml index b8c10424..90c2f5bb 100644 --- a/pom.xml +++ b/pom.xml @@ -2,17 +2,18 @@ 4.0.0 - io.ecocode - ecocode-java-plugin - 1.5.3-SNAPSHOT - + org.green-code-initiative + creedengo-java-plugin + + ${revision} + sonar-plugin - ecoCode - Java language + creedengo - Java language Provides rules to reduce the environmental footprint of your Java programs - 2023 + 2024 - https://github.com/green-code-initiative/ecoCode-java + https://github.com/green-code-initiative/creedengo-java green-code-initiative https://github.com/green-code-initiative @@ -27,55 +28,113 @@ - scm:git:https://github.com/green-code-initiative/ecocode-java - scm:git:https://github.com/green-code-initiative/ecocode-java - https://github.com/green-code-initiative/ecocode-java + scm:git:https://github.com/green-code-initiative/creedengo-java + scm:git:https://github.com/green-code-initiative/creedengo-java + https://github.com/green-code-initiative/creedengo-java HEAD GitHub - https://github.com/green-code-initiative/ecoCode-java/issues + https://github.com/green-code-initiative/creedengo-java/issues - 11 + + current-SNAPSHOT + + + + ${git.commit.timestamp.datetime} + + 17 ${java.version} ${java.version} ${java.version} - UTF-8 - ${encoding} - ${encoding} + + UTF-8 + UTF-8 + + + false green-code-initiative https://sonarcloud.io - 9.4.0.54424 - 7.19.0.31550 + + 9.9.0.65466 + + + 13.0.0.3026 + + + 8.23.0.42096 + + 2.21.0.4626 + + 1.25.1.3002 - 2.5.0.1358 + + 3.2.0 - 1.23.0.740 + + 0.7.0 - 5.9.1 - 3.23.1 - 5.3.1 + + https://repo1.maven.org/maven2 + + false - 1.7 + + - - 1.4.6 + + + + + + + + + + + + + + + + + + + + + + + + + + + 26.7.0.124771 + + + ${sonarjava.version} + + + - ${project.groupId} - ecocode-rules-specifications - ${ecocode-rules-specifications.version} + org.green-code-initiative + creedengo-rules-specifications + ${creedengo-rules-specifications.version} java @@ -88,9 +147,9 @@ - org.sonarsource.sonarqube + org.sonarsource.api.plugin sonar-plugin-api - ${sonarqube.version} + ${sonar.plugin.api.version} provided @@ -104,10 +163,28 @@ com.google.re2j re2j - ${google.re2j} + 1.8 + + + + org.slf4j + slf4j-api + 2.0.17 + + provided + + + + + org.green-code-initiative + creedengo-integration-test + ${creedengo-integration-test.version} + test + + org.sonarsource.java java-checks-testkit @@ -118,42 +195,57 @@ org.junit.jupiter junit-jupiter - ${junit.jupiter.version} + 5.14.3 test - org.assertj - assertj-core - ${assertJ.version} + org.mockito + mockito-junit-jupiter + 5.21.0 test - org.mockito - mockito-junit-jupiter - ${mockito.version} + org.reflections + reflections + 0.10.2 test + org.apache.maven.plugins maven-compiler-plugin - 3.11.0 + 3.15.0 org.apache.maven.plugins maven-surefire-plugin - 3.1.2 + 3.5.5 + + ${skip.unit.tests} + + src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks + + org.jacoco jacoco-maven-plugin - 0.8.10 + 0.8.14 prepare-agent @@ -163,6 +255,7 @@ report + verify report @@ -175,10 +268,10 @@ ${sonar-packaging.version} true - ecocodejava - fr.greencodeinitiative.java.JavaPlugin + creedengojava + org.greencodeinitiative.creedengo.java.JavaPlugin true - ${sonarqube.version} + ${sonarqube-plugin-api-min.version} true ${java.version} java @@ -193,7 +286,7 @@ org.codehaus.mojo buildnumber-maven-plugin - 3.1.0 + 3.3.0 validate @@ -211,7 +304,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.5.0 + 3.6.1 package @@ -236,7 +329,7 @@ - io.ecocode:ecocode-rules-specifications:* + org.green-code-initiative:creedengo-rules-specifications:* META-INF/** @@ -246,12 +339,12 @@ + org.apache.maven.plugins maven-dependency-plugin - 3.6.0 + 3.10.0 - copy test-compile @@ -263,37 +356,37 @@ org.slf4j slf4j-api - 1.7.30 + 2.0.17 jar org.apache.commons commons-collections4 - 4.0 + 4.5.0 jar javax javaee-api - 6.0 + 8.0.1 jar org.springframework spring-webmvc - 5.2.3.RELEASE + 6.2.10 jar org.springframework spring-web - 5.2.3.RELEASE + 6.2.10 jar org.springframework spring-context - 5.2.3.RELEASE + 6.2.10 jar @@ -305,7 +398,11 @@ org.springframework.data spring-data-commons - 2.2.4.RELEASE + + 2.7.18 + + + jar @@ -317,18 +414,22 @@ com.mycila license-maven-plugin + 4.1 Green Code Initiative - https://www.ecocode.io + https://green-code-initiative.org
com/mycila/maven/plugin/license/templates/GPL-3.txt
- **/*.java + ${project.basedir}/src/**/*.java + + ${project.basedir}/src/it/test-projects/** +
@@ -342,6 +443,95 @@
+ + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.1 + + + add-integration-test-sources + process-test-sources + + add-test-source + + + + ${project.basedir}/src/it/java + + + + + add-integration-test-resources + generate-test-resources + + add-test-resource + + + + + ${project.basedir}/src/it/resources + + + true + ${project.basedir}/src/it/resources-filtered + + + + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.4 + + + + integration-test + verify + + + + ${test-it.sonarqube.keepRunning} + ${test-it.orchestrator.artifactory.url} + ${test-it.sonarqube.version} + ${test-it.sonarqube.port} + + + ${project.baseUri}/target/${project.artifactId}-${project.version}.jar, + org.sonarsource.java:sonar-java-plugin:${test-it.sonarjava.version}, + + + + ${project.baseUri}/src/main/resources/org/greencodeinitiative/creedengo/java/creedengo_way_profile.json, + + + + org.green-code-initiative:creedengo-java-plugin-test-project|creedengo Java Sonar Plugin Test Project|${project.baseUri}/src/it/test-projects/creedengo-java-plugin-test-project/pom.xml, + + + + java|creedengo way, + + + + + +
+ + + + keep-running + + true + + 33333 + + +
diff --git a/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/GCIRulesIT.java b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/GCIRulesIT.java new file mode 100644 index 00000000..2ab7df8c --- /dev/null +++ b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/GCIRulesIT.java @@ -0,0 +1,587 @@ +package org.greencodeinitiative.creedengo.java.integration.tests; + +import org.junit.jupiter.api.Test; +import org.sonarqube.ws.Issues; +import org.sonarqube.ws.Measures; + +import java.util.List; +import java.util.Map; + +import org.greencodeinitiative.creedengo.integration.tests.GCIRulesBase; + +import static java.util.Optional.ofNullable; +import static org.assertj.core.api.Assertions.assertThat; + +class GCIRulesIT extends GCIRulesBase { + + @Test + void testMeasuresAndIssues() { + String projectKey = analyzedProjects.get(0).getProjectKey(); + + Map measures = getMeasures(projectKey); + + assertThat(ofNullable(measures.get("code_smells")).map(Measures.Measure::getValue).map(Integer::parseInt).orElse(0)) + .isGreaterThan(1); + + List projectIssues = searchIssuesForComponent(projectKey, null).getIssuesList(); + assertThat(projectIssues).isNotEmpty(); + } + + @Test + void testGCI27() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheck.java"; + String ruleId = "creedengo-java:GCI27"; + String ruleMsg = "Use System.arraycopy to copy arrays"; + int[] startLines = new int[]{ + 68, 73, 80, 89, 102, 111, + 122, 133, 156, 162, 170, 180, + 194, 204, 216, 228, 246, 253, + 262, 273, 288, 299, 312, 325, + 351, 358, 367, 378, 393, 406, + 432, 439, 448, 459, 474, 487 + }; + int[] endLines = new int[]{ + 70, 77, 86, 99, 108, 119, + 130, 141, 158, 166, 176, 190, + 200, 212, 224, 236, 249, 258, + 269, 284, 295, 308, 321, 334, + 354, 363, 374, 389, 402, 415, + 435, 444, 455, 470, 483, 496 + }; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI74() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheck.java"; + int[] startLines = new int[]{27, 31, 36, 42}; + int[] endLines = new int[]{27, 31, 36, 42}; + String ruleId = "creedengo-java:GCI74"; + String ruleMsg = "Don't use the query SELECT * FROM"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI3_forEachLoopIgnored() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForEachLoopIgnored.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI3_forLoopBad() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopBad.java"; + int[] startLines = new int[]{13}; + int[] endLines = new int[]{13}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI3_forEachLoopGood() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopGood.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI3_forLoopIgnored() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopIgnored.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI3_whileLoopBad() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopBad.java"; + int[] startLines = new int[]{35}; + int[] endLines = new int[]{35}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI3_whileLoopGood() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopGood.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI3_whileLoopIgnored() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopIgnored.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI3"; + String ruleMsg = "Avoid getting the size of the collection in the loop"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI2() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatement.java"; + + int[] startLines = new int[]{ + 41, 60, 62, 88, 105, 127, + 129, 148, 152, 154, 175, 181, + 207, 226, 228, 229, 231, 253, + 274, 276 + }; + + int[] endLines = new int[]{ + 41, 60, 64, 88, 107, 127, + 131, 150, 152, 156, 177, 183, + 209, 226, 234, 229, 233, 255, + 274, 278 + }; + + String ruleId = "creedengo-java:GCI2"; + String ruleMsg = "Use a switch statement instead of multiple if-else if possible"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI2_compareMethodNoIssue() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethodNoIssue.java"; + + int[] startLines = new int[]{}; + + int[] endLines = new int[]{}; + + String ruleId = "creedengo-java:GCI2"; + String ruleMsg = "Use a switch statement instead of multiple if-else if possible"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI2_interfaceNoIssue() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementInterfaceNoIssue.java"; + + int[] startLines = new int[]{}; + + int[] endLines = new int[]{}; + + String ruleId = "creedengo-java:GCI2"; + String ruleMsg = "Use a switch statement instead of multiple if-else if possible"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI2_noBlockNoIssue() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoBlockNoIssue.java"; + + int[] startLines = new int[]{}; + + int[] endLines = new int[]{}; + + String ruleId = "creedengo-java:GCI2"; + String ruleMsg = "Use a switch statement instead of multiple if-else if possible"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI2_noIssue() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoIssue.java"; + + int[] startLines = new int[]{}; + + int[] endLines = new int[]{}; + + String ruleId = "creedengo-java:GCI2"; + String ruleMsg = "Use a switch statement instead of multiple if-else if possible"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI77_invalid() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStatic.java"; + int[] startLines = new int[]{25}; + int[] endLines = new int[]{25}; + String ruleId = "creedengo-java:GCI77"; + String ruleMsg = "Avoid using Pattern.compile() in a non-static context."; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI77_valid1() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid1.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI77"; + String ruleMsg = "Avoid using Pattern.compile() in a non-static context."; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI77_valid2() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid2.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI77"; + String ruleMsg = "Avoid using Pattern.compile() in a non-static context."; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI77_valid3() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid3.java"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + String ruleId = "creedengo-java:GCI77"; + String ruleMsg = "Avoid using Pattern.compile() in a non-static context."; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI78() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchUpdateCheck.java"; + int[] startLines = new int[]{ + 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, + 79, 81, 82, 83, 84, 87, + 103, 105, 106, 107, 108, 109, + 110, 112, 130, 132, 133, 134, + 135, 136, 137, 139 + }; + int[] endLines = new int[]{ + 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, + 79, 81, 82, 83, 84, 87, + 103, 105, 106, 107, 108, 109, + 110, 112, 130, 132, 133, 134, + 135, 136, 137, 139 + }; + String ruleId = "creedengo-java:GCI78"; + String ruleMsg = "Avoid setting constants in batch update"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_15MIN); + } + + @Test + void testGCI1_loop() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheck.java"; + + int[] startLines = new int[]{32}; + + int[] endLines = new int[]{32}; + + String ruleId = "creedengo-java:GCI1"; + String ruleMsg = "Avoid Spring repository call in loop or stream"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_50MIN); + } + + @Test + void testGCI1_stream() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheck.java"; + + int[] startLines = new int[]{ + 37, 48, 59, 72, 87, 98, + 113, 123 + }; + + int[] endLines = new int[]{ + 37, 48, 59, 72, 87, 98, + 113, 123 + }; + + String ruleId = "creedengo-java:GCI1"; + String ruleMsg = "Avoid Spring repository call in loop or stream"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_50MIN); + } + + @Test + void testGCI72() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheck.java"; + String ruleId = "creedengo-java:GCI72"; + String ruleMsg = "Avoid SQL request in loop"; + int[] startLines = new int[]{74, 105, 136}; + int[] endLines = new int[]{74, 105, 136}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_10MIN); + } + + @Test + void testGCI5() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueries.java"; + String ruleId = "creedengo-java:GCI5"; + String ruleMsg = "You must not use Statement for a DML query"; + int[] startLines = new int[]{33}; + int[] endLines = new int[]{33}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_10MIN); + } + + @Test + void testGCI76() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollections.java"; + String ruleId = "creedengo-java:GCI76"; + String ruleMsg = "Avoid usage of static collections."; + int[] startLines = new int[]{27, 29, 31}; + int[] endLines = new int[]{27, 29, 31}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI76_good() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsGoodWay.java"; + String ruleId = "creedengo-java:GCI76"; + String ruleMsg = "Avoid usage of static collections."; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_20MIN); + } + + @Test + void testGCI79() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterface.java"; + String ruleId = "creedengo-java:GCI79"; + String ruleMsg = "try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface."; + int[] startLines = new int[]{40}; + int[] endLines = new int[]{53}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_15MIN); + } + + @Test + void testGCI32() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSize.java"; + String ruleId = "creedengo-java:GCI32"; + String ruleMsg = "Initialize StringBuilder or StringBuffer with appropriate size"; + int[] startLines = new int[]{38, 46}; + int[] endLines = new int[]{38, 46}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI67() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheck.java"; + String ruleId = "creedengo-java:GCI67"; + String ruleMsg = "Use ++i instead of i++"; + int[] startLines = new int[]{31, 51, 74}; + int[] endLines = new int[]{31, 51, 74}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI82() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstants.java"; + String ruleId = "creedengo-java:GCI82"; + String ruleMsg = "The variable is never reassigned and can be 'final'"; + int[] startLines = new int[]{9, 14, 15, 20, 26, 29, 48, 75, 108, 121, 146}; + int[] endLines = new int[]{9, 14, 15, 20, 26, 29, 48, 75, 108, 121, 146}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI82_lombok() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForLombok.java"; + String ruleId = "creedengo-java:GCI82"; + String ruleMsg = "The variable is never reassigned and can be 'final'"; + int[] startLines = new int[]{20, 29, 38, 41, 54}; + int[] endLines = new int[]{21, 30, 39, 42, 54}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI82_lombokWithoutImport() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsWithoutLombokImport.java"; + String ruleId = "creedengo-java:GCI82"; + String ruleMsg = "The variable is never reassigned and can be 'final'"; + int[] startLines = new int[]{11, 13, 34}; + int[] endLines = new int[]{11, 14, 34}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI82_record() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForRecord.java"; + String ruleId = "creedengo-java:GCI82"; + String ruleMsg = "The variable is never reassigned and can be 'final'"; + int[] startLines = new int[]{}; + int[] endLines = new int[]{}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI82_instanceOf() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForInstanceOf.java"; + String ruleId = "creedengo-java:GCI82"; + String ruleMsg = "The variable is never reassigned and can be 'final'"; + int[] startLines = new int[]{7}; + int[] endLines = new int[]{7}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI82_abstractMethods() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForAbstractMethod.java"; + String ruleId = "creedengo-java:GCI82"; + String ruleMsg = "The variable is never reassigned and can be 'final'"; + int[] startLines = new int[]{16, 20}; + int[] endLines = new int[]{16, 20}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI69() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoop.java"; + String ruleId = "creedengo-java:GCI69"; + String ruleMsg = "Do not call a function when declaring a for-type loop"; + int[] startLines = new int[]{65, 73, 81, 109, 130}; + int[] endLines = new int[]{65, 73, 81, 109, 130}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI28() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck.java"; + + int[] startLines = new int[]{34}; + + int[] endLines = new int[]{34}; + + String ruleId = "creedengo-java:GCI28"; + String ruleMsg = "Optimize Read File Exceptions"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI28_2() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck2.java"; + + int[] startLines = new int[]{32}; + + int[] endLines = new int[]{32}; + + String ruleId = "creedengo-java:GCI28"; + String ruleMsg = "Optimize Read File Exceptions"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI28_3() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck3.java"; + + int[] startLines = new int[]{32}; + + int[] endLines = new int[]{32}; + + String ruleId = "creedengo-java:GCI28"; + String ruleMsg = "Optimize Read File Exceptions"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI28_4() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck4.java"; + + int[] startLines = new int[]{31}; + + int[] endLines = new int[]{31}; + + String ruleId = "creedengo-java:GCI28"; + String ruleMsg = "Optimize Read File Exceptions"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI28_5() { + + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck5.java"; + + int[] startLines = new int[]{31}; + + int[] endLines = new int[]{31}; + + String ruleId = "creedengo-java:GCI28"; + String ruleMsg = "Optimize Read File Exceptions"; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines); + } + + @Test + void testGCI94() { + String filePath = "src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElse.java"; + String ruleId = "creedengo-java:GCI94"; + String ruleMsg = "Use optional orElseGet instead of orElse."; + int[] startLines = new int[]{29, 31, 33, 35, 55, 56, 57, 58}; + int[] endLines = new int[]{29, 31, 33, 35, 55, 56, 57, 58}; + + checkIssuesForFile(filePath, ruleId, ruleMsg, startLines, endLines, SEVERITY, TYPE, EFFORT_1MIN); + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/pom.xml b/src/it/test-projects/creedengo-java-plugin-test-project/pom.xml new file mode 100644 index 00000000..839969c9 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.green-code-initiative + creedengo-java-plugin-test-project + 0.0.1-SNAPSHOT + + creedengo Java Sonar Plugin Test Project + + + 17 + ${java.version} + ${java.version} + + target + + UTF-8 + ${encoding} + ${encoding} + + + + + org.springframework.data + spring-data-jpa + 3.3.0 + + + org.springframework + spring-beans + 5.3.25 + + + org.projectlombok + lombok + 1.18.46 + provided + + + + diff --git a/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheck.java similarity index 87% rename from src/test/files/AvoidSpringRepositoryCallInLoopCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheck.java index a18b484f..3d386901 100644 --- a/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; @@ -54,4 +54,4 @@ public interface EmployeeRepository extends JpaRepository { } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidSpringRepositoryCallInStreamCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheck.java similarity index 80% rename from src/test/files/AvoidSpringRepositoryCallInStreamCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheck.java index 35dc70ce..5e89dc3f 100644 --- a/src/test/files/AvoidSpringRepositoryCallInStreamCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; @@ -52,7 +52,7 @@ public void smellGetAllEmployeesByIdsForEachOrdered() { }); } - public List smellGetAllEmployeesByIdsMap() { + public List smellGetAllEmployeesByIdsMap() { List employees = new ArrayList<>(); Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return stream.map(id -> { @@ -60,11 +60,12 @@ public List smellGetAllEmployeesByIdsMap() { if (employee.isPresent()) { employees.add(employee.get()); } + return id; // Return the id }) .collect(Collectors.toList()); } - public List smellGetAllEmployeesByIdsPeek() { + public List smellGetAllEmployeesByIdsPeek() { List employees = new ArrayList<>(); Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return stream.peek(id -> { @@ -81,17 +82,18 @@ public List smellGetAllEmployeesByIdsWithOptional(List ids) { return ids .stream() .map(element -> { - Employee empl = new Employee(); + Employee empl = new Employee(1, "nom"); employees.add(empl); return employeeRepository.findById(element).orElse(empl);// Noncompliant {{Avoid Spring repository call in loop or stream}} }) .collect(Collectors.toList()); } - public List smellGetAllEmployeesByIds(List ids) { + public List> smellGetAllEmployeesByIds(List ids) { + List employees = new ArrayList<>(); Stream stream = ids.stream(); return stream.map(element -> { - Employee empl = new Employee(); + Employee empl = new Employee(1, "nom"); employees.add(empl); return employeeRepository.findById(element);// Noncompliant {{Avoid Spring repository call in loop or stream}} }) @@ -102,12 +104,14 @@ public List smellGetAllEmployeesByIdsWithoutStream(List ids) return employeeRepository.findAllById(ids); // Compliant } - public List smellDeleteEmployeeById(List ids) { + public List smellDeleteEmployeeById(List ids) { + List employees = new ArrayList<>(); Stream stream = ids.stream(); return stream.map(element -> { - Employee empl = new Employee(); + Employee empl = new Employee(1, "nom"); employees.add(empl); - return employeeRepository.deleteById(element);// Noncompliant {{Avoid Spring repository call in loop or stream}} + employeeRepository.deleteById(element);// Noncompliant {{Avoid Spring repository call in loop or stream}} + return element; // Return the id since deleteById returns void }) .collect(Collectors.toList()); } @@ -115,7 +119,7 @@ public List smellDeleteEmployeeById(List ids) { public List smellGetAllEmployeesByIdsWithSeveralMethods(List ids) { Stream stream = ids.stream(); return stream.map(element -> { - Employee empl = new Employee(); + Employee empl = new Employee(1, "nom"); return employeeRepository.findById(element).orElse(empl).anotherMethod().anotherOne();// Noncompliant {{Avoid Spring repository call in loop or stream}} }) .collect(Collectors.toList()); @@ -132,8 +136,10 @@ public Employee(Integer id, String name) { public Integer getId() { return id; } public String getName() { return name; } + public Employee anotherMethod() { return this; } + public Employee anotherOne() { return this; } } public interface EmployeeRepository extends JpaRepository { } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidMultipleIfElseStatement.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatement.java similarity index 97% rename from src/test/files/AvoidMultipleIfElseStatement.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatement.java index 435218fa..52bc42ac 100644 --- a/src/test/files/AvoidMultipleIfElseStatement.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatement.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; class AvoidMultipleIfElseStatementCheck { diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethod.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethod.java new file mode 100644 index 00000000..9d20ea00 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethod.java @@ -0,0 +1,69 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks; + +class AvoidMultipleIfElseStatementCompareMethod { + + public int compare(DummyClass2 o1, DummyClass2 o2) { + + if (o1.getField1().equals(o2.getField1())) { + if (o1.getField2().equals(o2.getField2())) { + return 0; + } + // First original + if (o1.getField3() && !o2.getField3()) { + return -1; + } else if (!o1.getField3() && o2.getField3()) { + return 1; + } + // First min posgafld + Long result = o1.getField4() - o2.getField4(); + if (result != 0) { + return result.intValue(); + } + + } + // First BQRY block + if (o1.getField2().startsWith("BQRY") && !o2.getField2().startsWith("BQRY")) { + return -1; + } else if (!o1.getField2().startsWith("BQRY") && o2.getField2().startsWith("BQRY")) { + return 1; + } + // If both block don't start with BQRY, sort alpha with String.compareTo method + return o1.getField2().compareTo(o2.getField2()); + } + + class DummyClass2 { + + public Object getField1() { + return 0; + } + + public String getField2() { + return ""; + } + + public boolean getField3() { + return true; + } + + public Long getField4() { + return 1000L; } + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethodNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethodNoIssue.java new file mode 100644 index 00000000..1095d923 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementCompareMethodNoIssue.java @@ -0,0 +1,70 @@ +package org.greencodeinitiative.creedengo.java.checks; + +class AvoidMultipleIfElseStatementCompareMethodNoIssue { + + public int compare(FieldVo o1, FieldVo o2) { + + if (o1.getIdBlock().equals(o2.getIdBlock())) { + if (o1.getIdField().equals(o2.getIdField())) { + return 0; + } + // First original + if (o1.isOriginal() && !o2.isOriginal()) { + return -1; + } else if (!o1.isOriginal() && o2.isOriginal()) { + return 1; + } + // First min posgafld + Long result = o1.getColumnPos() - o2.getColumnPos(); + if (result != 0) { + return result.intValue(); + } + + // First min ordgaflc + result = o1.getIndex() - o2.getIndex(); + return result.intValue(); + } + // First BQRY block + if (o1.getIdBlock().startsWith("BQRY") && !o2.getIdBlock().startsWith("BQRY")) { + return -1; + } else if (!o1.getIdBlock().startsWith("BQRY") && o2.getIdBlock().startsWith("BQRY")) { + return 1; + } + // If both block don't start with BQRY, sort alpha with String.compareTo method + return o1.getIdBlock().compareTo(o2.getIdBlock()); + } + + public static class FieldVo { + + private String idBlock; + + private String idField; + + private boolean original; + + private long columnPos; + + private long index; + + public String getIdBlock() { + return idBlock; + } + + public String getIdField() { + return idField; + } + + public boolean isOriginal() { + return original; + } + + public long getColumnPos() { + return columnPos; + } + + public long getIndex() { + return index; + } + } + +} diff --git a/src/test/files/AvoidMultipleIfElseStatementInterface.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementInterfaceNoIssue.java similarity index 62% rename from src/test/files/AvoidMultipleIfElseStatementInterface.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementInterfaceNoIssue.java index 43dd875a..d6771090 100644 --- a/src/test/files/AvoidMultipleIfElseStatementInterface.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementInterfaceNoIssue.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,10 +15,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; -interface AvoidMultipleIfElseStatementCheck { +interface AvoidMultipleIfElseStatementInterfaceNoIssue { - TransactionMetaData initMetaData(ITransactionFoundation transactionFoundation) throws ProgramException, MnemonicTemplateShellException; + Object initMetaData(Object transactionFoundation) throws IllegalAccessException; } diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoBlockNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoBlockNoIssue.java new file mode 100644 index 00000000..cf1a104e --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoBlockNoIssue.java @@ -0,0 +1,28 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks; + +class AvoidMultipleIfElseStatementNoBlockNoIssue { + + public boolean equals(Object obj) { + if (this == obj) + return true; + return false; + } + +} diff --git a/src/test/files/AvoidMultipleIfElseStatementNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoIssue.java similarity index 96% rename from src/test/files/AvoidMultipleIfElseStatementNoIssue.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoIssue.java index 32f4716b..53e72dd1 100644 --- a/src/test/files/AvoidMultipleIfElseStatementNoIssue.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNoIssue.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; class AvoidMultipleIfElseStatementCheckNoIssue { diff --git a/src/test/files/AvoidMultipleIfElseStatementNotBlock.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNotBlock.java similarity index 75% rename from src/test/files/AvoidMultipleIfElseStatementNotBlock.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNotBlock.java index 3e8f613a..9921ffd1 100644 --- a/src/test/files/AvoidMultipleIfElseStatementNotBlock.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementNotBlock.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,13 +15,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; class AvoidMultipleIfElseStatementNotBlock { public boolean equals(Object obj) { if (this == obj) return true; + return false; } -} \ No newline at end of file +} diff --git a/src/test/files/ArrayCopyCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheck.java similarity index 98% rename from src/test/files/ArrayCopyCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheck.java index 09c780ea..7d075c44 100644 --- a/src/test/files/ArrayCopyCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -242,7 +242,7 @@ public void copyWithForEachLoop() { } // Simple copy - int i = 0; + i = 0; for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} dest[i] = src[i]; i++; @@ -507,4 +507,4 @@ private boolean transform(boolean a) { return !a; } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck.java similarity index 72% rename from src/test/files/OptimizeReadFileExceptionCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck.java index e9fd260c..bd33a88f 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,10 +15,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.FileNotFoundException; class ReadFile { ReadFile(ReadFile readFile) { @@ -30,8 +33,8 @@ public void readPreferences(String filename) { try { in = new FileInputStream(filename); // Noncompliant {{Optimize Read File Exceptions}} } catch (FileNotFoundException e) { - logger.log(e); + System.out.println(e); } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck2.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck2.java similarity index 62% rename from src/test/files/OptimizeReadFileExceptionCheck2.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck2.java index 689dc187..7ad10f63 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck2.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck2.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,22 +15,25 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.FileNotFoundException; -class ReadFile { - ReadFile(ReadFile readFile) { +class ReadFile2 { + ReadFile2(ReadFile2 readFile) { } - public void readPreferences(String filename) { + public void readPreferences(String filename) throws Exception { //... try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} - logger.log("my log"); + System.out.println("my log"); } catch (FileNotFoundException e) { - logger.log(e); + System.out.println(e); } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck3.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck3.java similarity index 67% rename from src/test/files/OptimizeReadFileExceptionCheck3.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck3.java index 92dc1501..78e59393 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck3.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck3.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,22 +15,25 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.IOException; -class ReadFile { - ReadFile(ReadFile readFile) { +class ReadFile3 { + ReadFile3(ReadFile3 readFile) { } public void readPreferences(String filename) { //... try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} - logger.log("my log"); + System.out.println("my log"); } catch (IOException e) { - logger.log(e); + System.out.println(e); } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck4.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck4.java similarity index 68% rename from src/test/files/OptimizeReadFileExceptionCheck4.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck4.java index 5914e0fa..001e0059 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck4.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck4.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,22 +15,24 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; +import java.io.FileInputStream; +import java.io.InputStream; -class ReadFile { - ReadFile(ReadFile readFile) { +class ReadFile4 { + ReadFile4(ReadFile4 readFile) { } public void readPreferences(String filename) { //... try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} - logger.log("my log"); + System.out.println("my log"); } catch (Exception e) { - logger.log(e); + System.out.println(e); } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck5.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck5.java similarity index 68% rename from src/test/files/OptimizeReadFileExceptionCheck5.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck5.java index 6d8b553e..4b0ff359 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck5.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheck5.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,22 +15,24 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; +import java.io.FileInputStream; +import java.io.InputStream; -class ReadFile { - ReadFile(ReadFile readFile) { +class ReadFile5 { + ReadFile5(ReadFile5 readFile) { } public void readPreferences(String filename) { //... try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} - logger.log("my log"); + System.out.println("my log"); } catch (Throwable e) { - logger.log(e); + System.out.println(e); } //... } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForEachLoopIgnored.java similarity index 83% rename from src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForEachLoopIgnored.java index 46963cd7..ce4eeac9 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForEachLoopIgnored.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collection; import java.util.ArrayList; @@ -36,4 +36,4 @@ public void ignoredLoop() { System.out.println("numberList.size()"); } } -} \ No newline at end of file +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopBad.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopBad.java new file mode 100644 index 00000000..11254a13 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopBad.java @@ -0,0 +1,17 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayList; +import java.util.List; + +class AvoidGettingSizeCollectionInForLoopBad { + + public void badForLoop() { + final List numberList = new ArrayList<>(); + numberList.add(10); + numberList.add(20); + + for (int i = 0; i < numberList.size(); ++i) { // Noncompliant {{Avoid getting the size of the collection in the loop}} + System.out.println("numberList.size()"); + } + } +} diff --git a/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopGood.java similarity index 78% rename from src/test/files/AvoidGettingSizeCollectionInForLoopGood.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopGood.java index 5f2bcd2e..169d8d56 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopGood.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collection; import java.util.ArrayList; @@ -34,7 +34,7 @@ public void goodForLoop() { int size = numberList.size(); for (int i = 0; i < size; i++) { // Compliant System.out.println("numberList.size()"); - int size = numberList.size(); // Compliant with this rule + int innerSize = numberList.size(); // Compliant with this rule } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopIgnored.java similarity index 62% rename from src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopIgnored.java index 544e08e7..d837b7a7 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInForLoopIgnored.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,26 +15,26 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collection; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; -class AvoidGettingSizeCollectionInForLoopBad { - AvoidGettingSizeCollectionInForLoopBad() { +class GCI69AvoidGettingSizeCollectionInForLoopBad { + GCI69AvoidGettingSizeCollectionInForLoopBad() { } public void badForLoop() { - List numberList = new ArrayList(); + final List numberList = new ArrayList(); numberList.add(10); numberList.add(20); - Iterator it = numberList.iterator(); + final Iterator it = numberList.iterator(); for (; it.hasNext(); ) { // Ignored => compliant - it.next(); - System.out.println("numberList.size()"); + System.out.println(it.next()); } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopBad.java similarity index 79% rename from src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopBad.java index f47570c9..27d21981 100644 --- a/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopBad.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collection; import java.util.ArrayList; @@ -27,7 +27,7 @@ class AvoidGettingSizeCollectionInWhileLoopBad { } public void badWhileLoop() { - List numberList = new ArrayList(); + List numberList = new ArrayList<>(); numberList.add(10); numberList.add(20); @@ -37,4 +37,4 @@ public void badWhileLoop() { i++; } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopGood.java similarity index 84% rename from src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopGood.java index 57668687..713998d5 100644 --- a/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopGood.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collection; import java.util.ArrayList; @@ -39,4 +39,4 @@ public void goodWhileLoop() { i++; } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopIgnored.java similarity index 71% rename from src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopIgnored.java index 10c752f4..dbac3396 100644 --- a/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInWhileLoopIgnored.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,14 +15,15 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collection; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; -class AvoidGettingSizeCollectionInWhileLoopBad { - AvoidGettingSizeCollectionInWhileLoopBad() { +class AvoidGettingSizeCollectionInWhileLoopIgnored { + AvoidGettingSizeCollectionInWhileLoopIgnored() { } @@ -31,11 +32,11 @@ public void badWhileLoop() { numberList.add(10); numberList.add(20); - Iterator it = numberList.iterator(); + Iterator it = numberList.iterator(); int i = 0; while (it.hasNext()) { // Ignored => compliant it.next(); System.out.println("numberList.size()"); } } -} \ No newline at end of file +} diff --git a/src/test/files/InitializeBufferWithAppropriateSize.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSize.java similarity index 86% rename from src/test/files/InitializeBufferWithAppropriateSize.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSize.java index b5852a19..a83c21e7 100644 --- a/src/test/files/InitializeBufferWithAppropriateSize.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSize.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.sql.Connection; import java.sql.DriverManager; @@ -45,4 +45,4 @@ public void testBuilderCompliant() { public void testBuilderNonCompliant() { StringBuilder stringBuilder = new StringBuilder(); // Noncompliant {{Initialize StringBuilder or StringBuffer with appropriate size}} } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidStatementForDMLQueries.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueries.java similarity index 74% rename from src/test/files/AvoidStatementForDMLQueries.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueries.java index 5059b093..a4965f1f 100644 --- a/src/test/files/AvoidStatementForDMLQueries.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueries.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.sql.Connection; import java.sql.DriverManager; @@ -27,8 +27,9 @@ class AvoidStatementForDMLQueries { AvoidStatementForDMLQueries(AvoidStatementForDMLQueries mc) { } - public void insert() { + public void insert() throws Exception { + Connection connection = DriverManager.getConnection("myurl", "toor", ""); Statement statement = connection.createStatement(); statement.executeUpdate("INSERT INTO persons(id, name) VALUES(2, 'Toto')"); // Noncompliant {{You must not use Statement for a DML query}} } -} \ No newline at end of file +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheck.java new file mode 100644 index 00000000..c97ef08d --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheck.java @@ -0,0 +1,106 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks; + +class IncrementCheck { + + private class Foo { + public int i; //NOSONAR + } + + IncrementCheck(IncrementCheck mc) { + } + + int foo1() { + int counter = 0; + return counter++; // Noncompliant {{Use ++i instead of i++}} + } + + private int j = 0; + int foo10() { + return this.j++; // Compliant because maybe the use case needs to return j AND increment it + } + + int foo11() { + int counter = 0; + return ++counter; + } + + int foo12() { + Foo f = new Foo(); + return f.i++; // Compliant because maybe the use case needs to return j AND increment it + } + + int foo2() { + int counter = 0; + counter++; // Noncompliant {{Use ++i instead of i++}} + return counter; + } + + int foo22() { + int counter = 0; + ++counter; + return counter; + } + + int foo3() { + int counter = 0; + counter = counter + 197845 ; + return counter; + } + + int foo4() { + int counter = 0; + counter = counter + 35 + 78 ; + return counter; + } + + void foo50() { + for (int i=0; i < 10; i++) { // Noncompliant {{Use ++i instead of i++}} + System.out.println(i); //NOSONAR + } + } + + void foo51() { + for (int i=0; i < 10; ++i) { + System.out.println(i); //NOSONAR + } + } + + void bar61(int value) { + // For test purpose + } + + int foo61() { + int i = 0; + bar61(i++); // Compliant because maybe bar61 needs the unincremented value + return i; + } + + int foo62() { + int i = 0; + bar61(2 + i++); // Compliant because maybe bar61 needs the unincremented value + return i; + } + + void foo71() { + int counter = 0; + int a = 2 + counter++; // Compliant because we probably want to increment counter + // then to add it to 2 to initialize a + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoop.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoop.java new file mode 100644 index 00000000..a7a62132 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoop.java @@ -0,0 +1,156 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Collections; + + +class NoFunctionCallWhenDeclaringForLoop { + + public int getMyValue() { + return 6; + } + + public int incrementeMyValue(final int i) { + return i + 100; + } + + public void test1() { + for (int i = 0; i < 20; ++i) { + System.out.println(i); + final boolean b = getMyValue() > 6; + System.out.println(b); + } + } + + public void test2() { + final String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; + for (final String i : cars) { + System.out.println(i); + } + + } + + // compliant, the function is called only once in the initialization so it's not a performance issue + public void test3() { + for (int i = getMyValue(); i < 20; ++i) { + System.out.println(i); + final boolean b = getMyValue() > 6; + System.out.println(b); + } + } + + public void test4() { + for (int i = 0; i < getMyValue(); ++i) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + final boolean b = getMyValue() > 6; + System.out.println(b); + } + } + + public void test5() { + for (final int i = 0; i < getMyValue(); incrementeMyValue(i)) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + final boolean b = getMyValue() > 6; + System.out.println(b); + } + } + + public void test6() { + for (int i = getMyValue(); i < getMyValue(); ++i) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + final boolean b = getMyValue() > 6; + System.out.println(b); + } + } + + // compliant, iterators are allowed to be called in a for loop + public void test7() { + final List joursSemaine = Arrays.asList("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"); + + String jour = null; + // iterator is allowed + for (final Iterator iterator = joursSemaine.iterator(); iterator.hasNext(); jour = iterator.next()) { + System.out.println(jour); + } + + // subclass of iterator is allowed + for (final ListIterator iterator = joursSemaine.listIterator(); iterator.hasNext(); jour = iterator.next()) { + System.out.println(jour); + } + + // iterator called in an indirect way is allowed + for (final OtherClassWrapper otherClass = new OtherClassWrapper(joursSemaine.iterator()); otherClass.iterator.hasNext(); jour = otherClass.iterator.next()) { + System.out.println(jour); + } + + // but using a method that returns an iterator causes an issue + for (final OtherClassWrapper otherClass = new OtherClassWrapper(joursSemaine.iterator()); otherClass.getIterator().hasNext(); jour = otherClass.getIterator().next()) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(jour); + } + + } + + // compliant, enumeration is allowed + public void test8() { + final List joursSemaine = Arrays.asList("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"); + + String jour = null; + for (final Enumeration enumeration = Collections.enumeration(joursSemaine); enumeration.hasMoreElements(); jour = enumeration.nextElement()) { + System.out.println(jour); + } + + // enumeration called in an indirect way is allowed + for(final OtherClassWrapper otherClass = new OtherClassWrapper(Collections.enumeration(joursSemaine)); otherClass.enumeration.hasMoreElements(); jour = otherClass.enumeration.nextElement()) { + System.out.println(jour); + } + + // but using a method that returns an enumeration causes an issue + for(final OtherClassWrapper otherClass = new OtherClassWrapper(Collections.enumeration(joursSemaine)); otherClass.getEnumeration().hasMoreElements(); jour = otherClass.getEnumeration().nextElement()) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(jour); + } + + } + +} + +class OtherClassWrapper { + public Iterator iterator; + public Enumeration enumeration; + + public OtherClassWrapper(Iterator iterator){ + this.iterator = iterator; + } + public OtherClassWrapper(Enumeration enumeration){ + this.enumeration = enumeration; + } + + public Iterator getIterator(){ + return iterator; + } + + public Enumeration getEnumeration(){ + return enumeration; + } +} diff --git a/src/test/files/AvoidSQLRequestInLoopCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheck.java similarity index 95% rename from src/test/files/AvoidSQLRequestInLoopCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheck.java index 753a717a..f75e0c92 100644 --- a/src/test/files/AvoidSQLRequestInLoopCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.sql.Connection; import java.sql.DriverManager; @@ -148,4 +148,4 @@ public void testWithWhileLoop() { } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidFullSQLRequestCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheck.java similarity index 87% rename from src/test/files/AvoidFullSQLRequestCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheck.java index b388252a..2d6b2e6a 100644 --- a/src/test/files/AvoidFullSQLRequestCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.regex.Pattern; @@ -46,4 +46,4 @@ private void dummyCall(String request) { } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidUsageOfStaticCollections.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollections.java similarity index 57% rename from src/test/files/AvoidUsageOfStaticCollections.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollections.java index 35309972..43acc847 100644 --- a/src/test/files/AvoidUsageOfStaticCollections.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollections.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.*; @@ -24,11 +24,11 @@ */ public class AvoidUsageOfStaticCollections { - public static final List LIST = new ArrayList(); // Noncompliant {{Avoid usage of static collections.}} + public static final List LIST = new ArrayList<>(); // Noncompliant {{Avoid usage of static collections.}} - public static final Set SET = new HashSet(); // Noncompliant {{Avoid usage of static collections.}} + public static final Set SET = new HashSet<>(); // Noncompliant {{Avoid usage of static collections.}} - public static final Map MAP = new HashMap(); // Noncompliant {{Avoid usage of static collections.}} + public static final Map MAP = new HashMap<>(); // Noncompliant {{Avoid usage of static collections.}} public AvoidUsageOfStaticCollections() { } diff --git a/src/test/files/GoodUsageOfStaticCollections.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsGoodWay.java similarity index 66% rename from src/test/files/GoodUsageOfStaticCollections.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsGoodWay.java index 6d2d3c20..e7a60938 100644 --- a/src/test/files/GoodUsageOfStaticCollections.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsGoodWay.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,20 +15,20 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.*; /** * Compliant */ -public class GoodUsageOfStaticCollections { - public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections(); +public class AvoidUsageOfStaticCollectionsGoodWay { + public static volatile AvoidUsageOfStaticCollectionsGoodWay INSTANCE = new AvoidUsageOfStaticCollectionsGoodWay(); public final List LIST = new ArrayList(); // Compliant public final Set SET = new HashSet(); // Compliant public final Map MAP = new HashMap(); // Compliant - private GoodUsageOfStaticCollections() { + private AvoidUsageOfStaticCollectionsGoodWay() { } } diff --git a/src/test/files/AvoidRegexPatternNotStatic.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStatic.java similarity index 79% rename from src/test/files/AvoidRegexPatternNotStatic.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStatic.java index b5e19c6e..76387635 100644 --- a/src/test/files/AvoidRegexPatternNotStatic.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStatic.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.regex.Pattern; diff --git a/src/test/files/ValidRegexPattern.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid1.java similarity index 74% rename from src/test/files/ValidRegexPattern.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid1.java index aacb701e..638ffd96 100644 --- a/src/test/files/ValidRegexPattern.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid1.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,11 +15,11 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.regex.Pattern; -public class ValidRegexPattern { +public class AvoidRegexPatternNotStaticValid1 { private static final Pattern pattern = Pattern.compile("foo"); // Compliant diff --git a/src/test/files/ValidRegexPattern2.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid2.java similarity index 74% rename from src/test/files/ValidRegexPattern2.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid2.java index a674b9bc..0ef9517c 100644 --- a/src/test/files/ValidRegexPattern2.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid2.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,11 +15,11 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.regex.Pattern; -public class ValidRegexPattern2 { +public class AvoidRegexPatternNotStaticValid2 { private final Pattern pattern = Pattern.compile("foo"); // Compliant diff --git a/src/test/files/ValidRegexPattern3.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid3.java similarity index 72% rename from src/test/files/ValidRegexPattern3.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid3.java index 08676938..f1378974 100644 --- a/src/test/files/ValidRegexPattern3.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticValid3.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,15 +15,15 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.regex.Pattern; -public class ValidRegexPattern3 { +public class AvoidRegexPatternNotStaticValid3 { private final Pattern pattern; - public ValidRegexPattern3() { + public AvoidRegexPatternNotStaticValid3() { pattern = Pattern.compile("foo"); // Compliant } diff --git a/src/test/files/AvoidSetConstantInBatchUpdateCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchUpdateCheck.java similarity index 87% rename from src/test/files/AvoidSetConstantInBatchUpdateCheck.java rename to src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchUpdateCheck.java index 03f5e86a..8e20630a 100644 --- a/src/test/files/AvoidSetConstantInBatchUpdateCheck.java +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchUpdateCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,24 +15,26 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.util.regex.Pattern; import java.util.stream.IntStream; import java.util.stream.Stream; +import java.sql.DriverManager; +import java.sql.Connection; class AvoidSetConstantInBatchUpdateCheck { - void literalSQLrequest() { //dirty call + void literalSQLrequest() throws Exception { //dirty call int x = 0; Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle"); PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?)"); stmt.setInt(1, 101); stmt.setString(2, "Ratan"); - stmt.setBigDecimal(3, Bigdecimal.ONE); + stmt.setBigDecimal(3, BigDecimal.ONE); stmt.setBigDecimal(4, BigDecimal.valueOf(x)); stmt.setBoolean(5, Boolean.valueOf("true")); int i = stmt.executeUpdate(); @@ -40,7 +42,7 @@ void literalSQLrequest() { //dirty call con.close(); } - void batchInsertInForLoop(int[] data) { + void batchInsertInForLoop(int[] data) throws Exception { Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle"); PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?)"); @@ -49,7 +51,6 @@ void batchInsertInForLoop(int[] data) { stmt.setBoolean(2, true); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, (byte) 3); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setByte(4, 'v'); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, (short) 5); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, 6); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, (long) 7); // Noncompliant {{Avoid setting constants in batch update}} @@ -63,12 +64,13 @@ void batchInsertInForLoop(int[] data) { stmt.addBatch(); } int[] nr = stmt.executeBatch(); - logger.log("{} rows updated", IntStream.of(nr).sum()); + String nbRows = IntStream.of(nr).sum() + ""; + System.out.println(nbRows + " rows updated"); con.close(); } - int[] batchInsertInForeachLoop(DummyClass[] data) { + int[] batchInsertInForeachLoop(DummyClass[] data) throws Exception { try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -76,7 +78,6 @@ int[] batchInsertInForeachLoop(DummyClass[] data) { stmt.setInt(1, o.getField1()); stmt.setBoolean(2, Boolean.valueOf("false")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); - stmt.setByte(4, 'v'); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, (short) 5); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, 6); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, 7); // Noncompliant {{Avoid setting constants in batch update}} @@ -91,7 +92,7 @@ int[] batchInsertInForeachLoop(DummyClass[] data) { } - int[] batchInsertInWhileLoop(DummyClass[] data) { + int[] batchInsertInWhileLoop(DummyClass[] data) throws Exception { try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -102,7 +103,6 @@ int[] batchInsertInWhileLoop(DummyClass[] data) { stmt.setBoolean(2, Boolean.TRUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); stmt.setByte(4, Byte.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setByte(4, Character.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, Short.MIN_VALUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, Integer.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, Long.MIN_VALUE); // Noncompliant {{Avoid setting constants in batch update}} @@ -117,7 +117,7 @@ int[] batchInsertInWhileLoop(DummyClass[] data) { } } - int[] batchInsertInWhileLoop(DummyClass[] data) { + int[] batchInsertInWhileLoop2(DummyClass[] data) throws Exception { if (data.length == 0) { return new int[]{}; } @@ -130,11 +130,10 @@ int[] batchInsertInWhileLoop(DummyClass[] data) { stmt.setBoolean(2, Boolean.valueOf(true)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); stmt.setByte(4, Byte.valueOf((byte) 3)); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setByte(4, Character.valueOf('1')); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, Short.valueOf((short) 55)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, Integer.valueOf("222")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, Long.valueOf(0)); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setFloat(8, Float.valueOf(.33)); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setFloat(8, Float.valueOf(.33f)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setDouble(9, Double.valueOf(22)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setString(10, o.getField2()); stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant {{Avoid setting constants in batch update}} @@ -164,4 +163,4 @@ public double getField4() { } -} \ No newline at end of file +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterface.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterface.java new file mode 100644 index 00000000..70403c64 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterface.java @@ -0,0 +1,76 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks; + +import java.io.*; + +class FreeResourcesOfAutoCloseableInterface { + FreeResourcesOfAutoCloseableInterface(FreeResourcesOfAutoCloseableInterface mc) { + + } + + public void foo1() throws Exception { + String fileName = "./FreeResourcesOfAutoCloseableInterface.java"; + try (FileReader fr = new FileReader(fileName); + BufferedReader br = new BufferedReader(fr)) { // Compliant + } catch (IOException e) { + System.err.println(e.getMessage()); + } + } + + public void foo2() throws Exception { + String fileName = "./FreeResourcesOfAutoCloseableInterface.java"; + FileReader fr = null; + BufferedReader br = null; + try { // Noncompliant {{try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface.}} + fr = new FileReader(fileName); + br = new BufferedReader(fr); + System.out.println(br.readLine()); + } catch (IOException e) { + System.err.println(e.getMessage()); + } finally { + if (fr != null) { + fr.close(); + } + if (br != null) { + br.close(); + } + } + } + + /** + * The first method adds a "try" in the stack used to follow if the code is in a try + */ + public void callingMethodWithTheTry() throws IOException { + try { // Compliant + calledMethodWithoutTry(); + } finally { + // Empty block of code + } + } + + /** + * The "try" should have been popped from the stack before entering here + */ + private void calledMethodWithoutTry() throws IOException { + FileWriter myWriter = new FileWriter("somefilepath"); + myWriter.write("something"); + myWriter.flush(); + myWriter.close(); + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstants.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstants.java new file mode 100644 index 00000000..ce5c3caf --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstants.java @@ -0,0 +1,149 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.logging.Logger; + +public class MakeNonReassignedVariablesConstants { + + private final Logger logger = Logger.getLogger(""); // Compliant + + private Object myNonFinalAndNotReassignedObject = new Object(); // Noncompliant {{The variable is never reassigned and can be 'final'}} + private Object myNonFinalAndReassignedObject = new Object(); // Compliant + private final Object myFinalAndNotReassignedObject = new Object(); // Compliant + + private static final String CONSTANT = "toto"; // Compliant + private String varDefinedInClassNotReassigned = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String varDefinedInClassNotUsed = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String varDefinedInClassReassigned = "0"; // Compliant + private String varDefinedInConstructorReassigned = "1"; // Compliant + + // using "this" + private String varDefinedInClassNotReassignedByThis = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String varDefinedInClassReassignedByThis = "0"; // Compliant + private String varDefinedInConstructorReassignedByThis = "1"; // Compliant + + // passing through a method + private String varDefinedInClassReassignedInMethod = "0"; // Compliant + private String varDefinedInClassInFinalMethod = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String varDefinedInClassNotReassignedInMethod = "0"; // Compliant (the String was passed as a non-final parameter to the method) + private String varDefinedInClassReassignedInConstructor = "0"; // Compliant + private String varDefinedInClassInFinalConstructor = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String varDefinedInClassNotReassignedInConstructor = "0"; // Compliant (the String was passed as a non-final parameter to the constructor) + + public MakeNonReassignedVariablesConstants() { + varDefinedInConstructorReassigned = "3"; + this.varDefinedInConstructorReassignedByThis = "3"; + logger.info(varDefinedInConstructorReassigned); + logger.info(this.varDefinedInConstructorReassignedByThis); + } + + public void parameterReassigned(String reassigned) { + reassigned = "10"; + logger.info(reassigned); + } + + public void parameterNotReassigned(final String notReassigned) { + logger.info(notReassigned); + } + + public void parameterNotReassignedNotFinal(String notReassigned) { // Noncompliant {{The variable is never reassigned and can be 'final'}} + logger.info(notReassigned); + } + + void localVariableReassigned() { + String y1 = "10"; // Compliant + final String PI = "3.14159"; // Compliant + + y1 = "titi"; + + logger.info(y1); + logger.info(PI); + } + + void localVariableIncrement() { + String y2 = "10"; // Compliant + y2 += "titi"; + logger.info(y2); + } + + void localIntVariableIncrement() { + int y3 = 10; // Compliant + ++y3; + logger.info(y3+""); + } + + void localVariableNotReassigned() { + String y4 = "10"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + final String PI2 = "3.14159"; // Compliant + + logger.info(y4); + logger.info(PI2); + } + + void classVariableReassigned() { + varDefinedInClassReassigned = "1"; + + logger.info(varDefinedInClassReassigned); + logger.info(varDefinedInClassNotReassigned); + logger.info(CONSTANT); + } + + void classVariableReassignedBis() { + varDefinedInClassReassigned = "2"; // method to avoid sonarqube error asking for moving class variable "varDefinedInClassReassigned" to local variable method + myNonFinalAndReassignedObject = new Object(); + + logger.info(varDefinedInClassReassigned); + logger.info(myNonFinalAndReassignedObject.toString()); + logger.info(myFinalAndNotReassignedObject.toString()); + } + + void classVariableReassignedByThis() { + this.varDefinedInClassReassignedByThis = "1"; + + logger.info(this.varDefinedInClassReassignedByThis); + logger.info(this.varDefinedInClassNotReassignedByThis); + } + + void reassignedInMethod() { + String varDefinedInMethodReassignedInMethod = "0"; // Compliant + String varDefinedInMethodInFinalMethod = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + String varDefinedInMethodNotReassignedInMethod = "0"; // Compliant (the String was passed as a non-final parameter to the method) + + this.parameterReassigned(varDefinedInMethodReassignedInMethod); + this.parameterReassigned(this.varDefinedInClassReassignedInMethod); + this.parameterNotReassigned(varDefinedInMethodInFinalMethod); + this.parameterNotReassigned(this.varDefinedInClassInFinalMethod); + this.parameterNotReassignedNotFinal(varDefinedInMethodNotReassignedInMethod); + this.parameterNotReassignedNotFinal(this.varDefinedInClassNotReassignedInMethod); + } + + void reassignedInConstructor(){ + String varDefinedInMethodReassignedInConstructor = "0"; // Compliant + String varDefinedInMethodInFinalConstructor = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + String varDefinedInMethodNotReassignedInConstructor = "0"; // Compliant (the String was passed as a non-final parameter to the constructor) + Object o = null; + o = new reassignedInConstructor(varDefinedInMethodReassignedInConstructor); + o = new reassignedInConstructor(this.varDefinedInClassReassignedInConstructor); + o = new notReassignedInConstructor(varDefinedInMethodInFinalConstructor); + o = new notReassignedInConstructor(this.varDefinedInClassInFinalConstructor); + o = new notReassignedInConstructorNotFinal(varDefinedInMethodNotReassignedInConstructor); + o = new notReassignedInConstructorNotFinal(this.varDefinedInClassNotReassignedInConstructor); + } + +} + +class reassignedInConstructor{ + reassignedInConstructor(String reassignedInConstructor) { + reassignedInConstructor = "10"; + System.out.println(reassignedInConstructor); + } +} +class notReassignedInConstructor{ + notReassignedInConstructor(final String notReassignedInConstructor) { + System.out.println(notReassignedInConstructor); + } +} +class notReassignedInConstructorNotFinal{ + notReassignedInConstructorNotFinal(String notReassignedInConstructorNotFinal) { // Noncompliant {{The variable is never reassigned and can be 'final'}} + System.out.println(notReassignedInConstructorNotFinal); + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForAbstractMethod.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForAbstractMethod.java new file mode 100644 index 00000000..e5d075a7 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForAbstractMethod.java @@ -0,0 +1,23 @@ +package org.greencodeinitiative.creedengo.java.checks; + +@FunctionalInterface +interface EventListenerSample { + /** + * Callback method when an event occurs + * @param value Event data + * @return False if this event must stop at this treatment. + */ + boolean onEvent(T value); // Compliant +} + +interface InterfaceWithMultipleMethods { + void abstractMethod(String param); // Compliant + + default void defaultMethod(String param) { // Noncompliant {{The variable is never reassigned and can be 'final'}} + System.out.println(param); + } + + static void staticMethod(String param) { // Noncompliant {{The variable is never reassigned and can be 'final'}} + System.out.println(param); + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForInstanceOf.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForInstanceOf.java new file mode 100644 index 00000000..5ab7abd4 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForInstanceOf.java @@ -0,0 +1,30 @@ +package org.greencodeinitiative.creedengo.java.checks; + +public class MakeNonReassignedVariablesConstantsForInstanceOf { + + public String nonReasignedVariableWithPatternInstanceOfShouldBeNonCompliant() { + final Object o = "NON-COMPLIANT"; + if (o instanceof String var) { // Noncompliant {{The variable is never reassigned and can be 'final'}} + return var; + } + return ""; + } + + public String nonReasignedVariableWithPatternInstanceOfWithFinalShouldBeCompliant() { + final Object o = "COMPLIANT"; + if (o instanceof final String var) { // Compliant : here final keyword should be recognized and not trigger the rule + return var; + } + return ""; + } + + public String reasignedVariableWithPatternInstanceOfShouldBeCompliant() { + final Object o = "COMPLIANT"; + if (o instanceof String var) { // Compliant : Variable is reassigned + var = "REASSIGN"; + return var; + } + return ""; + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForLombok.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForLombok.java new file mode 100644 index 00000000..12c5880c --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForLombok.java @@ -0,0 +1,55 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import lombok.Setter; +import lombok.Data; +import lombok.AccessLevel; + +class myExtraClassWithLombokAttributeSetter { + + @Setter + private String myLombokManagedString = "initialValue"; // Compliant + +} + +@Setter +class myExtraClassWithLombokSetter { + + private String myExtraClassString = "initialValue"; // Compliant + private final String myExtraClassFinalString = "initialValue"; // Compliant + + @Setter(AccessLevel.NONE) // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String myExtraClassSetterNoneString = "initialValue"; +} + +@Data +class myExtraClassWithLombokData { + private String myExtraClassString = "initialValue"; // Compliant + private final String myExtraClassFinalString = "initialValue"; // Compliant + + @Setter(AccessLevel.NONE) // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String myExtraClassSetterNoneString = "initialValue"; +} + +// fully qualified annotations : valid Java, and the only available form when there is no lombok import +@Setter +class myExtraClassWithFullyQualifiedLombokSetter { + private String myExtraClassString = "initialValue"; // Compliant + + @Setter(value = AccessLevel.NONE) // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String myNamedArgumentSetterNoneString = "initialValue"; + + @Setter(lombok.AccessLevel.NONE) // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String myFullyQualifiedSetterNoneString = "initialValue"; +} + +@Data +class myExtraClassWithFullyQualifiedLombokData { + private String myExtraClassString = "initialValue"; // Compliant +} + +class myExtraClassWithFullyQualifiedFieldSetter { + @Setter + private String myFullyQualifiedSetterString = "initialValue"; // Compliant + + private String myPlainNotReassignedString = "initialValue"; // Noncompliant {{The variable is never reassigned and can be 'final'}} +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForRecord.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForRecord.java new file mode 100644 index 00000000..c02d0b8d --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsForRecord.java @@ -0,0 +1,9 @@ +package org.greencodeinitiative.creedengo.java.checks; + +public class MakeNonReassignedVariablesConstantsForRecord { + + private record myRecord( + String myImplicitlyFinalStringField, // Compliant + Integer myImplicitlyFinalIntField) // Compliant + { } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsWithoutLombokImport.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsWithoutLombokImport.java new file mode 100644 index 00000000..8a05b275 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsWithoutLombokImport.java @@ -0,0 +1,35 @@ +package org.greencodeinitiative.creedengo.java.checks; + +// No "import lombok.*" here on purpose : Lombok annotations are only used in their fully qualified form, +// which is valid Java and used to be a false positive (the rule required an explicit import to be found). + +class MakeNonReassignedVariablesConstantsWithoutLombokImport { + + @lombok.Setter + private String myLombokManagedString = "initialValue"; // Compliant + + private String myPlainNotReassignedString = "initialValue"; // Noncompliant {{The variable is never reassigned and can be 'final'}} + + @lombok.Setter(lombok.AccessLevel.NONE) // Noncompliant {{The variable is never reassigned and can be 'final'}} + private String mySetterNoneString = "initialValue"; + +} + +@lombok.Setter +class myClassWithFullyQualifiedLombokSetterAndNoImport { + private String myClassString = "initialValue"; // Compliant + private final String myClassFinalString = "initialValue"; // Compliant +} + +@lombok.Data +class myClassWithFullyQualifiedLombokDataAndNoImport { + private String myClassString = "initialValue"; // Compliant + private final String myClassFinalString = "initialValue"; // Compliant +} + +class myExtraClassWithFullyQualifiedFieldSetterAndNoImport { + @lombok.Setter + private String myFullyQualifiedSetterString = "initialValue"; // Compliant + + private String myPlainNotReassignedString = "initialValue"; // Noncompliant {{The variable is never reassigned and can be 'final'}} +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElse.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElse.java new file mode 100644 index 00000000..8d918a43 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElse.java @@ -0,0 +1,62 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.Optional; + +class UseOptionalOrElseGetVsOrElse { + + private static final String DEFAULT_NAME = "default"; + + private static Optional variable = Optional.empty(); + + public static final String NAME = Optional.of("creedengo").orElse(getUnpredictedMethod()); // Noncompliant {{Use optional orElseGet instead of orElse.}} + + public static final String NAME_CONCAT = Optional.of("creedengo").orElse("prefix_" + getUnpredictedMethod()); // Noncompliant {{Use optional orElseGet instead of orElse.}} + + public static final String NAME_NEW = Optional.of("creedengo").orElse(new StringBuilder().toString()); // Noncompliant {{Use optional orElseGet instead of orElse.}} + + public static final String NAME7 = variable.orElse(getUnpredictedMethod()); // Noncompliant {{Use optional orElseGet instead of orElse.}} + + public static final String NAME2 = Optional.of("creedengo").orElseGet(() -> getUnpredictedMethod()); // Compliant + + public static final String NAME3 = Optional.of("creedengo").orElseGet(UseOptionalOrElseGetVsOrElse::getUnpredictedMethod); // Compliant + + public static final String NAME4 = Optional.of("creedengo").orElse(DEFAULT_NAME); // Compliant - constant + + public static final String NAME5 = Optional.of("creedengo").orElse("fallback"); // Compliant - string literal + + public static final String NAME6 = Optional.of("creedengo").orElse(null); // Compliant - null literal + + public static final Boolean FLAG = Optional.of(Boolean.TRUE).orElse(Boolean.FALSE); // Compliant - static field reference + + private static String getUnpredictedMethod() { + return "unpredicted"; + } + + static void testVariableCases() { + Optional opt = Optional.of("creedengo"); + String r1 = opt.orElse(getUnpredictedMethod()); // Noncompliant {{Use optional orElseGet instead of orElse.}} + String r2 = opt.orElse("a" + getUnpredictedMethod()); // Noncompliant {{Use optional orElseGet instead of orElse.}} + String r3 = opt.orElse(Boolean.TRUE ? getUnpredictedMethod() : DEFAULT_NAME); // Noncompliant {{Use optional orElseGet instead of orElse.}} + String r4 = opt.orElse(new String("default")); // Noncompliant {{Use optional orElseGet instead of orElse.}} + String r5 = opt.orElse(DEFAULT_NAME); // Compliant - constant + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/tool_send_to_sonar.sh b/src/it/test-projects/creedengo-java-plugin-test-project/tool_send_to_sonar.sh new file mode 100755 index 00000000..c3309abd --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/tool_send_to_sonar.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env sh + +# "sonar.login" kept only for SONARQUBE < 10 + +# mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.11.0.3922:sonar -Dsonar.host.url=http://localhost:$1 -Dsonar.login=$2 -Dsonar.token=$2 +mvn org.sonarsource.scanner.maven:sonar-maven-plugin:4.0.0.4121:sonar -Dsonar.host.url=http://localhost:$1 -Dsonar.login=$2 -Dsonar.token=$2 diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java deleted file mode 100644 index 488ebd0c..00000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import java.util.Arrays; -import java.util.List; -import javax.annotation.Nonnull; - -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; -import org.sonar.plugins.java.api.tree.BaseTreeVisitor; -import org.sonar.plugins.java.api.tree.BinaryExpressionTree; -import org.sonar.plugins.java.api.tree.ExpressionTree; -import org.sonar.plugins.java.api.tree.Tree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -/** - * @deprecated because not useless since JDK 8 - */ -@Deprecated(forRemoval = true) -@Rule(key = "EC75") -@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S75") -public class AvoidConcatenateStringsInLoop extends IssuableSubscriptionVisitor { - - public static final String MESSAGE_RULE = "Don't concatenate Strings in loop, use StringBuilder instead."; - private static final String STRING_CLASS = String.class.getName(); - - private final StringConcatenationVisitor visitor = new StringConcatenationVisitor(); - - @Override - public List nodesToVisit() { - return Arrays.asList( - Tree.Kind.FOR_STATEMENT, - Tree.Kind.FOR_EACH_STATEMENT, - Tree.Kind.WHILE_STATEMENT - ); - } - - @Override - public void visitNode(@Nonnull Tree tree) { - tree.accept(visitor); - } - - private class StringConcatenationVisitor extends BaseTreeVisitor { - @Override - public void visitBinaryExpression(BinaryExpressionTree tree) { - if (tree.is(Tree.Kind.PLUS) && isStringType(tree.leftOperand())) { - reportIssue(tree, MESSAGE_RULE); - } else { - super.visitBinaryExpression(tree); - } - } - - @Override - public void visitAssignmentExpression(AssignmentExpressionTree tree) { - if (tree.is(Tree.Kind.PLUS_ASSIGNMENT) && isStringType(tree.variable())) { - reportIssue(tree, MESSAGE_RULE); - } else { - super.visitAssignmentExpression(tree); - } - } - - private boolean isStringType(ExpressionTree expressionTree) { - return expressionTree.symbolType().is(STRING_CLASS); - } - } - -} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java deleted file mode 100644 index 26a6dbdd..00000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import com.google.re2j.Pattern; -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.tree.Tree; -import org.sonar.plugins.java.api.tree.Tree.Kind; -import org.sonar.plugins.java.api.tree.VariableTree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -import java.util.Arrays; -import java.util.List; - -/** - * Check to avoid using global variables. - * - * @deprecated because not applicable to Java language, to be removed soon - */ -@Deprecated(forRemoval = true) -@Rule(key = "EC4") -@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "D4") -public class AvoidUsingGlobalVariablesCheck extends IssuableSubscriptionVisitor { - - private static final String ERROR_MESSAGE = "Avoid using global variables"; - private static final Pattern PATTERN = Pattern.compile("^.*(static).*$", Pattern.CASE_INSENSITIVE); - - @Override - public List nodesToVisit() { - return Arrays.asList(Kind.STATIC_INITIALIZER, Kind.VARIABLE, Kind.METHOD); - } - - @Override - public void visitNode(Tree tree) { - if (tree.is(Kind.STATIC_INITIALIZER)) { - reportIssue(tree, String.format(ERROR_MESSAGE, tree)); - } - if (tree.is(Kind.VARIABLE)) { - VariableTree variableTree = (VariableTree) tree; - int modifiersSize = (variableTree).modifiers().modifiers().size(); - for (int i = 0; i < modifiersSize; i++) { - String modifier = ((VariableTree) tree).modifiers().modifiers().get(i).modifier().toString(); - if (PATTERN.matcher(modifier).matches()) { - reportIssue(tree, String.format(ERROR_MESSAGE, modifier)); - } - } - } - } - -} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java deleted file mode 100644 index 47cbc2eb..00000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.JavaFileScannerContext; -import org.sonar.plugins.java.api.JavaVersion; -import org.sonar.plugins.java.api.tree.NewClassTree; -import org.sonar.plugins.java.api.tree.Tree; -import org.sonar.plugins.java.api.tree.TryStatementTree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - - -@Rule(key = "EC79") -@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S79") -public class FreeResourcesOfAutoCloseableInterface extends IssuableSubscriptionVisitor { - private final Deque withinTry = new LinkedList<>(); - private final Deque> toReport = new LinkedList<>(); - - private static final String JAVA_LANG_AUTOCLOSEABLE = "java.lang.AutoCloseable"; - protected static final String MESSAGE_RULE = "try-with-resources Statement needs to be implemented for any object that implements the AutoClosable interface."; - - @Override - @ParametersAreNonnullByDefault - public void leaveFile(JavaFileScannerContext context) { - withinTry.clear(); - toReport.clear(); - } - - @Override - public List nodesToVisit() { - return Arrays.asList(Tree.Kind.TRY_STATEMENT, Tree.Kind.NEW_CLASS); - } - - @Override - public void visitNode(Tree tree) { - if (tree.is(Tree.Kind.TRY_STATEMENT)) { - withinTry.push((TryStatementTree) tree); - if (withinTry.size() != toReport.size()) { - toReport.push(new ArrayList<>()); - } - } - if (tree.is(Tree.Kind.NEW_CLASS) && ((NewClassTree) tree).symbolType().isSubtypeOf(JAVA_LANG_AUTOCLOSEABLE) && withinStandardTryWithFinally()) { - assert toReport.peek() != null; - toReport.peek().add(tree); - } - } - - @Override - public void leaveNode(Tree tree) { - if (tree.is(Tree.Kind.TRY_STATEMENT)) { - List secondaryTrees = toReport.pop(); - if (!secondaryTrees.isEmpty()) { - reportIssue(tree, MESSAGE_RULE); - } - } - } - - private boolean withinStandardTryWithFinally() { - if (withinTry.isEmpty() || !withinTry.peek().resourceList().isEmpty()) return false; - assert withinTry.peek() != null; - return withinTry.peek().finallyBlock() != null; - } - - public boolean isCompatibleWithJavaVersion(JavaVersion version) { - return version.isJava7Compatible(); - } -} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java deleted file mode 100644 index aba735bf..00000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.JavaFileScanner; -import org.sonar.plugins.java.api.JavaFileScannerContext; -import org.sonar.plugins.java.api.tree.*; -import org.sonar.plugins.java.api.tree.Tree.Kind; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -import javax.annotation.CheckForNull; -import java.util.*; - -/** - * @deprecated not applicable because of existing Sonarqube native rules : - * - unused variable : https://rules.sonarsource.com/java/tag/unused/RSPEC-1481/ - * - useless assignment : https://rules.sonarsource.com/java/tag/unused/RSPEC-1854 - * - immediately return : https://rules.sonarsource.com/java/RSPEC-1488/ - */ -@Deprecated(forRemoval = true) -@Rule(key = "EC63") -@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S63") -public class UnnecessarilyAssignValuesToVariables extends BaseTreeVisitor implements JavaFileScanner { - - protected static final String MESSAGERULE1 = "The variable is declared but not really used"; - protected static final String MESSAGERULE2 = "Immediately throw this expression instead of assigning it to the temporary variable"; - protected static final String MESSAGERULE3 = "Immediately return this expression instead of assigning it to the temporary variable"; - private JavaFileScannerContext context; - private String errorMessage; - private final Map variableList = new HashMap<>(); - private static final Map> linesWithIssuesByVariable = new HashMap<>(); - - @Override - public void scanFile(JavaFileScannerContext context) { - this.context = context; - scan(context.getTree()); - } - - @Override - public void visitBlock(BlockTree tree) { - GetVariableVisitor getVariableVisitor = new GetVariableVisitor(); - CheckUseVariableVisitor checkVariable = new CheckUseVariableVisitor(); - super.visitBlock(tree); - checkImmediatelyReturnedVariable(tree); - tree.accept(getVariableVisitor); - tree.accept(checkVariable); - - variableList.forEach(this::reportIfUnknow); - variableList.clear(); - } - - private void reportIfUnknow(String name, Tree tree) { - Integer issueLine = tree.firstToken().range().start().line(); - - if (!(linesWithIssuesByVariable.containsKey(name) && linesWithIssuesByVariable.get(name).contains(issueLine))) { - if (!linesWithIssuesByVariable.containsKey(name)) { - linesWithIssuesByVariable.put(name, new ArrayList<>()); - } - - linesWithIssuesByVariable.get(name).add(issueLine); - - context.reportIssue(this, tree, MESSAGERULE1); - } - } - - private class GetVariableVisitor extends BaseTreeVisitor { - @Override - public void visitVariable(VariableTree tree) { - if (!tree.parent().is(Kind.METHOD)) { - variableList.put(tree.simpleName().name(), tree); - } - super.visitVariable(tree); - } - } - - private class CheckUseVariableVisitor extends BaseTreeVisitor { - - @Override - public void visitIfStatement(IfStatementTree tree) { - variableList.remove(tree.condition().toString()); - super.visitIfStatement(tree); - } - - @Override - public void visitUnaryExpression(UnaryExpressionTree tree) { - variableList.remove(tree.expression().toString()); - super.visitUnaryExpression(tree); - } - - @Override - public void visitForEachStatement(ForEachStatement tree) { - variableList.remove(tree.expression().toString()); - super.visitForEachStatement(tree); - } - - @Override - public void visitMethodInvocation(MethodInvocationTree tree) { - tree.arguments().forEach(e -> { - if (variableList.containsKey(e.toString())) { - variableList.remove(e.toString()); - } - }); - super.visitMethodInvocation(tree); - } - - @Override - public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { - variableList.remove(tree.expression().toString()); - super.visitMemberSelectExpression(tree); - } - - @Override - public void visitTypeCast(TypeCastTree tree) { - variableList.remove(tree.expression().toString()); - super.visitTypeCast(tree); - } - - @Override - public void visitBinaryExpression(BinaryExpressionTree tree) { - if (!tree.operatorToken().is(Kind.ASSIGNMENT)) { - variableList.remove(tree.leftOperand().toString()); - } - variableList.remove(tree.rightOperand().toString()); - super.visitBinaryExpression(tree); - } - - @Override - public void visitNewClass(NewClassTree tree) { - tree.arguments().forEach(e -> { - if (variableList.containsKey(e.toString())) { - variableList.remove(e.toString()); - } - }); - super.visitNewClass(tree); - } - - @Override - public void visitReturnStatement(ReturnStatementTree tree) { - if (tree != null) { - if (tree.expression() != null) { - variableList.remove(tree.expression().toString()); - } - super.visitReturnStatement(tree); - } - } - - @Override - public void visitThrowStatement(ThrowStatementTree tree) { - variableList.remove(tree.expression().toString()); - super.visitThrowStatement(tree); - } - - @Override - public void visitAssignmentExpression(AssignmentExpressionTree tree) { - variableList.remove(tree.expression().toString()); - super.visitAssignmentExpression(tree); - } - - } - - private void checkImmediatelyReturnedVariable(BlockTree tree) { - List statements = tree.body(); - int size = statements.size(); - if (size < 2) { - return; - } - StatementTree butLastStatement = statements.get(size - 2); - if (butLastStatement.is(Kind.VARIABLE)) { - VariableTree variableTree = (VariableTree) butLastStatement; - if (!variableTree.modifiers().annotations().isEmpty()) { - return; - } - StatementTree lastStatement = statements.get(size - 1); - String lastStatementIdentifier = getReturnOrThrowIdentifier(lastStatement); - if (lastStatementIdentifier != null) { - String identifier = variableTree.simpleName().name(); - if (lastStatementIdentifier.equals(identifier)) { - context.reportIssue(this, variableTree.initializer(), errorMessage); - } - } - } - } - - @CheckForNull - private String getReturnOrThrowIdentifier(StatementTree lastStatementOfBlock) { - errorMessage = null; - ExpressionTree expr = null; - if (lastStatementOfBlock.is(Kind.THROW_STATEMENT)) { - errorMessage = MESSAGERULE2; - expr = ((ThrowStatementTree) lastStatementOfBlock).expression(); - } else if (lastStatementOfBlock.is(Kind.RETURN_STATEMENT)) { - errorMessage = MESSAGERULE3; - expr = ((ReturnStatementTree) lastStatementOfBlock).expression(); - } - if (expr != null && expr.is(Kind.IDENTIFIER)) { - return ((IdentifierTree) expr).name(); - } - return null; - } - -} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java deleted file mode 100644 index 35c7f677..00000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import java.util.Arrays; -import java.util.List; - -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.tree.ForEachStatement; -import org.sonar.plugins.java.api.tree.Tree; -import org.sonar.plugins.java.api.tree.Tree.Kind; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -/** - * @deprecated there aren't enough good arguments and not enough green measures / benchmarks - * (check discussion on https://github.com/green-code-initiative/ecoCode/issues/240) - */ -@Deprecated(forRemoval = true) -@Rule(key = "EC53") -@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S53") -public class UseCorrectForLoop extends IssuableSubscriptionVisitor { - - protected static final String MESSAGERULE = "Avoid the use of Foreach with Arrays"; - - @Override - public List nodesToVisit() { - return Arrays.asList(Tree.Kind.FOR_EACH_STATEMENT); - } - - @Override - public void visitNode(Tree tree) { - - ForEachStatement forEachTree = (ForEachStatement) tree; - if (forEachTree.expression().symbolType().isArray()) { - reportIssue(tree, MESSAGERULE); - } - } -} diff --git a/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java b/src/main/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrar.java similarity index 58% rename from src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java rename to src/main/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrar.java index f972a202..791f0cef 100644 --- a/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrar.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,30 +15,12 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java; +package org.greencodeinitiative.creedengo.java; import java.util.Collections; import java.util.List; -import fr.greencodeinitiative.java.checks.ArrayCopyCheck; -import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; -import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; -import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; -import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; -import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; -import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; -import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; -import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; -import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; -import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; -import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; -import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; -import fr.greencodeinitiative.java.checks.IncrementCheck; -import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; -import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; -import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; -import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; -import fr.greencodeinitiative.java.checks.UseCorrectForLoop; +import org.greencodeinitiative.creedengo.java.checks.*; import org.sonar.plugins.java.api.CheckRegistrar; import org.sonar.plugins.java.api.JavaCheck; import org.sonarsource.api.sonarlint.SonarLintSide; @@ -51,10 +33,9 @@ */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { - private static final List> ANNOTATED_RULE_CLASSES = List.of( + static final List> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class, - AvoidConcatenateStringsInLoop.class, AvoidUsageOfStaticCollections.class, AvoidGettingSizeCollectionInLoop.class, AvoidRegexPatternNotStatic.class, @@ -63,14 +44,13 @@ public class JavaCheckRegistrar implements CheckRegistrar { AvoidSpringRepositoryCallInLoopOrStreamCheck.class, AvoidSQLRequestInLoop.class, AvoidFullSQLRequest.class, - UseCorrectForLoop.class, - UnnecessarilyAssignValuesToVariables.class, OptimizeReadFileExceptions.class, InitializeBufferWithAppropriateSize.class, - AvoidUsingGlobalVariablesCheck.class, AvoidSetConstantInBatchUpdate.class, FreeResourcesOfAutoCloseableInterface.class, - AvoidMultipleIfElseStatement.class + AvoidMultipleIfElseStatement.class, + UseOptionalOrElseGetVsOrElse.class, + MakeNonReassignedVariablesConstants.class ); /** diff --git a/src/main/java/org/greencodeinitiative/creedengo/java/JavaCreedengoWayProfile.java b/src/main/java/org/greencodeinitiative/creedengo/java/JavaCreedengoWayProfile.java new file mode 100644 index 00000000..3d48034c --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/JavaCreedengoWayProfile.java @@ -0,0 +1,40 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java; + +import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; +import org.sonarsource.analyzer.commons.BuiltInQualityProfileJsonLoader; + +import static org.greencodeinitiative.creedengo.java.JavaRulesDefinition.LANGUAGE; +import static org.greencodeinitiative.creedengo.java.JavaRulesDefinition.REPOSITORY_KEY; + +public final class JavaCreedengoWayProfile implements BuiltInQualityProfilesDefinition { + static final String PROFILE_NAME = "creedengo way"; + static final String PROFILE_PATH = JavaCreedengoWayProfile.class.getPackageName().replace('.', '/') + "/creedengo_way_profile.json"; + + @Override + public void define(Context context) { + NewBuiltInQualityProfile creedengoProfile = context.createBuiltInQualityProfile(PROFILE_NAME, LANGUAGE); + loadProfile(creedengoProfile); + creedengoProfile.done(); + } + + private void loadProfile(NewBuiltInQualityProfile profile) { + BuiltInQualityProfileJsonLoader.load(profile, REPOSITORY_KEY, PROFILE_PATH); + } +} diff --git a/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java b/src/main/java/org/greencodeinitiative/creedengo/java/JavaPlugin.java similarity index 82% rename from src/main/java/fr/greencodeinitiative/java/JavaPlugin.java rename to src/main/java/org/greencodeinitiative/creedengo/java/JavaPlugin.java index ff070c1b..ce2a95ce 100644 --- a/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/JavaPlugin.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java; +package org.greencodeinitiative.creedengo.java; import org.sonar.api.Plugin; diff --git a/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java b/src/main/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinition.java similarity index 77% rename from src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java rename to src/main/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinition.java index 958edc82..ff30929f 100644 --- a/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinition.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java; +package org.greencodeinitiative.creedengo.java; import java.util.ArrayList; @@ -28,11 +28,11 @@ * That allows to list the rules in the page "Rules". */ public class JavaRulesDefinition implements RulesDefinition { - private static final String RESOURCE_BASE_PATH = "io/ecocode/rules/java"; + private static final String RESOURCE_BASE_PATH = "org/green-code-initiative/rules/java"; - private static final String NAME = "ecoCode"; - private static final String LANGUAGE = "java"; - static final String REPOSITORY_KEY = "ecocode-java"; + private static final String NAME = "creedengo"; + static final String LANGUAGE = "java"; + static final String REPOSITORY_KEY = "creedengo-java"; private final SonarRuntime sonarRuntime; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheck.java similarity index 97% rename from src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheck.java index b594af9d..bc4d569e 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.ArrayList; import java.util.Arrays; @@ -53,7 +53,8 @@ * @author Aubay * @formatter:off */ -@Rule(key = "EC27") +@Rule(key = "GCI27") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC27") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRPS0027") public class ArrayCopyCheck extends IssuableSubscriptionVisitor { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequest.java similarity index 85% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequest.java index 88ff715c..e2c7fb67 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.List; import java.util.function.Predicate; @@ -31,7 +31,8 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC74") +@Rule(key = "GCI74") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC74") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S74") public class AvoidFullSQLRequest extends IssuableSubscriptionVisitor { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInLoop.java similarity index 93% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInLoop.java index c81d7953..53f2e085 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInLoop.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; @@ -34,7 +34,8 @@ import org.sonar.plugins.java.api.tree.WhileStatementTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC3") +@Rule(key = "GCI3") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC3") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GSCIL") public class AvoidGettingSizeCollectionInLoop extends IssuableSubscriptionVisitor { protected static final String MESSAGERULE = "Avoid getting the size of the collection in the loop"; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java similarity index 96% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java index 70c6c5e5..7343979c 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.HashMap; import java.util.List; @@ -35,7 +35,7 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; /** - * FUNCTIONAL DESCRIPTION : please see ASCIIDOC description file of this rule (inside `ecocode-rules-spcifications`) + * FUNCTIONAL DESCRIPTION : please see ASCIIDOC description file of this rule (inside `creedengo-rules-spcifications`) * TECHNICAL CHOICES : * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT not used because it isn't possible * to keep parent references to check later if variables already used or not in parent tree @@ -43,7 +43,8 @@ * - an "ELSE" statement is considered as a second IF statement using the same variables used on previous * - IF and ELSEIF statements are considered as an IF statement */ -@Rule(key = "EC2") +@Rule(key = "GCI2") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC2") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "AMIES") public class AvoidMultipleIfElseStatement extends IssuableSubscriptionVisitor { @@ -305,7 +306,9 @@ private Integer internalGetVariableUsageOfNearestParent(Map= 0 && nbParentUsed == null; i--) { Map variablesParentLevelMap = pDataMap.get(i); - nbParentUsed = variablesParentLevelMap.get(variableName); + if (variablesParentLevelMap != null) { + nbParentUsed = variablesParentLevelMap.get(variableName); + } } return nbParentUsed; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStatic.java similarity index 88% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStatic.java index 2561a6c0..beb1cea6 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStatic.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collections; import java.util.List; @@ -32,7 +32,8 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC77") +@Rule(key = "GCI77") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC77") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S77") public class AvoidRegexPatternNotStatic extends IssuableSubscriptionVisitor { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoop.java similarity index 92% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoop.java index 1e3aab82..0e830dcf 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoop.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; @@ -30,7 +30,8 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC72") +@Rule(key = "GCI72") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC72") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S72") public class AvoidSQLRequestInLoop extends IssuableSubscriptionVisitor { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdate.java similarity index 82% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdate.java index 4fe31abd..76f9ed51 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdate.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,14 +15,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.sql.PreparedStatement; import java.util.List; import java.util.stream.Stream; -import fr.greencodeinitiative.java.checks.enums.ConstOrLiteralDeclare; -import static fr.greencodeinitiative.java.checks.enums.ConstOrLiteralDeclare.isLiteral; +import org.greencodeinitiative.creedengo.java.checks.enums.ConstOrLiteralDeclare; +import static org.greencodeinitiative.creedengo.java.checks.enums.ConstOrLiteralDeclare.isLiteral; import static java.util.Arrays.asList; import org.sonar.check.Rule; @@ -39,11 +39,12 @@ import static org.sonar.plugins.java.api.tree.Tree.Kind.MEMBER_SELECT; import static org.sonar.plugins.java.api.tree.Tree.Kind.METHOD_INVOCATION; -@Rule(key = "EC78") +@Rule(key = "GCI78") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC78") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S78") public class AvoidSetConstantInBatchUpdate extends IssuableSubscriptionVisitor { - protected static final String MESSAGERULE = "Avoid setting constants in batch update"; + protected static final String MESSAGE_RULE = "Avoid setting constants in batch update"; private final AvoidSetConstantInBatchUpdateVisitor visitorInFile = new AvoidSetConstantInBatchUpdateVisitor(); @Override @@ -70,14 +71,14 @@ private class AvoidSetConstantInBatchUpdateVisitor extends BaseTreeVisitor { @Override public void visitMethodInvocation(MethodInvocationTree tree) { if (setters.matches(tree) && isConstant(tree.arguments().get(1))) { - reportIssue(tree, MESSAGERULE); + reportIssue(tree, MESSAGE_RULE); } else { super.visitMethodInvocation(tree); } } } - private static final boolean isConstant(Tree arg) { + private static boolean isConstant(Tree arg) { if (arg.is(METHOD_INVOCATION)) { MethodInvocationTree m = (MethodInvocationTree) arg; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopOrStreamCheck.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopOrStreamCheck.java similarity index 93% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopOrStreamCheck.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopOrStreamCheck.java index 3222799c..a71777c0 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopOrStreamCheck.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopOrStreamCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; import java.util.List; @@ -26,7 +26,8 @@ import org.sonar.plugins.java.api.tree.*; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC1") +@Rule(key = "GCI1") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC1") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRC1") public class AvoidSpringRepositoryCallInLoopOrStreamCheck extends IssuableSubscriptionVisitor { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueries.java similarity index 88% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueries.java index 592f92cb..cb335e04 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueries.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collections; import java.util.List; @@ -31,7 +31,8 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC5") +@Rule(key = "GCI5") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC5") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "SDMLQ1") public class AvoidStatementForDMLQueries extends IssuableSubscriptionVisitor { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollections.java similarity index 87% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollections.java index 18a7fb7f..8017381a 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollections.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collections; import java.util.List; @@ -30,7 +30,8 @@ import org.sonar.plugins.java.api.tree.VariableTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC76") +@Rule(key = "GCI76") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC76") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S76") public class AvoidUsageOfStaticCollections extends IssuableSubscriptionVisitor { diff --git a/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java new file mode 100644 index 00000000..2fc5c542 --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java @@ -0,0 +1,162 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import org.sonar.check.Rule; +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.JavaFileScannerContext; +import org.sonar.plugins.java.api.tree.NewClassTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.TryStatementTree; +import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; + +/** + * This rule checks that objects implementing AutoCloseable interface are properly managed + * using try-with-resources statement instead of try-finally blocks. + *

+ * Try-with-resources ensures proper resource management and reduces the risk of resource leaks. + * It also reduces boilerplate code and improves code readability. + *

+ * From an environmental perspective, proper resource management prevents resource leaks + * which can lead to increased memory consumption and unnecessary CPU cycles. + * + * @see Try-with-resources + */ +@Rule(key = "GCI79") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC79") +@DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S79") +public class FreeResourcesOfAutoCloseableInterface extends IssuableSubscriptionVisitor { + + /** + * Stack to track nested try statements while traversing the AST + */ + private final Deque tryStack = new ArrayDeque<>(); + + private static final String JAVA_LANG_AUTOCLOSEABLE = "java.lang.AutoCloseable"; + protected static final String MESSAGE_RULE = "try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface."; + + @Override + @ParametersAreNonnullByDefault + public void leaveFile(JavaFileScannerContext context) { + tryStack.clear(); + } + + @Override + @Nonnull + public List nodesToVisit() { + return List.of(Tree.Kind.TRY_STATEMENT, Tree.Kind.NEW_CLASS); + } + + @Override + public void visitNode(@Nonnull Tree tree) { + if (tree.is(Tree.Kind.TRY_STATEMENT)) { + handleTryStatement((TryStatementTree) tree); + } else if (tree.is(Tree.Kind.NEW_CLASS)) { + handleNewClass((NewClassTree) tree); + } + } + + @Override + public void leaveNode(@Nonnull Tree tree) { + if (tree.is(Tree.Kind.TRY_STATEMENT)) { + leaveTryStatement(); + } + } + + /** + * Handle entering a try statement by pushing it onto the stack + */ + private void handleTryStatement(@Nonnull TryStatementTree tryStatement) { + tryStack.push(new TryStatementContext(tryStatement)); + } + + /** + * Handle leaving a try statement by popping it from the stack and reporting issues if needed + */ + private void leaveTryStatement() { + if (!tryStack.isEmpty()) { + TryStatementContext context = tryStack.pop(); + if (!context.autoCloseableInstances.isEmpty()) { + reportIssue(context.tryStatement, MESSAGE_RULE); + } + } + } + + /** + * Handle new class instantiation to detect AutoCloseable objects + * that are created inside a try-finally block (without try-with-resources) + */ + private void handleNewClass(@Nonnull NewClassTree newClass) { + // Check if the new instance is an AutoCloseable + if (!newClass.symbolType().isSubtypeOf(JAVA_LANG_AUTOCLOSEABLE)) { + return; + } + + // Check if we are inside a non-compliant try statement + if (isInNonCompliantTry()) { + TryStatementContext context = tryStack.peek(); + if (context != null) { + context.autoCloseableInstances.add(newClass); + } + } + } + + /** + * Check if we are currently inside a try statement that: + * - Does NOT use try-with-resources (no resource list) + * - Has a finally block (indicating manual resource management) + * + * @return true if inside a non-compliant try statement + */ + private boolean isInNonCompliantTry() { + if (tryStack.isEmpty()) { + return false; + } + + TryStatementTree currentTry = tryStack.peek().tryStatement; + + // If try-with-resources is already used, it's compliant + if (!currentTry.resourceList().isEmpty()) { + return false; + } + + // If there's a finally block, it suggests manual resource management + return currentTry.finallyBlock() != null; + } + + /** + * Context class to track information about a try statement during AST traversal + */ + private static class TryStatementContext { + final TryStatementTree tryStatement; + final List autoCloseableInstances; + + TryStatementContext(@Nonnull TryStatementTree tryStatement) { + this.tryStatement = tryStatement; + this.autoCloseableInstances = new ArrayList<>(); + } + } +} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java similarity index 63% rename from src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java index 00c3094d..c418ad6d 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,18 +15,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collections; import java.util.List; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.tree.Arguments; +import org.sonar.plugins.java.api.tree.BinaryExpressionTree; import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.UnaryExpressionTree; import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC67") +@Rule(key = "GCI67") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC67") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S67") public class IncrementCheck extends IssuableSubscriptionVisitor { @@ -39,6 +43,13 @@ public List nodesToVisit() { @Override public void visitNode(Tree tree) { + UnaryExpressionTree unaryExprTree = (UnaryExpressionTree) tree; + + if (unaryExprTree.parent() instanceof BinaryExpressionTree + || unaryExprTree.parent() instanceof Arguments + || unaryExprTree.expression().is(Tree.Kind.MEMBER_SELECT)) { + return ; + } reportIssue(tree, MESSAGERULE); } } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSize.java similarity index 84% rename from src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSize.java index 44caa872..7bcb3b73 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSize.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Collections; import java.util.List; @@ -27,7 +27,8 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC32") +@Rule(key = "GCI32") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC32") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRSP0032") public class InitializeBufferWithAppropriateSize extends IssuableSubscriptionVisitor { diff --git a/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java new file mode 100644 index 00000000..64fbe177 --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java @@ -0,0 +1,316 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; +import org.sonar.check.Rule; +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.location.Position; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.*; +import org.sonar.plugins.java.api.tree.Tree.Kind; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; +import java.util.List; +import java.util.Objects; + +@Rule(key = "GCI82") +public class MakeNonReassignedVariablesConstants extends IssuableSubscriptionVisitor { + + protected static final String MESSAGE_RULE = "The variable is never reassigned and can be 'final'"; + + private static final Logger LOGGER = Loggers.get(MakeNonReassignedVariablesConstants.class); + + private static final String LOMBOK_PACKAGE = "lombok"; + private static final String SETTER = "Setter"; + private static final String DATA = "Data"; + private static final String ACCESS_LEVEL_NONE = "AccessLevel.NONE"; + private static final String NONE = "NONE"; + + @Override + public List nodesToVisit() { + return List.of(Kind.VARIABLE); + } + + @Override + public void visitNode(@Nonnull Tree tree) { + VariableTree variableTree = (VariableTree) tree; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Variable > {}", getVariableNameForLogger(variableTree)); + LOGGER.debug(" => isNotFinalAndNotStatic(variableTree) = {}", isNotFinalAndNotStatic(variableTree)); + LOGGER.debug(" => usages = {}", variableTree.symbol().usages().size()); + LOGGER.debug(" => isNotReassigned = {}", isNotReassigned(variableTree)); + LOGGER.debug(" => isPassedAsNonFinalParameter = {}", isPassedAsNonFinalParameter(variableTree)); + } + + if (isParameterOfAbstractMethod(variableTree)) + return; + + // the Lombok check is the most expensive predicate : it is evaluated last, on actual candidates only + if (isNotFromRecord(variableTree) && + isNotFinalAndNotStatic(variableTree) && + isNotReassigned(variableTree) && + !isLombokManaged(variableTree)) { + reportIssue(tree, MESSAGE_RULE); + } else { + super.visitNode(tree); + } + } + + private static boolean isParameterOfAbstractMethod(VariableTree variableTree) { + Tree parent = variableTree.parent(); + return parent != null && parent.is(Kind.METHOD) && ((MethodTree) parent).block() == null; + } + + private static boolean isNotFromRecord(VariableTree variableTree) { + Tree parent = variableTree.parent(); + if (parent == null) return false; + + return !parent.is(Kind.RECORD); + } + + private static boolean isNotReassigned(VariableTree variableTree) { + return variableTree.symbol() + .usages() + .stream() + .noneMatch(MakeNonReassignedVariablesConstants::parentIsAssignment) + && !isPassedAsNonFinalParameter(variableTree); // if a variable is passed into a method as a non-final parameter, it may have been reassigned + } + + private static boolean isPassedAsNonFinalParameter(VariableTree variableTree) { + return variableTree.symbol() + .usages() + .stream() + .anyMatch(MakeNonReassignedVariablesConstants::parentIsNonFinalParameter); + } + + private static boolean parentIsNonFinalParameter(Tree tree) { + // Skip the parent if it is a member select (e.g. "this.myVar") + while (tree.parent().is(Kind.MEMBER_SELECT)) { + tree = tree.parent(); + } + if(!parentIsKind(tree, Kind.ARGUMENTS)) + return false; + if(tree.parent() == null) + return false; + Arguments arguments = (Arguments) tree.parent(); + if (parentIsKind(arguments, Kind.METHOD_INVOCATION, Kind.NEW_CLASS)) { + MethodTree methodTree = arguments.parent().is(Kind.METHOD_INVOCATION) + ? ((MethodInvocationTree) arguments.parent()).methodSymbol().declaration() + : ((NewClassTree) arguments.parent()).methodSymbol().declaration(); + int argument_idx = arguments.indexOf(tree); + return methodTree != null && !hasModifier(methodTree.parameters().get(argument_idx).modifiers(), Modifier.FINAL); + } + return false; + + } + + private static boolean parentIsAssignment(Tree tree) { + // Skip the parent if it is a member select (e.g. "this.myVar") + while (tree.parent().is(Kind.MEMBER_SELECT)) { + tree = tree.parent(); + } + return parentIsKind(tree, + Kind.ASSIGNMENT, + Kind.MULTIPLY_ASSIGNMENT, + Kind.DIVIDE_ASSIGNMENT, + Kind.REMAINDER_ASSIGNMENT, + Kind.PLUS_ASSIGNMENT, + Kind.MINUS_ASSIGNMENT, + Kind.LEFT_SHIFT_ASSIGNMENT, + Kind.RIGHT_SHIFT_ASSIGNMENT, + Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, + Kind.AND_ASSIGNMENT, + Kind.XOR_ASSIGNMENT, + Kind.OR_ASSIGNMENT, + Kind.POSTFIX_INCREMENT, + Kind.POSTFIX_DECREMENT, + Kind.PREFIX_INCREMENT, + Kind.PREFIX_DECREMENT + ); + } + + private static boolean parentIsKind(Tree tree, Kind... orKind) { + Tree parent = tree.parent(); + if (parent == null) return false; + + for (Kind k : orKind) { + if (parent.is(k)) return true; + } + + return false; + } + + private boolean isNotFinalAndNotStatic(VariableTree variableTree) { + return hasNoneOf(variableTree.modifiers(), Modifier.FINAL, Modifier.STATIC) && !isFinalPatternVariable(variableTree); + } + + /** + * For a pattern variable ({@code instanceof final Type var}), the parser does not attach the + * {@code final} keyword to {@link VariableTree#modifiers()} : the keyword sits between the + * {@code instanceof} keyword and the pattern type, outside of any tree node's token range. + * It is recovered here by reading the raw source in that gap. + */ + private boolean isFinalPatternVariable(VariableTree variableTree) { + Tree parent = variableTree.parent(); + if (parent == null || !parent.is(Kind.TYPE_PATTERN) || !(parent.parent() instanceof PatternInstanceOfTree patternInstanceOf)) { + return false; + } + String textBeforeType = textBetween( + patternInstanceOf.instanceofKeyword().range().end(), + variableTree.type().firstToken().range().start() + ); + return "final".equals(textBeforeType.trim()); + } + + private String textBetween(Position start, Position end) { + List lines = context.getFileLines(); + if (start.line() == end.line()) { + return lines.get(start.line() - 1).substring(start.columnOffset(), end.columnOffset()); + } + StringBuilder result = new StringBuilder(lines.get(start.line() - 1).substring(start.columnOffset())); + for (int line = start.line() + 1; line < end.line(); line++) { + result.append(lines.get(line - 1)); + } + result.append(lines.get(end.line() - 1), 0, end.columnOffset()); + return result.toString(); + } + + private static boolean hasNoneOf(ModifiersTree modifiersTree, Modifier... unexpectedModifiers) { + return !hasAnyOf(modifiersTree, unexpectedModifiers); + } + + private static boolean hasAnyOf(ModifiersTree modifiersTree, Modifier... expectedModifiers) { + for(Modifier expectedModifier : expectedModifiers) { + if (hasModifier(modifiersTree, expectedModifier)) { + return true; + } + } + return false; + } + + public static boolean hasModifier(ModifiersTree modifiersTree, Modifier expectedModifier) { + for(ModifierKeywordTree modifierKeywordTree : modifiersTree.modifiers()) { + if (modifierKeywordTree.modifier() == expectedModifier) { + return true; + } + } + + return false; + } + + private String getVariableNameForLogger(VariableTree variableTree) { + String name = variableTree.simpleName().name(); + + if (variableTree.parent() != null) return name; + + if (variableTree.parent().is(Kind.CLASS)) { + ClassTree cTree = (ClassTree) variableTree.parent(); + name += " --- from CLASS '" + cTree.simpleName() + "'"; + } + if (variableTree.parent().is(Kind.BLOCK)) { + BlockTree bTree = (BlockTree) variableTree.parent(); + if (bTree.parent() != null && bTree.parent().is(Kind.METHOD)) { + MethodTree mTree = (MethodTree) bTree.parent(); + name += " --- from METHOD '" + mTree.simpleName() + "'"; + } + } + + return name; + + } + + /** + * A variable is "Lombok managed" when Lombok generates a setter for it : making it {@code final} + * would not compile, so the rule must stay silent. + *

+ * This happens when the field itself is annotated with {@code @Setter}, or when its owner class is + * annotated with {@code @Setter} or {@code @Data}. A field level {@code @Setter(AccessLevel.NONE)} + * explicitly disables the generation and therefore wins over the class level annotation. + */ + private static boolean isLombokManaged(VariableTree variableTree) { + AnnotationTree fieldSetter = findLombokAnnotation(variableTree.modifiers(), SETTER); + if (fieldSetter != null) { + return !isSetterDisabled(fieldSetter); + } + + // covers CLASS, but also ENUM and INTERFACE owners, which Kind.CLASS alone would miss + if (variableTree.parent() instanceof ClassTree classTree) { + ModifiersTree classModifiers = classTree.modifiers(); + return findLombokAnnotation(classModifiers, SETTER) != null + || findLombokAnnotation(classModifiers, DATA) != null; + } + + return false; + } + + @CheckForNull + private static AnnotationTree findLombokAnnotation(ModifiersTree modifiers, String simpleName) { + for (AnnotationTree annotation : modifiers.annotations()) { + if (isLombokAnnotation(annotation, simpleName)) { + return annotation; + } + } + return null; + } + + /** + * Relies on the semantic model when it is available : the resolved type handles the regular import, + * the wildcard import ({@code import lombok.*}) and the fully qualified usage ({@code @lombok.Setter}) + * indifferently, and rules out a same named annotation coming from another library. + *

+ * When Lombok is missing from the analysis classpath the type cannot be resolved, so we fall back on the + * written form and accept both {@code @Setter} and {@code @lombok.Setter}. + */ + private static boolean isLombokAnnotation(AnnotationTree annotation, String simpleName) { + String fullyQualifiedName = LOMBOK_PACKAGE + "." + simpleName; + + Type annotationType = annotation.symbolType(); + if (!annotationType.isUnknown()) { + return annotationType.is(fullyQualifiedName); + } + + String writtenName = writtenNameOf(annotation.annotationType()); + return simpleName.equals(writtenName) || fullyQualifiedName.equals(writtenName); + } + + /** + * Detects {@code AccessLevel.NONE}, whatever the way it is written : positional or named argument + * ({@code value = ...}), simple, fully qualified or statically imported constant. + */ + private static boolean isSetterDisabled(AnnotationTree annotation) { + return annotation.arguments() + .stream() + .map(MakeNonReassignedVariablesConstants::annotationArgumentValue) + .map(MakeNonReassignedVariablesConstants::writtenNameOf) + .filter(Objects::nonNull) + .anyMatch(value -> value.endsWith(ACCESS_LEVEL_NONE) || NONE.equals(value)); + } + + private static ExpressionTree annotationArgumentValue(ExpressionTree argument) { + return argument.is(Kind.ASSIGNMENT) + ? ((AssignmentExpressionTree) argument).expression() + : argument; + } + + /** + * Rebuilds the name as written in the source ({@code Setter}, {@code lombok.Setter}, + * {@code lombok.AccessLevel.NONE}) by walking the tree : {@code toString()} only returns the source + * text for identifiers, not for member selects. + * + * @return {@code null} when the tree is neither an identifier nor a member select + */ + @CheckForNull + private static String writtenNameOf(Tree tree) { + if (tree.is(Kind.IDENTIFIER)) { + return ((IdentifierTree) tree).name(); + } + if (tree.is(Kind.MEMBER_SELECT)) { + MemberSelectExpressionTree memberSelect = (MemberSelectExpressionTree) tree; + String qualifier = writtenNameOf(memberSelect.expression()); + return qualifier == null ? null : qualifier + "." + memberSelect.identifier().name(); + } + return null; + } + +} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java similarity index 80% rename from src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java index d4088bd2..1e57e86b 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.ArrayList; import java.util.Collection; @@ -26,6 +26,7 @@ import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.semantic.MethodMatchers; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; import org.sonar.plugins.java.api.tree.ClassTree; import org.sonar.plugins.java.api.tree.CompilationUnitTree; @@ -37,12 +38,27 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC69") +@Rule(key = "GCI69") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC69") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S69") public class NoFunctionCallWhenDeclaringForLoop extends IssuableSubscriptionVisitor { protected static final String MESSAGERULE = "Do not call a function when declaring a for-type loop"; + private static final String ITERATOR = "java.util.Iterator"; + private static final MethodMatchers ITERATOR_METHODS = MethodMatchers.create() + .ofSubTypes(ITERATOR) + .names("hasNext", "next") + .withAnyParameters() + .build(); + private static final String ENUMERATION = "java.util.Enumeration"; + private static final MethodMatchers ENUMERATION_METHODS = MethodMatchers.create() + .ofSubTypes(ENUMERATION) + .names("hasMoreElements", "nextElement") + .withAnyParameters() + .build(); + + private static final Map> linesWithIssuesByClass = new HashMap<>(); @Override @@ -58,23 +74,26 @@ public void visitNode(Tree tree) { if (null != condition) { method.condition().accept(invocationMethodVisitor); } + // update - // initaliser method.update().accept(invocationMethodVisitor); - method.initializer().accept(invocationMethodVisitor); } private class MethodInvocationInForStatementVisitor extends BaseTreeVisitor { @Override public void visitMethodInvocation(MethodInvocationTree tree) { - if (!lineAlreadyHasThisIssue(tree)) { + if (!lineAlreadyHasThisIssue(tree) && !isMethodAllowed(tree)) { report(tree); return; } super.visitMethodInvocation(tree); } + private boolean isMethodAllowed(MethodInvocationTree tree) { + return ITERATOR_METHODS.matches(tree) || ENUMERATION_METHODS.matches(tree); + } + private boolean lineAlreadyHasThisIssue(Tree tree) { if (tree.firstToken() != null) { final String classname = getFullyQualifiedNameOfClassOf(tree); diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptions.java similarity index 92% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptions.java index 2362404b..76a74b28 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptions.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks; import java.util.Arrays; @@ -32,7 +32,8 @@ import org.sonar.plugins.java.api.tree.TryStatementTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC28") +@Rule(key = "GCI28") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC28") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRSP0028") public class OptimizeReadFileExceptions extends IssuableSubscriptionVisitor { diff --git a/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java new file mode 100644 index 00000000..28f1ea50 --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java @@ -0,0 +1,88 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks; + +import org.sonar.check.Rule; +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; +import org.sonar.plugins.java.api.tree.MethodInvocationTree; +import org.sonar.plugins.java.api.tree.NewArrayTree; +import org.sonar.plugins.java.api.tree.NewClassTree; +import org.sonar.plugins.java.api.tree.Tree; +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.List; + +@Rule(key = "GCI94") +public class UseOptionalOrElseGetVsOrElse extends IssuableSubscriptionVisitor { + + private static final String MESSAGE_RULE = "Use optional orElseGet instead of orElse."; + private final UseOptionalOrElseGetVsOrElseVisitor visitorInFile = new UseOptionalOrElseGetVsOrElseVisitor(); + + @Override + public List nodesToVisit() { + return Collections.singletonList(Tree.Kind.METHOD_INVOCATION); + } + + @Override + public void visitNode(@Nonnull Tree tree) { + tree.accept(visitorInFile); + } + + private class UseOptionalOrElseGetVsOrElseVisitor extends BaseTreeVisitor { + @Override + public void visitMethodInvocation(MethodInvocationTree tree) { + if (!tree.methodSelect().is(Tree.Kind.MEMBER_SELECT)) { + return; + } + MemberSelectExpressionTree memberSelect = (MemberSelectExpressionTree) tree.methodSelect(); + if (memberSelect.identifier().name().equals("orElse") && + memberSelect.expression().symbolType().is("java.util.Optional") && + !tree.arguments().isEmpty() && + containsComputation(tree.arguments().get(0))) { + reportIssue(memberSelect, MESSAGE_RULE); + } + } + } + + private static boolean containsComputation(Tree argument) { + ComputationDetector detector = new ComputationDetector(); + argument.accept(detector); + return detector.found; + } + + private static class ComputationDetector extends BaseTreeVisitor { + boolean found = false; + + @Override + public void visitMethodInvocation(@Nonnull MethodInvocationTree tree) { + found = true; + } + + @Override + public void visitNewClass(@Nonnull NewClassTree tree) { + found = true; + } + + @Override + public void visitNewArray(@Nonnull NewArrayTree tree) { + found = true; + } + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/enums/ConstOrLiteralDeclare.java similarity index 96% rename from src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/enums/ConstOrLiteralDeclare.java index db01a76b..1ef973a5 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/enums/ConstOrLiteralDeclare.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks.enums; +package org.greencodeinitiative.creedengo.java.checks.enums; import java.math.BigDecimal; import java.util.Set; @@ -226,4 +226,4 @@ public static final boolean isLiteral(Tree arg) { arg.is(STRING_LITERAL) || arg.is(CHAR_LITERAL); } -} \ No newline at end of file +} diff --git a/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java b/src/main/java/org/greencodeinitiative/creedengo/java/utils/PrinterVisitor.java similarity index 89% rename from src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java rename to src/main/java/org/greencodeinitiative/creedengo/java/utils/PrinterVisitor.java index 2b709d79..fa245893 100644 --- a/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/utils/PrinterVisitor.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.utils; +package org.greencodeinitiative.creedengo.java.utils; import java.util.List; import java.util.function.Consumer; diff --git a/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java b/src/main/java/org/greencodeinitiative/creedengo/java/utils/StringUtils.java similarity index 81% rename from src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java rename to src/main/java/org/greencodeinitiative/creedengo/java/utils/StringUtils.java index b9b81c52..ce66a882 100644 --- a/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/utils/StringUtils.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.utils; +package org.greencodeinitiative.creedengo.java.utils; public final class StringUtils { diff --git a/src/main/resources/org/greencodeinitiative/creedengo/java/creedengo_way_profile.json b/src/main/resources/org/greencodeinitiative/creedengo/java/creedengo_way_profile.json new file mode 100644 index 00000000..059bf0f5 --- /dev/null +++ b/src/main/resources/org/greencodeinitiative/creedengo/java/creedengo_way_profile.json @@ -0,0 +1,23 @@ +{ + "name": "creedengo way", + "language": "java", + "ruleKeys": [ + "GCI1", + "GCI2", + "GCI3", + "GCI5", + "GCI27", + "GCI28", + "GCI32", + "GCI67", + "GCI69", + "GCI72", + "GCI74", + "GCI76", + "GCI77", + "GCI78", + "GCI79", + "GCI82", + "GCI94" + ] +} diff --git a/src/test/files/AvoidConcatenateStringsInLoop.java b/src/test/files/AvoidConcatenateStringsInLoop.java deleted file mode 100644 index 4e2a5877..00000000 --- a/src/test/files/AvoidConcatenateStringsInLoop.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.utils; - -public class AvoidConcatenateStringsInLoop { - - public String concatenateStrings(String[] strings) { - String result1 = ""; - - for (String string : strings) { - result1 += string; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} - } - return result1; - } - - public String concatenateStrings2() { - String result2 = ""; - - for (int i = 0; i < 1000; ++i) { - result2 += "another"; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} - } - return result2; - } - - public String concatenateStrings3() { - String result3 = ""; - - for (int i = 0; i < 1000; ++i) { - result3 = result3 + "another"; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} - } - return result3; - } - -} diff --git a/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java b/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java deleted file mode 100644 index 3c74c86d..00000000 --- a/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import java.util.Collection; -import java.util.ArrayList; -import java.util.List; - -class AvoidGettingSizeCollectionInForLoopBad { - AvoidGettingSizeCollectionInForLoopBad() { - - } - - public void badForLoop() { - List numberList = new ArrayList(); - numberList.add(10); - numberList.add(20); - - for (int i = 0; i < numberList.size(); i++) { // Noncompliant {{Avoid getting the size of the collection in the loop}} - System.out.println("numberList.size()"); - } - } -} \ No newline at end of file diff --git a/src/test/files/AvoidUsingGlobalVariablesCheck.java b/src/test/files/AvoidUsingGlobalVariablesCheck.java deleted file mode 100644 index 557d6fc9..00000000 --- a/src/test/files/AvoidUsingGlobalVariablesCheck.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -public class Openclass { - public static double price = 15.24; // Noncompliant {{Avoid using global variables}} - public static long pages = 1053; // Noncompliant {{Avoid using global variables}} - - public static void main(String[] args) { - double newPrice = Openclass.price; - long newPages = Openclass.pages; - System.out.println(newPrice); - System.out.println(newPages); - static long years = 3000; // Noncompliant {{Avoid using global variables}} - } - static{ // Noncompliant {{Avoid using global variables}} - int a = 4; - } - - public void printingA() { - System.out.println(a); - } - -} \ No newline at end of file diff --git a/src/test/files/FreeResourcesOfAutoCloseableInterface.java b/src/test/files/FreeResourcesOfAutoCloseableInterface.java deleted file mode 100644 index e1eaab59..00000000 --- a/src/test/files/FreeResourcesOfAutoCloseableInterface.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import java.io.*; - -class FreeResourcesOfAutoCloseableInterface { - FreeResourcesOfAutoCloseableInterface(FreeResourcesOfAutoCloseableInterface mc) { - - } - - public void foo1() { - String fileName = "./FreeResourcesOfAutoCloseableInterface.java"; - try (FileReader fr = new FileReader(fileName); - BufferedReader br = new BufferedReader(fr)) { - } catch (IOException e) { - System.err.println(e.getMessage()); - } - } - - public void foo2() { - String fileName = "./FreeResourcesOfAutoCloseableInterface.java"; - try { // Noncompliant - FileReader fr = new FileReader(fileName); - BufferedReader br = new BufferedReader(fr); - System.out.printl(br.readLine()); - } catch (IOException e) { - System.err.println(e.getMessage()); - } finally { - if (fr) { - fr.close(); - } - if (br) { - br.close(); - } - } - } -} \ No newline at end of file diff --git a/src/test/files/GoodWayConcatenateStringsLoop.java b/src/test/files/GoodWayConcatenateStringsLoop.java deleted file mode 100644 index c11c1ab6..00000000 --- a/src/test/files/GoodWayConcatenateStringsLoop.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.utils; - -public class GoodWayConcatenateStringsLoop { - - public String concatenateStrings(String[] strings) { - StringBuilder result = new StringBuilder(); - - for (String string : strings) { - result.append(string); - } - return result.toString(); - } - - public void testConcateOutOfLoop() { - String result = ""; - result += "another"; - } - - public void testConcateOutOfLoop2() { - String result = ""; - result = result + "another"; - } - - public String changeValueStringInLoop() { - String result3 = ""; - - for (int i = 0; i < 1; ++i) { - result3 = "another"; - } - return result3; - } - -} diff --git a/src/test/files/IncrementCheck.java b/src/test/files/IncrementCheck.java deleted file mode 100644 index 54b20bf9..00000000 --- a/src/test/files/IncrementCheck.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -class MyClass { - MyClass(MyClass mc) { - } - - int foo1() { - int counter = 0; - return counter++; // Noncompliant {{Use ++i instead of i++}} - } - - int foo11() { - int counter = 0; - return ++counter; - } - - void foo2(int value) { - int counter = 0; - counter++; // Noncompliant {{Use ++i instead of i++}} - } - - void foo22(int value) { - int counter = 0; - ++counter; - } - - void foo3(int value) { - int counter = 0; - counter = counter + 197845 ; - } - - void foo4(int value) { - int counter =0; - counter = counter + 35 + 78 ; - } - - void foo50(int value) { - for (int i=0; i < 10; i++) { // Noncompliant {{Use ++i instead of i++}} - System.out.println(i); - } - } - - void foo51(int value) { - for (int i=0; i < 10; ++i) { - System.out.println(i); - } - } -} \ No newline at end of file diff --git a/src/test/files/NoFunctionCallWhenDeclaringForLoop.java b/src/test/files/NoFunctionCallWhenDeclaringForLoop.java deleted file mode 100644 index da72a3ef..00000000 --- a/src/test/files/NoFunctionCallWhenDeclaringForLoop.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -class NoFunctionCallWhenDeclaringForLoop { - NoFunctionCallWhenDeclaringForLoop(NoFunctionCallWhenDeclaringForLoop mc) { - } - - public int getMyValue() { - return 6; - } - - public int incrementeMyValue(int i) { - return i + 100; - } - - public void test1() { - for (int i = 0; i < 20; i++) { - System.out.println(i); - boolean b = getMyValue() > 6; - } - } - - public void test2() { - String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; - for (String i : cars) { - System.out.println(i); - } - - } - - public void test3() { - for (int i = getMyValue(); i < 20; i++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} - System.out.println(i); - boolean b = getMyValue() > 6; - } - } - - public void test4() { - for (int i = 0; i < getMyValue(); i++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} - System.out.println(i); - boolean b = getMyValue() > 6; - } - } - - public void test5() { - for (int i = 0; i < getMyValue(); incrementeMyValue(i)) { // Noncompliant {{Do not call a function when declaring a for-type loop}} - System.out.println(i); - boolean b = getMyValue() > 6; - } - } - - public void test6() { - for (int i = getMyValue(); i < getMyValue(); i++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} - System.out.println(i); - boolean b = getMyValue() > 6; - } - } - -} \ No newline at end of file diff --git a/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java b/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java deleted file mode 100644 index 17eb069a..00000000 --- a/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -class UnnecessarilyAssignValuesToVariablesTestCheck { - UnnecessarilyAssignValuesToVariablesTestCheck(UnnecessarilyAssignValuesToVariablesTestCheck mc) { - } - - public int testSwitchCase() throws Exception { - int variableFor = 5; - int variableIf = 5; - int variableWhile = 5; - int variableExp = 5; - int variableReturn = 5; - int variableCLass = 5; - int[] intArray = {10, 20, 30, 40, 50}; - - Exception variableException = new Exception("message"); - int variableNotUse = 5; // Noncompliant {{The variable is declared but not really used}} - - - variableNotUse = 10; - for (variableFor = 0; variableFor < 5; ++variableFor) { - System.out.println(variableFor); - } - - for (int ia : intArray) { - System.out.println((char) ia); - } - - if (variableIf > 10) { - System.out.println(variableIf); - } - - while (variableWhile > 10) { - System.out.println(variableWhile); - } - - variableExp += 1; - variableNotUse = variableExp; - TestClass testClass = new TestClass(variableCLass); - if (testClass.isTrue()) { - throw variableException; - } - return variableReturn; - } - - private class TestClass { - TestClass(int i) { - ++i; - } - - public boolean isTrue() { - return true; - } - } - - - private int getIntValue() { - return 3; - } - - public int testNonCompliantReturn() { - int i = getIntValue(); // Noncompliant {{Immediately return this expression instead of assigning it to the temporary variable}} - return i; - } - - public int testCompliantReturn() { - return getIntValue(); - } - - public void testNonCompliantThrow() throws Exception { - Exception exception = new Exception("dummy"); // Noncompliant {{Immediately throw this expression instead of assigning it to the temporary variable}} - throw exception; - } - - public void testCompliantThrow() throws Exception { - throw new Exception("dummy"); - } -} \ No newline at end of file diff --git a/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java b/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java deleted file mode 100644 index f70c4c41..00000000 --- a/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -class UnnecessarilyAssignValuesToVariablesTestCheck { - UnnecessarilyAssignValuesToVariablesTestCheck(UnnecessarilyAssignValuesToVariablesTestCheck mc) { - } - - public void testSwitchCase() { - - ArrayList lst = new ArrayList(0); - if (lst == null) { - return; - } - System.out.println(lst); - } - -} \ No newline at end of file diff --git a/src/test/files/UseCorrectForLoopCheck.java b/src/test/files/UseCorrectForLoopCheck.java deleted file mode 100644 index 350ed6eb..00000000 --- a/src/test/files/UseCorrectForLoopCheck.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import java.util.Arrays; -import java.util.List; - -class UseCorrectForLoopCheck { - UseCorrectForLoopCheck(UseCorrectForLoopCheck mc) { - } - - private final Integer[] intArray = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - private final List intList = Arrays.asList(intArray); - - public void testForEachLoop() { - int dummy = 0; - for (Integer i : intArray) { // Noncompliant {{Avoid the use of Foreach with Arrays}} - dummy += i; - } - - for (Integer i : intList) { - dummy += i; - } - System.out.println(dummy); - } -} \ No newline at end of file diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java b/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java deleted file mode 100644 index fc857883..00000000 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.CheckVerifier; - -@Deprecated -class AvoidConcatenateStringsInLoopTest { - - @Test - void checkNonCompliantTests() { - CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidConcatenateStringsInLoop.java") - .withCheck(new AvoidConcatenateStringsInLoop()) - .verifyIssues(); - } - - @Test - void checkCompliantTests() { - CheckVerifier.newVerifier() - .onFile("src/test/files/GoodWayConcatenateStringsLoop.java") - .withCheck(new AvoidConcatenateStringsInLoop()) - .verifyNoIssues(); - } - -} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java b/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java deleted file mode 100644 index dda74370..00000000 --- a/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.CheckVerifier; - -@Deprecated -class UnnecessarilyAssignValuesToVariablesTest { - - @Test - void test() { - CheckVerifier.newVerifier() - .onFile("src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java") - .withCheck(new UnnecessarilyAssignValuesToVariables()) - .verifyIssues(); - } - - @Test - void testIgnoredEmptyReturn() { - CheckVerifier.newVerifier() - .onFile("src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java") - .withCheck(new UnnecessarilyAssignValuesToVariables()) - .verifyNoIssues(); - } - -} \ No newline at end of file diff --git a/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java b/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java deleted file mode 100644 index a853a6f5..00000000 --- a/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java.checks; - -import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.CheckVerifier; - -@Deprecated -class UseCorrectLoopCheckTest { - - @Test - void test() { - CheckVerifier.newVerifier() - .onFile("src/test/files/UseCorrectForLoopCheck.java") - .withCheck(new UseCorrectForLoop()) - .verifyIssues(); - } - -} \ No newline at end of file diff --git a/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrarTest.java similarity index 60% rename from src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrarTest.java index c38b4c09..89541a50 100644 --- a/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrarTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,9 +15,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java; +package org.greencodeinitiative.creedengo.java; + +import java.util.Set; import org.junit.jupiter.api.Test; +import org.reflections.Reflections; +import org.sonar.check.Rule; import org.sonar.plugins.java.api.CheckRegistrar; import static org.assertj.core.api.Assertions.assertThat; @@ -30,10 +34,16 @@ void checkNumberRules() { final JavaCheckRegistrar registrar = new JavaCheckRegistrar(); registrar.register(context); - - assertThat(context.checkClasses()).hasSize(19); + assertThat(context.checkClasses()) + .describedAs("All implemented rules must be registered into " + JavaCheckRegistrar.class) + .containsExactlyInAnyOrder(getDefinedRules().toArray(new Class[0])); assertThat(context.testCheckClasses()).isEmpty(); } + static Set> getDefinedRules() { + Reflections r = new Reflections(JavaCheckRegistrar.class.getPackageName() + ".checks"); + return r.getTypesAnnotatedWith(Rule.class); + } + } diff --git a/src/test/java/org/greencodeinitiative/creedengo/java/JavaCreedengoWayProfileTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/JavaCreedengoWayProfileTest.java new file mode 100644 index 00000000..7db81345 --- /dev/null +++ b/src/test/java/org/greencodeinitiative/creedengo/java/JavaCreedengoWayProfileTest.java @@ -0,0 +1,51 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java; + +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; +import org.sonar.check.Rule; + +import static org.greencodeinitiative.creedengo.java.JavaCheckRegistrarTest.getDefinedRules; +import static org.greencodeinitiative.creedengo.java.JavaCreedengoWayProfile.PROFILE_NAME; +import static org.greencodeinitiative.creedengo.java.JavaCreedengoWayProfile.PROFILE_PATH; +import static org.greencodeinitiative.creedengo.java.JavaRulesDefinition.LANGUAGE; +import static org.assertj.core.api.Assertions.assertThat; + +class JavaCreedengoWayProfileTest { + @Test + void should_create_creedengo_profile() { + BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); + + JavaCreedengoWayProfile definition = new JavaCreedengoWayProfile(); + definition.define(context); + + BuiltInQualityProfilesDefinition.BuiltInQualityProfile profile = context.profile(LANGUAGE, PROFILE_NAME); + + assertThat(profile.language()).isEqualTo(LANGUAGE); + assertThat(profile.name()).isEqualTo(PROFILE_NAME); + List definedRuleIds = getDefinedRules().stream().map(c -> c.getAnnotation(Rule.class).key()).collect(Collectors.toList()); + assertThat(profile.rules()) + .describedAs("All implemented rules must be declared in '%s' profile file: %s", PROFILE_NAME, PROFILE_PATH) + .map(BuiltInQualityProfilesDefinition.BuiltInActiveRule::ruleKey) + .containsExactlyInAnyOrderElementsOf(definedRuleIds); + } +} diff --git a/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/JavaPluginTest.java similarity index 84% rename from src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/JavaPluginTest.java index 0f2167d3..b54f59bc 100644 --- a/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/JavaPluginTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java; +package org.greencodeinitiative.creedengo.java; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinitionTest.java similarity index 56% rename from src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinitionTest.java index 2c655143..d0f53da3 100644 --- a/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinitionTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java; +package org.greencodeinitiative.creedengo.java; import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.BeforeEach; @@ -28,42 +28,17 @@ import org.sonar.api.server.rule.RulesDefinition.Rule; import org.sonar.api.utils.Version; +import static org.greencodeinitiative.creedengo.java.JavaCheckRegistrar.ANNOTATED_RULE_CLASSES; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; class JavaRulesDefinitionTest { private RulesDefinition.Repository repository; - private RulesDefinition.Context context; @BeforeEach void init() { - // TODO: Remove this check after Git repo split - /* - On an IDE (like IntelliJ), if the developer runs the unit tests without building/generating the Maven goals on the - "ecocode-rules-specifications" module before, the unit tests will not see the generated HTML descriptions (from ASCIIDOC files). - The developer must therefore configure his IDE to build the `ecocode-rules-specifications` module before launching the Tests. - - When the `java-plugin` submodule is in a specific Git repository, `ecocode-rules-specifications` will be fetched from a classic - external Maven dependency. There will therefore no longer be any need to perform this specific configuration. - */ - if (JavaRulesDefinition.class.getResource("/io/ecocode/rules/java/EC4.json") == null) { - String message = "'ecocode-rules-specification' resources corrupted. Please check build of 'ecocode-rules-specification' module"; - if (System.getProperties().keySet().stream().anyMatch(k -> k.toString().startsWith("idea."))) { - message += "\n\nOn 'IntelliJ IDEA':" + - "\n1. go to settings :" + - "\n > Build, Execution, Deployment > Build Tools > Maven > Runner" + - "\n2. check option:" + - "\n > Delegate IDE build/run actions to Maven" + - "\n3. Click on menu: " + - "\n > Build > Build Project" - ; - } - fail(message); - } - final SonarRuntime sonarRuntime = mock(SonarRuntime.class); doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); JavaRulesDefinition rulesDefinition = new JavaRulesDefinition(sonarRuntime); @@ -75,30 +50,29 @@ On an IDE (like IntelliJ), if the developer runs the unit tests without building @Test @DisplayName("Test repository metadata") void testMetadata() { - assertThat(repository.name()).isEqualTo("ecoCode"); + assertThat(repository.name()).isEqualTo("creedengo"); assertThat(repository.language()).isEqualTo("java"); - assertThat(repository.key()).isEqualTo("ecocode-java"); - assertThat(repository.rules()).hasSize(19); + assertThat(repository.key()).isEqualTo("creedengo-java"); } @Test void testRegistredRules() { - assertThat(repository.rules()).hasSize(19); + assertThat(repository.rules()).hasSize(ANNOTATED_RULE_CLASSES.size()); } @Test - @DisplayName("All rule keys must be prefixed by 'EC'") + @DisplayName("All rule keys must be prefixed by 'GCI'") void testRuleKeyPrefix() { SoftAssertions assertions = new SoftAssertions(); repository.rules().forEach( - rule -> assertions.assertThat(rule.key()).startsWith("EC") + rule -> assertions.assertThat(rule.key()).startsWith("GCI") ); assertions.assertAll(); } @Test void assertRuleProperties() { - Rule rule = repository.rule("EC67"); + Rule rule = repository.rule("GCI67"); assertThat(rule).isNotNull(); assertThat(rule.name()).isEqualTo("Use ++i instead of i++"); assertThat(rule.debtRemediationFunction().type()).isEqualTo(Type.CONSTANT_ISSUE); diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheckTest.java similarity index 66% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheckTest.java index 2a855e0c..f3db2b53 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInLoopCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,9 +15,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI1; -import fr.greencodeinitiative.java.utils.FilesUtils; +import org.greencodeinitiative.creedengo.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; +import org.greencodeinitiative.creedengo.java.utils.FilesUtils; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -26,7 +27,7 @@ class AvoidSpringRepositoryCallInLoopCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidSpringRepositoryCallInLoopCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI1/AvoidSpringRepositoryCallInLoopCheck.java") .withCheck(new AvoidSpringRepositoryCallInLoopOrStreamCheck()) .withClassPath(FilesUtils.getClassPath("target/test-jars")) .verifyIssues(); diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheckTest.java similarity index 66% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheckTest.java index e9fd4f35..222c90f8 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI1/AvoidSpringRepositoryCallInStreamCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,9 +15,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI1; -import fr.greencodeinitiative.java.utils.FilesUtils; +import org.greencodeinitiative.creedengo.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; +import org.greencodeinitiative.creedengo.java.utils.FilesUtils; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -26,7 +27,7 @@ class AvoidSpringRepositoryCallInStreamCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidSpringRepositoryCallInStreamCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI1/AvoidSpringRepositoryCallInStreamCheck.java") .withCheck(new AvoidSpringRepositoryCallInLoopOrStreamCheck()) .withClassPath(FilesUtils.getClassPath("target/test-jars")) .verifyIssues(); diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementTest.java similarity index 55% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementTest.java index f3f8ecdb..4eb1e99c 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI2/AvoidMultipleIfElseStatementTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI2; +import org.greencodeinitiative.creedengo.java.checks.AvoidMultipleIfElseStatement; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -24,11 +25,11 @@ class AvoidMultipleIfElseStatementTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidMultipleIfElseStatement.java") + .onFile(System.getProperty("testfiles.path") + "/GCI2/AvoidMultipleIfElseStatement.java") .withCheck(new AvoidMultipleIfElseStatement()) .verifyIssues(); CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidMultipleIfElseStatementNoIssue.java") + .onFile(System.getProperty("testfiles.path") + "/GCI2/AvoidMultipleIfElseStatementNoIssue.java") .withCheck(new AvoidMultipleIfElseStatement()) .verifyNoIssues(); } @@ -36,15 +37,23 @@ void test() { @Test void testInterfaceMethodStatement() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidMultipleIfElseStatementInterface.java") + .onFile(System.getProperty("testfiles.path") + "/GCI2/AvoidMultipleIfElseStatementInterfaceNoIssue.java") .withCheck(new AvoidMultipleIfElseStatement()) .verifyNoIssues(); } @Test - void testNotBlockStatement() { + void testNoBlockStatement() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidMultipleIfElseStatementNotBlock.java") + .onFile(System.getProperty("testfiles.path") + "/GCI2/AvoidMultipleIfElseStatementNoBlockNoIssue.java") + .withCheck(new AvoidMultipleIfElseStatement()) + .verifyNoIssues(); + } + + @Test + void testCompareMethod() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI2/AvoidMultipleIfElseStatementCompareMethodNoIssue.java") .withCheck(new AvoidMultipleIfElseStatement()) .verifyNoIssues(); } diff --git a/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheckTest.java similarity index 70% rename from src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheckTest.java index 5f0b1276..1ab0c890 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI27/ArrayCopyCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI27; +import org.greencodeinitiative.creedengo.java.checks.ArrayCopyCheck; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -28,9 +29,9 @@ class ArrayCopyCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/ArrayCopyCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI27/ArrayCopyCheck.java") .withCheck(new ArrayCopyCheck()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheckTest.java similarity index 64% rename from src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheckTest.java index b3ef8c89..4491fe3b 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI28/OptimizeReadFileExceptionCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI28; +import org.greencodeinitiative.creedengo.java.checks.OptimizeReadFileExceptions; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,7 +26,7 @@ class OptimizeReadFileExceptionCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/OptimizeReadFileExceptionCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI28/OptimizeReadFileExceptionCheck.java") .withCheck(new OptimizeReadFileExceptions()) .verifyIssues(); } @@ -33,7 +34,7 @@ void test() { @Test void test2() { CheckVerifier.newVerifier() - .onFile("src/test/files/OptimizeReadFileExceptionCheck2.java") + .onFile(System.getProperty("testfiles.path") + "/GCI28/OptimizeReadFileExceptionCheck2.java") .withCheck(new OptimizeReadFileExceptions()) .verifyIssues(); } @@ -41,7 +42,7 @@ void test2() { @Test void test3() { CheckVerifier.newVerifier() - .onFile("src/test/files/OptimizeReadFileExceptionCheck3.java") + .onFile(System.getProperty("testfiles.path") + "/GCI28/OptimizeReadFileExceptionCheck3.java") .withCheck(new OptimizeReadFileExceptions()) .verifyIssues(); } @@ -49,7 +50,7 @@ void test3() { @Test void test4() { CheckVerifier.newVerifier() - .onFile("src/test/files/OptimizeReadFileExceptionCheck4.java") + .onFile(System.getProperty("testfiles.path") + "/GCI28/OptimizeReadFileExceptionCheck4.java") .withCheck(new OptimizeReadFileExceptions()) .verifyIssues(); } @@ -57,7 +58,7 @@ void test4() { @Test void test5() { CheckVerifier.newVerifier() - .onFile("src/test/files/OptimizeReadFileExceptionCheck5.java") + .onFile(System.getProperty("testfiles.path") + "/GCI28/OptimizeReadFileExceptionCheck5.java") .withCheck(new OptimizeReadFileExceptions()) .verifyIssues(); } diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInLoopTest.java similarity index 63% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInLoopTest.java index 8083c1db..adfad5ab 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI3/AvoidGettingSizeCollectionInLoopTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,16 +15,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI3; +import org.greencodeinitiative.creedengo.java.checks.AvoidGettingSizeCollectionInLoop; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; class AvoidGettingSizeCollectionInLoopTest { @Test - public void testBadForLoop() { + void testBadForLoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInForLoopBad.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInForLoopBad.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyIssues(); } @@ -32,7 +33,7 @@ public void testBadForLoop() { @Test void testIgnoredForLoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInForLoopIgnored.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyNoIssues(); } @@ -40,7 +41,7 @@ void testIgnoredForLoop() { @Test void testGoodForLoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInForLoopGood.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInForLoopGood.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyNoIssues(); } @@ -48,7 +49,7 @@ void testGoodForLoop() { @Test void testBadWhileFoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInWhileLoopBad.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyIssues(); } @@ -56,7 +57,7 @@ void testBadWhileFoop() { @Test void testIgnoredWhileFoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInWhileLoopIgnored.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyNoIssues(); } @@ -64,7 +65,7 @@ void testIgnoredWhileFoop() { @Test void testGoodWhileLoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInWhileLoopGood.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyNoIssues(); } @@ -72,7 +73,7 @@ void testGoodWhileLoop() { @Test void testIgnoredForEachLoop() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java") + .onFile(System.getProperty("testfiles.path") + "/GCI3/AvoidGettingSizeCollectionInForEachLoopIgnored.java") .withCheck(new AvoidGettingSizeCollectionInLoop()) .verifyNoIssues(); } diff --git a/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSizeTest.java similarity index 68% rename from src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSizeTest.java index deef83e8..9c92dae3 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI32/InitializeBufferWithAppropriateSizeTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI32; +import org.greencodeinitiative.creedengo.java.checks.InitializeBufferWithAppropriateSize; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,9 +26,9 @@ class InitializeBufferWithAppropriateSizeTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/InitializeBufferWithAppropriateSize.java") + .onFile(System.getProperty("testfiles.path") + "/GCI32/InitializeBufferWithAppropriateSize.java") .withCheck(new InitializeBufferWithAppropriateSize()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueriesTest.java similarity index 68% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueriesTest.java index b74683eb..e593914c 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI5/AvoidStatementForDMLQueriesTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI5; +import org.greencodeinitiative.creedengo.java.checks.AvoidStatementForDMLQueries; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -24,7 +25,7 @@ class AvoidStatementForDMLQueriesTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidStatementForDMLQueries.java") + .onFile(System.getProperty("testfiles.path") + "/GCI5/AvoidStatementForDMLQueries.java") .withCheck(new AvoidStatementForDMLQueries()) .verifyIssues(); } diff --git a/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheckTest.java similarity index 69% rename from src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheckTest.java index e9d5b98e..1a5171f8 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI67/IncrementCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI67; +import org.greencodeinitiative.creedengo.java.checks.IncrementCheck; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,9 +26,9 @@ class IncrementCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/IncrementCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI67/IncrementCheck.java") .withCheck(new IncrementCheck()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoopTest.java similarity index 68% rename from src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoopTest.java index ef3c983f..d9d83fdf 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI69/NoFunctionCallWhenDeclaringForLoopTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI69; +import org.greencodeinitiative.creedengo.java.checks.NoFunctionCallWhenDeclaringForLoop; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -24,7 +25,7 @@ class NoFunctionCallWhenDeclaringForLoopTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/NoFunctionCallWhenDeclaringForLoop.java") + .onFile(System.getProperty("testfiles.path") + "/GCI69/NoFunctionCallWhenDeclaringForLoop.java") .withCheck(new NoFunctionCallWhenDeclaringForLoop()) .verifyIssues(); } diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheckTest.java similarity index 68% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheckTest.java index 5abed41f..7e99d797 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI72/AvoidSQLRequestInLoopCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI72; +import org.greencodeinitiative.creedengo.java.checks.AvoidSQLRequestInLoop; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,9 +26,9 @@ class AvoidSQLRequestInLoopCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidSQLRequestInLoopCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI72/AvoidSQLRequestInLoopCheck.java") .withCheck(new AvoidSQLRequestInLoop()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheckTest.java similarity index 68% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheckTest.java index 25ead7c4..28f27390 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI74/AvoidFullSQLRequestCheckTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI74; +import org.greencodeinitiative.creedengo.java.checks.AvoidFullSQLRequest; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,9 +26,9 @@ class AvoidFullSQLRequestCheckTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidFullSQLRequestCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI74/AvoidFullSQLRequestCheck.java") .withCheck(new AvoidFullSQLRequest()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsTests.java similarity index 67% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsTests.java index 2ac4ed35..b777f820 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI76/AvoidUsageOfStaticCollectionsTests.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI76; +import org.greencodeinitiative.creedengo.java.checks.AvoidUsageOfStaticCollections; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,7 +26,7 @@ class AvoidUsageOfStaticCollectionsTests { @Test void testHasIssues() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidUsageOfStaticCollections.java") + .onFile(System.getProperty("testfiles.path") + "/GCI76/AvoidUsageOfStaticCollections.java") .withCheck(new AvoidUsageOfStaticCollections()) .verifyIssues(); } @@ -33,7 +34,7 @@ void testHasIssues() { @Test void testNoIssues() { CheckVerifier.newVerifier() - .onFile("src/test/files/GoodUsageOfStaticCollections.java") + .onFile(System.getProperty("testfiles.path") + "/GCI76/AvoidUsageOfStaticCollectionsGoodWay.java") .withCheck(new AvoidUsageOfStaticCollections()) .verifyNoIssues(); } diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticTest.java similarity index 60% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticTest.java index 17502322..470658bc 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI77/AvoidRegexPatternNotStaticTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI77; +import org.greencodeinitiative.creedengo.java.checks.AvoidRegexPatternNotStatic; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,7 +26,7 @@ class AvoidRegexPatternNotStaticTest { @Test void testHasIssues() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidRegexPatternNotStatic.java") + .onFile(System.getProperty("testfiles.path") + "/GCI77/AvoidRegexPatternNotStatic.java") .withCheck(new AvoidRegexPatternNotStatic()) .verifyIssues(); } @@ -34,9 +35,9 @@ void testHasIssues() { void testHasNoIssues() { CheckVerifier.newVerifier() .onFiles( - "src/test/files/ValidRegexPattern.java", - "src/test/files/ValidRegexPattern2.java", - "src/test/files/ValidRegexPattern3.java" + System.getProperty("testfiles.path") + "/GCI77/AvoidRegexPatternNotStaticValid1.java", + System.getProperty("testfiles.path") + "/GCI77/AvoidRegexPatternNotStaticValid2.java", + System.getProperty("testfiles.path") + "/GCI77/AvoidRegexPatternNotStaticValid3.java" ) .withCheck(new AvoidRegexPatternNotStatic()) .verifyNoIssues(); diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchInsertTest.java similarity index 68% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchInsertTest.java index 8c138fde..8c6464a9 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI78/AvoidSetConstantInBatchInsertTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,8 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI78; +import org.greencodeinitiative.creedengo.java.checks.AvoidSetConstantInBatchUpdate; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -25,9 +26,9 @@ class AvoidSetConstantInBatchInsertTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidSetConstantInBatchUpdateCheck.java") + .onFile(System.getProperty("testfiles.path") + "/GCI78/AvoidSetConstantInBatchUpdateCheck.java") .withCheck(new AvoidSetConstantInBatchUpdate()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterfaceTest.java similarity index 66% rename from src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterfaceTest.java index 9a9ca492..d0836297 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI79/FreeResourcesOfAutoCloseableInterfaceTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,17 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI79; +import org.greencodeinitiative.creedengo.java.checks.FreeResourcesOfAutoCloseableInterface; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; class FreeResourcesOfAutoCloseableInterfaceTest { @Test - void test() { + void test_with_java7() { CheckVerifier.newVerifier() - .onFile("src/test/files/FreeResourcesOfAutoCloseableInterface.java") + .onFile(System.getProperty("testfiles.path") + "/GCI79/FreeResourcesOfAutoCloseableInterface.java") .withCheck(new FreeResourcesOfAutoCloseableInterface()) .withJavaVersion(7) .verifyIssues(); @@ -34,8 +35,9 @@ void test() { @Test void test_no_java_version() { CheckVerifier.newVerifier() - .onFile("src/test/files/FreeResourcesOfAutoCloseableInterface.java") + .onFile(System.getProperty("testfiles.path") + "/GCI79/FreeResourcesOfAutoCloseableInterface.java") .withCheck(new FreeResourcesOfAutoCloseableInterface()) .verifyIssues(); } -} \ No newline at end of file + +} diff --git a/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsTest.java new file mode 100644 index 00000000..313bd5cb --- /dev/null +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI82/MakeNonReassignedVariablesConstantsTest.java @@ -0,0 +1,74 @@ +/* + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.greencodeinitiative.creedengo.java.checks.GCI82; + +import org.greencodeinitiative.creedengo.java.checks.MakeNonReassignedVariablesConstants; +import org.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; + +class MakeNonReassignedVariablesConstantsTest { + + @Test + void test() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI82/MakeNonReassignedVariablesConstants.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyIssues(); + } + + @Test + void testLombok() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI82/MakeNonReassignedVariablesConstantsForLombok.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyIssues(); + } + + @Test + void testWithoutLombokImport() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI82/MakeNonReassignedVariablesConstantsWithoutLombokImport.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyIssues(); + } + + @Test + void testRecord() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI82/MakeNonReassignedVariablesConstantsForRecord.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyNoIssues(); + } + + @Test + void testInstanceOf() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI82/MakeNonReassignedVariablesConstantsForInstanceOf.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyIssues(); + } + + @Test + void testAbstractMethods() { + CheckVerifier.newVerifier() + .onFile(System.getProperty("testfiles.path") + "/GCI82/MakeNonReassignedVariablesConstantsForAbstractMethod.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyIssues(); + } + +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElseTest.java similarity index 61% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElseTest.java index 31e05b15..5818615e 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/GCI94/UseOptionalOrElseGetVsOrElseTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,20 +15,19 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.checks; +package org.greencodeinitiative.creedengo.java.checks.GCI94; +import org.greencodeinitiative.creedengo.java.checks.UseOptionalOrElseGetVsOrElse; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -@Deprecated -class AvoidUsingGlobalVariablesCheckCheckTest { +class UseOptionalOrElseGetVsOrElseTest { @Test void test() { CheckVerifier.newVerifier() - .onFile("src/test/files/AvoidUsingGlobalVariablesCheck.java") - .withCheck(new AvoidUsingGlobalVariablesCheck()) + .onFile(System.getProperty("testfiles.path") + "/GCI94/UseOptionalOrElseGetVsOrElse.java") + .withCheck(new UseOptionalOrElseGetVsOrElse()) .verifyIssues(); } - } diff --git a/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java b/src/test/java/org/greencodeinitiative/creedengo/java/utils/FilesUtils.java similarity index 92% rename from src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java rename to src/test/java/org/greencodeinitiative/creedengo/java/utils/FilesUtils.java index ed06d4ce..d32c90de 100644 --- a/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/utils/FilesUtils.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.utils; +package org.greencodeinitiative.creedengo.java.utils; import java.io.File; import java.io.IOException; diff --git a/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/utils/StringUtilsTest.java similarity index 84% rename from src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/utils/StringUtilsTest.java index 9e6d9328..de5082de 100644 --- a/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/utils/StringUtilsTest.java @@ -1,6 +1,6 @@ /* - * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs - * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * creedengo - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2024 Green Code Initiative (https://green-code-initiative.org/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package fr.greencodeinitiative.java.utils; +package org.greencodeinitiative.creedengo.java.utils; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; diff --git a/tool_build.sh b/tool_build.sh index bfac031a..a5f6a094 100755 --- a/tool_build.sh +++ b/tool_build.sh @@ -1,3 +1,3 @@ #!/usr/bin/env sh -mvn clean package -DskipTests +./mvnw clean package -DskipTests diff --git a/tool_compile.sh b/tool_compile.sh index 3d3e0d89..9d4da3c7 100755 --- a/tool_compile.sh +++ b/tool_compile.sh @@ -1,3 +1,3 @@ #!/usr/bin/env sh -mvn clean compile +./mvnw clean compile diff --git a/tool_release_1_prepare.sh b/tool_release_1_prepare.sh index e87b946d..7b996e3c 100755 --- a/tool_release_1_prepare.sh +++ b/tool_release_1_prepare.sh @@ -5,9 +5,9 @@ ### # creation of 2 commits with release and next SNAPSHOT -mvn release:prepare -B -ff -DpushChanges=false -DtagNameFormat=@{project.version} +./mvnw release:prepare -B -ff -DpushChanges=false -DtagNameFormat=@{project.version} sleep 2 # clean temporary files -mvn release:clean +./mvnw release:clean