diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b6e2d7e..bcfbdea 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 @@ -40,12 +40,6 @@ jobs: - name: Verify run: ./mvnw -e -B verify - - name: Set up JDK 17 - uses: actions/setup-java@v3 - with: - distribution: 'temurin' - java-version: 17 - - name: Cache SonarQube packages uses: actions/cache@v3 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bec331..467e711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [#59](https://github.com/green-code-initiative/ecoCode-java/pull/59) Add builtin profile `ecoCode way` to aggregate all implemented ecoCode rules by this plugin +- [#53](https://github.com/green-code-initiative/ecoCode-java/issues/53) Improve integration tests ### Changed diff --git a/README.md b/README.md index a28c058..1af3e3b 100644 --- a/README.md +++ b/README.md @@ -26,34 +26,28 @@ the [ecoCode repository](https://github.com/green-code-initiative/ecoCode#-sonar 🚀 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/ecocode-java-plugin-test-project`](./src/it/test-projects/ecocode-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 `ecocode` 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. + ```sh + ./mvnw verify -Pkeep-running -Dtest-it.additional-plugins=org.sonarsource.javascript:sonar-plugin:10.1.0.21143 + ``` - install different ecocode 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/ecoCode-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/ecoCode-common/blob/main/doc/INSTALL.md#configuration-sonarqube) for more details). 🛒 Distribution ------------------ @@ -63,9 +57,10 @@ Ready to use binaries are available [from GitHub](https://github.com/green-code- 🧩 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 | +| 2.0.+ | 9.9.+ LTS to 10.6.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). diff --git a/pom.xml b/pom.xml index ea5912d..0da8b0b 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-java-plugin 1.6.3-SNAPSHOT - + sonar-plugin ecoCode - Java language @@ -53,8 +53,13 @@ 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,9 +71,22 @@ 1.7 - + 1.6.5 + + https://repo1.maven.org/maven2 + + false + + + ${sonarqube.version} + + + ${sonarjava.version} + + + @@ -88,9 +106,9 @@ - org.sonarsource.sonarqube + org.sonarsource.api.plugin sonar-plugin-api - ${sonarqube.version} + ${sonar.plugin.api.version} provided @@ -142,6 +160,44 @@ 0.10.2 test + + + + org.sonarsource.orchestrator + sonar-orchestrator-junit5 + 4.9.0.1920 + test + + + org.sonarsource.java + test-classpath-reader + 8.5.0.37199 + 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 + @@ -333,8 +389,11 @@
com/mycila/maven/plugin/license/templates/GPL-3.txt
- **/*.java + ${project.basedir}/src/**/*.java + + ${project.basedir}/src/it/test-projects/** +
@@ -348,6 +407,94 @@ + + + + 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.2.5 + + + + 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/fr/greencodeinitiative/java/ecoCode_way_profile.json, + + + + io.ecocode:ecocode-java-plugin-test-project|ecoCode Java Sonar Plugin Test Project|${project.baseUri}/src/it/test-projects/ecocode-java-plugin-test-project/pom.xml, + + + + java|ecoCode way, + + + + + +
+ + + + keep-running + + true + 9000 + + + diff --git a/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java b/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java new file mode 100644 index 0000000..279e141 --- /dev/null +++ b/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java @@ -0,0 +1,448 @@ +package io.ecocode.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 io.ecocode.java.integration.tests.profile.ProfileBackup; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +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; +import static org.sonarqube.ws.Common.RuleType.CODE_SMELL; +import static org.sonarqube.ws.Common.Severity.MINOR; + +class LaunchSonarqubeAndBuildProjectIT { + private static final System.Logger LOGGER = System.getLogger(LaunchSonarqubeAndBuildProjectIT.class.getName()); + + private static OrchestratorExtension orchestrator; + private static List analyzedProjects; + + 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())); + } + + @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(); + } + + 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); + } + + @Test + void test() { + String projectKey = analyzedProjects.get(0).projectKey; + + 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(); + + List issuesForArrayCopyCheck = issuesForFile(projectKey, "src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java"); + + assertThat(issuesForArrayCopyCheck) + .hasSize(1) + .first().satisfies(issue -> { + assertThat(issue.getRule()).isEqualTo("ecocode-java:EC69"); + assertThat(issue.getSeverity()).isEqualTo(MINOR); + assertThat(issue.getLine()).isEqualTo(18); + assertThat(issue.getTextRange().getStartLine()).isEqualTo(18); + assertThat(issue.getTextRange().getEndLine()).isEqualTo(18); + assertThat(issue.getTextRange().getStartOffset()).isEqualTo(15); + assertThat(issue.getTextRange().getEndOffset()).isEqualTo(27); + assertThat(issue.getMessage()).isEqualTo("Do not call a function when declaring a for-type loop"); + assertThat(issue.getDebt()).isEqualTo("5min"); + assertThat(issue.getEffort()).isEqualTo("5min"); + assertThat(issue.getType()).isEqualTo(CODE_SMELL); + }); + } + + @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 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(LaunchSonarqubeAndBuildProjectIT::toPluginLocation) + .collect(Collectors.toSet()); + commaSeparatedValues(System.getProperty("test-it.additional-plugins", "")) + .map(LaunchSonarqubeAndBuildProjectIT::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) + ); + } + + private 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)); + } + } + + private static List issuesForFile(String projectKey, String file) { + return issuesForComponent(projectKey + ":" + file); + } + + private static List issuesForComponent(String componentKey) { + return newWsClient(orchestrator) + .issues() + .search(new SearchRequest().setComponentKeys(Collections.singletonList(componentKey))) + .getIssuesList(); + } + + private static Map getMeasures(String componentKey) { + List metricKeys = List.of( + "alert_status", + "blocker_violations", + "branch_coverage", + "bugs", + "class_complexity", + "classes", + "code_smells", + "cognitive_complexity", + "comment_lines", + "comment_lines_data", + "comment_lines_density", + "complexity", + "complexity_in_classes", + "complexity_in_functions", + "conditions_to_cover", + "confirmed_issues", + "coverage", + "critical_violations", + "development_cost", + "directories", + "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", + "file_complexity_distribution", + "files", + "function_complexity", + "function_complexity_distribution", + "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())); + } + + + private static WsClient newWsClient(Orchestrator orchestrator) { + return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() + .url(orchestrator.getServer().getUrl()) + .build()); + } +} \ No newline at end of file diff --git a/src/it/java/io/ecocode/java/integration/tests/profile/ProfileBackup.java b/src/it/java/io/ecocode/java/integration/tests/profile/ProfileBackup.java new file mode 100644 index 0000000..4b67287 --- /dev/null +++ b/src/it/java/io/ecocode/java/integration/tests/profile/ProfileBackup.java @@ -0,0 +1,163 @@ +package io.ecocode.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": "ecoCode way",
+ *  "language": "java",
+ *  "ruleKeys": [
+ * 	    "EC1",
+ * 	    "EC2"
+ *  ]
+ * }
+ * 
+ *

may produce following XML profile:

+ *
+ * <?xml version='1.0' encoding='UTF-8'?>
+ * <profile>
+ * 	<name>ecoCode way</name>
+ * 	<language>java</language>
+ * 	<rules>
+ * 		<rule>
+ * 			<repositoryKey>ecocode-java</repositoryKey>
+ * 			<key>EC1</key>
+ * 			<type>CODE_SMELL</type>
+ * 			<priority>MINOR</priority>
+ * 			<parameters />
+ * 		</rule>
+ * 		<rule>
+ * 			<repositoryKey>ecocode-java</repositoryKey>
+ * 			<key>EC2</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("io/ecocode/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 = "ecocode-" + 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(); + } +} \ No newline at end of file diff --git a/src/it/java/io/ecocode/java/integration/tests/profile/ProfileMetadata.java b/src/it/java/io/ecocode/java/integration/tests/profile/ProfileMetadata.java new file mode 100644 index 0000000..85b65f4 --- /dev/null +++ b/src/it/java/io/ecocode/java/integration/tests/profile/ProfileMetadata.java @@ -0,0 +1,42 @@ +package io.ecocode.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/io/ecocode/java/integration/tests/profile/RuleMetadata.java b/src/it/java/io/ecocode/java/integration/tests/profile/RuleMetadata.java new file mode 100644 index 0000000..21bd763 --- /dev/null +++ b/src/it/java/io/ecocode/java/integration/tests/profile/RuleMetadata.java @@ -0,0 +1,40 @@ +package io.ecocode.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/ecocode-java-plugin-test-project/pom.xml b/src/it/test-projects/ecocode-java-plugin-test-project/pom.xml new file mode 100644 index 0000000..c059b1f --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + + io.ecocode + ecocode-java-plugin-test-project + 0.0.1-SNAPSHOT + + ecoCode 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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java new file mode 100644 index 0000000..adee2b5 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -0,0 +1,493 @@ +package fr.greencodeinitiative.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; + } + +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java new file mode 100644 index 0000000..45c277e --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java @@ -0,0 +1,30 @@ +package fr.greencodeinitiative.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) { + + } + +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java new file mode 100644 index 0000000..467899d --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java @@ -0,0 +1,21 @@ +package fr.greencodeinitiative.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()"); + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java new file mode 100644 index 0000000..f990526 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java @@ -0,0 +1,20 @@ +package fr.greencodeinitiative.java.checks; + +import java.util.ArrayList; +import java.util.List; + +class AvoidGettingSizeCollectionInForLoopBad { + AvoidGettingSizeCollectionInForLoopBad() { + + } + + public void badForLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + for (int i = 0; i < numberList.size(); i++) { // Noncompliant {{Avoid getting the size of the collection in the loop}} + System.out.println("numberList.size()"); + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java new file mode 100644 index 0000000..fed87f5 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java @@ -0,0 +1,23 @@ +package fr.greencodeinitiative.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 + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java new file mode 100644 index 0000000..d9c4d51 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java @@ -0,0 +1,23 @@ +package fr.greencodeinitiative.java.checks; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +class AvoidGettingSizeCollectionInForLoopIgnored { + AvoidGettingSizeCollectionInForLoopIgnored() { + + } + + public void badForLoop() { + List numberList = new ArrayList(); + numberList.add(10); + numberList.add(20); + + Iterator it = numberList.iterator(); + for (; it.hasNext(); ) { // Ignored => compliant + it.next(); + System.out.println("numberList.size()"); + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java new file mode 100644 index 0000000..9b6fae7 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java @@ -0,0 +1,22 @@ +package fr.greencodeinitiative.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++; + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java new file mode 100644 index 0000000..b88e73a --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java @@ -0,0 +1,24 @@ +package fr.greencodeinitiative.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++; + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java new file mode 100644 index 0000000..62ed1fc --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java @@ -0,0 +1,24 @@ +package fr.greencodeinitiative.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()"); + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java new file mode 100644 index 0000000..329342a --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -0,0 +1,266 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java new file mode 100644 index 0000000..573cdc9 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java @@ -0,0 +1,70 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java new file mode 100644 index 0000000..1409a4e --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java @@ -0,0 +1,24 @@ +/* + * 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; + +interface AvoidMultipleIfElseStatementInterfaceNoIssue { + + Object initMetaData(Object transactionFoundation) throws IllegalAccessException; + +} diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java new file mode 100644 index 0000000..d66bfed --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java @@ -0,0 +1,28 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package fr.greencodeinitiative.java.checks; + +class AvoidMultipleIfElseStatementNoBlockNoIssue { + + public boolean equals(Object obj) { + if (this == obj) + return true; + return false; + } + +} diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java new file mode 100644 index 0000000..f4260da --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -0,0 +1,256 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java new file mode 100644 index 0000000..0474e45 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java @@ -0,0 +1,11 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java new file mode 100644 index 0000000..4981d0b --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java @@ -0,0 +1,134 @@ +package fr.greencodeinitiative.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()); + } + } + +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java new file mode 100644 index 0000000..41bb443 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java @@ -0,0 +1,151 @@ +package fr.greencodeinitiative.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; + } + } + + +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java new file mode 100644 index 0000000..ee93298 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -0,0 +1,57 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package fr.greencodeinitiative.java.checks; + +import org.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 { + + } + +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java new file mode 100644 index 0000000..38fa010 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java @@ -0,0 +1,125 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package fr.greencodeinitiative.java.checks; + +import org.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 { + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java new file mode 100644 index 0000000..87204a6 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java @@ -0,0 +1,20 @@ +package fr.greencodeinitiative.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}} + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java new file mode 100644 index 0000000..ac1b9f0 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java @@ -0,0 +1,19 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java new file mode 100644 index 0000000..06dc191 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java @@ -0,0 +1,38 @@ +package fr.greencodeinitiative.java.checks; + +import java.io.*; + +class FreeResourcesOfAutoCloseableInterface { + FreeResourcesOfAutoCloseableInterface(FreeResourcesOfAutoCloseableInterface mc) { + + } + + public void foo1() { + String fileName = "./FreeResourcesOfAutoCloseableInterface.java"; + try (FileReader fr = new FileReader(fileName); + BufferedReader br = new BufferedReader(fr)) { + } catch (IOException e) { + System.err.println(e.getMessage()); + } + } + + public void foo2() 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(); + } + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java new file mode 100644 index 0000000..8f8e55c --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java @@ -0,0 +1,17 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java new file mode 100644 index 0000000..6f279ed --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java @@ -0,0 +1,33 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java new file mode 100644 index 0000000..a88292b --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -0,0 +1,48 @@ +package fr.greencodeinitiative.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); + } + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java new file mode 100644 index 0000000..a02cc36 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java @@ -0,0 +1,26 @@ +package fr.greencodeinitiative.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}} + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java new file mode 100644 index 0000000..28da0a8 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -0,0 +1,58 @@ +package fr.greencodeinitiative.java.checks; + +class NoFunctionCallWhenDeclaringForLoop { + NoFunctionCallWhenDeclaringForLoop(NoFunctionCallWhenDeclaringForLoop mc) { + } + + public int getMyValue() { + return 6; + } + + public int incrementeMyValue(int i) { + return i + 100; + } + + public void test1() { + for (int i = 0; i < 20; i++) { + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test2() { + String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; + for (String i : cars) { + System.out.println(i); + } + + } + + public void test3() { + for (int i = getMyValue(); i < 20; i++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test4() { + for (int i = 0; i < getMyValue(); i++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test5() { + for (int i = 0; i < getMyValue(); incrementeMyValue(i)) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test6() { + for (int i = getMyValue(); i < getMyValue(); i++) { // Noncompliant {{Do not call a function when declaring a for-type loop}} + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java new file mode 100644 index 0000000..6991122 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java @@ -0,0 +1,29 @@ +package fr.greencodeinitiative.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()); + } + //... + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java new file mode 100644 index 0000000..9b0833d --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java @@ -0,0 +1,27 @@ +package fr.greencodeinitiative.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()); + } + //... + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java new file mode 100644 index 0000000..18c2344 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java @@ -0,0 +1,26 @@ +package fr.greencodeinitiative.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()); + } + //... + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java new file mode 100644 index 0000000..3843580 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java @@ -0,0 +1,25 @@ +package fr.greencodeinitiative.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()); + } + //... + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java new file mode 100644 index 0000000..7a0e84a --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java @@ -0,0 +1,25 @@ +package fr.greencodeinitiative.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()); + } + //... + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java new file mode 100644 index 0000000..c21e2a4 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java @@ -0,0 +1,32 @@ +package fr.greencodeinitiative.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) { + } +} \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java new file mode 100644 index 0000000..5ed3652 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java @@ -0,0 +1,12 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java new file mode 100644 index 0000000..d6d9efd --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java @@ -0,0 +1,12 @@ +package fr.greencodeinitiative.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/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java new file mode 100644 index 0000000..e190734 --- /dev/null +++ b/src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java @@ -0,0 +1,16 @@ +package fr.greencodeinitiative.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(); + } +}