diff --git a/.gitattributes b/.gitattributes index 12b960c..9039a78 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,4 +4,8 @@ # 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/workflows/_BACKUP_manual_release.yml b/.github/workflows/_BACKUP_manual_release.yml index 90818a5..af210fe 100644 --- a/.github/workflows/_BACKUP_manual_release.yml +++ b/.github/workflows/_BACKUP_manual_release.yml @@ -31,9 +31,9 @@ jobs: git config user.name 'github-actions[bot]' git config user.email '' - name: Maven release - run: mvn release:prepare -B -ff -DtagNameFormat=@{project.version} + run: ./mvnw release:prepare -B -ff -DtagNameFormat=@{project.version} - name: Maven release clean - run: mvn release:clean + run: ./mvnw release:clean - name: Get last TAG run: echo "LAST_TAG=$(git tag --sort=-version:refname | head -n 1)" >> $GITHUB_ENV - name: Extract release notes @@ -44,7 +44,7 @@ jobs: with: ref: ${{ env.LAST_TAG }} - name: Build project - run: mvn -e -B clean package -DskipTests + run: ./mvnw -e -B clean package -DskipTests - name: Create release id: create_release uses: actions/create-release@v1 @@ -60,7 +60,7 @@ jobs: id: export_jar_files uses: actions/upload-artifact@v3 with: - name: ecocode-plugins + name: creedengo-plugins path: lib - name: Export LAST_TAG id: export_last_tag @@ -77,7 +77,7 @@ jobs: id: import_jar_files uses: actions/download-artifact@v3 with: - name: ecocode-plugins + name: creedengo-plugins path: lib - name: Upload Release Asset - Java Plugin id: upload-release-asset @@ -86,6 +86,6 @@ jobs: 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_path: lib/creedengo-java-plugin-${{ needs.build.outputs.last_tag }}.jar + asset_name: creedengo-java-plugin-${{ needs.build.outputs.last_tag }}.jar asset_content_type: application/zip diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 60db5ba..ca18bee 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,11 +24,11 @@ jobs: with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v3 with: distribution: 'temurin' - java-version: 11 + java-version: 17 - name: Cache Maven packages uses: actions/cache@v3 @@ -38,13 +38,7 @@ jobs: 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 + run: ./mvnw -e -B verify - name: Cache SonarQube packages uses: actions/cache@v3 @@ -57,4 +51,4 @@ jobs: 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: ./mvnw -e -B org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=green-code-initiative_creedengo-java diff --git a/.github/workflows/build_container.yml b/.github/workflows/build_container.yml index eda94a3..08fb38b 100644 --- a/.github/workflows/build_container.yml +++ b/.github/workflows/build_container.yml @@ -14,12 +14,12 @@ on: 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: diff --git a/.github/workflows/tag_release.yml b/.github/workflows/tag_release.yml index b405ace..c91930c 100644 --- a/.github/workflows/tag_release.yml +++ b/.github/workflows/tag_release.yml @@ -29,7 +29,7 @@ jobs: id: extract-release-notes uses: ffurrer2/extract-release-notes@v1 - name: Build project - run: mvn -e -B clean package -DskipTests + run: ./mvnw -e -B clean package -DskipTests - name: Create release id: create_release uses: actions/create-release@v1 @@ -43,9 +43,9 @@ jobs: body: ${{ steps.extract-release-notes.outputs.release_notes }} - name: Export plugin Jar files id: export_jar_files - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: ecocode-plugins + name: creedengo-plugins path: target - name: Export UPLOAD_URL id: export_upload_url @@ -58,9 +58,9 @@ jobs: steps: - name: Import plugin JAR files id: import_jar_files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: - name: ecocode-plugins + name: creedengo-plugins path: target - name: Upload Release Asset - Java Plugin id: upload-release-asset @@ -69,6 +69,6 @@ jobs: 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_path: target/creedengo-java-plugin-${{ github.ref_name }}.jar + asset_name: creedengo-java-plugin-${{ github.ref_name }}.jar asset_content_type: application/zip diff --git a/.gitignore b/.gitignore index 67cc592..3633a5c 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/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /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 554bf66..b8e7099 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,15 +9,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#239](https://github.com/green-code-initiative/creedengo-rules-specifications/issues/239) Add new Java rule GCI24 : Optimize Database SQL Queries (Clause LIMIT / WHERE) + ### Changed +- compatibility updates for SonarQube 25.1.0 and 25.2.0 compatibility + ### Deleted +## [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/ecoCode-java/issues/60) Check + update for SonarQube 10.6.0 compatibility +- [#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 @@ -25,30 +58,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#15](https://github.com/green-code-initiative/ecoCode-java/issues/15) correction NullPointer in EC2 rule +- [#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/ecoCode-java/issues/12) Add support for SonarQube 10.4 "DownloadOnlyWhenRequired" feature +- [#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/ecoCode-java/pull/6) Delete deprecated java rules EC4, EC53, EC63 and EC75 +- [#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 @@ -61,9 +94,12 @@ 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.6.1...HEAD) -[1.6.1](https://github.com/green-code-initiative/ecoCode-java/compare/1.6.0...1.6.1) -[1.6.0](https://github.com/green-code-initiative/ecoCode-java/compare/1.5.2...1.6.0) -[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.1.0...HEAD) +[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 86b0ab3..c46ab38 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 77e81dc..aeeae91 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 421eacd..0128aab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,19 @@ ARG MAVEN_BUILDER=3-openjdk-17-slim -ARG SONARQUBE_VERSION=10.6.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 FROM maven:${MAVEN_BUILDER} AS builder -COPY . /usr/src/ecocode +COPY . /usr/src/creedengo -WORKDIR /usr/src/ecocode +WORKDIR /usr/src/creedengo COPY src src/ COPY pom.xml tool_build.sh ./ RUN ./tool_build.sh FROM sonarqube:${SONARQUBE_VERSION} -COPY --from=builder /usr/src/ecocode/target/ecocode-*.jar /opt/sonarqube/extensions/plugins/ +COPY --from=builder /usr/src/creedengo/target/creedengo-*.jar /opt/sonarqube/extensions/plugins/ USER sonarqube diff --git a/INSTALL.md b/INSTALL.md index ee50d0a..82cd69d 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 a28c058..3e3b36e 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,67 @@ 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.6.+ | 9.4.+ LTS to 10.6.0 | 11 / 17 | +| Plugin version | SonarQube version | Java version | +|----------------|---------------------|------------------------------------------------------------------------------------------------| +| 1.6.+ | 9.4.+ LTS to 10.6.0 | 11 / 17 | +| 1.7.+ | 9.9.+ LTS to 10.6.0 | [17](https://docs.sonarsource.com/sonarqube/9.9/requirements/prerequisites-and-overview/#java) | +| 2.0.+ | 9.9.+ LTS to 25.2.0 | [17](https://docs.sonarsource.com/sonarqube/9.9/requirements/prerequisites-and-overview/#java) | > 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 13bf375..d48fa61 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/docker-compose.yml b/docker-compose.yml index e84e389..98a460d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,9 @@ -name: sonarqube_ecocode_java +name: sonarqube_creedengo_java services: sonar: build: . - container_name: sonar_ecocode_java + container_name: sonar_creedengo_java ports: - ":9000" networks: @@ -28,7 +28,7 @@ services: db: image: postgres:12 - container_name: postgresql_ecocode_java + container_name: postgresql_creedengo_java networks: - sonarnet volumes: diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..19529dd --- /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 0000000..249bdf3 --- /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 1c657cb..b854b95 100644 --- a/pom.xml +++ b/pom.xml @@ -2,17 +2,17 @@ 4.0.0 - io.ecocode - ecocode-java-plugin - 1.6.3-SNAPSHOT - + org.green-code-initiative + creedengo-java-plugin + 2.1.1-SNAPSHOT + 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,15 +27,15 @@ - 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 @@ -53,8 +53,14 @@ green-code-initiative https://sonarcloud.io - 9.4.0.54424 - 7.19.0.31550 + + 9.9.7.96285 + + 9.8.0.203 + + + 7.16.0.30901 + 2.5.0.1358 @@ -66,16 +72,43 @@ 1.7 - - 1.6.2 + + 2.1.0 + + + https://repo1.maven.org/maven2 + + false + + + + + + + + + + + + + + + 25.2.0.102705 + + + + ${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 +121,9 @@ - org.sonarsource.sonarqube + org.sonarsource.api.plugin sonar-plugin-api - ${sonarqube.version} + ${sonar.plugin.api.version} provided @@ -136,6 +169,56 @@ test + + org.reflections + reflections + 0.10.2 + test + + + + + org.sonarsource.orchestrator + sonar-orchestrator-junit5 + 5.1.0.2254 + test + + + org.sonarsource.java + test-classpath-reader + 8.8.0.37665 + test + + + org.sonarsource.sonarqube + sonar-ws + ${sonarqube.version} + test + + + io.github.jycr + java-data-url-handler + 0.0.1 + test + + + org.slf4j + slf4j-api + 2.0.13 + test + + + ch.qos.logback + logback-classic + 1.5.6 + test + + + org.projectlombok + lombok + 1.18.36 + test + @@ -143,17 +226,17 @@ org.apache.maven.plugins maven-compiler-plugin - 3.11.0 + 3.13.0 org.apache.maven.plugins maven-surefire-plugin - 3.1.2 + 3.5.2 org.jacoco jacoco-maven-plugin - 0.8.10 + 0.8.12 prepare-agent @@ -175,8 +258,8 @@ ${sonar-packaging.version} true - ecocodejava - fr.greencodeinitiative.java.JavaPlugin + creedengojava + org.greencodeinitiative.creedengo.java.JavaPlugin true ${sonarqube.version} true @@ -193,7 +276,7 @@ org.codehaus.mojo buildnumber-maven-plugin - 3.1.0 + 3.2.1 validate @@ -211,7 +294,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.5.0 + 3.6.0 package @@ -236,7 +319,7 @@ - io.ecocode:ecocode-rules-specifications:* + org.green-code-initiative:creedengo-rules-specifications:* META-INF/** @@ -249,7 +332,7 @@ org.apache.maven.plugins maven-dependency-plugin - 3.6.0 + 3.8.1 @@ -317,18 +400,21 @@ com.mycila license-maven-plugin - 4.1 + 4.6 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 +428,95 @@
+ + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + 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.2 + + + + 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/BuildProjectEngine.java b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/BuildProjectEngine.java new file mode 100644 index 0000000..c9c40f9 --- /dev/null +++ b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/BuildProjectEngine.java @@ -0,0 +1,417 @@ +package org.greencodeinitiative.creedengo.java.integration.tests; + +import java.net.MalformedURLException; +import java.net.URI; +import java.nio.file.Path; +import java.text.MessageFormat; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.sonar.orchestrator.Orchestrator; +import com.sonar.orchestrator.build.MavenBuild; +import com.sonar.orchestrator.container.Server; +import com.sonar.orchestrator.junit5.OrchestratorExtension; +import com.sonar.orchestrator.junit5.OrchestratorExtensionBuilder; +import com.sonar.orchestrator.locator.FileLocation; +import com.sonar.orchestrator.locator.Location; +import com.sonar.orchestrator.locator.MavenLocation; +import com.sonar.orchestrator.locator.URLLocation; +import lombok.Getter; +import org.greencodeinitiative.creedengo.java.integration.tests.profile.ProfileBackup; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.sonarqube.ws.Issues; +import org.sonarqube.ws.Measures; +import org.sonarqube.ws.client.HttpConnector; +import org.sonarqube.ws.client.WsClient; +import org.sonarqube.ws.client.WsClientFactories; +import org.sonarqube.ws.client.issues.SearchRequest; +import org.sonarqube.ws.client.measures.ComponentRequest; + +import static java.lang.System.Logger.Level.INFO; +import static java.util.Optional.ofNullable; +import static java.util.function.Predicate.not; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.assertj.core.api.Assertions.assertThat; + +abstract class BuildProjectEngine { + + private static final System.Logger LOGGER = System.getLogger(BuildProjectEngine.class.getName()); + + protected static OrchestratorExtension orchestrator; + protected static List analyzedProjects; + + @BeforeAll + static void setup() { + LOGGER.log( + INFO, + "\n" + + "====================================================================================================\n" + + "Launching SonarQube server with following JAVA System properties: {0}\n" + + "====================================================================================================\n" + , + Stream + .of( + "test-it.sonarqube.keepRunning", + "test-it.orchestrator.artifactory.url", + "test-it.sonarqube.version", + "test-it.plugins", + "test-it.additional-profile-uris", + "test-it.test-projects", + "test-it.test-project-profile-by-language" + ) + .filter(k -> System.getProperty(k) != null) + .map(k -> MessageFormat + .format( + "-D{0}=\"{1}\"", + k, + System.getProperty(k).replaceAll("\\s+", " ") + ) + ) + .collect(Collectors.joining("\n", "\n\n", "\n\n")) + ); + launchSonarqube(); + launchAnalysis(); + } + + @AfterAll + static void tearDown() { + if ("true".equalsIgnoreCase(System.getProperty("test-it.sonarqube.keepRunning"))) { + try (Scanner in = new Scanner(System.in)) { + LOGGER.log(INFO, () -> + MessageFormat.format( + "\n" + + "\n====================================================================================================" + + "\nSonarQube available at: {0} (to login: admin/admin)" + + "\n====================================================================================================" + + "\n", + orchestrator.getServer().getUrl() + ) + ); + do { + LOGGER.log(INFO, "✍ Please press CTRL+C to stop"); + } + while (!in.nextLine().isEmpty()); + } + } + if (orchestrator != null) { + orchestrator.stop(); + } + } + + private static void launchSonarqube() { + String orchestratorArtifactoryUrl = systemProperty("test-it.orchestrator.artifactory.url"); + String sonarqubeVersion = systemProperty("test-it.sonarqube.version"); + Optional sonarqubePort = ofNullable(System.getProperty("test-it.sonarqube.port")).map(String::trim).filter(not(String::isEmpty)); + + OrchestratorExtensionBuilder orchestratorExtensionBuilder = OrchestratorExtension + .builderEnv() + .useDefaultAdminCredentialsForBuilds(true) + .setOrchestratorProperty("orchestrator.artifactory.url", orchestratorArtifactoryUrl) + .setSonarVersion(sonarqubeVersion) + .setServerProperty("sonar.forceAuthentication", "false") + .setServerProperty("sonar.web.javaOpts", "-Xmx1G"); + + sonarqubePort.ifPresent(s -> orchestratorExtensionBuilder.setServerProperty("sonar.web.port", s)); + + additionalPluginsToInstall().forEach(orchestratorExtensionBuilder::addPlugin); + additionalProfiles().forEach(orchestratorExtensionBuilder::restoreProfileAtStartup); + + orchestrator = orchestratorExtensionBuilder.build(); + orchestrator.start(); + LOGGER.log(INFO, () -> MessageFormat.format("SonarQube server available on: {0}", orchestrator.getServer().getUrl())); + } + + private static void launchAnalysis() { + Server server = orchestrator.getServer(); + Map qualityProfileByLanguage = testProjectProfileByLanguage(); + + analyzedProjects = getProjectsToAnalyze(); + + analyzedProjects + .stream() + // - Prepare/create SonarQube project for the test project + .peek(projectToAnalyze -> projectToAnalyze.provisionProjectIntoServer(server)) + // - Configure the test project + .peek(projectToAnalyze -> projectToAnalyze.associateProjectToQualityProfile(server, qualityProfileByLanguage)) + .map(ProjectToAnalyze::createMavenBuild) + // - Run SonarQube Scanner on test project + .peek(p -> LOGGER.log(INFO, () -> MessageFormat.format("Running SonarQube Scanner on project: {0}", p.getPom()))) + .forEach(orchestrator::executeBuild); + } + + private static String systemProperty(String propertyName) { + return ofNullable(System.getProperty(propertyName)) + .orElseThrow(() -> new IllegalStateException( + String.format( + "System property `%s` must be defined. See `%s` (in section: `plugin[maven-failsafe-plugin]/systemPropertyVariables`) for sample value.", + propertyName, + Path.of("pom.xml").toAbsolutePath() + ) + )); + } + + /** + * Projects to analyze + */ + private static List getProjectsToAnalyze() { + return commaSeparatedValues(systemProperty("test-it.test-projects")) + .map(projectToAnalyzeDefinition -> pipeSeparatedValues(projectToAnalyzeDefinition).collect(toList())) + .filter(projectToAnalyzeDefinition -> projectToAnalyzeDefinition.size() == 3) + .map(projectToAnalyzeDefinition -> { + // Project Key + String projectKey = projectToAnalyzeDefinition.get(0); + // Project Name + String projectName = projectToAnalyzeDefinition.get(1); + // Project POM URI + URI projectPom = URI.create(projectToAnalyzeDefinition.get(2)); + return new ProjectToAnalyze(projectPom, projectKey, projectName); + }) + .collect(toList()); + } + + private static Stream commaSeparatedValues(String value) { + return splitAndTrim(value, "\\s*,\\s*"); + } + + private static Stream pipeSeparatedValues(String value) { + return splitAndTrim(value, "\\s*\\|\\s*"); + } + + private static Stream colonSeparatedValues(String value) { + return splitAndTrim(value, "\\s*\\:\\s*"); + } + + private static Stream splitAndTrim(String value, String regexSeparator) { + return Stream + .of(value.split(regexSeparator)) + .map(String::trim) + .filter(not(String::isEmpty)); + } + + private static Set additionalPluginsToInstall() { + Set plugins = commaSeparatedValues(systemProperty("test-it.plugins")) + .map(BuildProjectEngine::toPluginLocation) + .collect(Collectors.toSet()); + commaSeparatedValues(System.getProperty("test-it.additional-plugins", "")) + .map(BuildProjectEngine::toPluginLocation) + .forEach(plugins::add); + return plugins; + } + + private static Set additionalProfiles() { + return commaSeparatedValues(systemProperty("test-it.additional-profile-uris")) + .map(URI::create) + .map(ProfileBackup::new) + .map(ProfileBackup::profileDataUri) + .map(URLLocation::create) + .collect(Collectors.toSet()); + } + + private static Map testProjectProfileByLanguage() { + // Comma separated list of profiles to associate to each "test project" + // Syntaxe: `language:profileName` + return commaSeparatedValues(systemProperty("test-it.test-project-profile-by-language")) + .map(languageAndProfileDefinitions -> pipeSeparatedValues(languageAndProfileDefinitions).collect(toList())) + .filter(languageAndProfile -> languageAndProfile.size() == 2) + .collect(toMap( + // Language + languageAndProfile -> languageAndProfile.get(0), + // Profile name + languageAndProfile -> languageAndProfile.get(1) + )); + } + + private static Location toPluginLocation(String location) { + if (location.startsWith("file://")) { + try { + return FileLocation.of(URI.create(location).toURL()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } + List pluginGAVvalues = colonSeparatedValues(location).collect(toList()); + if (pluginGAVvalues.size() != 3) { + throw new IllegalArgumentException("Invalid plugin GAV definition (`groupId:artifactId:version`): " + location); + } + return MavenLocation.of( + // groupId + pluginGAVvalues.get(0), + // artifactId + pluginGAVvalues.get(1), + // version + pluginGAVvalues.get(2) + ); + } + + protected static List issuesForFile(String projectKey, String file) { + return issuesForComponent(projectKey + ":" + file); + } + + protected static List issuesForComponent(String componentKey) { + return newWsClient(orchestrator) + .issues() + .search(new SearchRequest().setComponentKeys(Collections.singletonList(componentKey))) + .getIssuesList(); + } + + protected static Map getMeasures(String componentKey) { + List metricKeys = List.of( + "alert_status", + "blocker_violations", + "branch_coverage", + "bugs", +// "class_complexity", // suppr en 25.1 + "classes", + "code_smells", + "cognitive_complexity", + "comment_lines", + "comment_lines_data", + "comment_lines_density", + "complexity", +// "complexity_in_classes", // suppr en 25.1 +// "complexity_in_functions", // suppr en 25.1 + "conditions_to_cover", + "confirmed_issues", + "coverage", + "critical_violations", + "development_cost", +// "directories", // suppr en 10.2 + "duplicated_blocks", + "duplicated_files", + "duplicated_lines", + "duplicated_lines_density", + "duplications_data", + "effort_to_reach_maintainability_rating_a", + "executable_lines_data", + "false_positive_issues", +// "file_complexity", // suppr en 25.1 +// "file_complexity_distribution", // suppr en 25.1 + "files", +// "function_complexity", // suppr en 25.1 +// "function_complexity_distribution", // suppr en 25.1 + "functions", + "generated_lines", + "generated_ncloc", + "info_violations", + "last_commit_date", + "line_coverage", + "lines", + "lines_to_cover", + "major_violations", + "minor_violations", + "ncloc", + "ncloc_data", + "ncloc_language_distribution", + "new_blocker_violations", + "new_branch_coverage", + "new_bugs", + "new_code_smells", + "new_conditions_to_cover", + "new_coverage", + "new_critical_violations", + "new_development_cost", + "new_duplicated_blocks", + "new_duplicated_lines", + "new_duplicated_lines_density", + "new_info_violations", + "new_line_coverage", + "new_lines", + "new_lines_to_cover", + "new_maintainability_rating", + "new_major_violations", + "new_minor_violations", + "new_reliability_rating", + "new_reliability_remediation_effort", + "new_security_hotspots", + "new_security_hotspots_reviewed", + "new_security_hotspots_reviewed_status", + "new_security_hotspots_to_review_status", + "new_security_rating", + "new_security_remediation_effort", + "new_security_review_rating", + "new_technical_debt", + "new_violations", + "new_vulnerabilities", + "open_issues", + "projects", + "public_api", + "public_documented_api_density", + "public_undocumented_api", + "quality_gate_details", + "quality_profiles", + "reliability_rating", + "reliability_remediation_effort", + "reopened_issues", + "security_hotspots", + "security_hotspots_reviewed", + "security_hotspots_reviewed_status", + "security_hotspots_to_review_status", + "security_rating", + "security_remediation_effort", + "security_review_rating", + "skipped_tests", + "sqale_rating", + "statements", + "unanalyzed_c", + "unanalyzed_cpp", + "violations" + ); + return newWsClient(orchestrator) + .measures() + .component( + new ComponentRequest() + .setComponent(componentKey) + .setMetricKeys(metricKeys) + ) + .getComponent().getMeasuresList() + .stream() + .collect(Collectors.toMap(Measures.Measure::getMetric, Function.identity())); + } + + protected static WsClient newWsClient(Orchestrator orchestrator) { + return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() + .url(orchestrator.getServer().getUrl()) + .build()); + } + + @Getter + protected static class ProjectToAnalyze { + private final Path pom; + private final String projectKey; + private final String projectName; + + private ProjectToAnalyze(URI pom, String projectKey, String projectName) { + this.pom = Path.of(pom); + assertThat(this.pom).isRegularFile(); + this.projectKey = projectKey; + this.projectName = projectName; + } + + public MavenBuild createMavenBuild() { + return MavenBuild.create(pom.toFile()) + .setCleanPackageSonarGoals() + .setProperty("sonar.projectKey", projectKey) + .setProperty("sonar.projectName", projectName) + .setProperty("sonar.scm.disabled", "true"); + } + + private void provisionProjectIntoServer(Server server) { + server.provisionProject(projectKey, projectName); + + } + + private void associateProjectToQualityProfile(Server server, Map qualityProfileByLanguage) { + qualityProfileByLanguage.forEach((language, profileName) -> server.associateProjectToQualityProfile(projectKey, language, profileName)); + } + } + +} 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 0000000..46eaeb6 --- /dev/null +++ b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/GCIRulesIT.java @@ -0,0 +1,119 @@ +package org.greencodeinitiative.creedengo.java.integration.tests; + +import org.assertj.core.groups.Tuple; +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 static java.util.Optional.ofNullable; +import static org.assertj.core.api.Assertions.assertThat; +import static org.sonarqube.ws.Common.RuleType.CODE_SMELL; +import static org.sonarqube.ws.Common.Severity.MINOR; + +class GCIRulesIT extends BuildProjectEngine { + + @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 = issuesForComponent(projectKey); + assertThat(projectIssues).isNotEmpty(); + + } + + @Test + void testGCI3() { + String projectKey = analyzedProjects.get(0).getProjectKey(); + + List issues = issuesForFile(projectKey, + "src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopBad.java"); + + assertThat(issues) + .hasSize(2) + .extracting("rule", "message", "line", "textRange.startLine", "textRange.endLine", + "textRange.startOffset", "textRange.endOffset", "severity", "type", "debt", "effort") + .containsExactlyInAnyOrder( + Tuple.tuple("creedengo-java:GCI3", "Avoid getting the size of the collection in the loop", + 13, 13, 13, 28, 45, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI69", "Do not call a function when declaring a for-type loop", + 13, 13, 13, 28, 45, MINOR, CODE_SMELL, "5min", "5min") + ); + + } + + @Test + void testGCI69() { + String projectKey = analyzedProjects.get(0).getProjectKey(); + + List issues = issuesForFile(projectKey, + "src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java"); + + assertThat(issues) + .hasSize(4) + .extracting("rule", "message", "line", "textRange.startLine", "textRange.endLine", + "textRange.startOffset", "textRange.endOffset", "severity", "type", "debt", "effort") + .containsExactly( + Tuple.tuple("creedengo-java:GCI69", "Do not call a function when declaring a for-type loop", + 58, 58, 58, 28, 40, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI69", "Do not call a function when declaring a for-type loop", + 66, 66, 66, 34, 46, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI69", "Do not call a function when declaring a for-type loop", + 74, 74, 74, 39, 51, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI69", "Do not call a function when declaring a for-type loop", + 101, 101, 101, 108, 132, MINOR, CODE_SMELL, "5min", "5min") + ); + + } + + @Test + void testGCI82() { + String projectKey = analyzedProjects.get(0).getProjectKey(); + + List issues = issuesForFile(projectKey, + "src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java"); + + assertThat(issues) + .hasSize(4) + .extracting("rule", "message", "line", "textRange.startLine", "textRange.endLine", + "textRange.startOffset", "textRange.endOffset", "severity", "type", "debt", "effort") + .contains( + Tuple.tuple("creedengo-java:GCI82", "The variable is never reassigned and can be 'final'", + 7, 7, 7, 4, 67, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI82", "The variable is never reassigned and can be 'final'", + 12, 12, 12, 4, 56, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI82", "The variable is never reassigned and can be 'final'", + 13, 13, 13, 4, 50, MINOR, CODE_SMELL, "5min", "5min"), + Tuple.tuple("creedengo-java:GCI82", "The variable is never reassigned and can be 'final'", + 45, 45, 45, 8, 25, MINOR, CODE_SMELL, "5min", "5min") + ); + + } + + @Test + void testGCI94() { + String projectKey = analyzedProjects.get(0).getProjectKey(); + + List issues = issuesForFile(projectKey, + "src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java"); + + assertThat(issues) + .hasSize(1) + .extracting("rule", "message", "line", "textRange.startLine", "textRange.endLine", + "textRange.startOffset", "textRange.endOffset", "severity", "type", "debt", "effort") + .containsExactly( + Tuple.tuple( + "creedengo-java:GCI94", "Use optional orElseGet instead of orElse.", + 25, 25, 25, 38, 69, MINOR, CODE_SMELL, "1min", "1min") + ); + + } + +} diff --git a/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/ProfileBackup.java b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/ProfileBackup.java new file mode 100644 index 0000000..26feba2 --- /dev/null +++ b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/ProfileBackup.java @@ -0,0 +1,163 @@ +package org.greencodeinitiative.creedengo.java.integration.tests.profile; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Base64; +import java.util.List; +import java.util.stream.Collectors; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; + +/** + * Manage XML Backup file of profile based on JSON official profile. + * + *

Example, following JSON profile:

+ *
+ * {
+ *  "name": "creedengo way",
+ *  "language": "java",
+ *  "ruleKeys": [
+ * 	    "GCI1",
+ * 	    "GCI2"
+ *  ]
+ * }
+ * 
+ *

may produce following XML profile:

+ *
+ * <?xml version='1.0' encoding='UTF-8'?>
+ * <profile>
+ * 	<name>creedengo way</name>
+ * 	<language>java</language>
+ * 	<rules>
+ * 		<rule>
+ * 			<repositoryKey>creedengo-java</repositoryKey>
+ * 			<key>GCI1</key>
+ * 			<type>CODE_SMELL</type>
+ * 			<priority>MINOR</priority>
+ * 			<parameters />
+ * 		</rule>
+ * 		<rule>
+ * 			<repositoryKey>creedengo-java</repositoryKey>
+ * 			<key>GCI2</key>
+ * 			<type>CODE_SMELL</type>
+ * 			<priority>MINOR</priority>
+ * 			<parameters />
+ * 		</rule>
+ * 	</rules>
+ * </profile>
+ * 
+ */ +public class ProfileBackup { + private static final MessageFormat TEMPLATE_PROFIL = new MessageFormat( + "\n" + + "\n" + + " {0}\n" + + " {1}\n" + + " \n" + + " {2}\n" + + " \n" + + "\n" + ); + private static final MessageFormat TEMPLATE_RULE = new MessageFormat( + "\n" + + " {0}\n" + + " {1}\n" + + " {2}\n" + + " {3}\n" + + " \n" + + "\n" + ); + + private final ObjectMapper mapper; + private final URI jsonProfile; + + public ProfileBackup(URI jsonProfile) { + this.mapper = new ObjectMapper(); + // Ignore unknown properties + this.mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); + + this.jsonProfile = jsonProfile; + } + + private transient ProfileMetadata profileMetadata; + + private ProfileMetadata profileMetadata() { + if (profileMetadata == null) { + try (InputStream profilJsonFile = jsonProfile.toURL().openStream()) { + profileMetadata = mapper.readValue(profilJsonFile, ProfileMetadata.class); + } catch (IOException e) { + throw new RuntimeException("Unable to load JSON Profile: " + jsonProfile, e); + } + } + return profileMetadata; + } + + private RuleMetadata loadRule(String language, String ruleKey) { + try (InputStream ruleMetadataJsonFile = ClassLoader.getSystemResourceAsStream("org/green-code-initiative/rules/" + language + "/" + ruleKey + ".json")) { + RuleMetadata result = mapper.readValue(ruleMetadataJsonFile, RuleMetadata.class); + result.setKey(ruleKey); + return result; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private String xmlProfile() throws IOException { + ProfileMetadata profileMetadata = profileMetadata(); + String language = profileMetadata.getLanguage(); + List rules = profileMetadata.getRuleKeys().stream() + .map(ruleKey -> this.loadRule(language, ruleKey)) + .collect(Collectors.toList()); + StringBuilder output = new StringBuilder(); + String repositoryKey = "creedengo-" + profileMetadata.getLanguage(); + rules.forEach(rule -> output.append( + xmlRule( + repositoryKey, + rule.getKey(), + rule.getType(), + rule.getDefaultSeverity().toUpperCase() + )) + ); + return TEMPLATE_PROFIL.format(new Object[]{ + profileMetadata.getName(), + profileMetadata.getLanguage(), + output.toString() + }); + } + + private String xmlRule(String repositoryKey, String key, String type, String priority) { + return TEMPLATE_RULE.format(new Object[]{ + repositoryKey, + key, + type, + priority + }); + } + + /** + * Get the content of XML Profil in datauri format. + */ + public URL profileDataUri() { + try { + String xmlProfileContent = xmlProfile(); + String xmlProfileBase64encoded = Base64.getEncoder().encodeToString(xmlProfileContent.getBytes()); + return new URL("data:text/xml;base64," + xmlProfileBase64encoded); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public String language() { + return profileMetadata().getLanguage(); + } + + + public String name() { + return profileMetadata().getName(); + } +} diff --git a/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/ProfileMetadata.java b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/ProfileMetadata.java new file mode 100644 index 0000000..8078914 --- /dev/null +++ b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/ProfileMetadata.java @@ -0,0 +1,42 @@ +package org.greencodeinitiative.creedengo.java.integration.tests.profile; + +import java.util.List; + +public class ProfileMetadata { + private String name; + private String language; + private List ruleKeys; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public List getRuleKeys() { + return ruleKeys; + } + + public void setRuleKeys(List ruleKeys) { + this.ruleKeys = ruleKeys; + } + + @Override + public String toString() { + return "ProfileMetadata{" + + "name='" + name + '\'' + + ", language='" + language + '\'' + + ", ruleKeys=" + ruleKeys + + '}'; + } +} diff --git a/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/RuleMetadata.java b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/RuleMetadata.java new file mode 100644 index 0000000..8f6bc99 --- /dev/null +++ b/src/it/java/org/greencodeinitiative/creedengo/java/integration/tests/profile/RuleMetadata.java @@ -0,0 +1,40 @@ +package org.greencodeinitiative.creedengo.java.integration.tests.profile; + +public class RuleMetadata { + private String key; + private String type; + private String defaultSeverity; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDefaultSeverity() { + return defaultSeverity; + } + + public void setDefaultSeverity(String defaultSeverity) { + this.defaultSeverity = defaultSeverity; + } + + @Override + public String toString() { + return "RuleMetadata{" + + "key='" + key + '\'' + + ", type='" + type + '\'' + + ", defaultSeverity='" + defaultSeverity + '\'' + + '}'; + } +} 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 0000000..cfb7ba4 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/pom.xml @@ -0,0 +1,37 @@ + + + 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 + + + + \ 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/ArrayCopyCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheck.java new file mode 100644 index 0000000..a7dbff8 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheck.java @@ -0,0 +1,493 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.Arrays; + +class ArrayCopyCheck { + + public void copyArrayOK() { + final int len = 5; + final boolean[] src = new boolean[len]; + boolean[] dest = new boolean[len]; + + // Copy with clone + dest = src.clone(); + + // Copy with System.arraycopy() + System.arraycopy(src, 0, dest, 0, src.length); + + // Copy with Arrays.copyOf() + dest = Arrays.copyOf(src, src.length); + } + + public void nonRegression() { + final int len = 5; + final boolean[] src = new boolean[len]; + boolean[] dest = new boolean[len]; + + // Simple assignation + for (int i = 0; i < len; i++) { + dest[i] = true; + } + + // Edit same array + for (int i = 0; i < len - 1; i++) { + dest[i] = dest[i + 1]; + } + + // Objects assignations + String a = null; + String b = "Sample Value"; + for (int i = 0; i < len; i++) { + a = b; + } + } + + public void copyWithForLoop() { + final int len = 5; + final boolean[] src = new boolean[len]; + boolean[] dest = new boolean[len]; + + // Simple copy + for (int i = 0; i < len; i++) { + dest[i] = src[i]; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested conditions + for (int i = 0; i < len; i++) { + if (i + 2 < len) { + dest[i] = src[i + 2]; + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested ELSE conditions + for (int i = 0; i < len; i++) { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with more nested conditions + for (int i = 0; i < len; i++) { + if (i + 2 < len) { + if (dest != null) { + if (src != null) { + if (i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch + for (int i = 0; i < len; i++) { + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch and if + for (int i = 0; i < len; i++) { + try { + if (dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in catch + for (int i = 0; i < len; i++) { + try { + dest.toString(); + } catch (RuntimeException e) { + if (dest != null) { + dest[i] = src[i]; + } + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in finally + for (int i = 0; i < len; i++) { + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Array transformation + for (int i = 0; i < len; i++) { + dest[i] = transform(src[i]); + } + } + + public void copyWithForEachLoop() { + final int len = 5; + final boolean[] src = new boolean[len]; + boolean[] dest = new boolean[len]; + + // Simple copy by foreach + int i = -1; + for (boolean b : src) { + dest[++i] = b; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested conditions by foreach + i = -1; + for (boolean b : src) { + if (b) { + dest[++i] = b; + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested ELSE conditions by foreach + i = -1; + for (boolean b : src) { + if (i + 2 >= len) { + i++; + } else { + dest[++i] = b; + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with more nested conditions + i = -1; + for (boolean b : src) { + if (i + 2 < len) { + if (dest != null) { + if (src != null) { + if (i > 1 && i + 2 < src.length) { + dest[++i] = b; + } + } + } + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch + i = -1; + for (boolean b : src) { + try { + dest[++i] = b; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch and if + i = -1; + for (boolean b : src) { + try { + if (dest != null) { + dest[++i] = b; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in catch + i = -1; + for (boolean b : src) { + try { + dest.toString(); + } catch (RuntimeException e) { + if (dest != null) { + dest[++i] = b; + } + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in finally + i = -1; + for (boolean b : src) { + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[++i] = b; + } + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Array transformation + i = -1; + for (boolean b : src) { + dest[++i] = transform(b); + } + + // Simple copy + i = 0; + for (boolean b : src) { + dest[i] = src[i]; + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested conditions + i = 0; + for (boolean b : src) { + if (b) { + dest[i] = src[i]; + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested ELSE conditions + i = 0; + for (boolean b : src) { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with more nested conditions + i = 0; + for (boolean b : src) { + if (i + 2 < len) { + if (dest != null) { + if (src != null) { + if (i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch + i = 0; + for (boolean b : src) { + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch and if + i = 0; + for (boolean b : src) { + try { + if (dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in catch + i = 0; + for (boolean b : src) { + try { + dest.toString(); + } catch (RuntimeException e) { + if (dest != null) { + dest[i] = src[i]; + } + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in finally + i = 0; + for (boolean b : src) { + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Array transformation + i = 0; + for (boolean b : src) { + dest[i] = transform(src[i]); + i++; + } + } + + public void copyWithWhileLoop() { + final int len = 5; + final boolean[] src = new boolean[len]; + boolean[] dest = new boolean[len]; + + // Simple copy + int i = 0; + while (i < len) { + dest[i] = src[i]; + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested conditions + i = 0; + while (i < len) { + if (i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested ELSE conditions + i = 0; + while (i < len) { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with more nested conditions + i = 0; + while (i < len) { + if (i + 2 < len) { + if (dest != null) { + if (src != null) { + if (i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch and if + i = 0; + while (i < len) { + try { + if (dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in catch + i = 0; + while (i < len) { + try { + dest.toString(); + } catch (RuntimeException e) { + if (dest != null) { + dest[i] = src[i]; + } + } + i++; + } // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Array transformation + i = 0; + while (i < len) { + dest[i] = transform(src[i]); + i++; + } + } + + public void copyWithDoWhileLoop() { + final int len = 5; + final boolean[] src = new boolean[len]; + boolean[] dest = new boolean[len]; + + // Simple copy + int i = 0; + do { + dest[i] = src[i]; + i++; + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested conditions + i = 0; + do { + if (i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with nested ELSE conditions + i = 0; + do { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy with more nested conditions + i = 0; + do { + if (i + 2 < len) { + if (dest != null) { + if (src != null) { + if (i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch and if + i = 0; + do { + try { + if (dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Copy nested by try/catch in catch + i = 0; + do { + try { + dest.toString(); + } catch (RuntimeException e) { + if (dest != null) { + dest[i] = src[i]; + } + } + i++; + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} + + // Array transformation + i = 0; + do { + dest[i] = transform(src[i]); + i++; + } while (i < len); + } + + private boolean transform(boolean a) { + return !a; + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequestCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequestCheck.java new file mode 100644 index 0000000..a525a42 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequestCheck.java @@ -0,0 +1,30 @@ +package org.greencodeinitiative.creedengo.java.checks; + +class AvoidFullSQLRequestCheck { + AvoidFullSQLRequestCheck(AvoidFullSQLRequestCheck mc) { + } + + public void literalSQLrequest() { + dummyCall(" sElEcT * fRoM myTable"); // Noncompliant {{Don't use the query SELECT * FROM}} + dummyCall(" sElEcT user fRoM myTable"); + + dummyCall("SELECTABLE 2*2 FROMAGE"); //not sql + dummyCall("SELECT *FROM table"); // Noncompliant {{Don't use the query SELECT * FROM}} + } + + + public void variableSQLrequest() { + String requestNonCompiliant = " SeLeCt * FrOm myTable"; // Noncompliant {{Don't use the query SELECT * FROM}} + String requestCompiliant = " SeLeCt user FrOm myTable"; + dummyCall(requestNonCompiliant); + dummyCall(requestCompiliant); + + String noSqlCompiliant = "SELECTABLE 2*2 FROMAGE"; //not sql + String requestNonCompiliant_nSpace = "SELECT *FROM table"; // Noncompliant {{Don't use the query SELECT * FROM}} + } + + private void dummyCall(String request) { + + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java new file mode 100644 index 0000000..c24f9c9 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java @@ -0,0 +1,21 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayList; +import java.util.List; + +class AvoidGettingSizeCollectionInForEachLoopIgnored { + AvoidGettingSizeCollectionInForEachLoopIgnored(AvoidGettingSizeCollectionInForEachLoopIgnored obj) { + + } + + public void ignoredLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + for (Integer i : numberList) { // Ignored + int size = numberList.size(); // Compliant with this rule + System.out.println("numberList.size()"); + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopBad.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopBad.java new file mode 100644 index 0000000..03efe7c --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/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 + System.out.println("numberList.size()"); + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopGood.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopGood.java new file mode 100644 index 0000000..88d9886 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopGood.java @@ -0,0 +1,23 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.Collection; +import java.util.ArrayList; +import java.util.List; + +class AvoidGettingSizeCollectionInForLoopGood { + AvoidGettingSizeCollectionInForLoopGood(AvoidGettingSizeCollectionInForLoopGood obj) { + + } + + public void goodForLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + int size = numberList.size(); + for (int i = 0; i < size; i++) { // Compliant + System.out.println("numberList.size()"); + int size2 = numberList.size(); // Compliant with this rule + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java new file mode 100644 index 0000000..3ef6359 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java @@ -0,0 +1,24 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +class AvoidGettingSizeCollectionInForLoopIgnored { + AvoidGettingSizeCollectionInForLoopIgnored() { + + } + + public void badForLoop() { + final List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + final Iterator it = numberList.iterator(); + for (; it.hasNext(); ) { // Ignored => compliant + System.out.println(it.next()); + } + } + + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java new file mode 100644 index 0000000..7410af9 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java @@ -0,0 +1,22 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayList; +import java.util.List; + +class AvoidGettingSizeCollectionInWhileLoopBad { + AvoidGettingSizeCollectionInWhileLoopBad() { + + } + + public void badWhileLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + int i = 0; + while (i < numberList.size()) { // Noncompliant {{Avoid getting the size of the collection in the loop}} + System.out.println("numberList.size()"); + i++; + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java new file mode 100644 index 0000000..a09e89e --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java @@ -0,0 +1,24 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayList; +import java.util.List; + +class AvoidGettingSizeCollectionInWhileLoopGood { + AvoidGettingSizeCollectionInWhileLoopGood(AvoidGettingSizeCollectionInWhileLoopGood obj) { + + } + + public void goodWhileLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + int size = numberList.size(); + int i = 0; + while (i < size) { // Compliant + System.out.println("numberList.size()"); + int size2 = numberList.size(); // Compliant with this rule + i++; + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java new file mode 100644 index 0000000..c22b216 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java @@ -0,0 +1,24 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +class AvoidGettingSizeCollectionInWhileLoopIgnored { + AvoidGettingSizeCollectionInWhileLoopIgnored() { + + } + + public void badWhileLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + Iterator it = numberList.iterator(); + int i = 0; + while (it.hasNext()) { // Ignored => compliant + it.next(); + System.out.println("numberList.size()"); + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java new file mode 100644 index 0000000..23ad4cc --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java @@ -0,0 +1,266 @@ +package org.greencodeinitiative.creedengo.java.checks; + +class AvoidMultipleIfElseStatement { + +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// // +// // NON COMPLIANT use cases +// // +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // NON COMPLIANT + // USE CASE : Non compliant use case to check if following is NON OK : + // - two uses of the same variable + // - usage of the same variable on different levels of IF statements + public int shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if a variable is not used max twice on several IF / ELSE statements + // at the same level + public int shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb3 == 1 + && nb3 == 2 + && nb3 == 3) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { + nb2 = 2; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT COMPLIANT : + // one variable is used maximum in two IF / ELSE / ELSEIF statements + public int shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + nb1 = 3; + } + + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 4; + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - same variable used maximum twice : no compliant because 2 IFs and 1 ELSE + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatementsAtDifferentsLevels() + { + int nb1 = 0; + + if (nb1 == 1) { + if (nb1 == 2) { + nb1 = 1; + } else { + nb1 = 3; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } else { + nb1 = 2; + } + + return nb1; + } + + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 3; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario2() + { + int nb1 = 0; + + if (nb1 == 1) { + if (nb1 == 3) { + nb1 = 4; + } else { + nb1 = 5; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { + nb1 = 3; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } + + return nb1; + } + + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario3() + { + int nb1 = 0; + int nb2 = 0; + + if (nb1 == 1) { + if (nb1 == 3) { + nb1 = 4; + } else { + nb1 = 5; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } else if (nb2 == 2) { + if (nb1 == 4) { + nb1 = 5; + } else { + nb1 = 6; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario4() + { + int nb1 = 0; + int nb2 = 0; + + if (nb1 == 1) { + if (nb2 == 3) { + nb1 = 4; + } else { + nb1 = 5; + } + } else if (nb2 == 2) { + if (nb1 == 3) { + nb1 = 4; + } else { + nb1 = 5; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - the same variable must used maximum twice + // - usage of the same variable on different levels of IF / ELSE statements + public int shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { + if (nb1 == 3) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 4; + } else { + nb1 = 5; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - more than twice uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeNotCompliantBecauseTheSameVariableIsUsedMoreThanTwice() // NOT Compliant + { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; + } else { + nb2 = 4; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + + return nb2; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - more than twice uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeNotCompliantBecauseTheSameVariableIsUsedManyTimes() // NOT Compliant + { + int nb1 = 0; + int nb2 = 10; + int nb3 = 11; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; + } else if (nb3 == nb1) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb2 = 3; + } else { + nb2 = 4; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + + return nb2; + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java new file mode 100644 index 0000000..1095d92 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/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/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java new file mode 100644 index 0000000..d677109 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java @@ -0,0 +1,24 @@ +/* + * 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; + +interface AvoidMultipleIfElseStatementInterfaceNoIssue { + + 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/AvoidMultipleIfElseStatementNoBlockNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java new file mode 100644 index 0000000..cf1a104 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/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/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementNoIssue.java new file mode 100644 index 0000000..f787785 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -0,0 +1,256 @@ +package org.greencodeinitiative.creedengo.java.checks; + +class AvoidMultipleIfElseStatementNoIssue { + + // inital RULES : please see HTML description file of this rule (resources directory) + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // + // COMPLIANT use cases + // + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public int shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb3 != 1 && nb1 > 1) { + nb1 = 1; + } else { + nb2 = 2; + } + + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public int shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDiffLevels() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb1 < 1) { + if (nb2 == 2) { + nb3 = 3; + } else { + nb3 = 4; + } + } else { + nb2 = 2; + } + + if (nb3 >= 1) { + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + } else { + nb1 = 2; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public int shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDiffVariablesUsedAtDiffLevelsScenario2() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb1 <= 1) { + if (nb2 == 2) { + if (nb3 == 2) { + nb3 = 3; + } else { + nb3 = 4; + } + } else { + nb3 = 4; + } + } else { + nb2 = 2; + } + + if (nb3 == 1) { + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + } else { + nb1 = 2; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements + public int shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 1; + } + + if (nb1 == 2) { + nb1 = 3; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different levels of IF statements + public int shouldBeCompliantBecauseSereralVariablesUsedMaximumTwiceInComposedElseStatements() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb2 == 2) { + nb1 = 1; + } else { + if (nb3 == 4) { + nb1 = 3; + } else { + nb1 = 6; + } + } + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfOrElseIfStatements() // Compliant + { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; + } + + return nb2; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrElseIfStatements() // Compliant + { + int nb1 = 0; + int nb2 = 10; + int nb3 = 3; + int nb4 = 1; + int nb5 = 2; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb3 == nb2) { + nb2 = 2; + } else if (nb4 == nb5) { + nb2 = 4; + } else { + nb2 = 3; + } + + return nb2; + } + + // COMPLIANT + // USE CASE : Compliant use case to check if following is OK : + // - usage of the same variable on different levels of IF statements but with incompatible type for a switch + public float shouldBeCompliantBecauseVariableHasNotCompatibleTypeFloatForSwitch() + { + float nb1 = 0.0f; + + if (nb1 > 1) { + nb1 = 2.1f; + } else { + if (nb1 > 2) { + nb1 = 1.1f; + } + } + + return nb1; + } + + // COMPLIANT + // USE CASE : Compliant use case to check if following is OK : + // - usage of the same variable on different levels of IF statements but with incompatible type for a switch + public double shouldBeCompliantBecauseVariableHasNotCompatibleTypeDoubleForSwitch() + { + double nb1 = 0.0; + + if (nb1 > 1) { + nb1 = 2.1; + } else { + if (nb1 > 2) { + nb1 = 1.1; + } + } + + return nb1; + } + + // COMPLIANT + // USE CASE : Compliant use case to check if following is OK : + // - usage of the same variable on different levels of IF statements but with instanceof keys + // - with a variable used 4 times + public int shouldBeCompliantBecauseVariableUsed4TimesWithInstanceOfKeys() + { + int nb1 = 0; + Object obj = new Object(); + + if (obj instanceof String) { + nb1 = 1; + } else { + if (obj instanceof Integer) { + nb1 = 2; + } else { + if (obj instanceof Double) { + nb1 = 3; + } else { + nb1 = 4; + } + } + } + + return nb1; + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStatic.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStatic.java new file mode 100644 index 0000000..20d9c24 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStatic.java @@ -0,0 +1,11 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.regex.Pattern; + +public class AvoidRegexPatternNotStatic { + + public boolean foo() { + final Pattern pattern = Pattern.compile("foo"); // Noncompliant {{Avoid using Pattern.compile() in a non-static context.}} + return pattern.matcher("foo").find(); + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoopCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoopCheck.java new file mode 100644 index 0000000..cb18589 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoopCheck.java @@ -0,0 +1,134 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; + +class AvoidSQLRequestInLoopCheck { + AvoidSQLRequestInLoopCheck(AvoidSQLRequestInLoopCheck mc) { + } + + public void testWithNoLoop() { + try { + // create our mysql database connection + String myDriver = "driver"; + String myUrl = "driver"; + Class.forName(myDriver); + Connection conn = DriverManager.getConnection(myUrl, "toor", ""); + + // our SQL SELECT query. + // if you only need a few columns, specify them by name instead of using "*" + String query = "SELECT * FROM users"; + + // create the java statement + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(query); + + // iterate through the java resultset + while (rs.next()) { + int id = rs.getInt("id"); + System.out.println(id); + } + st.close(); + } catch (Exception e) { + System.err.println("Got an exception! "); + System.err.println(e.getMessage()); + } + } + + public void testWithForLoop() { + try { + // create our mysql database connection + String myDriver = "driver"; + String myUrl = "driver"; + Class.forName(myDriver); + Connection conn = DriverManager.getConnection(myUrl, "toor", ""); + + // our SQL SELECT query. + // if you only need a few columns, specify them by name instead of using "*" + String baseQuery = "SELECT name FROM users where id = "; + + for (int i = 0; i < 20; i++) { + + // create the java statement + String query = baseQuery.concat("" + i); + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(query); // Noncompliant {{Avoid SQL request in loop}} + + // iterate through the java resultset + while (rs.next()) { + String name = rs.getString("name"); + System.out.println(name); + } + st.close(); + } + } catch (Exception e) { + System.err.println("Got an exception! "); + System.err.println(e.getMessage()); + } + } + + public void testWithForEachLoop() { + try { + // create our mysql database connection + String myDriver = "driver"; + String myUrl = "driver"; + Class.forName(myDriver); + Connection conn = DriverManager.getConnection(myUrl, "toor", ""); + + // our SQL SELECT query. + // if you only need a few columns, specify them by name instead of using "*" + String query = "SELECT * FROM users"; + int[] intArray = {10, 20, 30, 40, 50}; + for (int i : intArray) { + System.out.println(i); + // create the java statement + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(query); // Noncompliant {{Avoid SQL request in loop}} + + // iterate through the java resultset + while (rs.next()) { + int id = rs.getInt("id"); + System.out.println(id); + } + st.close(); + } + } catch (Exception e) { + System.err.println("Got an exception! "); + System.err.println(e.getMessage()); + } + } + + public void testWithWhileLoop() { + try { + // create our mysql database connection + String myDriver = "driver"; + String myUrl = "driver"; + Class.forName(myDriver); + Connection conn = DriverManager.getConnection(myUrl, "toor", ""); + + // our SQL SELECT query. + // if you only need a few columns, specify them by name instead of using "*" + String query = "SELECT * FROM users"; + int i = 0; + while (i < -1) { + + // create the java statement + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(query); // Noncompliant {{Avoid SQL request in loop}} + + // iterate through the java resultset + while (rs.next()) { + int id = rs.getInt("id"); + System.out.println(id); + } + st.close(); + } + } catch (Exception e) { + System.err.println("Got an exception! "); + System.err.println(e.getMessage()); + } + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdateCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdateCheck.java new file mode 100644 index 0000000..30654d9 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdateCheck.java @@ -0,0 +1,151 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.stream.IntStream; + +class AvoidSetConstantInBatchUpdateCheck { + + void literalSQLrequest() throws SQLException { //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(4, BigDecimal.valueOf(x)); + stmt.setBoolean(5, Boolean.valueOf("true")); + int i = stmt.executeUpdate(); + System.out.println(i + " records inserted"); + con.close(); + } + + void batchInsertInForLoop(int[] data) throws SQLException { + + Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle"); + PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?)"); + for (int i = 0; i < data.length; i++) { + stmt.setInt(1, data[i]); + + 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, (byte) '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}} + stmt.setLong(7, 7l); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setFloat(8, (float) 8.); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setFloat(8, 8.f); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setDouble(9, 9.); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setDouble(9, 9.); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setString(10, "10"); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setBigDecimal(11, BigDecimal.valueOf(.77)); // Noncompliant {{Avoid setting constants in batch update}} + stmt.addBatch(); + } + int[] nr = stmt.executeBatch(); + System.out.printf("{} rows updated", IntStream.of(nr).sum()); + con.close(); + } + + + int[] batchInsertInForeachLoop(DummyClass[] data) throws SQLException { + + try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { + PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); + for (DummyClass o : 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, (byte) '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}} + stmt.setFloat(8, (float) 8.); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setDouble(9, o.getField4()); + stmt.setString(10, o.getField2()); + stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant {{Avoid setting constants in batch update}} + stmt.addBatch(); + } + return stmt.executeBatch(); + } + } + + + int[] batchInsertInWhileLoop2(DummyClass[] data) throws SQLException { + + try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { + PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); + int i = 0; + while (i < data.length) { + DummyClass o = data[i]; + stmt.setInt(1, o.getField1()); + 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, (byte) 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}} + stmt.setFloat(8, Float.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setDouble(9, Double.MIN_VALUE); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setString(10, o.getField2()); + stmt.setBigDecimal(11, BigDecimal.TEN); // Noncompliant {{Avoid setting constants in batch update}} + stmt.addBatch(); + i++; + } + return stmt.executeBatch(); + } + } + + int[] batchInsertInWhileLoop(DummyClass[] data) throws SQLException { + if (data.length == 0) { + return new int[]{}; + } + try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { + PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); + int i = 0; + do { + DummyClass o = data[i]; + stmt.setInt(1, o.getField1()); + 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.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(.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}} + stmt.addBatch(); + i++; + } while (i < data.length); + return stmt.executeBatch(); + } + } + + class DummyClass { + + public int getField1() { + return 0; + } + + public String getField2() { + return ""; + } + + public byte getField3() { + return 'A'; + } + + public double getField4() { + return .1; + } + } + + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopCheck.java new file mode 100644 index 0000000..6e1a2d8 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -0,0 +1,57 @@ +/* + * 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.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.*; + +public class AvoidSpringRepositoryCallInLoopCheck { + @Autowired + private EmployeeRepository employeeRepository; + + public List smellGetAllEmployeesByIds(List ids) { + List employees = new ArrayList<>(); + for (Integer id : ids) { + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} + if (employee.isPresent()) { + employees.add(employee.get()); + } + } + return employees; + } + + public class Employee { + private Integer id; + private String name; + + public Employee(Integer id, String name) { + this.id = id; + this.name = name; + } + + public Integer getId() { return id; } + public String getName() { return name; } + } + + public interface EmployeeRepository extends JpaRepository { + + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInStreamCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInStreamCheck.java new file mode 100644 index 0000000..1716a3d --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInStreamCheck.java @@ -0,0 +1,125 @@ +/* + * 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.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class AvoidSpringRepositoryCallInStreamCheck { + + @Autowired + private EmployeeRepository employeeRepository; + + public List smellGetAllEmployeesByIdsForEach() { + List employees = new ArrayList<>(); + Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + stream.forEach(id -> { + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} + employee.ifPresent(employees::add); + }); + return employees; + } + + public List smellGetAllEmployeesByIdsForEachOrdered() { + List employees = new ArrayList<>(); + Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + stream.forEachOrdered(id -> { + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} + employee.ifPresent(employees::add); + }); + return employees; + } + + 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 -> { + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} + employee.ifPresent(employees::add); + return employees; + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIdsPeek() { + Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + return stream.peek(id -> { + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIdsWithOptional(List ids) { + return ids + .stream() + .map(element -> { + Employee employ = new Employee(1, "name"); + return employeeRepository.findById(element).orElse(employ);// Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + public List> smellGetAllEmployeesByIds(List ids) { + Stream stream = ids.stream(); + return stream.map(element -> { + return employeeRepository.findById(element);// Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIdsWithoutStream(List ids) { + return employeeRepository.findAllById(ids); // Compliant + } + + public List> smellDeleteEmployeeById(List ids) { + Stream stream = ids.stream(); + return stream.map(id -> { + return employeeRepository.findById(id);// Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIdsWithSeveralMethods(List ids) { + Stream stream = ids.stream(); + return stream.map(element -> { + Employee empl = new Employee(1, "name"); + return employeeRepository.findById(element).orElse(empl);// Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + public static class Employee { + private final Integer id; + private final String name; + + public Employee(Integer id, String name) { + this.id = id; + this.name = name; + } + + public Integer getId() { return id; } + public String getName() { return name; } + } + + public interface EmployeeRepository extends JpaRepository { + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueries.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueries.java new file mode 100644 index 0000000..def8b5b --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueries.java @@ -0,0 +1,20 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.*; +import java.sql.PreparedStatement; + +import javax.sql.DataSource; + + +class AvoidStatementForDMLQueries { + AvoidStatementForDMLQueries(AvoidStatementForDMLQueries mc) { + } + + public void insert() throws SQLException { + Connection connection = DriverManager.getConnection("URL"); + Statement statement = connection.createStatement(); + statement.executeUpdate("INSERT INTO persons(id, name) VALUES(2, 'Toto')"); // Noncompliant {{You must not use Statement for a DML query}} + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollections.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollections.java new file mode 100644 index 0000000..476fbda --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollections.java @@ -0,0 +1,19 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.*; + +/** + * Not compliant + */ +public class AvoidUsageOfStaticCollections { + + 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 Map MAP = new HashMap(); // Noncompliant {{Avoid usage of static collections.}} + + public AvoidUsageOfStaticCollections() { + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java new file mode 100644 index 0000000..95ed350 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java @@ -0,0 +1,38 @@ +package org.greencodeinitiative.creedengo.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() throws IOException { + String fileName = "./FreeResourcesOfAutoCloseableInterface.java"; + FileReader fr = null; + BufferedReader br = null; + try { // Noncompliant + 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(); + } + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GoodUsageOfStaticCollections.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GoodUsageOfStaticCollections.java new file mode 100644 index 0000000..ebe2f8b --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GoodUsageOfStaticCollections.java @@ -0,0 +1,17 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.*; + +/** + * Compliant + */ +public class GoodUsageOfStaticCollections { + public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections(); + + public final List LIST = new ArrayList(); // Compliant + public final Set SET = new HashSet(); // Compliant + public final Map MAP = new HashMap(); // Compliant + + private GoodUsageOfStaticCollections() { + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GoodWayConcatenateStringsLoop.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GoodWayConcatenateStringsLoop.java new file mode 100644 index 0000000..605a67c --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/GoodWayConcatenateStringsLoop.java @@ -0,0 +1,33 @@ +package org.greencodeinitiative.creedengo.java.checks; + +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/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java new file mode 100644 index 0000000..fc513b9 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java @@ -0,0 +1,48 @@ +package org.greencodeinitiative.creedengo.java.checks; + +class IncrementCheck { + IncrementCheck(IncrementCheck 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); + } + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSize.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSize.java new file mode 100644 index 0000000..8cc73e2 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSize.java @@ -0,0 +1,26 @@ +package org.greencodeinitiative.creedengo.java.checks; + +class InitializeBufferWithAppropriateSize { + InitializeBufferWithAppropriateSize(InitializeBufferWithAppropriateSize mc) { + } + + public void testBufferCompliant() { + StringBuffer stringBuffer = new StringBuffer(16); + } + + public void testBufferCompliant2() { + StringBuffer stringBuffer = new StringBuffer(Integer.valueOf(16)); + } + + public void testBufferNonCompliant() { + StringBuffer stringBuffer = new StringBuffer(); // Noncompliant {{Initialize StringBuilder or StringBuffer with appropriate size}} + } + + public void testBuilderCompliant() { + StringBuilder stringBuilder = new StringBuilder(16); + } + + public void testBuilderNonCompliant() { + StringBuilder stringBuilder = new StringBuilder(); // Noncompliant {{Initialize StringBuilder or StringBuffer with appropriate size}} + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java new file mode 100644 index 0000000..bef640d --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java @@ -0,0 +1,69 @@ +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 + + public MakeNonReassignedVariablesConstants() { + varDefinedInConstructorReassigned = "3"; + logger.info(varDefinedInConstructorReassigned); + } + + 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()); + } + +} \ 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/NoFunctionCallWhenDeclaringForLoop.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java new file mode 100644 index 0000000..4232607 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -0,0 +1,119 @@ +package org.greencodeinitiative.creedengo.java.integration.tests;/* + * 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 . + */ +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Arrays; +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 OtherClassWithIterator otherClass = new OtherClassWithIterator(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 OtherClassWithIterator otherClass = new OtherClassWithIterator(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); + } + + } + +} + +class OtherClassWithIterator { + public final Iterator iterator; + + public OtherClassWithIterator(Iterator iterator){ + this.iterator = iterator; + } + + public Iterator getIterator(){ + return iterator; + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck.java new file mode 100644 index 0000000..91520bd --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck.java @@ -0,0 +1,29 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +import static java.lang.System.Logger.Level.ERROR; + +class OptimizeReadFileExceptionCheck { + + Logger logger = Logger.getLogger(""); + + OptimizeReadFileExceptionCheck(OptimizeReadFileExceptionCheck readFile) { + } + + public void readPreferences(String filename) { + //... + InputStream in = null; + try { + in = new FileInputStream(filename); // Noncompliant {{Optimize Read File Exceptions}} + } catch (FileNotFoundException e) { + logger.info(e.getMessage()); + } + //... + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck2.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck2.java new file mode 100644 index 0000000..205b814 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck2.java @@ -0,0 +1,27 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +class OptimizeReadFileExceptionCheck2 { + + Logger logger = Logger.getLogger(""); + + OptimizeReadFileExceptionCheck2(OptimizeReadFileExceptionCheck2 readFile) { + } + + public void readPreferences(String filename) throws IOException { + //... + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} + logger.info("my log"); + } catch (FileNotFoundException e) { + logger.info(e.getMessage()); + } + //... + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck3.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck3.java new file mode 100644 index 0000000..a26b6ea --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck3.java @@ -0,0 +1,26 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +class OptimizeReadFileExceptionCheck3 { + + Logger logger = Logger.getLogger(""); + + OptimizeReadFileExceptionCheck3(OptimizeReadFileExceptionCheck3 readFile) { + } + + public void readPreferences(String filename) { + //... + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} + logger.info("my log"); + } catch (IOException e) { + logger.info(e.getMessage()); + } + //... + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck4.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck4.java new file mode 100644 index 0000000..80a75d9 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck4.java @@ -0,0 +1,25 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +class OptimizeReadFileExceptionCheck4 { + + Logger logger = Logger.getLogger(""); + + OptimizeReadFileExceptionCheck4(OptimizeReadFileExceptionCheck4 readFile) { + } + + public void readPreferences(String filename) { + //... + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} + logger.info("my log"); + } catch (Exception e) { + logger.info(e.getMessage()); + } + //... + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck5.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck5.java new file mode 100644 index 0000000..2115bef --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheck5.java @@ -0,0 +1,25 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +class OptimizeReadFileExceptionCheck5 { + + Logger logger = Logger.getLogger(""); + + OptimizeReadFileExceptionCheck5(OptimizeReadFileExceptionCheck5 readFile) { + } + + public void readPreferences(String filename) { + //... + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} + logger.info("my log"); + } catch (Throwable e) { + logger.info(e.getMessage()); + } + //... + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeSQLQueriesWithLimit.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeSQLQueriesWithLimit.java new file mode 100644 index 0000000..e592528 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/OptimizeSQLQueriesWithLimit.java @@ -0,0 +1,32 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import org.springframework.data.jpa.repository.Query; + +import java.util.ArrayList; +import java.util.List; + +class OptimizeSQLQueriesWithLimit { + + public void literalSQLrequest() { + dummyCall("SELECT user FROM myTable"); // Noncompliant {{Optimize Database SQL Queries (Clause LIMIT)}} + dummyCall("SELECT user FROM myTable LIMIT 50"); // Compliant + } + + @Query("select t from Todo t where t.status != 'COMPLETED'") // Noncompliant {{Optimize Database SQL Queries (Clause LIMIT)}} + public List findAllUsers() { + return new ArrayList<>(); + } + + @Query("select t from Todo t where t.status != 'COMPLETED' LIMIT 25") // Compliant + public List findFirstUsers() { + return new ArrayList<>(); + } + + private void callQuery() { + String sql1 = "SELECT user FROM myTable"; // Noncompliant {{Optimize Database SQL Queries (Clause LIMIT)}} + String sql2 = "SELECT user FROM myTable LIMIT 50"; // Compliant + } + + private void dummyCall(String request) { + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java new file mode 100644 index 0000000..20a0dec --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java @@ -0,0 +1,35 @@ +/* + * 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 . + */ + +import java.util.Optional; + +class UseOptionalOrElseGetVsOrElse { + + 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 NAME2 = Optional.of("creedengo").orElseGet(() -> getUnpredictedMethod()); // Compliant + + public static final String NAME3 = variable.orElse(getUnpredictedMethod()); // Compliant + + private static String getUnpredictedMethod() { + return "unpredicted"; + } + +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern.java new file mode 100644 index 0000000..9943c20 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern.java @@ -0,0 +1,12 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.regex.Pattern; + +public class ValidRegexPattern { + + private static final Pattern pattern = Pattern.compile("foo"); // Compliant + + public boolean foo() { + return pattern.matcher("foo").find(); + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern2.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern2.java new file mode 100644 index 0000000..3ceb82a --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern2.java @@ -0,0 +1,12 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.regex.Pattern; + +public class ValidRegexPattern2 { + + private final Pattern pattern = Pattern.compile("foo"); // Compliant + + public boolean foo() { + return pattern.matcher("foo").find(); + } +} diff --git a/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern3.java b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern3.java new file mode 100644 index 0000000..a9b64c2 --- /dev/null +++ b/src/it/test-projects/creedengo-java-plugin-test-project/src/main/java/org/greencodeinitiative/creedengo/java/checks/ValidRegexPattern3.java @@ -0,0 +1,16 @@ +package org.greencodeinitiative.creedengo.java.checks; + +import java.util.regex.Pattern; + +public class ValidRegexPattern3 { + + private final Pattern pattern; + + public ValidRegexPattern3() { + pattern = Pattern.compile("foo"); // Compliant + } + + public boolean foo() { + return pattern.matcher("foo").find(); + } +} 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 0000000..c3309ab --- /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/JavaCheckRegistrar.java b/src/main/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrar.java similarity index 65% rename from src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java rename to src/main/java/org/greencodeinitiative/creedengo/java/JavaCheckRegistrar.java index f4ef343..521f5b8 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,26 +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.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.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 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; @@ -47,7 +33,7 @@ */ @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, AvoidUsageOfStaticCollections.class, @@ -62,7 +48,10 @@ public class JavaCheckRegistrar implements CheckRegistrar { InitializeBufferWithAppropriateSize.class, AvoidSetConstantInBatchUpdate.class, FreeResourcesOfAutoCloseableInterface.class, - AvoidMultipleIfElseStatement.class + AvoidMultipleIfElseStatement.class, + UseOptionalOrElseGetVsOrElse.class, + MakeNonReassignedVariablesConstants.class, + LimitDbQueryResult.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 0000000..3d48034 --- /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 ff070c1..ce2a95c 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 958edc8..ff30929 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 b594af9..bc4d569 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 88ff715..e2c7fb6 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 c81d795..53f2e08 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 97% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatement.java index 4dc77ba..7343979 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 { 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 2561a6c..beb1cea 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 1e3aab8..0e830dc 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 87% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchUpdate.java index 4fe31ab..20c3e23 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,7 +39,8 @@ 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 { 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 3222799..a71777c 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 592f92c..cb335e0 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 18a7fb7..8017381 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/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java similarity index 90% rename from src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.java index 47cbc2e..2b66914 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterface.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; @@ -35,7 +35,8 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC79") +@Rule(key = "GCI79") +@DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC79") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S79") public class FreeResourcesOfAutoCloseableInterface extends IssuableSubscriptionVisitor { private final Deque withinTry = new LinkedList<>(); 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 81% rename from src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheck.java index 00c3094..d5a2a42 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,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; @@ -26,7 +26,8 @@ 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 { 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 44caa87..7bcb3b7 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/LimitDbQueryResult.java b/src/main/java/org/greencodeinitiative/creedengo/java/checks/LimitDbQueryResult.java new file mode 100644 index 0000000..1059576 --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/LimitDbQueryResult.java @@ -0,0 +1,49 @@ +/* + * 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.LiteralTree; +import org.sonar.plugins.java.api.tree.Tree; + +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +@Rule(key = "GCI24") +public class LimitDbQueryResult extends IssuableSubscriptionVisitor { + + protected static final String MESSAGE_RULE = "Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)"; + + private static final Pattern PATTERN = Pattern.compile("(LIMIT|TOP|ROW_NUMBER|FETCH FIRST|WHERE)", Pattern.CASE_INSENSITIVE); + + @Override + public List nodesToVisit() { + return Collections.singletonList(Tree.Kind.STRING_LITERAL); + } + + @Override + public void visitNode(Tree tree) { + String value = ((LiteralTree) tree).value().toUpperCase(); + if (value.contains("SELECT") && value.contains("FROM") && !PATTERN.matcher(value).find()) { + reportIssue(tree, MESSAGE_RULE); + } + } + +} 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 0000000..6533256 --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstants.java @@ -0,0 +1,127 @@ +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.tree.*; +import org.sonar.plugins.java.api.tree.Tree.Kind; + +import javax.annotation.Nonnull; +import java.util.List; + +@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); + + @Override + public List nodesToVisit() { + return List.of(Kind.VARIABLE); + } + + @Override + public void visitNode(@Nonnull Tree tree) { + VariableTree variableTree = (VariableTree) tree; + LOGGER.debug("Variable > " + getVariableNameForLogger(variableTree)); + LOGGER.debug(" => isNotFinalAndNotStatic(variableTree) = " + isNotFinalAndNotStatic(variableTree)); + LOGGER.debug(" => usages = " + variableTree.symbol().usages().size()); + LOGGER.debug(" => isNotReassigned = " + isNotReassigned(variableTree)); + + if (isNotFinalAndNotStatic(variableTree) && isNotReassigned(variableTree)) { + reportIssue(tree, MESSAGE_RULE); + } else { + super.visitNode(tree); + } + } + + private static boolean isNotReassigned(VariableTree variableTree) { + return variableTree.symbol() + .usages() + .stream() + .noneMatch(MakeNonReassignedVariablesConstants::parentIsAssignment); + } + + private static boolean parentIsAssignment(Tree tree) { + 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 static boolean isNotFinalAndNotStatic(VariableTree variableTree) { + return hasNoneOf(variableTree.modifiers(), Modifier.FINAL, Modifier.STATIC); + } + + 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; + + } + +} 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 85% rename from src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java rename to src/main/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoop.java index d4088bd..b364b55 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; @@ -37,7 +37,8 @@ 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 { @@ -58,23 +59,30 @@ 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) && !isIteratorMethod(tree)) { report(tree); return; } super.visitMethodInvocation(tree); } + private boolean isIteratorMethod(MethodInvocationTree tree) { + boolean isIterator = tree.methodSymbol().owner().type().isSubtypeOf("java.util.Iterator"); + String methodName = tree.methodSelect().lastToken().text(); + boolean isMethodNext = methodName.equals("next"); + boolean isMethodHasNext = methodName.equals("hasNext"); + return isIterator && (isMethodNext || isMethodHasNext); + } + 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 2362404..76a74b2 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 0000000..ec971a6 --- /dev/null +++ b/src/main/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElse.java @@ -0,0 +1,59 @@ +/* + * 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.Tree; +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +@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) && + Objects.requireNonNull(tree.methodSelect().firstToken()).text().equals("Optional")) { + MemberSelectExpressionTree memberSelect = (MemberSelectExpressionTree) tree.methodSelect(); + if (memberSelect.identifier().name().equals("orElse")) { + reportIssue(memberSelect, MESSAGE_RULE); + } + } + } + } +} 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 db01a76..1ef973a 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 2b709d7..fa24589 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 b9b81c5..ce66a88 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 0000000..681074f --- /dev/null +++ b/src/main/resources/org/greencodeinitiative/creedengo/java/creedengo_way_profile.json @@ -0,0 +1,24 @@ +{ + "name": "creedengo way", + "language": "java", + "ruleKeys": [ + "GCI1", + "GCI2", + "GCI3", + "GCI5", + "GCI24", + "GCI27", + "GCI28", + "GCI32", + "GCI67", + "GCI69", + "GCI72", + "GCI74", + "GCI76", + "GCI77", + "GCI78", + "GCI79", + "GCI82", + "GCI94" + ] +} diff --git a/src/test/files/ArrayCopyCheck.java b/src/test/files/ArrayCopyCheck.java index 09c780e..79d8353 100644 --- a/src/test/files/ArrayCopyCheck.java +++ b/src/test/files/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 @@ -507,4 +507,4 @@ private boolean transform(boolean a) { return !a; } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidFullSQLRequestCheck.java b/src/test/files/AvoidFullSQLRequestCheck.java index b388252..2d6b2e6 100644 --- a/src/test/files/AvoidFullSQLRequestCheck.java +++ b/src/test/files/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/AvoidGettingSizeCollectionInForEachLoopIgnored.java b/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java index 46963cd..ce4eeac 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java +++ b/src/test/files/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/test/files/AvoidGettingSizeCollectionInForLoopBad.java b/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java index 3c74c86..b437655 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java +++ b/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java @@ -1,38 +1,17 @@ -/* - * 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; +package org.greencodeinitiative.creedengo.java.checks; -import java.util.Collection; import java.util.ArrayList; import java.util.List; class AvoidGettingSizeCollectionInForLoopBad { - AvoidGettingSizeCollectionInForLoopBad() { - - } public void badForLoop() { - List numberList = new ArrayList(); + 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}} + 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/AvoidGettingSizeCollectionInForLoopGood.java b/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java index 5f2bcd2..691bc33 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java +++ b/src/test/files/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; @@ -37,4 +37,4 @@ public void goodForLoop() { int size = numberList.size(); // Compliant with this rule } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java b/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java index 544e08e..c1fa56c 100644 --- a/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java +++ b/src/test/files/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,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.Collection; import java.util.ArrayList; import java.util.List; -class AvoidGettingSizeCollectionInForLoopBad { +class GCI69AvoidGettingSizeCollectionInForLoopBad { AvoidGettingSizeCollectionInForLoopBad() { } 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/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java index f47570c..def86d2 100644 --- a/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java +++ b/src/test/files/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; @@ -37,4 +37,4 @@ public void badWhileLoop() { i++; } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java b/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java index 5766868..713998d 100644 --- a/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java +++ b/src/test/files/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/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java index 10c752f..9900958 100644 --- a/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java +++ b/src/test/files/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,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; @@ -38,4 +38,4 @@ public void badWhileLoop() { System.out.println("numberList.size()"); } } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidMultipleIfElseStatement.java b/src/test/files/AvoidMultipleIfElseStatement.java index 435218f..52bc42a 100644 --- a/src/test/files/AvoidMultipleIfElseStatement.java +++ b/src/test/files/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/test/files/AvoidMultipleIfElseStatementCompareMethod.java b/src/test/files/AvoidMultipleIfElseStatementCompareMethod.java index 7c52751..fdf00d6 100644 --- a/src/test/files/AvoidMultipleIfElseStatementCompareMethod.java +++ b/src/test/files/AvoidMultipleIfElseStatementCompareMethod.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 AvoidMultipleIfElseStatementCompareMethod { @@ -51,4 +51,4 @@ public int compare(FieldVo o1, FieldVo o2) { return o1.getIdBlock().compareTo(o2.getIdBlock()); } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidMultipleIfElseStatementInterface.java b/src/test/files/AvoidMultipleIfElseStatementInterface.java index 43dd875..c9c7604 100644 --- a/src/test/files/AvoidMultipleIfElseStatementInterface.java +++ b/src/test/files/AvoidMultipleIfElseStatementInterface.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; interface AvoidMultipleIfElseStatementCheck { diff --git a/src/test/files/AvoidMultipleIfElseStatementNoIssue.java b/src/test/files/AvoidMultipleIfElseStatementNoIssue.java index 32f4716..53e72dd 100644 --- a/src/test/files/AvoidMultipleIfElseStatementNoIssue.java +++ b/src/test/files/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/test/files/AvoidMultipleIfElseStatementNotBlock.java index 3e8f613..46a5691 100644 --- a/src/test/files/AvoidMultipleIfElseStatementNotBlock.java +++ b/src/test/files/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,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 AvoidMultipleIfElseStatementNotBlock { @@ -24,4 +24,4 @@ public boolean equals(Object obj) { return true; } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidRegexPatternNotStatic.java b/src/test/files/AvoidRegexPatternNotStatic.java index b5e19c6..7638763 100644 --- a/src/test/files/AvoidRegexPatternNotStatic.java +++ b/src/test/files/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/AvoidSQLRequestInLoopCheck.java b/src/test/files/AvoidSQLRequestInLoopCheck.java index 753a717..f75e0c9 100644 --- a/src/test/files/AvoidSQLRequestInLoopCheck.java +++ b/src/test/files/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/AvoidSetConstantInBatchUpdateCheck.java b/src/test/files/AvoidSetConstantInBatchUpdateCheck.java index 03f5e86..6e4ecf4 100644 --- a/src/test/files/AvoidSetConstantInBatchUpdateCheck.java +++ b/src/test/files/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,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.math.BigDecimal; import java.sql.PreparedStatement; @@ -164,4 +164,4 @@ public double getField4() { } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java b/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java index a18b484..3d38690 100644 --- a/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java +++ b/src/test/files/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/test/files/AvoidSpringRepositoryCallInStreamCheck.java index 35dc70c..6acf592 100644 --- a/src/test/files/AvoidSpringRepositoryCallInStreamCheck.java +++ b/src/test/files/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; @@ -136,4 +136,4 @@ public Employee(Integer id, String name) { public interface EmployeeRepository extends JpaRepository { } -} \ No newline at end of file +} diff --git a/src/test/files/AvoidStatementForDMLQueries.java b/src/test/files/AvoidStatementForDMLQueries.java index 5059b09..a056dbb 100644 --- a/src/test/files/AvoidStatementForDMLQueries.java +++ b/src/test/files/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; @@ -31,4 +31,4 @@ public void insert() { 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/test/files/AvoidUsageOfStaticCollections.java b/src/test/files/AvoidUsageOfStaticCollections.java index 3530997..f14de6a 100644 --- a/src/test/files/AvoidUsageOfStaticCollections.java +++ b/src/test/files/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.*; diff --git a/src/test/files/FreeResourcesOfAutoCloseableInterface.java b/src/test/files/FreeResourcesOfAutoCloseableInterface.java index e1eaab5..08ba162 100644 --- a/src/test/files/FreeResourcesOfAutoCloseableInterface.java +++ b/src/test/files/FreeResourcesOfAutoCloseableInterface.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.io.*; @@ -43,11 +43,11 @@ public void foo2() { System.err.println(e.getMessage()); } finally { if (fr) { - fr.close(); + org.close(); } if (br) { br.close(); } } } -} \ No newline at end of file +} diff --git a/src/test/files/GoodUsageOfStaticCollections.java b/src/test/files/GoodUsageOfStaticCollections.java index 6d2d3c2..9da5eae 100644 --- a/src/test/files/GoodUsageOfStaticCollections.java +++ b/src/test/files/GoodUsageOfStaticCollections.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.*; diff --git a/src/test/files/GoodWayConcatenateStringsLoop.java b/src/test/files/GoodWayConcatenateStringsLoop.java index c11c1ab..a082875 100644 --- a/src/test/files/GoodWayConcatenateStringsLoop.java +++ b/src/test/files/GoodWayConcatenateStringsLoop.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 class GoodWayConcatenateStringsLoop { diff --git a/src/test/files/IncrementCheck.java b/src/test/files/IncrementCheck.java index 54b20bf..d3c7755 100644 --- a/src/test/files/IncrementCheck.java +++ b/src/test/files/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 @@ -60,4 +60,4 @@ void foo51(int value) { System.out.println(i); } } -} \ No newline at end of file +} diff --git a/src/test/files/InitializeBufferWithAppropriateSize.java b/src/test/files/InitializeBufferWithAppropriateSize.java index b5852a1..a83c21e 100644 --- a/src/test/files/InitializeBufferWithAppropriateSize.java +++ b/src/test/files/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/LimitDbQueryResult.java b/src/test/files/LimitDbQueryResult.java new file mode 100644 index 0000000..d3415e7 --- /dev/null +++ b/src/test/files/LimitDbQueryResult.java @@ -0,0 +1,84 @@ +/* + * 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 . + */ +class LimitDbQueryResult { + + public void callLiteralSQLString() { + dummyCall("SELECT user FROM myTable"); // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + dummyCall("SELECT user " + " FROM myTable"); // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + dummyCall("SELECT user FROM myTable LIMIT 50"); // Compliant + dummyCall("SELECT user FROM myTable WHERE user.name = 'titi'"); // Compliant + } + + private void buildAndCallQuery() { + String sql1 = "SELECT user FROM myTable"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + String sql2 = "SELECT user FROM myTable LIMIT 50"; // Compliant + String sql3 = "SELECT user FROM myTable WHERE user.name = 'titi'"; // Compliant + String sql4 = "SELECT user"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + sql4 += "FROM myTable"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + + dummyCall(sql1); + dummyCall(sql2); + dummyCall(sql3); + dummyCall(sql4); + } + + private void callQueryWithReturn() { + String sql1 = "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + dumyCall(""); + return sql1; + } + + private void callQueryWithReturn() { + String sql1 = "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + return sql1; + } + + private void callQueryWithReturn2() { + return "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + } + + private void callQueryWithReturn3() { + String sql2 = "SELECT user"; // Compliant (more exactly, not controlled and not issued because string returned) + sql2 += "FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + return sql2; + } + + private void callQueryWithInput(String sqlInit) { + String sql1 = "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because input string used) + sql1 += sqlInit; + dummyCall(sql1); + } + + private void buildAndCallQueryCompliant() + { + String sql4 = "SELECT user"; // Compliant because of coming next + sql4 += " FROM myTable"; // Compliant because of coming next + sql4 += " LIMIT 10"; // Compliant) + dummyCall(sql4); + } + + private void buildAndCallQueryNonCompliant() + { + String sql4 = "SELECT user"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + sql4 += " FROM myTable"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + dummyCall(sql4); + } + + private void dummyCall(String request) { + } +} \ No newline at end of file diff --git a/src/test/files/LimitDbQueryResultFINALRESULT.java b/src/test/files/LimitDbQueryResultFINALRESULT.java new file mode 100644 index 0000000..f3e8da2 --- /dev/null +++ b/src/test/files/LimitDbQueryResultFINALRESULT.java @@ -0,0 +1,85 @@ +/* + * 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 . + */ +// TODO DDC : class to delete because is only the final class with all tests to be OK +class LimitDbQueryResult { + + public void callLiteralSQLString() { + dummyCall("SELECT user FROM myTable"); // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + dummyCall("SELECT user " + " FROM myTable"); // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + dummyCall("SELECT user FROM myTable LIMIT 50"); // Compliant + dummyCall("SELECT user FROM myTable WHERE user.name = 'titi'"); // Compliant + } + + private void buildAndCallQuery() { + String sql1 = "SELECT user FROM myTable"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + String sql2 = "SELECT user FROM myTable LIMIT 50"; // Compliant + String sql3 = "SELECT user FROM myTable WHERE user.name = 'titi'"; // Compliant + String sql4 = "SELECT user"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + sql4 += "FROM myTable"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + + dummyCall(sql1); + dummyCall(sql2); + dummyCall(sql3); + dummyCall(sql4); + } + + private void callQueryWithReturn() { + String sql1 = "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + dumyCall(""); + return sql1; + } + + private void callQueryWithReturn() { + String sql1 = "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + return sql1; + } + + private void callQueryWithReturn2() { + return "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + } + + private void callQueryWithReturn3() { + String sql2 = "SELECT user"; // Compliant (more exactly, not controlled and not issued because string returned) + sql2 += "FROM myTable"; // Compliant (more exactly, not controlled and not issued because string returned) + return sql2; + } + + private void callQueryWithInput(String sqlInit) { + String sql1 = "SELECT user FROM myTable"; // Compliant (more exactly, not controlled and not issued because input string used) + sql1 += sqlInit; + dummyCall(sql1); + } + + private void buildAndCallQueryCompliant() + { + String sql4 = "SELECT user"; // Compliant because of coming next + sql4 += " FROM myTable"; // Compliant because of coming next + sql4 += " LIMIT 10"; // Compliant) + dummyCall(sql4); + } + + private void buildAndCallQueryNonCompliant() + { + String sql4 = "SELECT user"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + sql4 += " FROM myTable"; // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + dummyCall(sql4); + } + + private void dummyCall(String request) { + } +} \ No newline at end of file diff --git a/src/test/files/LimitDbQueryResultInterface.java b/src/test/files/LimitDbQueryResultInterface.java new file mode 100644 index 0000000..b8aa01f --- /dev/null +++ b/src/test/files/LimitDbQueryResultInterface.java @@ -0,0 +1,29 @@ +/* + * 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 . + */ +interface LimitDbQueryResultInterface { + + @Query("select t from Todo t") // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + List getTodo(); + + @Query("select t from Todo t where t.status != 'COMPLETED'") // Compliant + List getTodoNotCompleted(); + + @Query("select t from Todo t where t.status != 'COMPLETED' LIMIT 25") // Compliant + List getTodoNotCompletedLimit25(); + +} \ No newline at end of file diff --git a/src/test/files/LimitDbQueryResultInterfaceFINALRESULT.java b/src/test/files/LimitDbQueryResultInterfaceFINALRESULT.java new file mode 100644 index 0000000..a4f382b --- /dev/null +++ b/src/test/files/LimitDbQueryResultInterfaceFINALRESULT.java @@ -0,0 +1,33 @@ +/* + * 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 . + */ +// TODO DDC : class to delete because is only the final class with all tests to be OK +interface LimitDbQueryResultInterface { + + @Query("select t from Todo t") // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + List getTodo(); + + @Query("select t " + "from Todo t") // Noncompliant {{Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)}} + List getTodo2(); + + @Query("select t from Todo t where t.status != 'COMPLETED'") // Compliant + List getTodoNotCompleted(); + + @Query("select t from Todo t where t.status != 'COMPLETED' LIMIT 25") // Compliant + List getTodoNotCompletedLimit25(); + +} \ No newline at end of file diff --git a/src/test/files/MakeNonReassignedVariablesConstants.java b/src/test/files/MakeNonReassignedVariablesConstants.java new file mode 100644 index 0000000..bef640d --- /dev/null +++ b/src/test/files/MakeNonReassignedVariablesConstants.java @@ -0,0 +1,69 @@ +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 + + public MakeNonReassignedVariablesConstants() { + varDefinedInConstructorReassigned = "3"; + logger.info(varDefinedInConstructorReassigned); + } + + 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()); + } + +} \ No newline at end of file diff --git a/src/test/files/NoFunctionCallWhenDeclaringForLoop.java b/src/test/files/NoFunctionCallWhenDeclaringForLoop.java index da72a3e..4232607 100644 --- a/src/test/files/NoFunctionCallWhenDeclaringForLoop.java +++ b/src/test/files/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) +package org.greencodeinitiative.creedengo.java.integration.tests;/* + * 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,59 +15,105 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Arrays; class NoFunctionCallWhenDeclaringForLoop { - NoFunctionCallWhenDeclaringForLoop(NoFunctionCallWhenDeclaringForLoop mc) { - } public int getMyValue() { return 6; } - public int incrementeMyValue(int i) { + public int incrementeMyValue(final int i) { return i + 100; } public void test1() { - for (int i = 0; i < 20; i++) { + for (int i = 0; i < 20; ++i) { System.out.println(i); - boolean b = getMyValue() > 6; + final boolean b = getMyValue() > 6; + System.out.println(b); } } public void test2() { - String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; - for (String i : cars) { + 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++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + for (int i = getMyValue(); i < 20; ++i) { System.out.println(i); - boolean b = getMyValue() > 6; + 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}} + 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; + final boolean b = getMyValue() > 6; + System.out.println(b); } } public void test5() { - for (int i = 0; i < getMyValue(); incrementeMyValue(i)) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + 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); - boolean b = getMyValue() > 6; + 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}} + 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; + 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 OtherClassWithIterator otherClass = new OtherClassWithIterator(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 OtherClassWithIterator otherClass = new OtherClassWithIterator(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); } + + } + +} + +class OtherClassWithIterator { + public final Iterator iterator; + + public OtherClassWithIterator(Iterator iterator){ + this.iterator = iterator; } -} \ No newline at end of file + public Iterator getIterator(){ + return iterator; + } +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck.java b/src/test/files/OptimizeReadFileExceptionCheck.java index e9fd260..2bafe97 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck.java +++ b/src/test/files/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,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,4 +34,4 @@ public void readPreferences(String filename) { } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck2.java b/src/test/files/OptimizeReadFileExceptionCheck2.java index 689dc18..4d1e761 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck2.java +++ b/src/test/files/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,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; @@ -33,4 +33,4 @@ public void readPreferences(String filename) { } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck3.java b/src/test/files/OptimizeReadFileExceptionCheck3.java index 92dc150..7b9292f 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck3.java +++ b/src/test/files/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,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; @@ -33,4 +33,4 @@ public void readPreferences(String filename) { } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck4.java b/src/test/files/OptimizeReadFileExceptionCheck4.java index 5914e0f..5096450 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck4.java +++ b/src/test/files/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,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; @@ -33,4 +33,4 @@ public void readPreferences(String filename) { } //... } -} \ No newline at end of file +} diff --git a/src/test/files/OptimizeReadFileExceptionCheck5.java b/src/test/files/OptimizeReadFileExceptionCheck5.java index 6d8b553..8754e26 100644 --- a/src/test/files/OptimizeReadFileExceptionCheck5.java +++ b/src/test/files/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,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; @@ -33,4 +33,4 @@ public void readPreferences(String filename) { } //... } -} \ No newline at end of file +} diff --git a/src/test/files/UseOptionalOrElseGetVsOrElse.java b/src/test/files/UseOptionalOrElseGetVsOrElse.java new file mode 100644 index 0000000..20a0dec --- /dev/null +++ b/src/test/files/UseOptionalOrElseGetVsOrElse.java @@ -0,0 +1,35 @@ +/* + * 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 . + */ + +import java.util.Optional; + +class UseOptionalOrElseGetVsOrElse { + + 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 NAME2 = Optional.of("creedengo").orElseGet(() -> getUnpredictedMethod()); // Compliant + + public static final String NAME3 = variable.orElse(getUnpredictedMethod()); // Compliant + + private static String getUnpredictedMethod() { + return "unpredicted"; + } + +} diff --git a/src/test/files/ValidRegexPattern.java b/src/test/files/ValidRegexPattern.java index aacb701..c52eb0e 100644 --- a/src/test/files/ValidRegexPattern.java +++ b/src/test/files/ValidRegexPattern.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/ValidRegexPattern2.java b/src/test/files/ValidRegexPattern2.java index a674b9b..4c2c0e0 100644 --- a/src/test/files/ValidRegexPattern2.java +++ b/src/test/files/ValidRegexPattern2.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/ValidRegexPattern3.java b/src/test/files/ValidRegexPattern3.java index 0867693..8cf4166 100644 --- a/src/test/files/ValidRegexPattern3.java +++ b/src/test/files/ValidRegexPattern3.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/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 02270ca..89541a5 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(15); + 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 0000000..7db8134 --- /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 0f2167d..b54f59b 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 81% rename from src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/JavaRulesDefinitionTest.java index ad1b536..d0f53da 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,6 +28,7 @@ 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.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -36,8 +37,6 @@ class JavaRulesDefinitionTest { private RulesDefinition.Repository repository; - private int rulesSize; - @BeforeEach void init() { final SonarRuntime sonarRuntime = mock(SonarRuntime.class); @@ -46,36 +45,34 @@ void init() { RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); repository = context.repository(rulesDefinition.repositoryKey()); - rulesSize = 15; } @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(rulesSize); + assertThat(repository.key()).isEqualTo("creedengo-java"); } @Test void testRegistredRules() { - assertThat(repository.rules()).hasSize(rulesSize); + 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/ArrayCopyCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheckTest.java similarity index 80% rename from src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/ArrayCopyCheckTest.java index 5f0b127..49deaa1 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -33,4 +33,4 @@ void test() { .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/AvoidFullSQLRequestCheckTest.java similarity index 80% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidFullSQLRequestCheckTest.java index 25ead7c..889721b 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -30,4 +30,4 @@ void test() { .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInLoopTest.java similarity index 91% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidGettingSizeCollectionInLoopTest.java index c957692..4d4b3fd 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementTest.java similarity index 89% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidMultipleIfElseStatementTest.java index 2cf8869..f63326e 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStaticTest.java similarity index 85% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidRegexPatternNotStaticTest.java index 1750232..874b03b 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoopCheckTest.java similarity index 80% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSQLRequestInLoopCheckTest.java index 5abed41..bd64a6a 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -30,4 +30,4 @@ void test() { .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchInsertTest.java similarity index 81% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSetConstantInBatchInsertTest.java index 8c138fd..9dffe6f 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -30,4 +30,4 @@ void test() { .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java similarity index 78% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java index 2a855e0..8041f0a 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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; -import fr.greencodeinitiative.java.utils.FilesUtils; +import org.greencodeinitiative.creedengo.java.utils.FilesUtils; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java similarity index 78% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java index e9fd4f3..1be55d7 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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; -import fr.greencodeinitiative.java.utils.FilesUtils; +import org.greencodeinitiative.creedengo.java.utils.FilesUtils; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueriesTest.java similarity index 80% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidStatementForDMLQueriesTest.java index b74683e..3caac84 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollectionsTests.java similarity index 84% rename from src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/AvoidUsageOfStaticCollectionsTests.java index 2ac4ed3..876525f 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java similarity index 84% rename from src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java index 9a9ca49..aecce2d 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -38,4 +38,4 @@ void test_no_java_version() { .withCheck(new FreeResourcesOfAutoCloseableInterface()) .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheckTest.java similarity index 80% rename from src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/IncrementCheckTest.java index e9d5b98..d11de84 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -30,4 +30,4 @@ void test() { .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSizeTest.java similarity index 81% rename from src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/InitializeBufferWithAppropriateSizeTest.java index deef83e..0261b8f 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; @@ -30,4 +30,4 @@ void test() { .verifyIssues(); } -} \ No newline at end of file +} diff --git a/src/test/java/org/greencodeinitiative/creedengo/java/checks/LimitDbQueryResultTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/LimitDbQueryResultTest.java new file mode 100644 index 0000000..ea4d1a9 --- /dev/null +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/LimitDbQueryResultTest.java @@ -0,0 +1,42 @@ +/* + * 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.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; + +class LimitDbQueryResultTest { + + // TODO DDC : to be re-enabled to get all use cases +// @Test +// void testClass() { +// CheckVerifier.newVerifier() +// .onFile("src/test/files/LimitDbQueryResult.java") +// .withCheck(new LimitDbQueryResult()) +// .verifyIssues(); +// } + + @Test + void testInterface() { + CheckVerifier.newVerifier() + .onFile("src/test/files/LimitDbQueryResultInterface.java") + .withCheck(new LimitDbQueryResult()) + .verifyIssues(); + } + +} diff --git a/src/test/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstantsTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstantsTest.java new file mode 100644 index 0000000..837a632 --- /dev/null +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/MakeNonReassignedVariablesConstantsTest.java @@ -0,0 +1,33 @@ +/* + * 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.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; + +class MakeNonReassignedVariablesConstantsTest { + + @Test + void test() { + CheckVerifier.newVerifier() + .onFile("src/test/files/MakeNonReassignedVariablesConstants.java") + .withCheck(new MakeNonReassignedVariablesConstants()) + .verifyIssues(); + } + +} diff --git a/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java similarity index 81% rename from src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java index ef3c983..e4dff73 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheckTest.java similarity index 89% rename from src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java rename to src/test/java/org/greencodeinitiative/creedengo/java/checks/OptimizeReadFileExceptionCheckTest.java index b3ef8c8..d3f1def 100644 --- a/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/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,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.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; diff --git a/src/test/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElseTest.java b/src/test/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElseTest.java new file mode 100644 index 0000000..2edc271 --- /dev/null +++ b/src/test/java/org/greencodeinitiative/creedengo/java/checks/UseOptionalOrElseGetVsOrElseTest.java @@ -0,0 +1,31 @@ +/* + * 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.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; + +class UseOptionalOrElseGetVsOrElseTest { + @Test + void test() { + CheckVerifier.newVerifier() + .onFile("src/test/files/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 ed06d4c..d32c90d 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 9e6d932..de5082d 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 bfac031..a5f6a09 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 3d3e0d8..9d4da3c 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 e87b946..7b996e3 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